这个程序是在网上看到的 里面的小毛病我给改过来了 现在能用
这个程序是应用了1。6的新加进的两个类来完成系统托盘的程序
大家会发现在1。6实现系统托盘是多么的简单
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyFrame extends JFrame
{
private TrayIcon trayIcon;
public MyFrame()
{
setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
if (SystemTray.isSupported())
{
setVisible(false);
minimizeToTray();
} else
{
System.exit(0);
}
}
});
JPanel root = new JPanel();
JButton exitButton = new JButton("ok");
exitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
root.add(exitButton);
getContentPane().add(root);
pack();
initTrayIcon();
}
public void minimizeToTray()
{
SystemTray tray = SystemTray.getSystemTray();
try{
tray.add(trayIcon);
}catch(AWTException e){System.out.println(e);}
}
private void initTrayIcon()
{
Image image =
Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/logo.png"));
PopupMenu popup = new PopupMenu();
MenuItem exitItem = new MenuItem("Show");
ActionListener showListener = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
setVisible(true);
SystemTray.getSystemTray().remove(trayIcon);
}
};
exitItem.addActionListener(showListener);
popup.add(exitItem);
trayIcon = new TrayIcon(image, "MyTray", popup);
trayIcon.addActionListener(showListener);
}
public static void main(String[] args)
{
MyFrame frame = new MyFrame();
frame.setTitle("MyFrame");
frame.setVisible(true);
}
}