Search code examples
javaswingjoptionpane

How to prevent JFrame from coming to top after closing JOptionPane?


I am automating certain actions on a web browser. Upon completing a number of actions, a JOptionPane would pop up to ask the user if they would like to continue.

After I clicked 'Yes', my main frame would pop up over my web browser, which ruins my workflow.

I could get the browser to move to the front of the main frame, but I would like to know if it is possible to prevent the main frame from popping up after selecting an option in the JOptionPane dialog?


Solution

  • I couldn't find any options on JOptionPane so I started looking into how easy it would be to reimplement it using another JFrame. I decided to disable the main frame and enable it back later (it seems that this is what JOptionPane does internally anyway) and before I reimplemented JOptionPane I have noticed that it solves the problem:

    public static void main(String[] args) {
        final JFrame frame = new JFrame();
    
        JButton button = new JButton("hello");
        button.addActionListener(e -> {
            frame.setEnabled(false); // disable main frame
            JOptionPane.showMessageDialog(frame, "hello");
            frame.setEnabled(true); // enable main frame
        });
        frame.setContentPane(button);
    
        frame.setVisible(true);
        frame.setSize(600, 480);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    }
    

    However I am not sure if this will work on all platforms. Does it help you?

    If not, I would recommend replacing JOptionPane.showMessageDialog(frame, "hello"); with your own JFrame so you have full control over it. You will have to add WindowListener to enable main frame when it's closed. However you will loose a blocking functionality - this may be more difficult to implement than it's worth it.