Processing Key Events: Code Sample     Peter Komisar


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

// the MenuItem invokes the ActionListener whose method causes the process to end
// the KeyListener is being used by the upper case letter A Key to write to the text area

class KeyT implements KeyListener, ActionListener{

// variables declared in class scope so they are available for reference from class methods

JTextArea jta;
JMenuItem jExit;

// The constructor

KeyT( ){
JFrame jf=new JFrame();
JMenuBar jbar=new JMenuBar();
JMenu jmenu=new JMenu("Menu");
 jExit=new JMenuItem("Exit");
jExit.addActionListener(this);

//  Here, a key stroke combo is associated with the menu event
// KeyStroke uses methods instead of constructor to return an instance of itself
// It takes a virtual key constant representing the key, and the modifier as arguments

jExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.CTRL_MASK));
jmenu.add(jExit);
jbar.add(jmenu);
jf.setJMenuBar(jbar);

 jta=new JTextArea("Set your keyboard to Caps Lock and press the letter A \n");
jf.getContentPane().add(jta);
jta.addKeyListener(this);
jf.setSize(400,300);
jf.setVisible(true);
}
/* methods of KeyListener interface */

public void keyPressed(KeyEvent e) {
 if(e.getKeyChar()==e.VK_A )
 jta.setText("Don't read this subliminal message \n");
 }

public void keyReleased(KeyEvent e) {
  // Invoked when a key has been released.
  if(e.getKeyChar()==e.VK_A )
  jta.setText("\n A is for Apple ");
}

public void keyTyped(KeyEvent e){ /*  stub */ }
// the ActionListener method
public void actionPerformed(ActionEvent ae){
System.exit(0);
}
public static void main(String [] args){
 new KeyT();
  }
 }