真正的全屏 JFrame/Swing 在 Mac OSX 中的应用

True Full Screen JFrame/Swing Application in Mac OSX

我正在开发应用程序并使用 Swing 制作 GUI。我希望我的应用程序是全屏的。我可以轻松设置 window 的大小,但是我无法使应用程序真正全屏显示(IE 隐藏了苹果菜单栏和停靠栏)。我在网上找到的所有答案似乎都不适合我。我是 Java 的新手,非常感谢您的帮助。

frame = new JFrame("Test");
    frame.setTitle("Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel emptyLabel = new JLabel("");
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
    frame.setSize((int)dimension.getWidth(), (int)dimension.getHeight());
    int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2); // X center
    int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);  //Y center
    frame.setLocation(x, y); //Set Frame Location
    frame.setResizable(false); //Frame is not resizable
    frame.setUndecorated(true);  //No decoration for the frame
    frame.setAlwaysOnTop(true);
    frame.setVisible(true); //Make visible

Windows 和 MacOS 下的全屏支持有不同的用户期望...

您可以在两者上使用 Full screen exclusive mode,但是 Mac 用户在全屏应用程序方面有不同的例外情况,因为 MacOS 支持全屏应用程序OS 水平

我用 Java 8 在 Mavericks 上测试了以下代码(基于 this example),它工作正常。

public static void enableOSXFullscreen(Window window) {
    try {
        Class util = Class.forName("com.apple.eawt.FullScreenUtilities");
        Class params[] = new Class[]{Window.class, Boolean.TYPE};
        Method method = util.getMethod("setWindowCanFullScreen", params);
        method.invoke(util, window, true);
    } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | ClassNotFoundException ex) {
        ex.printStackTrace();
    }
}

public static void requestOSXFullscreen(Window window) {
    try {
        Class appClass = Class.forName("com.apple.eawt.Application");
        Class params[] = new Class[]{};

        Method getApplication = appClass.getMethod("getApplication", params);
        Object application = getApplication.invoke(appClass);
        Method requestToggleFulLScreen = application.getClass().getMethod("requestToggleFullScreen", Window.class);

        requestToggleFulLScreen.invoke(application, window);
    } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
        ex.printStackTrace();
    }
}

用户接受您的应用程序时遇到的最困难的障碍之一是如何满足他们当前的期望。做一些他们不习惯的事情,无论您的应用程序多么出色,他们都不会喜欢您(恕我直言)。