Java Swing GUI

KeyListener – Java Swing – Example

In this tutorial, we are going to see an example of KeyListener in java Swing. Java KeyListener is notified every time you change the state of a key. It is notified by KeyEvent. The KeyListener interface exists in java.awt.event package. It has three methods.

The three methods of KeyListener interface are given below:

  • keyPressed(KeyEvent e)
  • keyReleased(KeyEvent e)
  • keyTyped(KeyEvent e)


 

Example : KeyListener in Java Swing
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class KeyListenerTest extends JFrame implements KeyListener
{
  JLabel label;
  JTextField text;
  
  KeyListenerTest()
  {  
    label = new JLabel();
    label.setBounds(20,20,100,20);
    text = new JTextField();
    text.setBounds(20,50,200,30);
    text.addKeyListener(this);
    
    add(label);
    add(text);
    setSize(250,150);
    setLayout(null);
    setVisible(true);
  }
  public void keyPressed(KeyEvent e) {
    label.setText("Key pressed");
  }
  public void keyReleased(KeyEvent e) {
    label.setText("Key released");
  }
  public void keyTyped(KeyEvent e) {
    label.setText("Key typed");
  }

  public static void main(String[] args) {
    new KeyListenerTest();
  }
}

Output:


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *