首页 > 编程语言 >swing程序最小化至系统托盘

swing程序最小化至系统托盘

时间:2022-11-07 11:34:26浏览次数:40  
标签:java 系统托盘 awt new MenuItem swing 最小化 import frame

将  0.png 放到 d:\a\0.png (没找到上传附件的地方,也是醉了,随便下载个png  即可)路径下,然后运行即可

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 javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
/**
* swing程序最小化至系统托盘
* @author yll
*/
public class TestSysteTray {
public static void main(String args[]) {

TrayIcon trayIcon = null;
if (SystemTray.isSupported()) // 判断系统是否支持系统托盘
{
SystemTray tray = SystemTray.getSystemTray(); // 创建系统托盘
Image image = Toolkit.getDefaultToolkit().getImage("D:\\a\\0.png");// 载入图片,这里要写你的图标路径哦

ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame frame = new JFrame();
frame.setBounds(400, 400, 200, 200);// 界面大小
JLabel label = new JLabel("欢迎使用托盘系统");
frame.add(label);
frame.setVisible(true);
}

};
// 创建弹出菜单
PopupMenu popup = new PopupMenu();
//主界面选项
MenuItem mainFrameItem = new MenuItem("main frame");
mainFrameItem.addActionListener(listener);

//退出程序选项
MenuItem exitItem = new MenuItem("exit");
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (JOptionPane.showConfirmDialog(null, "确定退出系统") == 0) {
System.exit(0);
}
}
});

popup.add(mainFrameItem);
popup.add(exitItem);

trayIcon = new TrayIcon(image, "托盘图标", popup);// 创建trayIcon
trayIcon.addActionListener(listener);
try {
tray.add(trayIcon);
} catch (AWTException e1) {
e1.printStackTrace();
}
}
}
}

标签:java,系统托盘,awt,new,MenuItem,swing,最小化,import,frame
From: https://blog.51cto.com/u_15862653/5828355

相关文章