随着 Java se 6.0 的推出
JDK6.0 对java Desktop 编程提供了更强大的支持,其中本人最期望 系统托盘 也问世了
在这里简单与大家分享一下代码
java 代码
- package test;
- 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.MouseEvent;
- import java.awt.event.MouseListener;
- public class Test{
- public static void main(String[] args)throws Exception{
- final TrayIcon trayIcon;
- if (SystemTray.isSupported()) {
- SystemTray tray = SystemTray.getSystemTray();
- Image image = Toolkit.getDefaultToolkit().getImage("C:\\tray.gif");
- MouseListener mouseListener = new MouseListener() {
- public void mouseClicked(MouseEvent e) {
- System.out.println("Tray Icon - Mouse clicked!");
- }
- public void mouseEntered(MouseEvent e) {
- System.out.println("Tray Icon - Mouse entered!");
- }
- public void mouseExited(MouseEvent e) {
- System.out.println("Tray Icon - Mouse exited!");
- }
- public void mousePressed(MouseEvent e) {
- System.out.println("Tray Icon - Mouse pressed!");
- }
- public void mouseReleased(MouseEvent e) {
- System.out.println("Tray Icon - Mouse released!");
- }
- };
- ActionListener exitListener = new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- System.out.println("Exiting...");
- System.exit(0);
- }
- };
- PopupMenu popup = new PopupMenu();
- MenuItem defaultItem = new MenuItem("Exit");
- defaultItem.addActionListener(exitListener);
- popup.add(defaultItem);
- trayIcon = new TrayIcon(image, "Tray Demo", popup);
- ActionListener actionListener = new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- trayIcon.displayMessage("Action Event",
- "An Action Event Has Been Performed!",
- TrayIcon.MessageType.INFO);
- }
- };
- trayIcon.setImageAutoSize(true);
- trayIcon.addActionListener(actionListener);
- trayIcon.addMouseListener(mouseListener);
- try {
- tray.add(trayIcon);
- } catch (AWTException e) {
- System.err.println("TrayIcon could not be added.");
- }
- } else {
- // System Tray is not supported.
- }
- }
- }
先修改图标的路径 Image image = Toolkit.getDefaultToolkit().getImage("C:\\tray.gif");
最后 compile and run 一下这个class ,你就会奇的发现系统右下角出现了你想到的系统托盘........