[置顶] JAVA为程序添加系统托盘

系统托盘是个特殊的区域,可以驻留程序,系统托盘显示在桌面的底部,Windows的系统托盘就显示在任务栏的状态区。

下面是一个创建系统托盘的实例。

package tray; import java.awt.AWTException; import java.awt.Image; import java.awt.MenuItem; import java.awt.PopupMenu; import java.awt.SystemTray; import java.awt.TrayIcon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import javax.swing.*; public class SystemTrayDemo extends JFrame{ /** * 为程序添加系统托盘 * @author Sun1956 */ private ImageIcon imageIcon; private TrayIcon trayIcon; private PopupMenu popMenu; private MenuItem exit,show; private SystemTray systemTray; //构造方法 public SystemTrayDemo() { if (SystemTray.isSupported()) { //判断是否支持系统托盘 //以system.png为图片创建图标,图片system.png在你的工程目录下(eclipse中,其它IDE没有测试) imageIcon = new ImageIcon("system.png"); trayIcon = new TrayIcon(imageIcon.getImage()); //创建托盘图标 trayIcon.setToolTip("系统托盘"); popMenu = new PopupMenu(); //创建弹出菜单 //创建菜单项 exit = new MenuItem("退出"); show = new MenuItem("显示主窗体"); //添加到popMenu popMenu.add(show); popMenu.add(exit); trayIcon.setPopupMenu(popMenu); systemTray = SystemTray.getSystemTray(); //获得托盘对象 try { systemTray.add(trayIcon); //添加托盘图标 } catch (AWTException e) { // TODO Auto-generated catch block e.printStackTrace(); } //添加监听器 exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { System.exit(0); } }); show.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { showFrame(); } }); } } //显示窗体 public void showFrame() { setVisible(true); } //Main method public static void main(String[] args) { JFrame frame = new SystemTrayDemo(); frame.setTitle("使用系统托盘"); frame.setSize(300,200); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //注意: 不能设置为JFrame.EXIT_ON_CLOSE,否则会直接退出程序 } }



你可能感兴趣的:(java,java,java,swing,swing,系统托盘)