More Events
Keyboard Events Now that you’re an expert on MouseEvents, let’s try the keyboard. There are many similarities so this lesson will be a little different.
Keyboard Events This might seem a little backwards, but here we go: Open KeyboardAndFocusDemo.java file from DocSharing and run it.
Keyboard Events Press the right and left arrow keys, as well as the “g” and “b” keys. What happens? (If nothing, you need to click on the applet first.)
Keyboard Events Keyboard events are very similar to Mouse events. There are some differences, and the following notes discuss some things you’ll see in the code.
Keyboard Events Events are classes that have methods. One method you’ll see is getKeyChar(). This gets the character (letter) from the key, and usually stores it in a “char” variable.
Keyboard Events “char” types can be compared using the == test: if(char == ‘B’) tests if the character is the same as CAPITAL B.
Keyboard Events Sometimes keys don’t have characters. For example, the “arrow” keys. For those, we use getKeyCode() These return an integer, so you’ll see it stored like: int key = evt.getKeyCode();
Keyboard Events To use keys like the arrow keys, Java made a “virtual key” for them. The following code compares the key “heard” to the left arrow key: int key = evt.getKeyCode(); if (key == KeyEvent.VK_LEFT) //do something…
Java - Assignment And that’s all of the new information. Now it’s time to apply these notes, and those from Applets, Graphics, and Mouse Events! Please head over to the Key Lab!