直接上方法,
不过有些问题要注意,最后会说明!
private void systemTray() {
if (SystemTray.isSupported()) { // 判断系统是否支持托盘功能.
// 创建托盘右击弹出菜单
PopupMenu popupMenu = new PopupMenu();
//创建弹出菜单中的退出项
MenuItem itemExit = new MenuItem("Exit");
itemExit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
popupMenu.add(itemExit);
//创建托盘图标
ImageIcon icon = new ImageIcon(getClass().getResource("image/timg.jpg"));
// 创建图片对象
TrayIcon trayIcon = new TrayIcon(icon.getImage(), "Scan Upload",
popupMenu);
//这句话很重要,不然托盘图标不显示!!!
trayIcon.setImageAutoSize(true);
trayIcon.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TwainADF_VerificationForm.this.setVisible(true);
}
});
//把托盘图标添加到系统托盘
//这个可以点击关闭之后再放到托盘里面,在此是打开程序直接显示托盘图标了
try {
SystemTray.getSystemTray().add(trayIcon);
} catch (AWTException e1) {
e1.printStackTrace();
}
}
}
JDialog 取消右上角关闭事件
this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
PS:
1 图片显示空白
trayIcon.setImageAutoSize(true);这句话必须要要
2 图片存放路径问题:
在这个类的同级,创建image文件夹,图片塞进去。
然后复制到 target目录,一样复制一份到同样的类的同级
3 取消和隐藏JDialog关闭按钮
方法1, 禁用关闭
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
方法2, 隐藏
dialog.setUndecorated(true);
4 托盘图片切换
PopupMenu popupMenu = new PopupMenu();
//默认/选中 字体
Font defaultFont=new Font("宋体", Font.PLAIN,12);
Font selectFont=new Font("宋体", Font.BOLD,20);
MenuItem itemSimple = new MenuItem("Simple");
MenuItem itemMulti = new MenuItem("Multi");
MenuItem itemExit = new MenuItem("Exit");
//单个打印菜单
itemSimple.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AppConfig.uploadFileType=1;
//改变字体
Font fontSimple=new Font("宋体", Font.BOLD,20);
itemSimple.setFont(selectFont);
itemMulti.setFont(defaultFont);
//改变托盘图标
trayIcon.setImage(new ImageIcon(getClass().getResource("image/image-regular.png")).getImage());
}
});
popupMenu.add(itemSimple);
//多个打印菜单
itemMulti.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AppConfig.uploadFileType=2;
//改变字体
Font fontMulti=new Font("宋体", Font.BOLD,20);
itemMulti.setFont(selectFont);
itemSimple.setFont(defaultFont);
//改变托盘图标
trayIcon.setImage(new ImageIcon(getClass().getResource("image/images-regular.png")).getImage());
}
});
popupMenu.add(itemMulti);