gpt4 book ai didi

java - 如何使光标默认出现在 JTextField 中?

转载 作者:行者123 更新时间:2023-11-29 07:47:28 26 4
gpt4 key购买 nike

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

关于java - 如何使光标默认出现在 JTextField 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24346146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com