by Dinesh Thakur Category: Swing

Key events occur when a key is pressed, released or typed on a component. Objects representing key events are created from KeyEvent class. The corresponding listener interface for KeyEvent class is KeyListener. Each listener for KeyEvent should implement the KeyListener interface. The KeyListener interface defines three methods.

public void keyTyped(KeyEvent e)

public void keyPressed(KeyEvent t e)

public void keyReleased(KeyEvent e)

 Demonstrate the event handling mechanism using KeyListener interface

import javax.swing.*;

import java.awt.event.*;
import java.awt.*;
class KeyListenerExample extends JFrame implements KeyListener
{
       JTextField data;
       JTextArea  txtData;
       String s="";
       KeyListenerExample()
       {
         JPanel panell = new JPanel(new FlowLayout());
         JPanel panel2 = new JPanel(new FlowLayout());
         data = new JTextField(20);
         txtData = new JTextArea(20,30);
         data.addKeyListener(this);
         panell.add(data);
         panel2.add(txtData);
         add(panell,BorderLayout.NORTH);
         add(panel2,BorderLayout.CENTER);
       }
      public void keyTyped(KeyEvent e)
      {
        s  += "\n KeyTyped = " + String.valueOf(e.getKeyChar());
        System.out.println(s);
        txtData.setText(s);
      }
     public void keyPressed(KeyEvent e)
     {
       s += "\n KeyPressed = " +String.valueOf(e.getKeyCode());
       System.out.println(s);
       txtData.setText(s);
     }
     public void keyReleased(KeyEvent e)
     {
       s += "\n KeyReleased = " +String.valueOf(e.getKeyCode());
       System.out.println(s);
       txtData.setText(s);
     }
   }
   class KeyListenerJavaExample
   {
      public static void main(String[] args)
      {
         KeyListenerExample frame = new KeyListenerExample();
         frame.setTitle("KeyListener Java Example");
         frame.setBounds(100,200,350,300);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
     }
   }

KeyListener in Java Swing Example



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content





Popular Article