Java JTextField handle key event and get key char

Description

Java JTextField handle key event and get key char


import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JTextField;

class MyKeyListener implements KeyListener {
   public void keyTyped(KeyEvent e) {
      char c = e.getKeyChar();
      System.out.println("Key Typed: " + c);
   }//  www. j  a  v  a  2 s.c  om

   public void keyPressed(KeyEvent e) {
      char c = e.getKeyChar();
      System.out.println("Key Pressed: " + c);
   }

   public void keyReleased(KeyEvent e) {
      char c = e.getKeyChar();
      System.out.println("Key Released: " + c);
   }
}

public class Main {

   public static void main(String[] a) {
      JFrame frame = new JFrame("Key event");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      JTextField textField = new JTextField();
      textField.addKeyListener(new MyKeyListener());

      frame.add(textField);
      frame.setSize(300, 200);
      frame.setVisible(true);
   }

}



PreviousNext

Related