简体   繁体   English

允许“Enter”键按下提交按钮,而不是仅使用MouseClick

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

I'm learning Swing class now and everything about it. 我现在正在学习Swing课程以及它的一切。 I've got this toy program I've been putting together that prompts for a name and then presents a JOptionPane with the message "You've entered (Your Name)". 我已经把这个玩具程序放在一起,提示输入一个名字然后出现一个JOptionPane,上面写着“你输入了(你的名字)”。 The submit button I use can only be clicked on, but I'd like to get it to work with the Enter button too. 我只能点击我使用的提交按钮,但我也想让它与Enter按钮一起使用。 I've tried adding a KeyListener, as is recommended in the Java book I'm using (Eventful Java, Bruce Danyluk and Murtagh). 我已经尝试添加KeyListener,正如我正在使用的Java书中推荐的那样(Eventful Java,Bruce Danyluk和Murtagh)。

NamePrompt在此输入图像描述

This is my code: 这是我的代码:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class NamePrompt extends JFrame{


    private static final long serialVersionUID = 1L;

    String name;

    public NamePrompt(){

        setLayout(new BorderLayout());

        JLabel enterYourName = new JLabel("Enter Your Name Here:");
        JTextField textBoxToEnterName = new JTextField(21);
        JPanel panelTop = new JPanel();
        panelTop.add(enterYourName);
        panelTop.add(textBoxToEnterName);

        JButton submit = new JButton("Submit");
        submit.addActionListener(new SubmitButton(textBoxToEnterName));
        submit.addKeyListener(new SubmitButton(textBoxToEnterName));
        JPanel panelBottom = new JPanel();
        panelBottom.add(submit);

        //Add panelTop to JFrame
        add(panelTop, BorderLayout.NORTH);
        add(panelBottom, BorderLayout.SOUTH);

        //JFrame set-up
        setTitle("Name Prompt Program");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);


    }



    public static void main(String[] args) {
        NamePrompt promptForName = new NamePrompt();
        promptForName.setVisible(true); 
    }


}

And this is the actionListener, keyListener class: 这是actionListener,keyListener类:

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;


public class SubmitButton implements ActionListener, KeyListener {

    JTextField nameInput;


    public SubmitButton(JTextField textfield){
        nameInput = textfield;
    }

    @Override
    public void actionPerformed(ActionEvent submitClicked) {

        Component frame = new JFrame();
        JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput.getText());
    }

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

    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyTyped(KeyEvent arg0) {

    }
}

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). 对于每个帧,您可以设置一个默认按钮,该按钮将自动侦听Enter键(可能还有其他一些我不知道的事件)。 When you hit enter in that frame, the ActionListeners their actionPerformed() method will be invoked. 当您在该帧中按Enter键时,将调用ActionListeners的actionPerformed()方法。


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. 就我所看到的,你的代码问题在于,每次敲击键时都会弹出对话框,因为你没有把它放在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. 您正在将键侦听器添加到“提交”按钮而不是TextField。 Change your code to this: 将您的代码更改为:

SubmitButton listener = new SubmitButton(textBoxToEnterName);
textBoxToEnterName.addActionListener(listener);
submit.addKeyListener(listener);

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 这是使用JRootPane#setDefaultButton和键绑定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 当然,这假设具有焦点的组件不消耗有问题的键事件(例如消耗空间的第二个按钮或输入

In the ActionListener Class you can simply add 在ActionListener类中,您只需添加即可

public void actionPerformed(ActionEvent event) {
    if (event.getSource()==textField){
        textButton.doClick();
    }
    else if (event.getSource()==textButton) {
        //do something
    }
}
 switch(KEYEVENT.getKeyCode()){
      case KeyEvent.VK_ENTER:
           // I was trying to use case 13 from the ascii table.
           //Krewn Generated method stub... 
           break;
 }

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();

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 这是一种简单的方法,但对任何键都有反应

textField_in = new JTextField();
textField_in.addKeyListener(new KeyAdapter() {

    @Override
    public void keyPressed(KeyEvent arg0) {
        System.out.println(arg0.getExtendedKeyCode());
        if (arg0.getKeyCode()==10) {
            String name = textField_in.getText();
            textField_out.setText(name);
        }

    }

});
textField_in.setBounds(173, 40, 86, 20);
frame.getContentPane().add(textField_in);
textField_in.setColumns(10);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM