Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

why can't I set focus to a Text box

Status
Not open for further replies.

drkestrel

MIS
Sep 25, 2000
439
GB
I have a JPasswordField in a GridLayout JPanel which in turn is put in another GridLayout JPanel.

After initialising all items, I tried different permutations of the following in an attempt to set focus to the password textbox, but none work. Why and how could I get it workin?
myPassword.setRquestFocusEnabled(true);
myPassword.requestFocus();
myPassword.moveCaretPosition(1);
myPassword.moveCaretPosition(0);

I also tried them before AND after this.pack() and this.show(). Note that the class is a modal JDialog with a parent Frame.
 
I forget the reason for this, but the upshot is you have to set the focus in another thread after swing displays the dialog box.

Add an inner class to your dialog box to handle window events:

class SymWindow extends java.awt.event.WindowAdapter
{
public void windowActivated( java.awt.event.WindowEvent event )
{
Object object = event.getSource();
if( object == JDialogWindowName.this )
{
JDialogWindowName_windowActivated( event );
}
}
}

Now add a method to set the focus after the window is activated:

Component focusObject = null;
void JDialogWindowName_windowActivated( java.awt.event.WindowEvent event )
{
if( focusObject != myPassword )
{
focusObject = myPassword;
Runnable doRequestFocus = new Runnable()
{
public void run()
{
focusObject.requestFocus();
}
};
SwingUtilities.invokeLater( doRequestFocus );
}
}

 
What if I have another thread that was spawned off from the main Thread (i.e. the Frame that 'owns' the JDialog).

When would this thread that set the focus be at a dead state?
 
I'm not sure I understand your question, sorry. This little thread that sets the focus just does it and goes away. I don't think you have to worry about it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top