JonK
JonK

Reputation: 37

(Java) Can I use KeyListener to input text? (inside event dispatching thread)

I'm building a Swing game that is drawn entirely (everything, menus included) in single JPanel object. I have a game loop in this JPanel, which handles everything from updating the state of the game to drawing it and so on.

Now, I need to somehow enable the player to type in their own text in some of the menus. Creating a new player profile, saving some other information and the like. I can't seem to find a good way for doing this. Using a Scanner is obviously out of the question, since doing that will interrupt the event dispatching thread, freezing the game on the spot (I learned that the hard way).

I have concluded that the only way to do this is to use the KeyListener to somehow record the keys I have pressed on the keyboard. I have been experimenting with its keyTyped method, but my results have been poor. I have been able to make it record my keypresses, but the problem is, it records EVERY key I have pressed, including backspace, control, TAB, and so on... Plus, every character that I type is outputted capitalized, regardless of whether I have Caps Lock on or not.

I hope you understand what I'm trying to achieve here. So my real question: Is there any easy way to record typing using KeyListener? Or is there some other way that can be used inside of the event dispatching thread?

Upvotes: 1

Views: 219

Answers (1)

tddmonkey
tddmonkey

Reputation: 21184

Your options are:

  1. Use a standard popup dialog and get your text that way
  2. Embed a text field into your panel to receive input

The problem is that a KeyListener is just that, it listens for key events. The standard text input components combine this with a DocumentListener for processing text

Upvotes: 1

Related Questions