java – Spring Boot使用SystemTray图标
作者:互联网
我正在设置一个Spring Boot应用程序,并希望主机可以访问一个可以访问某些bean信息的系统托盘图标.
我目前尝试使用@Autowired详细信息为我的SystemTrayIcon创建一个Bean.但是,当我尝试添加SystemTrayIcon时,我得到以下异常:
Caused by: java.awt.HeadlessException
at java.awt.TrayIcon.<init>(Unknown Source)
at java.awt.TrayIcon.<init>(Unknown Source)
at java.awt.TrayIcon.<init>(Unknown Source)
at hermes.subsrciber.systemTray.HermesTrayIcon.<init>(HermesTrayIcon.java:36)
at hermes.subscriber.boot.AppStarter.trayIcon(AppStarter.java:83)
at hermes.subscriber.boot.AppStarter$$EnhancerBySpringCGLIB$$c4f80849.CGLIB$trayIcon$3(<generated>)
at hermes.subscriber.boot.AppStarter$$EnhancerBySpringCGLIB$$c4f80849$$FastClassBySpringCGLIB$$d62ab0bd.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
at hermes.subscriber.boot.AppStarter$$EnhancerBySpringCGLIB$$c4f80849.trayIcon(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
... 17 more
有没有什么方法可以让SpringBoot应用程序访问系统托盘图标?
我相信我可以简单地在Main方法中定义它(沿着SpringApplication.run)但是我无法自动装配我的属性.
这种设置可行吗?
解决方法:
解决方案是,而不是使用SpringApplication.run(MyConfig.class,args),使用以下设置:
SpringApplicationBuilder builder = new SpringApplicationBuilder(MyConfig.class);
builder.headless(false);
ConfigurableApplicationContext context = builder.run(args);
要实际添加系统图标,我添加了一个followign类型的bean:
public class MyTrayIcon extends TrayIcon {
private static final String IMAGE_PATH = "/path/icon_16x16.png";
private static final String TOOLTIP = "Text";
private PopupMenu popup;
private SystemTray tray;
public MyTrayIcon(){
super(createImage(IMAGE_PATH,TOOLTIP),TOOLTIP);
popup = new PopupMenu();
tray = SystemTray.getSystemTray();
}
@PostConstruct
private void setup() throws AWTException{
// popup.add(itemAbout);
// here add the items to your popup menu. These extend MenuItem
// popup.addSeparator();
setPopupMenu(popup);
tray.add(this);
}
protected static Image createImage(String path, String description){
URL imageURL = MyTrayIcon.class.getResource(path);
if(imageURL == null){
System.err.println("Failed Creating Image. Resource not found: "+path);
return null;
}else {
return new ImageIcon(imageURL,description).getImage();
}
}
}
标签:headless,system-tray,java,spring 来源: https://codeday.me/bug/20191005/1855978.html