Java KeyEvent: how to read in two keys at once - java

I am making a simple game(my first time using key reader) and am using WASD inputs to move the character. I want to make it so that if you press, say, W and A at the same time, you go diagonal. Does anyone know how to do this?

Don't use a KeyListener. Swing was designed to be used with Key Bindings.
Either way you can't listen for multiple keys at once so you need to keep track of which keys have been pressed. Since you want to do animation you would generally use a Swing Timer to schedule the animation. Then every time the Timer fires you check which keys are pressed and move you character based on the keys pressed.
Check out KeyboardAnimation.java source code from Motion Using The Keyboard for an example that demonstrates this approach. This article also gives reasons why key bindings are preferred over a KeyListener.

Related

Java Keypressed event on netbeans gui does not work?

I use Netbeans form template to build gui and add Keypress event on form(right-click > Event > KeyPressed) like a code below.
But it seems System.out.print or another action does not perform anything.
So how should I do to fix this problem?
private void formKeyPressed(java.awt.event.KeyEvent evt) {
char PressedChar = evt.getKeyChar();
System.out.print(PressedChar);
}
So how should I do to fix this problem?
Swing is designed to be used with Key bindings which is a more flexible and reliable approach that brings with these benefits:
Separates the action itself from the key strokes.
There are different conditions to trigger those actions: WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
We can take advantage of those conditions to attach different actions to different components relying on a precedence-based policy (see the example presented here).
Having said this, we'd rarely want to listen for any key pressed to do something but for some specific key stroke or key combination in order to perform some action. However if your use case is such then yes, you'll need a KeyListener, but please take a look to this answer by #camickr to do it correctly.
See also this topic: Key bindings vs. key listeners in Java, and How to Use Key Bindings tutorial

Changing 2 images at mousePressed

I have 2 images of legs of a character, I want them to be changing while I pressed the keyboard for example left or right arrow key. It's like the character is walking. How to do this in java slick2d? I have no codes to provide because I have no Idea how to start coding it. Thank you very much.
If you just want to handle basic input and you don't need to use slick2D then you can just use a KeyListener or MouseListener for input. These are Java features and are very simple to use.
To use Slick2D, my best guess would be to start here,
Slick Commands
These are for more advanced inputs I believe but you should do some research on each to see what you need to use.

Capturing specific keystrokes in Java Swing

