Java JFrame handle key event

Description

Java JFrame handle key event


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

import javax.swing.JFrame;
import javax.swing.JTextArea;

public class Main extends JFrame implements KeyListener {
  private JTextArea textArea = new JTextArea(10, 15); // set up JTextArea

  // Main constructor
  public Main() {
    super("Demonstrating Keystroke Events");
    textArea.setText("Press any key on the keyboard...");
    textArea.setEnabled(false);//from ww  w. j a v  a 2 s.  c  o  m
    //textArea.setDisabledTextColor(Color.BLACK);
    add(textArea);
    addKeyListener(this); 
  }
  // handle press of any key
  @Override
  public void keyPressed(KeyEvent event) {
    String s = String.format("Key pressed: %s", KeyEvent.getKeyText(event.getKeyCode())); // show pressed key
    System.out.println(s);
    display(event); // set output lines two and three
  }

  // handle release of any key
  @Override
  public void keyReleased(KeyEvent event) {
    String s = String.format("Key released: %s", KeyEvent.getKeyText(event.getKeyCode())); // show released key
    System.out.println(s);
    display(event); // set output lines two and three
  }

  // handle press of an action key
  @Override
  public void keyTyped(KeyEvent event) {
    String s= String.format("Key typed: %s", event.getKeyChar());
    System.out.println(s);
    display(event); // set output lines two and three
  }

  // set second and third lines of output
  private void display(KeyEvent event) {
    String s = String.format("This key is %san action key", (event.isActionKey() ? "" : "not "));
    System.out.println(s);
    String temp = KeyEvent.getKeyModifiersText(event.getModifiers());

    s = String.format("Modifier keys pressed: %s", (temp.equals("") ? "none" : temp)); // output modifiers
    System.out.println(s);
  }

  public static void main(String[] args) {
    Main Main = new Main();
    Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Main.setSize(350, 100);
    Main.setVisible(true);
  }
}



PreviousNext

Related