You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在macOS中将JMenuBar添加到屏幕菜单栏?

macOS Swing 菜单栏显示问题修复方案

核心配置步骤

  • 必须在所有Swing组件初始化前设置系统属性,顺序错误会导致配置失效:
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    System.setProperty("apple.awt.application.name", "你的应用名称");
    
  • 若使用FlatLaf,需确保主题初始化在上述属性设置之后,避免样式冲突:
    // 先设置系统属性
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    System.setProperty("apple.awt.application.name", "My macOS App");
    // 再初始化FlatLaf主题
    FlatLightLaf.setup();
    

解决菜单栏与标题栏重叠问题

如果设置后仍出现重叠,可通过以下两种方式调整:

  • 手动为窗口内容区域添加顶部边距:
    JFrame frame = new JFrame();
    frame.getContentPane().setBorder(BorderFactory.createEmptyBorder(20, 0, 0, 0));
    
  • 禁用FlatLaf的菜单栏嵌入特性:
    System.setProperty("flatlaf.menuBarEmbedded", "false");
    

完整示例代码

import com.formdev.flatlaf.FlatLightLaf;
import javax.swing.*;

public class MacMenuBarFix {
    public static void main(String[] args) {
        // 前置系统属性配置
        System.setProperty("apple.laf.useScreenMenuBar", "true");
        System.setProperty("apple.awt.application.name", "My App");
        System.setProperty("flatlaf.menuBarEmbedded", "false");

        // 初始化FlatLaf主题
        FlatLightLaf.setup();

        // 创建菜单栏
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("文件");
        fileMenu.add(new JMenuItem("打开"));
        fileMenu.add(new JMenuItem("保存"));
        menuBar.add(fileMenu);

        // 创建窗口
        JFrame frame = new JFrame("窗口标题");
        frame.setJMenuBar(menuBar);
        frame.setSize(600, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

额外注意事项

  • 确认使用的是macOS专属的64位JDK包,你的17.0.4.1版本符合要求,但需避免使用跨平台通用包
  • 也可通过启动参数配置属性,替代代码内设置:
    java -Dapple.laf.useScreenMenuBar=true -Dapple.awt.application.name="My App" -jar your-app.jar
    

内容的提问来源于stack exchange,提问作者Rishon_JR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 18:55:29