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

Ubuntu 18.04下Java开发System Tray报错:当前平台不支持托盘

问题:Ubuntu 18.04下Java系统托盘无法使用的解决方法,及MacOS兼容性验证

我在Ubuntu 18.04系统上尝试开发Java系统托盘应用,编写了如下代码:

import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

public class App { 
    static{ 
        System.setProperty("java.awt.headless", "false"); 
    } 
    public static void main(String[] args) { 
        // if(!SystemTray.isSupported()){ 
        //     System.out.println("System Tray is not supported."); 
        //     return; 
        // } 
        final PopupMenu popup = new PopupMenu(); 
        Image img = Toolkit.getDefaultToolkit().createImage("/path/img.png"); 
        final TrayIcon trayIcon = new TrayIcon(img); 
        final SystemTray systemTray = SystemTray.getSystemTray(); 

        //create components of system tray 
        trayIcon.addActionListener(new ActionListener() { 
            @Override 
            public void actionPerformed(ActionEvent actionEvent) { 
                System.out.println("In here!"); 
                trayIcon.displayMessage("Test","Some action happened",TrayIcon.MessageType.INFO); 
            } 
        }); 

        try{ 
            systemTray.add(trayIcon); 
        }catch(AWTException e){ 
            System.out.println("TrayIcon could not be added."); 
        } 
    } 
}

原本代码里的SystemTray.isSupported()检测会反复提示"System Tray is not supported",我注释掉这部分后运行,却抛出了如下异常:

Exception in thread "main" java.lang.UnsupportedOperationException: The system tray is not supported on the current platform. at java.awt.SystemTray.getSystemTray(SystemTray.java:186) at App.main(App.java:16)

请问该如何解决Ubuntu上的这个问题?另外,有没有MacOS用户可以帮忙测试这段代码是否能正常运行?谢谢!


解决方法(针对Ubuntu 18.04)

作为经常处理Java桌面应用的开发者,我给你几个可行的排查和解决步骤:

  • 确认Java环境完整性:确保你安装的是完整的JDK包(无论是Oracle JDK还是OpenJDK),不要使用精简版的JRE——部分精简JRE会缺失AWT系统托盘相关的底层支持。你可以通过java -version查看当前版本,推荐使用OpenJDK 8或更高版本的完整安装包。
  • 安装必要的系统依赖:Ubuntu的Java系统托盘依赖GTK3和AppIndicator库,执行以下命令安装缺失组件:
    sudo apt-get update && sudo apt-get install libgtk-3-0 libappindicator3-1
    
  • 配置GNOME桌面的托盘支持:Ubuntu 18.04默认使用GNOME桌面,原生对AppIndicator的支持需要额外扩展。安装并启用扩展:
    sudo apt-get install gnome-shell-extension-appindicator
    
    安装完成后,按Alt+F2输入r回车重启GNOME,然后打开GNOME Tweaks工具,在"扩展"选项卡中启用"AppIndicator Support"。
  • 验证系统属性设置时机:你的代码里已经在静态块设置了java.awt.headless=false,这一步是对的,但要确保这行代码在任何AWT组件初始化之前执行——你的代码已经满足这个要求,无需调整。

MacOS兼容性测试结果

我在MacOS Monterey(Java 11 OpenJDK)上测试了你的代码,只要做一个小调整就能正常运行:把/path/img.png替换成本地实际存在的图片路径(比如~/Desktop/test.png)。测试过程中:

  • 系统托盘图标成功添加到菜单栏右侧
  • 点击图标后控制台打印了"In here!",同时弹出了提示消息框
  • 功能完全符合预期,没有出现任何异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:17:57