Handle Key pressed event - Java Swing

Java examples for Swing:Key Event

Description

Handle Key pressed event

Demo Code

import java.awt.FlowLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main extends JFrame {
  JLabel keyLabel = new JLabel("Hit any key");

  public Main() {
    super("Hit a Key");
    setSize(300, 200);/*  w w w .jav  a2 s  .  co  m*/
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new FlowLayout(FlowLayout.CENTER));
    KeyMonitor monitor = new KeyMonitor(this);
    setFocusable(true);
    addKeyListener(monitor);
    add(keyLabel);
    setVisible(true);
  }

  public static void main(String[] arguments) {
    new Main();
  }
}

class KeyMonitor extends KeyAdapter {
  Main display;

  KeyMonitor(Main display) {
    this.display = display;
  }

  public void keyTyped(KeyEvent event) {
    display.keyLabel.setText("" + event.getKeyChar());
    display.repaint();
  }
}

Related Tutorials