在 Mac 上,当单击窗口标题栏上的“x”按钮时,应用程序预计会“隐藏”到 Dock 中,并在 Dock 中再次单击时恢复。
在 Windows 和 Linux 上,应用程序只需单击“x”按钮即可终止。
如何根据用户所在的操作系统在 Java Swing 应用程序中复制此行为?
不知道是否有更好的方法,但你可以使用以下方式获取操作系统:
System.getProperty(...);
查看
System.getProperties()
方法以获取要查询的有效属性列表,包括操作系统。
一旦您拥有了可以使用的操作系统:
frame.setDefaultCloseOperation(...)
很简单,只需使用
WindowListener
接口来处理窗口关闭事件并控制基于操作系统的行为,让我用一个例子来解释它,在我的示例中,MainFrame
类扩展了JFrame
并设置默认关闭操作为DO_NOTHING_ON_CLOSE
,添加WindowListener
来处理窗口关闭事件!
看看这个:
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")) {
//hiding the window on Mac
setVisible(false);
} else {
//for closing 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);
});
}
}