系統托盤也就是桌面右下角的圖標。。
此程序實現的功能是點擊窗體關閉按鈕不退出程序,而是隱藏到系統托盤里面。
實質上也只是把窗體不可見了。。。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
import java.awt.AWTException; 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.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.ImageIcon; import javax.swing.JFrame; public class TestTray extends JFrame { private static final long serialVersionUID = -7078030311369039390L; public TestTray() { this .setSize( 500 , 400 ); this .setLocationRelativeTo( null ); // 把窗體設置在屏幕中間 systemTray(); // 設置系統托盤 // 添加關閉按鈕事件,關閉時候實質是把窗體隱藏 this .addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { TestTray. this .setVisible( false ); } }); this .setVisible( true ); } /** * 處理系統托盤 */ private void systemTray() { if (SystemTray.isSupported()) { // 判斷系統是否支持托盤功能. // 創建托盤右擊彈出菜單 PopupMenu popupMenu = new PopupMenu(); //創建彈出菜單中的退出項 MenuItem itemExit = new MenuItem( "退出系統" ); itemExit.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit( 0 ); } }); popupMenu.add(itemExit); //創建托盤圖標 TrayIcon trayIcon = new TrayIcon(icon.getImage(), "測試系統托盤" , popupMenu); trayIcon.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TestTray. this .setVisible( true ); } }); //把托盤圖標添加到系統托盤 //這個可以點擊關閉之后再放到托盤里面,在此是打開程序直接顯示托盤圖標了 try { SystemTray.getSystemTray().add(trayIcon); } catch (AWTException e1) { e1.printStackTrace(); } } } public static void main(String[] args) { new TestTray(); } } |