默认情况下如何使光标出现在JTextField中?

时间:2014-06-21 21:48:44

标签: java swing cursor focus jtextfield

我希望默认情况下将光标显示在JTextField“框”中。目前,我必须将光标放在框中才会出现。这是代码。

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

1 个答案:

答案 0 :(得分:5)

您可以通过调用requestFocusInWindow来简单地请求关注文本字段。只要包含文本字段的框架可见,就可以调用它:

box.requestFocusInWindow();