// This simple example shows how to get set up to handle Key events. // When you run it, press the "c" key and watch the console. import java.awt.GridLayout; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class KeyPressExample extends JFrame implements KeyListener { static final int FRAME_WIDTH = 800; static final int FRAME_HEIGHT = 300; static final int SPECIAL_KEY = 'c'; public KeyPressExample() { super(); JPanel pan = new JPanel(); JButton button; pan.setLayout(new GridLayout(2,2)); for (int i=1; i<=4; i++){ pan.add(button = new JButton(i + "")); button.setFocusable(false); // This line is critical. If the buttons can get the focus, // key evants will be associated with them instead of with the JFrame. } this.add(pan); this.addKeyListener(this); } public void keyPressed(KeyEvent e) { if (e.getKeyChar()== SPECIAL_KEY) System.out.println("Pressed"); } public void keyReleased(KeyEvent e) { if (e.getKeyChar()== SPECIAL_KEY) System.out.println("Released"); } public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } /** * @param args */ public static void main(String[] args) { JFrame frame = new KeyPressExample(); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setTitle("First Graphics"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }