How do I make a JTextField get the focus initially in a JPanel shown using JOptionPane.showConfirmDialog ?

I have a JTextField on a JPanel.  I am using the JPanel in JOptionPane.showConfirmDialog(myPanel, ....)

The JTextField is on myPanel which uses a Border Layout.  How can I make the JTextField have the focus when I show the JOptionPane?

Normally I would use jTextField.requestFocus(true);

Who is Participating?
aciuicaConnect With a Mentor Commented:
Or if you want to keep it modal you can try something like that:
JOptionPane pane = new JOptionPane(myPanel);
JDialog dialog = pane.createDialog(null, "Title");
dialog.addWindowListener(new WindowAdapter() {
    public void windowOpened(WindowEvent e) {

I think txtfield.requestFocusInWindow() worked for me

JOptionPane will probably pop up modal, so you need it make not modal if
you care about focus in another window

   JOptionPane pane = new JOptionPane(message);
        JDialog dialog = pane.createDialog(this, title);

This focus thing is very sensitive, you need to test

objectsConnect With a Mentor Commented:
> Normally I would use jTextField.requestFocus(true);

you should avoid using requestFocus()
This may be overkill depending on what you are trying to do, but you can define your own FocusTraversalPolicy for the window.  Then when you impolement the getFirstComponenet(Container) method (and optionally, the getDefaultComponenet(Container)).  This will also allow you to define a tab order.  

Here's the link to Java's tutorial - its pretty simple to implement: 
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.