Java中实现系统托盘功能(代码全贴,附加运行截图)
Java中如何,实现系统托盘功能.
示例图
项目包结构图
系统运行截图
应用核心逻辑说明,隐藏到托盘实质就是讲窗体隐藏.即setVisible(false),显示窗体即就是讲setVisible(true).
项目代码如下:
1 package org.pdp.frame;
2
3 import java.awt.AWTException;
4 import java.awt.MenuItem;
5 import java.awt.PopupMenu;
6 import java.awt.SystemTray;
7 import java.awt.TrayIcon;
8 import java.awt.event.ActionEvent;
9 import java.awt.event.ActionListener;
10 import java.net.URL;
11
12 import javax.swing.ImageIcon;
13 import javax.swing.JFrame;
14 import javax.swing.JMenu;
15 import javax.swing.JMenuBar;
16 import javax.swing.JMenuItem;
17
18
19 public class MainFrame extends JFrame implements ActionListener{
20
21 private static final long serialVersionUID = -7078030311369039390L;
22 private JMenu menu;
23 private JMenuBar jmenuBar;
24 private String [] jmItemName = {"置于托盘","系统退出"};
25
26 public MainFrame(){
27 super("电话薄");
28 init();
29 this.setSize(500,400);
30 this.setJMenuBar(jmenuBar);
31 this.setLocationRelativeTo(null);
32 systemTray(); //系统托盘
33 }
34
35 /**
36 * 初始化界面
37 */
38 public void init(){
39 menu = new JMenu("系统窗体");
40 for(int i=0; i<jmItemName.length; i++){
41 JMenuItem menuItem = new JMenuItem(jmItemName[i]);
42 menuItem.addActionListener(this);
43 menu.add(menuItem);
44 }
45 this.jmenuBar = new JMenuBar();
46 this.jmenuBar.add(menu);
47 }
48
49 @Override
50 public void actionPerformed(ActionEvent e) {
51 String actions = e.getActionCommand();
52 if("置于托盘".equals(actions)){
53 this.setVisible(false);
54 }
55 if("系统退出".equals(actions)){
56 System.exit(0);
57 }
58
59 }
60
61 /**系统托盘图标处理.*/
62 private void systemTray(){
63 if(SystemTray.isSupported()){ //判断系统是否支持托盘功能.
64 URL resource = this.getClass().getResource("systray.jpg"); //获得图片路径
65 ImageIcon icon = new ImageIcon(resource); //创建图片对象
66 PopupMenu popupMenu = new PopupMenu(); //创建弹出菜单对象
67 MenuItem itemExit = new MenuItem("退出系统"); //创建弹出菜单中的退出项
68 MenuItem itemShow = new MenuItem("显示窗体"); //创建弹出菜单中的显示主窗体项.
69 itemExit.addActionListener(new ActionListener() { //给退出像添加事件监听
70 @Override
71 public void actionPerformed(ActionEvent e) {
72 System.exit(0);
73 }
74 });
75 itemShow.addActionListener(new ActionListener() { //给窗体最小化添加事件监听.
76 @Override
77 public void actionPerformed(ActionEvent e) {
78 setVisible(true);
79 }
80 });
81 popupMenu.add(itemExit);
82 popupMenu.add(itemShow);
83 TrayIcon trayIcon = new TrayIcon(icon.getImage(),"电话薄系统",popupMenu);
84 SystemTray sysTray = SystemTray.getSystemTray();
85 try {
86 sysTray.add(trayIcon);
87 } catch (AWTException e1) { }
88 }
89 }
90
91 /**
92 * 主方法
93 * @param args
94 */
95 public static void main(String[] args) {
96
97 new MainFrame().setVisible(true);
98
99 }
100
101 }
转载请注明出处[http://www.cnblogs.com/dennisit/archive/2012/12/25/2833060.html]
热爱生活,热爱Coding,敢于挑战,用于探索 ...