Results 1 to 1 of 1
  1. #1
    Java Example is offline Moderator
    Join Date
    Sep 2014
    Rep Power

    Default How to implement KeyListener in java?

    In this tutorial, we will illustrate how to handle different key events on the Java Awt component by using the event handling in Java. In the example below several key events are applied on the component like the key pressed, key release. All the key events are handled through the KeyListener Interface that has been implemented in the main class of the program. Here in the program, we show how to display the specific message on the frame according to the event. When key is pressed then the message "Key Pressed" will be seen on the frame and when we stop pressing keys then the message "Key Released" will be seen. For this KeyListener interface is used. It will generate the KeyEvent and we can the check the exact event by using different method like the keyTyped(), keyPressed() and the keyReleased() method which are used for retrieving the generated specific event.

    Java Code: Program to implement keyListener in java
    import java.awt.*;
    import java.awt.event.*;
    public class KeyListenerTester extends Frame implements KeyListener {
        TextField t1;
        Label l1;
        public KeyListenerTester(String s) {
            Panel p = new Panel();
            l1 = new Label("Key Listener!");
            setSize(200, 100);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
        public void keyTyped(KeyEvent e) {
            l1.setText("Key Typed");
        public void keyPressed(KeyEvent e) {
            l1.setText("Key Pressed");
        public void keyReleased(KeyEvent e) {
            l1.setText("Key Released");
        public static void main(String[] args) {
            new KeyListenerTester("Key Listener Tester");
    Output of program:

    Figure: KeyListener implementation
    Attached Thumbnails Attached Thumbnails How to implement KeyListener in java?-key-released.jpg  
    Last edited by Java Example; 09-14-2014 at 09:42 PM.

Similar Threads

  1. How to implement REST in java?
    By milind_bharambe in forum New To Java
    Replies: 1
    Last Post: 11-11-2013, 12:33 PM
  2. KeyListener java applet
    By happyjoker in forum Java Applets
    Replies: 2
    Last Post: 04-16-2011, 12:24 PM
  3. Help with KeyListener in Java Swing
    By codeRunner1 in forum AWT / Swing
    Replies: 1
    Last Post: 02-27-2011, 11:48 PM
  4. How can we implement IPC in java
    By samson in forum Networking
    Replies: 1
    Last Post: 04-04-2007, 06:38 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts