JavaSwing实现系统托盘

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;



public class AddTrayIcon implements ActionListener {

    /*

     * 此类用于添加系统托盘 只需要将frame传递过来即可

     */

    private MenuItem openItem;

    private MenuItem exitItem;



    public AddTrayIcon() {

        addTrayIcon();

    }



    private void addTrayIcon() { // 添加系统图盘

        if (SystemTray.isSupported()) { // 判断系统是否支持图盘

            SystemTray tray = SystemTray.getSystemTray();

            Image image = Toolkit.getDefaultToolkit().getImage(

                    "lib/images/Snake.jpg");

            PopupMenu popup = new PopupMenu(); // 为托盘添加菜单

            {

                openItem = new MenuItem("打开                                ");   //PopupMenu没有像JPopupMenu一样直接实现设置大小的方法

                openItem.addActionListener(this);

                popup.add(openItem);



                exitItem = new MenuItem("退出");

                exitItem.addActionListener(this);

                popup.add(exitItem);

            }

            TrayIcon trayIcon = new TrayIcon(image, "ACM图书管理系统", popup);

            trayIcon.addMouseListener(new java.awt.event.MouseAdapter() {

                @Override

                public void mouseClicked(MouseEvent e) {

                    if (e.getClickCount() == 2) {

                        MainFrame.frame.setVisible(true);

                    }

                }

            });

            try {

                tray.add(trayIcon);

            } catch (Exception e) {

                e.printStackTrace();

            }



        }



    }



    public void actionPerformed(ActionEvent aet) {

        if (aet.getSource() == openItem) { // 显示主界面

            MainFrame.frame.setVisible(true);

        }

        if (aet.getSource() == exitItem) { // 退出系统

            System.exit(0);

        }



    }

}

 

你可能感兴趣的:(java)