Search code examples
javaswingfocusjoptionpane

JFrame loses focus after closing a JOptionPane and can't set it back


I have a JOptionPane that shows an input dialog with a JTextField. When this dialog is closed, it returns the text inserted.

But when any button (Confirm/Cancel) is pressed and the dialog is closed, the main window loses focus and I'm unable to set on it again.

String menuName = (String) JOptionPane.showInputDialog (
    new JFrame(), 
    "Insert new Menu Name"
);

How can I set focus on the main window when this dialog closes?


Solution

  • You should be passing the parent component as the first parameter, not some random new frame you created.

    Supposing you are launching this from within a JFrame method, you can run

    String menuName = (String) JOptionPane.showInputDialog (
        this, // parent component is the JFrame you are launching this from
        "Insert new Menu Name"
    );
    

    In some cases, eg when running this from an onLostFocus implementation of a FocusListener you need to run this after all current events have been handled. This can be done by posting an event at the end of the event queue. Use SwingUtilities.invokeLater to do that.

    So if you are in such a situation, launch the dialog as follows. Suppose the frame class you are running this from is called MyFrame:

    SwingUtilities.invokeLater(new Runnable(){
        @Override
        public void run() {
            String menuName = (String) JOptionPane.showInputDialog (
                MyFrame.this, // parent component is the JFrame you are launching this from
                "Insert new Menu Name"
            );
            // do stuff with menuName
        }
    });