I made some searches and I didn\'t find how to call a function when the user press the key \"space bar\", I have this code:
edtCodigos.addKeyListener(new KeyAdap
"The users are used to type "space bar" to finish an operation like payment in a cashier."
Personally, I would just use an ActionListener
so that the Enter key triggers the event. It just seems more natural.
import java.awt.event.*;
import javax.swing.*;
public class TestTextField {
public static void main(String[] args) {
final JTextField field = new JTextField(15);
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println("Enter Pressed: " + field.getText());
}
});
JOptionPane.showMessageDialog(null, field);
}
}
If you want to use Space, you can bind the key the field using Key Bindings
import java.awt.event.ActionEvent;
import javax.swing.*;
public class TestTextField {
public static void main(String[] args) {
final JTextField field = new JTextField(15);
InputMap imap = field.getInputMap(JComponent.WHEN_FOCUSED);
imap.put(KeyStroke.getKeyStroke("SPACE"), "spaceAction");
ActionMap amap = field.getActionMap();
amap.put("spaceAction", new AbstractAction(){
public void actionPerformed(ActionEvent e) {
System.out.println("Space Pressed: " + field.getText());
}
});
JOptionPane.showMessageDialog(null, field);
}
}
You could even go as far as using a DocumentListener to listen for changes in the underlying document of the text field, and check the last character entered was a space (but this seems like a bit much - Just some info for you to learn the workings for text components :-)
Pick your flavor. I like the first.