Java examples for Swing:Key Event
Add Key Listener to JFrame
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);//from w ww . j a v a2s . c o m setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout(FlowLayout.CENTER)); KeyAdapter monitor = new KeyAdapter() { public void keyTyped(KeyEvent event) { keyLabel.setText("" + event.getKeyChar()); repaint(); } }; setFocusable(true); addKeyListener(monitor); add(keyLabel); setVisible(true); } public static void main(String[] arguments) { new Main(); } }