How do I use requestFocus in a Java JFrame GUI?

混江龙づ霸主 提交于 2020-01-07 05:53:06

问题


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

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

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;
}

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...


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/4964990/how-do-i-use-requestfocus-in-a-java-jframe-gui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!