Ti fornisco del codice molto semplice, vedi se ti e' utile.
codice:
public class KeyDemo extends JFrame implements KeyListener {
private String line1 = "", line2 = "", line3 = "";
private JTextArea textArea;
/** Creates a new instance of KeyDemo */
public KeyDemo() {
super("Demostrating Keystroke Event");
//imposta una JTextArea
textArea = new JTextArea(10, 15);
textArea.setText("Press any on the keyboard...");
textArea.setEnabled(false);
textArea.setDisabledTextColor(Color.GRAY);
getContentPane().add(textArea);
addKeyListener(this);
Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
setBounds(center.x - 350/2, center.y -100/2, 350, 100);
setVisible(true);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
KeyDemo appliction = new KeyDemo();
appliction.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void keyTyped(java.awt.event.KeyEvent e) {
line1 = "Key typed: " + e.getKeyText(e.getKeyCode());
setLine2and3(e);
}
public void keyReleased(java.awt.event.KeyEvent e) {
line1 = "key released: " + e.getKeyText(e.getKeyCode());
setLine2and3(e);
}
public void keyPressed(java.awt.event.KeyEvent e) {
if(e.getKeyCode() == 87)
System.out.println("Premuto W");
line1 = "key pressed: " + e.getKeyText(e.getKeyCode());
setLine2and3(e);
}
private void setLine2and3 (KeyEvent e) {
System.out.println(e.getKeyCode());
line2 = "This key is " + (e.isActionKey() ? "" : "not ") + "an action key";
String temp = e.getKeyModifiersText(e.getModifiers());
line3 = "Modifier keys pressed: " + (temp.equals("") ? "none " : temp);
textArea.setText(line1 + "\n" + line2 + "\n" + line3 + "\n");
}
}