Search code examples
javaswingcursorfocusjtextfield

How to make cursor appear in JTextField by default?


I want to make a cursor appear in the JTextField "box" by default. Currently, I have to place the cursor in the box before it will appear. Here is code.

class XYZ extends JFrame implements ActionListener {

    JTextField box = new JTextField();
    JButton again = new JButton("Restart");
    JButton ext = new JButton("Exit");

    XYZ() {
        box.addActionListener(this);
        again.addActionListener(this);
        ext.addActionListener(this);

        box.setPreferredSize(new Dimension(20,20));
        box.setHorizontalAlignment(JTextField.CENTER)

        JPanel s3 = new JPanel(new BorderLayout()); //This holds the 3 panels below
        JPanel restart = new JPanel(new BorderLayout()); //this holds a button
        JPanel leave = new JPanel(new BorderLayout());   //also holds a button

        //The following holds a JLabel and the textfield
        JPanel middle = new JPanel(new FlowLayout(FlowLayout.CENTER,20,0)); 
        JLabel j2 = new JLabel("Enter your guess!");

        middle.add(j2);
        middle.add(box);

        restart.add(again,BorderLayout.SOUTH);
        leave.add(ext,BorderLayout.SOUTH);

        //Adding the 3 panels to s3
        s3.add(middle,BorderLayout.CENTER);
        s3.add(restart,BorderLayout.WEST);  
        s3.add(leave,BorderLayout.EAST);
    }
}

Solution

  • You can simply request the textfield to be focused by calling requestFocusInWindow. Simply invoke this once the frame containing the textfield is visible:

    box.requestFocusInWindow();