0

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

mKorbel
  • 109,525
  • 20
  • 134
  • 319
CppLearner
  • 16,273
  • 32
  • 108
  • 163
  • 2
    If the API says you should use requestFocusInWindow() why would you post code that uses requestFocus(). Follow the recommendation of the API. – camickr Feb 11 '11 at 05:04

2 Answers2

3

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

Lawrence Dol
  • 63,018
  • 25
  • 139
  • 189
  • 1
    +1 A good case for meaningful field names. Also a note to the OP: It is generally neither necessary nor a good idea to extend top-level containers (JApplet aside). Instead create the GUI in a JPanel and add it to the TLC (JApplet included). – Andrew Thompson Feb 11 '11 at 05:51
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.

camickr
  • 321,443
  • 19
  • 166
  • 288