系统托盘也就是桌面右下角的图标。。
此程序实现的功能是点击窗体关闭按钮不退出程序,而是隐藏到系统托盘里面。
实质上也只是把窗体不可见了。。。
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();
}
}
|