There are a lot of topics on how to capture keystrokes in Java Swing, but I'd like to ask about the best practice. For example, I have a window in which I wish to listen to a keystroke of either F1 or Command-P on a Mac (or CTRL-P on a PC).
Reading The official Javadoc for KeyEvent, it seems that it is a better practice to use Key Typed events rather than Key Pressed or Key Released events, because they are higher-level. This makes sense to me, and I've even found that in order to make sure the program is platform-agnostic, I have to specify a keystroke object thusly:
private KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_P, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
This should allow for capturing of either the Command accelerator key on a Mac, and the CTRL accelerator key on a PC. (I hope I'm using those terms correctly.) So now that I have a KeyStroke object, how do I go about checking it against a KeyEvent object in my KeyListener? And throwing a check for an F1 key event as well only complicates the matter further, though hopefully not too much.
Suggestions?
So now that I have a KeyStroke object, how do I go about checking it against a KeyEvent object in my KeyListener?
You don't use a KeyListener. Swing was designed to be used with Key Bindings.
Check out Key Bindings which contains a program to list the default bindings of each Swing component. It also give some example of how you might create your own ey Bindings. It also contains a link to the Swing tutorial on Key Bindings which explains the whole process in more detail

Weird behavior of keyboard events in Java

When I press "Delete" button on the keyboard, program gets three events - KEY_PRESSED, KEY_TYPED, and KEY_RELEASED. The problem is, in KEY_PRESSED and KEY_RELEASED, parameter "keyCode" is set, but in the KEY_TYPED it is not (in fact, there no meaningful info in that event). With F5 key, it is even funnier - KEY_PRESSED and KEY_RELEASED are registered, but KEY_TYPED never occurs.
The listener was added via Toolkit.getDefaultToolkit().addAWTEventListener(). Using JDK 6.26.
What could be my problem?
EDIT:
Here are the events that happen when Delete key is pressed:
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=127,keyText=Delete,keyChar=Delete,keyLocation=KEY_LOCATION_STANDARD,rawCode=119,primaryLevelUnicode=127,scancode=0] on javax.swing.JButton[,0,0,61x30,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.synth.SynthBorder#50f38cf0,flags=288,maximumSize=,minimumSize=,preferredSize=,defaultIcon=javax.swing.ImageIcon#6ae2d0b2,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=SVG,defaultCapable=false]
java.awt.event.KeyEvent[KEY_TYPED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar=Delete,keyLocation=KEY_LOCATION_UNKNOWN,rawCode=0,primaryLevelUnicode=127,scancode=0] on javax.swing.JButton[,0,0,61x30,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.synth.SynthBorder#50f38cf0,flags=288,maximumSize=,minimumSize=,preferredSize=,defaultIcon=javax.swing.ImageIcon#6ae2d0b2,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=SVG,defaultCapable=false]
java.awt.event.KeyEvent[KEY_RELEASED,keyCode=127,keyText=Delete,keyChar=Delete,keyLocation=KEY_LOCATION_STANDARD,rawCode=119,primaryLevelUnicode=127,scancode=0] on javax.swing.JButton[,0,0,61x30,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.synth.SynthBorder#50f38cf0,flags=288,maximumSize=,minimumSize=,preferredSize=,defaultIcon=javax.swing.ImageIcon#6ae2d0b2,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=SVG,defaultCapable=false]
better would be implements KeyBindings
part of keyboard are reserved Keys for built-in JComponent funcionality, more informations from #camickrs UIManager Defaults
depends of reason(s) why you needed implents KeyListener, because for there are lots of another Listeners for various JComponent, that should be filtering or register text changes inside
some of JComponent Models generated Events from Mouse and Keyboard input
From the JavaDoc The "key typed" event. This event is generated when a character is entered. In the simplest case, it is produced by a single key press. Often, however, characters are produced by series of key presses, and the mapping from key pressed events to key typed events may be many-to-one or many-to-many.
You are trying to get the F5 key which is probably not registered as a character being entered. By using the KEY_RELEASED you will consistently get the result you are looking for and the API is behaving as expected.
Key typed events ALWAYS generate '0' as the key code. Look up the method getKeyChar() instead, or (as has been suggested) listen for keyReleased() instead.
getKeyChar(): http://goo.gl/ajH03

SWT: Check if multiple keys are pressed at the same time

I want do develop a little game in java and swt.
For this reason, I have to react to KeyEvents.
How can I check if e.g. the up arrow key and 'q' are pressed together?
Thanks in advance
phineas
SWT does not have a concept of pressed together (unless you are talking about standard modifier keys such as shift, alt, etc). What you can do is catch both the up arrow and 'q' key events separately. If timing is an issue then you can compare the two time stamps (There is a time field in KeyEvent) and determine what your definition of together is (50 ms? you may want to experiment).
If q is being used like a modifier then this is easier because you can set a flag when q is pressed and when the up arrow is pushed you can check whether the q flag is set. This would be much easier than worrying about timing. Of course don't forget to clear the q flag when the key is released.
Actually, you can implement that. Each key down and key up has it's own event fired, so you know exactly what keys are being pressed when and what keys are down at any moment.
Example: When the down arrow's key down event is fired, you start moving the right paddle down. When the X key's key down event is fired you start moving the left paddle down. When the X key's key up event is fired, you stop moving the left paddle, and when the down arrow's key up event is fired, you stop moving the right paddle. => You control them independently of each other.
You can wrap all that in some sort of utility that will make the solution cleaner.
rancidfishbreath's solution will work. For an excellent example, see http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet25.java
Thanks for your answers!
I just thought I could develop a little pong game quite fast, but I didn't kow key bindings are so difficult to handle! The main obstacle is that the two paddles must be moved in an independent way (currently the pressing keys interfere the opponents moves and vice versa).

Categories

Resources