java - MacOS 上带有 JavaFX 的状态菜单
问题描述
有没有办法创建状态菜单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
,因此您的应用程序的行为就像它的背景一样。
推荐阅读
- python - Python shift() 来自同一列,如 Excel 中的日期
- sql-server - SQL 'SET' 问题超出光标
- javascript - 只显示小数的一部分但不改变它们的真实值
- sql - 连接出现的绝对值等于单个出现的绝对值的表
- asp.net-core - 跨多个 Web 应用程序使用的作业调度程序
- django - django 测试 - 如何避免 ForeignKeyViolation
- spring-boot - 同一页面中有多个相似的表单
- javascript - socket.io 服务器不断收到连接事件,但客户端从不连接
- python - 使用保留索引重塑 Numpy 数组
- html - 为什么滚动快照类型不起作用