I want my JTextField to process the text not only when ENTER is pressed,
but also when SPACE is pressed. You can see in the code below that I associated the action that is usually associated with ENTER to SPACE, but I get some unexpected behavior (see below).
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class Test extends JFrame {
private JTextField textField;
public Test() {
textField = new JTextField();
add(textField);
InputMap inputMap = this.textField.getInputMap();
Object actionSubmit = inputMap.get(KeyStroke.getKeyStroke("ENTER"));
Object actionSubmitSp = inputMap.get(KeyStroke.getKeyStroke("SPACE"));
System.out.println("actionSubmit for space = " + actionSubmitSp);
ActionMap actionMap = this.textField.getActionMap();
Action action = actionMap.get(actionSubmit);
System.out.println("actionSubmit = " + actionSubmit);
textField.getInputMap().put(KeyStroke.getKeyStroke("SPACE"),
actionSubmit);
textField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
textField.setText(null);
System.out.println("event received:[" +
evt.getActionCommand() + "]");
}
});
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Test test = new Test();
test.pack();
test.setVisible(true);
}
});
}
}
If I type “x SPACE” an ActionEvent is produced and the JTextField is cleared.
However the refreshed JTextField
is not a “null” string as requested, but ” “. The SPACE from the previous action
has “leaked” to the refreshed JTextField, which is quite annoying.
I looked in the swing code a bit. My best guess is that an ActionEvent is generated from some KeyEvent’s, and KeyEvent.isConsumed() has different consequences depending if the KeyEvent was a ENTER or a SPACE (an ENTER is swallowed, but not a SPACE).
Anyone knows how to fix this? Or knows a different method to accomplish my goal?
Multiple events are being generated. Your code is being executed on a
keyPressedevent. However using the space bar also results in akeyTypedevent being generated. This is handled by the text component after thekeyPressedcode has been executed, so theDocumentis cleared and then a space is added to it.Don’t use a
KeyListener.Add your code to the end of the EDT so that is executes AFTER the
Documenthas been updated with the space: