event

A complete Key Event example

With example we shall show you how to create a simple application that can handle all key events. This is very useful when your application gets lots of keyboard input form the user.

In short, all you have to do in order to construct a simple application that demonstrates all key events is:

  • Create a class that implements ActionListener and KeyListener interfaces.
  • Override keyPressed, keyTyped, keyReleased to customize the handling of these specific events.
  • Use event and input maps to print out the key events that occurred.

Let’s see the code snippet below:

package com.javacodegeeks.snippets.desktop;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class CompleteDemo extends JPanel implements KeyListener, ActionListener {

    JTextArea textArea;
    JTextField textFiled;
    static final String nl = "n";

    public static void main(String[] args) {

  javax.swing.SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

    createAndShowGUI();

}

  });
    }

    public CompleteDemo() {

  super(new BorderLayout());

  JButton jb = new JButton("Clear");

  jb.addActionListener(this);

  textFiled = new JTextField(20);

  textFiled.addKeyListener(this);

  //typingArea.setFocusTraversalKeysEnabled(false);

  textArea = new JTextArea();

  textArea.setEditable(false);

  JScrollPane scrPanl = new JScrollPane(textArea);

  scrPanl.setPreferredSize(new Dimension(375, 125));

  add(textFiled, BorderLayout.PAGE_START);

  add(scrPanl, BorderLayout.CENTER);

  add(jb, BorderLayout.PAGE_END);
    }

    @Override
    public void keyPressed(KeyEvent event) {

  display(event, "KEY PRESSED: ");
    }

    @Override
    public void keyTyped(KeyEvent event) {

  display(event, "KEY TYPED: ");
    }

    @Override
    public void actionPerformed(ActionEvent event) {

  //Clear the text components.

  textArea.setText("");

  textFiled.setText("");

  //Return the focus to the typing area.

  textFiled.requestFocusInWindow();
    }

    @Override
    public void keyReleased(KeyEvent event) {

  display(event, "KEY RELEASED: ");
    }

    protected void display(KeyEvent event, String str) {

  String keystr, modStr, tmpStr, actionstr, locStr;

  int eventID = event.getID();

  if (eventID == KeyEvent.KEY_TYPED) {

char key = event.getKeyChar();

keystr = "key str = '" + key + "'";

  } else {

int kCode = event.getKeyCode();

keystr = "kCode = " + kCode + " ("

  + KeyEvent.getKeyText(kCode) + ")";

  }

  int mods = event.getModifiersEx();

  modStr = "mods = " + mods;

  tmpStr = KeyEvent.getModifiersExText(mods);

  if (tmpStr.length() > 0) {

modStr += " (" + tmpStr + ")";

  } else {

modStr += " (no mods)";

  }

  actionstr = "action key? ";

  if (event.isActionKey()) {

actionstr += "YES";

  } else {

actionstr += "NO";

  }

  locStr = "key location: ";

  int location = event.getKeyLocation();

  if (location == KeyEvent.KEY_LOCATION_STANDARD) {

locStr += "standard";

  } else if (location == KeyEvent.KEY_LOCATION_LEFT) {

locStr += "left";

  } else if (location == KeyEvent.KEY_LOCATION_RIGHT) {

locStr += "right";

  } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {

locStr += "numpad";

  } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)

locStr += "unknown";

  }

  textArea.append(str + nl + "    " + keystr + nl + "    "

    + modStr + nl + "    " + actionstr + nl

    + "    " + locStr + nl);

  textArea.setCaretPosition(textArea.getDocument().getLength());
    }

    private static void createAndShowGUI() {

  //Make sure we have nice window decorations.

  JFrame.setDefaultLookAndFeelDecorated(true);

  //Create and set up the window.

  JFrame frame = new JFrame("KeyEventDemo");

  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  //Create and set up the content pane.

  JComponent newContentPane = new CompleteDemo();

  newContentPane.setOpaque(true); //content panes must be opaque

  frame.setContentPane(newContentPane);

  //Display the window.

  frame.pack();

  frame.setVisible(true);
    }

}

 
This as an example on how to monitor all keyevents in a Java Desktop Application.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button