How to Detect a KeyPress in Java

Save

Although most needs to get user input are handled quite easily in Swing via standard components -- for example, getting text through a JTextField component -- sometimes it's necessary to get the exact key presses from the user. Perhaps a specific key combination will cause a certain action, or perhaps you want to prevent certain key strokes from having their default effect, such as allowing only alphabetic characters in a text box. Regardless of the scenario, getting the key the user pressed is simple.

Things You'll Need

  • Java SDK
  • Integrated Development Environment, such as Eclipse or NetBeans, recommended but not required
  • Create a simple class that creates and displays a JFrame for now:

    import java.awt.Dimension;

    import java.lang.reflect.InvocationTargetException;

    import javax.swing.JFrame;

    import javax.swing.SwingUtilities;

    public final class KeyPressTester implements Runnable {

    public static void main(String[] args) throws InterruptedException, InvocationTargetException {

    SwingUtilities.invokeAndWait(new KeyPressTester());

    }

    @Override

    public void run() {

    frame = new JFrame("KeyPress Tester");

    frame.setSize(new Dimension(800, 600));

    frame.setVisible(true);

    }

    private JFrame frame;

    }

  • Modify the run() method to add a KeyListener to the frame with the following implementation:

        frame.addKeyListener(new KeyListener() {

    @Override

    public void keyTyped(KeyEvent e) {

    }

    @Override

    public void keyReleased(KeyEvent e) {

    }

    @Override

    public void keyPressed(KeyEvent e) {

    System.out.println("Key Character: " + e.getKeyChar() + "; Key Code: " + KeyEvent.getKeyText(e.getKeyCode()));

    }

    });

  • Compile and execute the program. If you press a key when the frame has focus, you should see console output that describes the key you pressed, including both the actual text character (if available) and the text of the key, such as Shift, Ctrl, Backspace, etc.

Tips & Warnings

  • Review the other methods available on the supplied KeyEvent parameter. They can be used to indicate that the user pressed a modifier key, such as "Alt" or "Ctrl," along with the specified key, and differentiate between, for example, the left and right shift keys. Also explore the other two events available in the KeyListener, keyTyped and keyReleased, as they trap slightly different versions of key board events and might be more applicable to different situations.
  • Photo Credit Comstock/Comstock/Getty Images
Promoted By Zergnet

Comments

Resources

You May Also Like

  • How to Get Keyboard Input in Java

    Command-line programs are run in a console window, such as the Windows "Command Prompt" or a Linux terminal, by typing the program...

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!