给Java Swing程序添加系统托盘图标
时间: 2024-02-19 08:03:45 浏览: 84
增加系统托盘图标
4星 · 用户满意度95%
可以使用Java AWT中的SystemTray类和TrayIcon类来实现在Java Swing程序中添加系统托盘图标的功能。以下是一个简单的示例代码:
```java
import java.awt.*;
import javax.swing.*;
public class TrayIconExample {
public static void main(String[] args) {
// Check if the system supports system tray
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
// Create a tray icon
Image icon = new ImageIcon("icon.png").getImage();
TrayIcon trayIcon = new TrayIcon(icon, "Tray Icon Example");
// Add the tray icon to the system tray
SystemTray tray = SystemTray.getSystemTray();
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added");
return;
}
// Show a message when the tray icon is clicked
trayIcon.addActionListener(e -> JOptionPane.showMessageDialog(null, "Tray Icon Clicked"));
// Create a popup menu for the tray icon
PopupMenu popupMenu = new PopupMenu();
MenuItem exitItem = new MenuItem("Exit");
exitItem.addActionListener(e -> System.exit(0));
popupMenu.add(exitItem);
trayIcon.setPopupMenu(popupMenu);
// Display a message in the tray icon tooltip
trayIcon.setToolTip("This is a tray icon example");
}
}
```
这个示例代码会创建一个系统托盘图标,并在点击图标时显示一个消息框。同时,它也为图标添加了一个弹出菜单和一个提示消息。注意,需要将图标文件放在程序运行的目录下,并将其命名为"icon.png"。
阅读全文