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);
});
}
}