In order to have custom button captions in an input dialog, I created the following code:
String key = null;
JTextField txtKey = new JTextField();
in
The trick is to (a) use an AncestorListener on the text component to request focus, and when the focus is lost again (given to the default button), ask for focus a second time using a FocusListener on the text component (but don't keep asking for focus after that):
final JPasswordField accessPassword = new JPasswordField();
accessPassword.addAncestorListener( new AncestorListener()
{
@Override
public void ancestorRemoved( final AncestorEvent event )
{
}
@Override
public void ancestorMoved( final AncestorEvent event )
{
}
@Override
public void ancestorAdded( final AncestorEvent event )
{
// Ask for focus (we'll lose it again)
accessPassword.requestFocusInWindow();
}
} );
accessPassword.addFocusListener( new FocusListener()
{
@Override
public void focusGained( final FocusEvent e )
{
}
@Override
public void focusLost( final FocusEvent e )
{
if( isFirstTime )
{
// When we lose focus, ask for it back but only once
accessPassword.requestFocusInWindow();
isFirstTime = false;
}
}
private boolean isFirstTime = true;
} );
Dialog Focus shows how you can easily set the focus on any component in a modal dialog.