Make sure that my JTextField has the focus when a JFrame is created
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
class Main extends JFrame {
JTextField field1 = new JTextField(10);;
JTextField field2 = new JTextField(10);;
JPanel panel = new JPanel();
public Main() {
panel.add(new JLabel("Field 1:"));
panel.add(field1);
panel.add(new JLabel("Field 2:"));
panel.add(field2);
getContentPane().add("Center", panel);
addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent e) {
field1.requestFocus();
}
});
pack();
setVisible(true);
}
public static void main(String[] argv) {
new Main();
}
}
Related examples in the same category