Allowing the “Enter” key to press the submit button, as opposed to only using MouseClick

前端 未结 7 1140
清歌不尽
清歌不尽 2020-11-27 04:23

I\'m learning Swing class now and everything about it. I\'ve got this toy program I\'ve been putting together that prompts for a name and then presents a JOptionPane with th

相关标签:
7条回答
  • 2020-11-27 04:52

    There is a simple trick for this. After you constructed the frame with all it buttons do this:

    frame.getRootPane().setDefaultButton(submitButton);
    

    For each frame, you can set a default button that will automatically listen to the Enter key (and maybe some other event's I'm not aware of). When you hit enter in that frame, the ActionListeners their actionPerformed() method will be invoked.


    And the problem with your code as far as I see is that your dialog pops up every time you hit a key, because you didn't put it in the if-body. Try changing it to this:

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode()==KeyEvent.VK_ENTER){
            System.out.println("Hello");
    
            JOptionPane.showMessageDialog(null , "You've Submitted the name " + nameInput.getText());
        }
    
    }
    

    UPDATE: I found what is wrong with your code. You are adding the key listener to the Submit button instead of to the TextField. Change your code to this:

    SubmitButton listener = new SubmitButton(textBoxToEnterName);
    textBoxToEnterName.addActionListener(listener);
    submit.addKeyListener(listener);
    
    0 讨论(0)
  • 2020-11-27 04:57
     switch(KEYEVENT.getKeyCode()){
          case KeyEvent.VK_ENTER:
               // I was trying to use case 13 from the ascii table.
               //Krewn Generated method stub... 
               break;
     }
    
    0 讨论(0)
  • 2020-11-27 04:59

    Without a frame this works for me:

    JTextField tf = new JTextField(20);
    tf.addKeyListener(new KeyAdapter() {
    
      public void keyPressed(KeyEvent e) {
        if (e.getKeyCode()==KeyEvent.VK_ENTER){
           SwingUtilities.getWindowAncestor(e.getComponent()).dispose();
        }
      }
    });
    String[] options = {"Ok", "Cancel"};
    int result = JOptionPane.showOptionDialog(
        null, tf, "Enter your message", 
        JOptionPane.OK_CANCEL_OPTION,
        JOptionPane.QUESTION_MESSAGE,
        null,
        options,0);
    
    message = tf.getText();
    
    0 讨论(0)
  • 2020-11-27 05:03

    You can use the top level containers root pane to set a default button, which will allow it to respond to the enter.

    SwingUtilities.getRootPane(submitButton).setDefaultButton(submitButton);
    

    This, of course, assumes you've added the button to a valid container ;)

    UPDATED

    This is a basic example using the JRootPane#setDefaultButton and key bindings API

    public class DefaultButton {
    
        public static void main(String[] args) {
            new DefaultButton();
        }
    
        public DefaultButton() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    JFrame frame = new JFrame("Test");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
    
            });
        }
    
        public class TestPane extends JPanel {
    
            private JButton button;
            private JLabel label;
            private int count;
    
            public TestPane() {
    
                label = new JLabel("Press the button");
                button = new JButton("Press me");
    
                setLayout(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridy = 0;
                add(label, gbc);
                gbc.gridy++;
                add(button, gbc);
                gbc.gridy++;
                add(new JButton("No Action Here"), gbc);
    
                button.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        doButtonPressed(e);
                    }
    
                });
    
                InputMap im = button.getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
                ActionMap am = button.getActionMap();
    
                im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "spaced");
                am.put("spaced", new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        doButtonPressed(e);
                    }
    
                });
    
            }
    
            @Override
            public void addNotify() {
                super.addNotify();
                SwingUtilities.getRootPane(button).setDefaultButton(button);
            }
    
            protected void doButtonPressed(ActionEvent evt) {
                count++;
                label.setText("Pressed " + count + " times");
            }
    
        }
    
    }
    

    This of course, assumes that the component with focus does not consume the key event in question (like the second button consuming the space or enter keys

    0 讨论(0)
  • 2020-11-27 05:06

    I know this isn't the best way to do it, but right click the button in question, events, key, key typed. This is a simple way to do it, but reacts to any key

    0 讨论(0)
  • 2020-11-27 05:07

    In the ActionListener Class you can simply add

    public void actionPerformed(ActionEvent event) {
        if (event.getSource()==textField){
            textButton.doClick();
        }
        else if (event.getSource()==textButton) {
            //do something
        }
    }
    
    0 讨论(0)
提交回复
热议问题