Java Textfield焦点

Tyz*_*zak 2 java swing focus

你好我有焦点的问题

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

我试过了

mytext.requestFocus();
Run Code Online (Sandbox Code Playgroud)

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

Joh*_*ohn 7

来自Swing教程

如果要在第一次激活窗口时确保特定组件获得焦点,则可以在实现组件之后但在显示帧之前调用组件上的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.
Run Code Online (Sandbox Code Playgroud)


Pac*_*ace 5

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

mytext.selectAll();
Run Code Online (Sandbox Code Playgroud)

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

  • 还有`select(int,int)`用于更细粒度的控制:http://java.sun.com/javase/6/docs/api/javax/swing/text/JTextComponent.html#select(int, %20int) (2认同)