本实例是用来制作应用程序的系统托盘,比如类似qq在窗体的右下角的图标格式。代码直接复制可用。
1 import java.awt.AWTException; 2 import java.awt.Image; 3 import java.awt.MenuItem; 4 import java.awt.PopupMenu; 5 import java.awt.SystemTray; 6 import java.awt.TrayIcon; 7 import java.awt.event.ActionEvent; 8 import java.awt.event.ActionListener; 9 import java.net.URL; 10 11 import javax.swing.*; 12 13 public class SystemTrayDemo extends JFrame{ 14 15 /** 16 * 为程序添加系统托盘 17 */ 18 private ImageIcon imageIcon; 19 private TrayIcon trayIcon; 20 private PopupMenu popMenu; 21 private MenuItem exit,show; 22 private SystemTray systemTray; 23 //构造方法 24 public SystemTrayDemo() { 25 if (SystemTray.isSupported()) { //判断是否支持系统托盘 26 //以system.png为图片创建图标,图片system.png在你的工程目录下(eclipse中,其它IDE没有测试) 27 imageIcon = new ImageIcon("images/q.png"); 28 trayIcon = new TrayIcon(imageIcon.getImage()); //创建托盘图标 29 trayIcon.setToolTip("系统托盘"); 30 popMenu = new PopupMenu(); //创建弹出菜单 31 //创建菜单项 32 exit = new MenuItem("退出"); 33 show = new MenuItem("显示主窗体"); 34 //添加到popMenu 35 popMenu.add(show); 36 popMenu.add(exit); 37 trayIcon.setPopupMenu(popMenu); 38 systemTray = SystemTray.getSystemTray(); //获得托盘对象 39 try { 40 systemTray.add(trayIcon); //添加托盘图标 41 } catch (AWTException e) { 42 e.printStackTrace(); 43 } 44 //添加监听器 45 exit.addActionListener(new ActionListener() { 46 public void actionPerformed(ActionEvent arg0) { 47 System.exit(0); 48 } 49 }); 50 show.addActionListener(new ActionListener() { 51 52 @Override 53 public void actionPerformed(ActionEvent arg0) { 54 showFrame(); 55 } 56 }); 57 } 58 } 59 //显示窗体 60 public void showFrame() { 61 setVisible(true); 62 } 63 64 //Main method 65 public static void main(String[] args) { 66 JFrame frame = new SystemTrayDemo(); 67 frame.setTitle("使用系统托盘"); 68 frame.setSize(300,200); 69 frame.setLocationRelativeTo(null); 70 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //注意: 不能设置为JFrame.EXIT_ON_CLOSE,否则会直接退出程序 71 72 } 73 74 }
时间: 2024-10-06 18:57:24