简体   繁体   English

在任何TextField上按Enter键时的操作

[英]Action when Enter key pressed on ANY TextField

Please do note that this is a different question, 请注意这是一个不同的问题,

I am writing a java program. 我正在写一个java程序。 I have a form with 10 JTextFields and a 'Submit' button. 我有一个包含10个JTextFields和一个“提交”按钮的表单。 How do I make the method for 'Submit' button to be called when the user presses the enter key on ANY of the 10 text fields? 当用户在10个文本字段中的任何一个上按下回车键时,如何调用“提交”按钮的方法?

Should I add KeyListeners to all of the 10 or is there a more efficient way since the text fields and the button are inside a JPanel? 我应该将KeyListeners添加到所有10个中吗?还是有更有效的方法,因为文本字段和按钮在JPanel中?

No, Create an common event handler like this ,And attach it to all 不,创建一个这样的公共事件处理程序,并将其附加到所有

Below is a Mock code: 下面是模拟代码:

 KeyAdapter event=  new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                //do something
            }

            public void keyTyped(KeyEvent e) {
                // TODO: Do something for the keyTyped event
            }

            public void keyPressed(KeyEvent e) {
                // TODO: Do something for the keyPressed event
            }
        });


txtField1.addKeyListener(event);
txtField2.addKeyListener(event);
-----

may be a loop also :) 可能是一个循环也:)

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

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