packageui;importjava.awt.AWTException;importjava.awt.EventQueue;importjava.awt.MenuItem;importjava.awt.PopupMenu;importjava.awt.SystemTray;importjava.awt.TrayIcon;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjavax.swing.ImageIcon;importjavax.swing.JFrame;public class TuoPanDemo extendsJFrame
{private static final long serialVersionUID = 1L;//当前操作系统的托盘对象
privateSystemTray sysTray;//托盘图标
privateTrayIcon trayIcon;//图片
private ImageIcon icon = null;//消息是否需要闪烁。默认false不需要闪烁。这个状态需要跨线程修改的。//所以为了健壮代码、线程安全,注意使用关键字volatile
private volatile boolean msgNeedFlash = false;public static voidmain(String[] args)
{
EventQueue.invokeLater(newRunnable()
{public voidrun()
{try{
TuoPanDemo frame= newTuoPanDemo();
frame.setVisible(true);
}catch(Exception e)
{
e.printStackTrace();
}
}
});
}publicTuoPanDemo()
{
setBounds(100, 100, 450, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//这句可以注释掉的,用托盘右键退出程序即可。
getContentPane().setLayout(null);
setLocationRelativeTo(null);
createTrayIcon();//这里可以开启检测是否有消息的线程,如果有,就闪烁图标
newThread(runnableFlash).start();
}private voidcreateTrayIcon()
{//实例化当前操作系统的托盘对象
sysTray =SystemTray.getSystemTray();//实例化一个图标
icon = new ImageIcon(TuoPanDemo.class.getResource("/img/rabbit_24px.png"));//Java托盘程序必须有一个右键菜单
PopupMenu popupMenu = newPopupMenu();
MenuItem menuOpen= new MenuItem("Open Msg");
MenuItem menuExit= new MenuItem("Exit");
popupMenu.add(menuOpen);
popupMenu.add(menuExit);//为右键弹出菜单项添加事件
menuOpen.addActionListener(newActionListener()
{
@Overridepublic voidactionPerformed(ActionEvent e)
{
EventQueue.invokeLater(newRunnable()
{
@Overridepublic voidrun()
{
Msg msg= newMsg();
msg.setVisible(true); //显示窗口
msg.toFront(); //显示窗口到最前端
}
});
msgNeedFlash= false; //消息打开了,就不要闪烁了
}
});
menuExit.addActionListener(newActionListener()
{
@Overridepublic voidactionPerformed(ActionEvent e)
{
System.exit(0);
}
});//实例化托盘图标
trayIcon = new TrayIcon(icon.getImage(), "消息盒子", popupMenu);//图标大小自适应
trayIcon.setImageAutoSize(true);//将托盘图标添入托盘
try{
sysTray.add(trayIcon);
}catch(AWTException e1)
{
e1.printStackTrace();
}
}private Runnable runnableFlash = newRunnable()
{
@Overridepublic voidrun()
{while (true)
{if (msgNeedFlash == true)//如果新消息需要闪烁
{try{//闪动消息的空白时间
trayIcon.setImage(new ImageIcon("").getImage());
Thread.sleep(500);//闪动消息的提示图片
trayIcon.setImage(icon.getImage());
Thread.sleep(500);
}catch(Exception e)
{
e.printStackTrace();
}
}else //如果不需要闪烁,就重置托盘图标
{
trayIcon.setImage(icon.getImage());try{
Thread.sleep(1000 * 10);//10秒闪烁一次。可以在这里读数据库是否有新的审批
msgNeedFlash = true;
}catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
};
}