开发者

How do I use requestFocus in a Java JFrame GUI?

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 recommen开发者_如何学运维ded, 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...


Well, you have textfield1.requestFocus(), but your description would imply you need textfield2.requestFocus(). (that's 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