package com.tray;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
public class Jframe extends JFrame {
public final SystemTray systemtray = SystemTray.getSystemTray(); //得到当前系统托盘
Image image = Toolkit.getDefaultToolkit().getImage("tray.png");
PopupMenu pmenu = new PopupMenu(); //托盘图标的弹出式菜单
MenuItem openmenu = new MenuItem("打开"); //弹出菜单的打开选项
MenuItem closemenu = new MenuItem("关闭"); //弹出菜单的关闭选项
TrayIcon trayicon = null; //系统托盘图标
public Jframe() {
setTitle("这是一个测试系统托盘图标的窗口");
setVisible(true);
setBounds(400, 200, 400, 400);
openmenu.addActionListener(new MenuListen(this));
closemenu.addActionListener(new MenuListen(this));
pmenu.add(openmenu); //在弹出式菜单里面加入菜单。
pmenu.add(closemenu);
trayicon = new TrayIcon(image, "我的系统托盘图标", pmenu); // 创建一个带图片,提示名,弹出菜单的托盘图标
trayicon.setImageAutoSize(true); // 设置系统图标大小自动。
trayicon.addMouseListener(new MouseAdapter() { // 设置双击系统托盘图标显示主窗口
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
setVisible(true);
}
}
});
try {
systemtray.add(trayicon); // 将图标添加到系统托盘
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.addWindowListener(new WindowListener() { //添加窗口关闭事件
@Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
setVisible(false);
}
@Override
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
});
}
class MenuListen implements ActionListener { // 弹出菜单的监听事件
public Jframe jf = null;
public MenuListen(Jframe jf) {
this.jf = jf;
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("关闭")) {
System.exit(0);
} else
jf.setVisible(true);
}
}
public static void main(String[] args) { //测试的主函数
Jframe jf = new Jframe();
}
}