javaswingjframejoptionpanealways-on-top

How to end Swing program with always-on-top dialog?


How to finish the program? I mean that after executing it and closing the dialog the Java process does not finish. It can be viewed in Eclipse so the red icon is still active and the program does not finish.

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Main {

    public static void main(String[] args) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setAlwaysOnTop(true);
        JOptionPane.showMessageDialog(
            frame, "test info", "test header", JOptionPane.INFORMATION_MESSAGE);
    }
}

Solution

  • Dispose the frame after the dialog is set visible.

    import javax.swing.*;
    
    public class Main {
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("frame");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setAlwaysOnTop(true);
            JOptionPane.showMessageDialog(
                frame, "test info", "test header", JOptionPane.INFORMATION_MESSAGE);
            // When a frame is disposed, the exit action will be called.
            frame.dispose();
        }
    }