Java AWT KeyEvent get key char

Description

Java AWT KeyEvent get key char

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

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

public class Main {
   public static void main(String[] args) {
      JFrame frame = new JFrame("Window Title");

      frame.setBounds(50, 100, 300, 300);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      JTextField typingArea = new JTextField(20);
      typingArea.addKeyListener(new KeyListener() {
         public void keyTyped(KeyEvent e) {
            displayInfo(e, "KEY TYPED: ");
         }// w  w  w. java  2  s.  c  om
         public void keyPressed(KeyEvent e) {
            displayInfo(e, "KEY PRESSED: ");
         }
         public void keyReleased(KeyEvent e) {
            displayInfo(e, "KEY RELEASED: ");
         }
         protected void displayInfo(KeyEvent e, String s) {
            int id = e.getID();
            if (id == KeyEvent.KEY_TYPED) {
               char c = e.getKeyChar();
               System.out.println("key character = '" + c + "'");
            } else {
               int keyCode = e.getKeyCode();
               System.out.println("key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode) + ")");
            }           
         }
      });
      frame.add(typingArea);
      frame.setVisible(true);
   }
}
import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

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

public class Main extends JFrame {
  JTextField keyText = new JTextField(80);
  JLabel keyLabel = new JLabel("Press any key in the text field.");

  public Main() {
    super("KeyViewer");
    setSize(350, 100);/*  ww w  . j ava  2  s  . c  o  m*/
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    keyText.addKeyListener(new KeyAdapter() {
      public void keyTyped(KeyEvent input) {
        char key = input.getKeyChar();
        keyLabel.setText("You pressed " + key);
      }
    });
    BorderLayout bord = new BorderLayout();
    setLayout(bord);
    add(keyLabel, BorderLayout.NORTH);
    add(keyText, BorderLayout.CENTER);
    setVisible(true);
  }

  public static void main(String[] arguments) {
    new Main();
  }
}



PreviousNext

Related