Key events occur when a key is pressed on the keyboard. Any component can generate these events, and a class must implement KeyListener interface to support them. The following example shows how to use key events in Swing. Hi, everyone, please explain displaying JPanel, ON button click in the same Frame i've displayed a new JFrame with respect to button click but not JPanel.
The following Java code shows an example program that implements the KeyListener
interface. When executed, the Java code will show a very simple Swing Graphical User Interface.
Background
The GUI is made up of a JFrame
which contains two JTextAreas
. The first, feedbackText
JTextArea
, is placed inside a JScrollPane
and is used to display text generated by the KeyListener
events. The JScrollPane
allows the user to see all the lines of text generated by the KeyListener
events.
The second is the inputText JTextArea
. This JTextArea
has the focus and will generate KeyListener
events as the user types into it. By default, the inputArea JTextArea
will have the focus when the JFrame
appears.
The KeyListener
interface could have been implemented as a separate class, or extending the JFrame
, but in this instance using an anonymous inner class makes the most sense.
The keyPressed
method is called when a user presses down on a key and the keyReleased
method is called when a key is released. The keyTyped
method is called when a character key is typed into the inputText JTextArea
.