首页 > 解决方案 > MacOS 上带有 JavaFX 的状态菜单

问题描述

有没有办法创建状态菜单JavaFXJavaFX似乎没有任何类似 的文档。在此处输入图像描述

左侧菜单非常简单:

MenuBar menuBar = new MenuBar();
menuBar.useSystemMenuBarProperty().set(true);

Menu menu = new Menu("java");
MenuItem item = new MenuItem("Test");
menu.getItems().add(item);
menuBar.getMenus().add(menu);

BorderPane borderPane = new BorderPane();
borderPane.setTop(menuBar);
primaryStage.setScene(new Scene(borderPane));
primaryStage.show();

标签: javamacosjavafx

解决方案


所以,有办法显示菜单java.awt.SystemTray

public static void showMenu(Image trayImage, String... items) {

    if (!java.awt.SystemTray.isSupported())
        throw new UnsupportedOperationException("No system tray support, application exiting.");

    java.awt.Toolkit.getDefaultToolkit();

    java.awt.SystemTray tray = java.awt.SystemTray.getSystemTray();
    java.awt.TrayIcon trayIcon = new java.awt.TrayIcon(trayImage);
    java.awt.PopupMenu rootMenu = new java.awt.PopupMenu();

    for (String item : items) rootMenu.add(new MenuItem(item));

    trayIcon.setPopupMenu(rootMenu);

    try {
        tray.add(trayIcon);
    } catch (Throwable e) {
        throw new RuntimeException("Unable to init system tray");
    }
}

SystemTray仅支持图像作为根项,但有办法将文本转换为图像:

static BufferedImage textToImage(String text) {
    return textToImage(text, java.awt.Font.decode(null), 13);
}

static BufferedImage textToImage(String Text, Font font, float size) {
    font = font.deriveFont(size);

    FontRenderContext frc = new FontRenderContext(null, true, true);

    LineMetrics lm = font.getLineMetrics(Text, frc);
    Rectangle2D r2d = font.getStringBounds(Text, frc);
    BufferedImage img = new BufferedImage((int) Math.ceil(r2d.getWidth()), (int) Math.ceil(r2d.getHeight()), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = img.createGraphics();
    g2d.setRenderingHints(RenderingProperties);
    g2d.setBackground(new Color(0, 0, 0, 0));
    g2d.setColor(Color.BLACK);

    g2d.clearRect(0, 0, img.getWidth(), img.getHeight());
    g2d.setFont(font);
    g2d.drawString(Text, 0, lm.getAscent());
    g2d.dispose();

    return img;
}

最后的用法示例:

public static void main(String[] args) {
    System.setProperty("apple.awt.UIElement", "true");
    showMenu(textToImage("Hello"), "Item - 1", "Item - 2");
}

apple.awt.UIElement=true当您需要摆脱默认的 java 菜单和图标时,系统属性很有用cmd-tab,因此您的应用程序的行为就像它的背景一样。


推荐阅读