分类:
2009-01-14 17:29:31
实例(JDK 6)
package systray;
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 javax.swing.JFrame;
import javax.swing.JLabel;
public class TestSysteTray {
static JFrame frame;
public static void main(String args[]){
TrayIcon trayIcon = null;
frame = new JFrame();
frame.setBounds(400,400,200,200);
JLabel label =new JLabel("welcome JDK1.6");
frame.add(label);
frame.setVisible(true);
if(SystemTray.isSupported()) {//判断系统是否支持系统托盘
SystemTray tray = SystemTray.getSystemTray(); //获取系统托盘
Image image = Toolkit.getDefaultToolkit().getImage("images/user_edit.png");//载入图片
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(true);
}
};
//创建托盘图标的右键弹出菜单,open与exit.
PopupMenu popup = new PopupMenu();
MenuItem defaultItem = new MenuItem("open");
defaultItem.addActionListener(listener);
MenuItem exitItem = new MenuItem("exit");
exitItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
popup.add(defaultItem);
popup.add(exitItem);
trayIcon = new TrayIcon(image, "My System Tray ", popup);//创建托盘图标
trayIcon.addActionListener(listener);//双击托盘图标时打开窗体
try {
tray.add(trayIcon);//将图标加入到系统托盘区
} catch (AWTException e1) {
e1.printStackTrace();
}
}
}
}