Tyzak
Tyzak

Reputation: 2436

Java Textfield focus

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?

Upvotes: 2

Views: 12208

Answers (2)

John
John

Reputation: 6805

From the Swing Tutorial

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:

//...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.

Upvotes: 7

Pace
Pace

Reputation: 43937

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.

Upvotes: 5

Related Questions