Process key event for JTextField in Java
Description
The following code shows how to process key event for JTextField.
Example
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
/* w w w . ja v a 2 s . c o m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.Document;
public class Main {
// Test method
public static void main(String[] args) {
JFrame f = new JFrame();
f.setLayout(new FlowLayout());
final PassiveTextField ptf = new PassiveTextField(32);
JTextField tf = new JTextField(32);
JPanel p = new JPanel();
JButton b = new JButton("OK");
p.add(b);
f.getContentPane().add(ptf);
f.getContentPane().add(tf);
f.getContentPane().add(p);
ActionListener l = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Action event from a text field");
}
};
ptf.addActionListener(l);
tf.addActionListener(l);
// Make the button the default button
f.getRootPane().setDefaultButton(b);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Content of text field: <" + ptf.getText() + ">");
}
});
f.pack();
f.setVisible(true);
}
}
class PassiveTextField extends JTextField {
public PassiveTextField() {
this(null, null, 0);
}
public PassiveTextField(String text) {
this(null, text, 0);
}
public PassiveTextField(int columns) {
this(null, null, columns);
}
public PassiveTextField(String text, int columns) {
this(null, text, columns);
}
public PassiveTextField(Document doc, String text, int columns) {
super(doc, text, columns);
}
public void processComponentKeyEvent(KeyEvent evt) {
switch (evt.getID()) {
case KeyEvent.KEY_PRESSED:
case KeyEvent.KEY_RELEASED:
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
return;
}
break;
case KeyEvent.KEY_TYPED:
if (evt.getKeyChar() == '\r') {
return;
}
break;
}
super.processComponentKeyEvent(evt);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »