KeyListener – Java Swing – Example
In this tutorial, we are going to see an example of KeyListener in java Swing. Java KeyListener is notified every time you change the state of a key. It is notified by KeyEvent. The KeyListener interface exists in java.awt.event package. It has three methods.
The three methods of KeyListener interface are given below:
- keyPressed(KeyEvent e)
- keyReleased(KeyEvent e)
- keyTyped(KeyEvent e)
[st_adsense]
Example : KeyListener in Java Swing
import java.awt.*; import javax.swing.*; import java.awt.event.*; public class KeyListenerTest extends JFrame implements KeyListener { JLabel label; JTextField text; KeyListenerTest() { label = new JLabel(); label.setBounds(20,20,100,20); text = new JTextField(); text.setBounds(20,50,200,30); text.addKeyListener(this); add(label); add(text); setSize(250,150); setLayout(null); setVisible(true); } public void keyPressed(KeyEvent e) { label.setText("Key pressed"); } public void keyReleased(KeyEvent e) { label.setText("Key released"); } public void keyTyped(KeyEvent e) { label.setText("Key typed"); } public static void main(String[] args) { new KeyListenerTest(); } }
Output:
[st_adsense]