在 Pop!_OS 22.04 LTS 中,如何使用 Java 显示托盘图标

问题描述 投票:0回答:1

我尝试了 AWT、Swing 和 JavaFX,它们都输出相同的消息:“不支持 SystemTray”。

我还尝试了AppIndicator 和 KStatusNotifierItem 支持,但这没有帮助。

某些应用程序,例如 Dropbox 和 Solaar,确实有托盘图标。

java linux swing javafx trayicon
1个回答
0
投票

尝试添加检查是否支持 SystemTray。

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

public class TrayIconExample {
    public static void main(String[] args) {
        if (!SystemTray.isSupported()) {
            System.out.println("SystemTray is not supported");
            return;
        }

        // Create a pop-up menu components
        PopupMenu popup = new PopupMenu();
        MenuItem exitItem = new MenuItem("Exit");

        // Add components to pop-up menu
        popup.add(exitItem);

        // Create an image icon
        ImageIcon icon = new ImageIcon("path/to/icon.png");
        Image image = icon.getImage();

        // Create a tray icon
        TrayIcon trayIcon = new TrayIcon(image, "Tray Demo", popup);
        trayIcon.setImageAutoSize(true);

        // Get the system tray instance
        SystemTray tray = SystemTray.getSystemTray();

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

        // Add action listener for the exit item
        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
    }
}

java-gnome 库的另一个例子

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.jna.platform.gtk.Gtk;
import com.sun.jna.platform.gtk.GtkApplication;
import com.sun.jna.platform.gtk.StockIcon;
import com.sun.jna.platform.gtk.StatusIcon;

public class TrayIconExample {
    public interface CLibrary extends Library {
        CLibrary INSTANCE = (CLibrary) Native.load("c", CLibrary.class);
    }

    public static void main(String[] args) {
        GtkApplication app = GtkApplication.getInstance();
        StatusIcon icon = new StatusIcon();
        icon.setTitle("My Tray Icon");
        icon.setFromFile(StockIcon.loadIcon(StockIcon.FILE));
        icon.setStatus(Gtk.ApplicationStatus.RUNNING);
        icon.setTooltipText("Click me!");
        icon.setHasMenu(true);
        icon.setContextMenu(new TrayIconMenu());
        icon.setIconFromFile(StockIcon.loadIcon(StockIcon.FILE));
        icon.show();
        app.run();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.