我想使用JPopupMenu创建System Tray但是它只接受awt的PopupMenu。
我使用以下代码:
package UserInterface;
import java.awt.AWTException;
import java.awt.Font;
import java.awt.Image;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
public class StartBarMenu extends JPopupMenu {
private static final long serialVersionUID = 1L;
public StartBarMenu() {
JMenuItem mntmTwincloud = new JMenuItem("Cloud");
mntmTwincloud.setFont(new Font("Segoe Print", Font.BOLD, 14));
this.add(mntmTwincloud);
JMenuItem mntmCapacity = new JMenuItem("X GB of Y GB used");
this.add(mntmCapacity);
this.addSeparator();
JMenuItem mntmOpenTwinCloud = new JMenuItem("Open Cloud folder");
this.add(mntmOpenTwinCloud);
JCheckBoxMenuItem chckbxmntmEnableAutoSync = new JCheckBoxMenuItem(
"Enable Auto Sync");
this.add(chckbxmntmEnableAutoSync);
chckbxmntmEnableAutoSync.setState(true);
JMenuItem mntmShareFile = new JMenuItem("Share File");
this.add(mntmShareFile);
JMenuItem mntmLogOut = new JMenuItem("Log Out");
this.add(mntmLogOut);
JMenuItem mntmExit = new JMenuItem("Exit");
this.add(mntmExit);
addPopUpToTry();
}
private void addPopUpToTry() {
final SystemTray tray = SystemTray.getSystemTray();
final TrayIcon trayIcon = new TrayIcon(createImage("bulb.gif", "tray icon"));
trayIcon.setPopupMenu(this); // Error
trayIcon.setImageAutoSize(true);
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
return;
}
}
protected static Image createImage(String path, String description) {
URL imageURL = TrayIconDemo.class.getResource(path);
if (imageURL == null) {
System.err.println("Resource not found: " + path);
return null;
} else {
return (new ImageIcon(imageURL, description)).getImage();
}
}
}
但是,trayIcon.setPopupMenu(this);
会出现以下错误。
TrayIcon类型中的方法setPopupMenu(PopupMenu)不是 适用于参数(JPopupMenu)
当我将JPopupMenu更改为awt PopupMenu并进行其他必要的更改时,我可以成功运行代码。但我不想使用PopupMenu。
如何使用JPopupMenu并将其放入系统托盘?