如何在 Java JFrame GUI 中使用 requestFocus?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4964990/
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-10-30 08:49:23  来源:igfitidea点击:

How do I use requestFocus in a Java JFrame GUI?

javaswinguser-interfacefocusmanager

提问by CppLearner

I am given an assignment but I am totally new to Java (I have been programming in C++ and Python for two years).

我得到了一项作业,但我对 Java 完全陌生(我已经用 C++ 和 Python 编程了两年)。

So we are doing GUI and basically we extended JFrame and added a couple fields.

所以我们正在做 GUI,基本上我们扩展了 JFrame 并添加了几个字段。

Say we have a field named "Text 1" and "Text 2". When user presses enter with the cursor in Text 1, move the focus to Text 2. I tried to add

假设我们有一个名为“Text 1”和“Text 2”的字段。当用户在文本 1 中使用光标按下 Enter 键时,将焦点移至文本 2。我尝试添加

private JTextField textfield1() {

    textfield1 = new JTextField();
    textfield1.setPreferredSize(new Dimension(200, 20));

    textfield1.addActionListener(
                           new ActionListener() {
                        public void actionPerformed(ActionEvent e) {

                            textfield1text = textfield1.getText().trim();
                            textfield1.setText(textfield1text);
                            System.out.println(textfield1text);

                            textfield1.requestFocus();
                        }
                    });

    return textfield1;
}

But that doesn't work at all.

但这根本行不通。

I noticed that requestFocus is not recommended, and instead one should use requestFocusWindows. But I tried that too. Upon some readings it seems like I have to do keyboard action and listener? But my teacher said it only requires 1 line...

我注意到不推荐使用 requestFocus,而应该使用 requestFocusWindows。但我也试过了。经过一些阅读,似乎我必须做键盘动作和听者?但是我的老师说它只需要 1 行...

回答by Lawrence Dol

Well, you have textfield1.requestFocus(), but your description would imply you need textfield2.requestFocus(). (that's 2).

嗯,你有textfield1.requestFocus(),但你的描述暗示你需要textfield2.requestFocus()。(那是2)。

回答by camickr

Another option might be to use:

另一种选择可能是使用:

textField1.transferFocus();

This way you don't need to know the name of the next component on the form.

这样您就不需要知道表单上下一个组件的名称。