javamacosswingawt

How to close/hide/restore a Swing application according to the OS default behaviour


On Mac, apps are expected to "hide" into the dock when clicking the "x" button on the window's title bar, and restore when being clicked on again in the dock.

On Windows and Linux, apps simply terminate upon clicking the "x" button.

How do I replicate this behaviour in a Java Swing application, depending on which operating system the user is on?


Solution

  • it's easy, just use the WindowListener interface to handle the window closing event and control the behavior based on the operating system, let me explain it with an example, in my example,the MainFrame class extends JFrame and sets the default close operation to DO_NOTHING_ON_CLOSE and the WindowListener is added to handle the window closing event!

    check this out:

    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.SwingUtilities;
    
    public class MainFrame extends JFrame {
    
        public MainFrame() {
            setTitle("YOUR APP");
            setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    handleWindowClosing();
                }
            });
        }
    
        private void handleWindowClosing() {
            String os = System.getProperty("os.name").toLowerCase();
            if (os.contains("mac")) {
                // Minimize the window on Mac
                setExtendedState(JFrame.ICONIFIED);
            } else {
                // Close the window on other platforms
                dispose();
            }
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> {
                MainFrame frame = new MainFrame();
                frame.setSize(110, 110);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            });
        }
    }