有没有办法用 JavaFX
创建状态菜单? JavaFX
的文档似乎没有任何类似内容。
左侧菜单非常简单:
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();
最佳答案
因此,可以使用 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
图标时很有用,因此您的应用程序的行为就像背景。
关于java - 在 MacOS 上使用 JavaFX 的状态菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53821444/