javacodex.com
Java Examples
Java Examples
memu home questions

KeyListener

The event occurs when the component has the focus and a key on the keyboard is pressed, released, or typed. The key pressed and released events are triggered when you press or release any key on the keyboard. The key typed event is triggered only when a Unicode character is typed. For example, when you type character ’a’ on the keyboard, a key pressed, a key typed, and a key released event are triggered in sequence.

Source: (KeyListenerExample.java)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
public class KeyListenerExample {
  public static void main(String [] args) {
 
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("KeyListener Example");
    frame.setSize(300,150);
 
    final JLabel label = new JLabel();
    frame.add(label);
 
    frame.addKeyListener(new KeyListener() {
        public void keyTyped(KeyEvent ke) { 
          label.setText("Key Typed: " + ke.getKeyChar());
        }
        public void keyPressed(KeyEvent ke) {}
        public void keyReleased(KeyEvent ke) {}
    });
 
    frame.setVisible(true);			
  }
}
 

Output:

$ java KeyListenerExample
Output



Contact: javacodex@yahoo.com