Java 在 JTextField 中检测输入按下

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4419667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:16:18  来源:igfitidea点击:

Detect enter press in JTextField

javaswingjtextfield

提问by a sandwhich

Is it possible to detect when someone presses Enterwhile typing in a JTextField in java? Without having to create a button and set it as the default.

是否可以检测到有人Enter在 Java 中输入 JTextField时按下了什么?无需创建按钮并将其设置为默认值。

采纳答案by camickr

A JTextFieldwas designed to use an ActionListenerjust like a JButtonis. See the addActionListener()method of JTextField.

AJTextField被设计为ActionListener像 a JButtonis一样使用a 。见addActionListener()方法JTextField

For example:

例如:

Action action = new AbstractAction()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        System.out.println("some action");
    }
};

JTextField textField = new JTextField(10);
textField.addActionListener( action );

Now the event is fired when the Enterkey is used.

现在,当使用Enter键时会触发该事件。

Also, an added benefit is that you can share the listener with a button even if you don't want to make the button a default button.

此外,一个额外的好处是即使您不想将按钮设为默认按钮,您也可以与按钮共享侦听器。

JButton button = new JButton("Do Something");
button.addActionListener( action );

Note, this example uses an Action, which implements ActionListenerbecause Actionis a newer API with addition features. For example you could disable the Actionwhich would disable the event for both the text field and the button.

请注意,此示例使用了Action,它实现了ActionListener因为Action是具有附加功能的较新 API。例如,您可以禁用Action这将禁用文本字段和按钮的事件。

回答by kyorilys

JTextField function=new JTextField(8);   
function.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent e){

                        //statements!!!

                }});

all you need to do is addActionListener to the JTextField like above! After you press Enterthe action will performed what you want at the statement!

您需要做的就是像上面一样将ActionListener 添加到 JTextField 中!在您按下Enter该动作后,您将在语句中执行您想要的操作!

回答by Ionic? Biz?u

Add an event for KeyPressed.

为 增加一个事件KeyPressed

private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
  if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
      // Enter was pressed. Your code goes here.
   }
} 

回答by Avnish alok

public void keyReleased(KeyEvent e)
{
    int key=e.getKeyCode();
    if(e.getSource()==textField)
    {
        if(key==KeyEvent.VK_ENTER)
        { 
            Toolkit.getDefaultToolkit().beep();
            textField_1.requestFocusInWindow();                     
        }
    }

To write logic for 'Enter press' in JTextField, it is better to keep logic inside the keyReleased()block instead of keyTyped()& keyPressed().

要为 'Enter press' in 编写逻辑,JTextField最好将逻辑保留在keyReleased()块内,而不是keyTyped()& keyPressed()

回答by greg

First add action command on JButton or JTextField by:

首先通过以下方式在 JButton 或 JTextField 上添加操作命令:

JButton.setActionCommand("name of command");
JTextField.setActionCommand("name of command");

Then add ActionListener to both JTextField and JButton.

然后将 ActionListener 添加到 JTextField 和 JButton。

JButton.addActionListener(listener);
JTextField.addActionListener(listener);

After that, On you ActionListener implementation write

之后,在你的 ActionListener 实现上写

@Override
public void actionPerformed(ActionEvent e)
{
    String actionCommand = e.getActionCommand();

    if(actionCommand.equals("Your actionCommand for JButton") || actionCommand.equals("Your   actionCommand for press Enter"))
    {
        //Do something
    }
}

回答by iamprogrammer

Just use this code:

只需使用此代码:

SwingUtilities.getRootPane(myButton).setDefaultButton(myButton);

回答by alexcornejo

If you want to set a default button action in a JTextField enter, you have to do this:

如果要在 JTextField 输入中设置默认按钮操作,则必须执行以下操作:

//put this after initComponents();

textField.addActionListener(button.getActionListeners()[0]);

It is [0] because a button can has a lot of actions, but normally just has one (ActionPerformed).

它是 [0] 因为一个按钮可以有很多动作,但通常只有一个 (ActionPerformed)。

回答by diegod3v

Do you want to do something like this ?

你想做这样的事情吗?

JTextField mTextField = new JTextField();
    mTextField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_ENTER){
                // something like...
               //mTextField.getText();
               // or...
               //mButton.doClick();
            }
        }

    });

回答by Thomas B?hm

The other answers (including the accepted ones) are good, but if you already use Java8, you can do the following (in a shorter, newer way):

其他答案(包括已接受的答案)都很好,但如果您已经使用 Java8,则可以执行以下操作(以更短、更新的方式):

textField.addActionListener(
    ae -> {
        //dostuff
    }
);

As the accepted answer told, you can simply react with an ActionListener, which catches the Enter-Key.

正如接受的答案所说,您可以简单地用一个 做出反应ActionListener,它会捕获 Enter-Key。

However, my approach takes benefit of the functional concepts which was introduced in Java 8.

但是,我的方法利用了 Java 8 中引入的函数概念。

If you want to use the same action for example for a button and the JTextField, you can do the following:

如果您想对按钮和 JTextField 使用相同的操作,您可以执行以下操作:

ActionListener l = ae -> {
    //do stuff
}

button.addActionListener(l);
textField.addActionListener(l);

If further explaination is needed, please let me know!

如果需要进一步解释,请告诉我!