Java - JTextField - Call function when user press “space bar”

前端 未结 1 1994
野性不改
野性不改 2021-01-28 14:36

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         


        
1条回答
  •  被撕碎了的回忆
    2021-01-28 14:43

    "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.

    0 讨论(0)
提交回复
热议问题