Java Reference
In-Depth Information
Part of this ActionEvent is an action command. By default, the action command of the event is
the current contents of the component. With the Swing JTextField , you can also set this action
command to be something different from the content. The JTextField has an actionCommand
property. When it is set to null (the default setting), the action command for the ActionEvent
takes the contents of the component. However, if you set the actionCommand property for the
JTextField , then that actionCommand setting is part of the ActionEvent .
The following code demonstrates this difference. There are two text fields. When Enter is
pressed in the first text field, causing the registered ActionListener to be notified, “Yo” is
printed out. When Enter is pressed in the second text field, the contents are printed out.
JTextField nameTextField = new JTextField();
JTextField cityTextField = new JTextField();
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Command: " + actionEvent.getActionCommand());
}
};
nameTextField.setActionCommand("Yo");
nameTextField.addActionListener(actionListener);
cityTextField.addActionListener(actionListener);
Listening to JTextField Events with an KeyListener
With the Swing text components, you normally don't listen for key events with a KeyListener
at least not to validate input. Running the following example demonstrates that you can still
find out when a key has been pressed or released, not just when it has been typed.
KeyListener keyListener = new KeyListener() {
public void keyPressed(KeyEvent keyEvent) {
printIt("Pressed", keyEvent);
}
public void keyReleased(KeyEvent keyEvent) {
printIt("Released", keyEvent);
}
public void keyTyped(KeyEvent keyEvent) {
printIt("Typed", keyEvent);
}
private void printIt(String title, KeyEvent keyEvent) {
int keyCode = keyEvent.getKeyCode();
String keyText = KeyEvent.getKeyText(keyCode);
System.out.println(title + " : " + keyText);
}
};
nameTextField.addKeyListener(keyListener);
cityTextField.addKeyListener(keyListener);
Search WWH ::




Custom Search