使用Java实现系统托盘功能的介绍(附源码以及截图)
Java中如何,实现系统托盘功能.
示例图
项目包结构图
系统运行截图
应用核心逻辑说明,隐藏到托盘实质就是讲窗体隐藏.即setVisible(false),显示窗体即就是讲setVisible(true).
项目代码如下:
package org.pdp.frame;
import java.awt.AWTException;
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.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class MainFrame extends JFrame implements ActionListener{
private static final long serialVersionUID = -7078030311369039390L;
private JMenu menu;
private JMenuBar jmenuBar;
private String [] jmItemName = {"置于托盘","系统退出"};
public MainFrame(){
super("电话薄");
init();
this.setSize(500,400);
this.setJMenuBar(jmenuBar);
this.setLocationRelativeTo(null);
systemTray(); //系统托盘
}
/**
* 初始化界面
*/
public void init(){
menu = new JMenu("系统窗体");
for(int i=0; i<jmItemName.length; i++){
JMenuItem menuItem = new JMenuItem(jmItemName[i]);
menuItem.addActionListener(this);
menu.add(menuItem);
}
this.jmenuBar = new JMenuBar();
this.jmenuBar.add(menu);
}
@Override
public void actionPerformed(ActionEvent e) {
String actions = e.getActionCommand();
if("置于托盘".equals(actions)){
this.setVisible(false);
}
if("系统退出".equals(actions)){
System.exit(0);
}
}
/**系统托盘图标处理.*/
private void systemTray(){
if(SystemTray.isSupported()){ //判断系统是否支持托盘功能.
URL resource = this.getClass().getResource("systray.jpg"); //获得图片路径
ImageIcon icon = new ImageIcon(resource); //创建图片对象
PopupMenu popupMenu = new PopupMenu(); //创建弹出菜单对象
MenuItem itemExit = new MenuItem("退出系统"); //创建弹出菜单中的退出项
MenuItem itemShow = new MenuItem("显示窗体"); //创建弹出菜单中的显示主窗体项.
itemExit.addActionListener(new ActionListener() { //给退出像添加事件监听
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
itemShow.addActionListener(new ActionListener() { //给窗体最小化添加事件监听.
@Override
public void actionPerformed(ActionEvent e) {
setVisible(true);
}
});
popupMenu.add(itemExit);
popupMenu.add(itemShow);
TrayIcon trayIcon = new TrayIcon(icon.getImage(),"电话薄系统",popupMenu);
SystemTray sysTray = SystemTray.getSystemTray();
try {
sysTray.add(trayIcon);
} catch (AWTException e1) { }
}
}
/**
* 主方法
* @param args
*/
public static void main(String[] args) {
new MainFrame().setVisible(true);
}
}
相关文章
MyBatis-Plus 之selectMaps、selectObjs、selectCount、selectO
本文主要介绍了MyBatis-Plus 之selectMaps、selectObjs、selectCount、selectOne的使用,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2022-03-03IDEA创建Maven项目后报错不出现src文件夹的情况解决
最近刚开始学习maven,正准备使用idea创建一个maven项目练手,却发现自己创建的maven项目始终没有src目录,下面这篇文章主要给大家介绍了关于IDEA创建Maven项目后报错不出现src文件夹的情况解决,需要的朋友可以参考下2023-05-05关于Java Guava ImmutableMap不可变集合源码分析
这篇文章主要介绍Java Guava不可变集合ImmutableMap的源码分析的相关资料,需要的朋友可以参考下面具体的文章内容2021-09-09java IO流 之 输出流 OutputString()的使用
这篇文章主要介绍了java IO流 之 输出流 OutputString()的使用的相关资料,需要的朋友可以参考下2016-12-12
最新评论