Java6学习笔记49——制作程序到系统托盘

import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.PopupMenu;
import java.awt.MenuItem;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class TrayDemo extends JFrame implements ActionListener {
public static void main(String arg[]) {
new TrayDemo();
}
public TrayDemo() {
super("TrayDemo");//调用父类的构造方法
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
} );
buildFrame();

if(!SystemTray.isSupported()) {//判断是否支持
System.out.println("The system tray is not available.");
return;
}
SystemTray tray = SystemTray.getSystemTray();//得到SystemTray对象
Image image = Toolkit.getDefaultToolkit().getImage("bulb.gif");//加载Icon文件
PopupMenu popup = buildMenu();//添加弹出式菜单
TrayIcon trayicon = new TrayIcon(image,"Tray demo program",popup);
trayicon.setImageAutoSize(true);//自动调整大小
try {
tray.add(trayicon);//添加icon
} catch(AWTException e) {
System.out.println("Cannot add tray icon");
}

setLocation(250,150);
setVisible(true);
}
private void buildFrame() {
JButton exitButton = new JButton("Exit");
exitButton.addActionListener(this);
add(exitButton);
setSize(300,200);
}
private PopupMenu buildMenu() {
PopupMenu popup = new PopupMenu();
popup.add(new MenuItem("About"));
popup.addSeparator();
MenuItem hideItem = new MenuItem("Hide");
hideItem.addActionListener(this);
popup.add(hideItem);
MenuItem showItem = new MenuItem("Show");
showItem.addActionListener(this);
popup.add(showItem);
MenuItem exitItem = new MenuItem("Exit");
exitItem.addActionListener(this);
popup.add(exitItem);
return(popup);
}
public void actionPerformed(ActionEvent e) {
String selection = e.getActionCommand();
if(selection.equals("Exit")) {
System.exit(0);
} else if(selection.equals("Hide")) {
setVisible(false);
} else if(selection.equals("Show")) {
setVisible(true);
}
}
}

你可能感兴趣的:(java,swing)