我想默认使光标出现在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);
    }
}

最佳答案

您只需调用requestFocusInWindow即可简单地请求文本字段为焦点。一旦包含文本字段的框架可见,只需调用此方法:

box.requestFocusInWindow();

10-02 00:48
查看更多