问题描述
我收到了一份作业,但我对 Java 完全陌生(我已经用 C++ 和 Python 编程了两年).
I am given an assignment but I am totally new to Java (I have been programming in C++ and Python for two years).
所以我们正在做 GUI,基本上我们扩展了 JFrame 并添加了几个字段.
So we are doing GUI and basically we extended JFrame and added a couple fields.
假设我们有一个名为Text 1"和Text 2"的字段.当用户在文本 1 中使用光标按下 Enter 键时,将焦点移至文本 2.我尝试添加
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
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;
}
但这根本行不通.
我注意到不推荐使用 requestFocus,而应该使用 requestFocusWindows.但我也试过了.经过一些阅读,似乎我必须做键盘动作和听者?但是我的老师说它只需要 1 行...
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...
推荐答案
好吧,你有 textfield1.requestFocus()
,但你的描述暗示你需要 textfield2.requestFocus()代码>.(这是2).
Well, you have textfield1.requestFocus()
, but your description would imply you need textfield2.requestFocus()
. (that's 2).
这篇关于如何在 Java JFrame GUI 中使用 requestFocus?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!