Java程序实现系统托盘菜单

Java 1.6 引进的SystemTray(托盘菜单)。

(SystemTrayTrayIcon)用来实现Java托盘菜单,详细代码:

import java.awt.FlowLayout;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
 * Java托盘菜单
 * @author 小叶
 * @since 2011-08-29 23:36
 *
 */
public class SystemTrayFrame extends JFrame {
	/**系统托盘*/
	private SystemTray systemTray;
    
	/**托盘图标*/
	private TrayIcon trayIcon;

	public SystemTrayFrame() throws Exception {
		setTitle("托盘菜单");
		setLayout(new FlowLayout(FlowLayout.CENTER));
		add(new JButton("托盘菜单"));
		setSize(180, 100);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				setVisible(false);
			}
		});

		if (SystemTray.isSupported()) { //当前平台是否支持系统托盘
			//创建一个右键弹出菜单
			PopupMenu popupMenu = new PopupMenu();
			MenuItem mi = new MenuItem("打开主面板");
			MenuItem exit = new MenuItem("退出");
			popupMenu.add(mi);
			popupMenu.add(exit);
			mi.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					setVisible(true);
				}

			});
			exit.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					System.exit(0);
				}
			});
			ClassLoader cl = this.getClass().getClassLoader();
			URL url = cl.getResource("resource/tray.jpg");
			ImageIcon icon = new ImageIcon(url);
			//创建托盘图标
			trayIcon = new TrayIcon(icon.getImage(), "Java托盘菜单", popupMenu);
			//获取托盘菜单
			systemTray = SystemTray.getSystemTray();
			//添加托盘图标
			systemTray.add(trayIcon);
		}
	}
}

效果图:

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值