Java 文本字段焦点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2167760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 19:48:14  来源:igfitidea点击:

Java Textfield focus

javaswingfocus

提问by Tyzak

Hello I have a problem with the focus

你好我对焦有问题

mytext= new JTextField();
mytext.requestFocus(true);
gc.fill =GridBagConstraints.HORIZONTAL ;
gc.gridx =3; gc.gridy=4;
gbl.setConstraints(mytext,gc);
jContentPane.add(mytext);

I tried

我试过

mytext.requestFocus();

too

and how can I auto-select the text in the textfield so the text is marked?

以及如何自动选择文本字段中的文本以便标记文本?

回答by John

From the Swing Tutorial

来自Swing 教程

If you want to ensure that a particular component gains the focus the first time a window is activated, you can call the requestFocusInWindow method on the component after the component has been realized, but before the frame is displayed. The following sample code shows how this operation can be done:

如果要确保某个特定组件在第一次激活窗口时获得焦点,可以在实现该组件之后,但在显示框架之前调用该组件上的 requestFocusInWindow 方法。以下示例代码显示了如何完成此操作:

//...Where initialization occurs...
JFrame frame = new JFrame("Test");
JPanel panel = new JPanel(new BorderLayout());

//...Create a variety of components here...

//Create the component that will have the initial focus.
JButton button = new JButton("I am first");
panel.add(button);
frame.getContentPane().add(panel);  //Add it to the panel

frame.pack();  //Realize the components.
//This button will have the initial focus.
button.requestFocusInWindow(); 
frame.setVisible(true); //Display the window.

回答by Pace

As for selecting all the text you should use...

至于选择你应该使用的所有文本......

mytext.selectAll();

As for getting focus, maybe you should try the requestFocus function after everything has been added to jContentPane.

至于获得焦点,也许您应该在将所有内容添加到 jContentPane 后尝试 requestFocus 函数。