Make sure that my JTextField has the focus when a JFrame is created in Java

Description

The following code shows how to make sure that my JTextField has the focus when a JFrame is created.

Example


import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/*from  w w w  . j  a v  a2  s  .c om*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public 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();
  }
}

The code above generates the following result.

Make sure that my JTextField has the focus when a JFrame is created in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer