SystemTray 是操作系统提供的用于显示系统通知和图标的区域。在 Java 中,可以通过 java.awt.SystemTray
类来访问和操作 SystemTray。Spring Boot 作为一个框架,可以通过集成 Java 的 SystemTray 功能来实现在系统托盘显示图标。
以下是一个简单的示例,展示如何在 Spring Boot 应用中使用 SystemTray 图标:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
@SpringBootApplication
public class SystemTrayApp {
public static void main(String[] args) {
SpringApplication.run(SystemTrayApp.class, args);
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
final PopupMenu popup = new PopupMenu();
final SystemTray tray = SystemTray.getSystemTray();
Image image = null;
try {
URL imageUrl = SystemTrayApp.class.getResource("/path/to/icon.png");
image = ImageIO.read(imageUrl);
} catch (IOException e) {
e.printStackTrace();
}
final TrayIcon trayIcon = new TrayIcon(image, "Spring Boot App");
final MenuItem exitItem = new MenuItem("Exit");
popup.add(exitItem);
trayIcon.setPopupMenu(popup);
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
}
}
}
SystemTray.isSupported()
返回值。通过以上步骤和示例代码,你可以在 Spring Boot 应用中成功集成 SystemTray 图标功能。
领取专属 10元无门槛券
手把手带您无忧上云