当前位置:主页 >> Java基础 >> 正文
Java实现把窗体隐藏到系统托盘
阅读:278 输入:2017-09-21 10:20:30
package pretoct;

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.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
 
import javax.swing.ImageIcon;
import javax.swing.JFrame;
 
public class TestTray extends JFrame {
 
 private static final long serialVersionUID = -7078030311369039390L;
 
 public TestTray() {
 this.setSize(500, 400);
 
 this.setLocationRelativeTo(null);// 把窗体设置在屏幕中间
 
 systemTray(); // 设置系统托盘
 
 // 添加关闭按钮事件,关闭时候实质是把窗体隐藏
 this.addWindowListener(new WindowAdapter() {
  @Override
  public void windowClosing(WindowEvent e) {
  TestTray.this.setVisible(false);
  }
 });
 this.setVisible(true);
 }
 
 /**
 * 处理系统托盘
 */
 private void systemTray() {
 if (SystemTray.isSupported()) { // 判断系统是否支持托盘功能.
  // 创建托盘右击弹出菜单
  PopupMenu popupMenu = new PopupMenu();
   
  //创建弹出菜单中的退出项
  MenuItem itemExit = new MenuItem("退出系统");
  itemExit.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent e) {
    System.exit(0);
   }
   });
  popupMenu.add(itemExit);
   
  //创建托盘图标
  ImageIcon icon = new ImageIcon("img/icon.png"); // 创建图片对象
  TrayIcon trayIcon = new TrayIcon(icon.getImage(), "测试系统托盘",
   popupMenu);
  trayIcon.addActionListener(new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent e) {
   TestTray.this.setVisible(true);
  }
  });
   
  //把托盘图标添加到系统托盘
  //这个可以点击关闭之后再放到托盘里面,在此是打开程序直接显示托盘图标了
  try {
  SystemTray.getSystemTray().add(trayIcon);
  } catch (AWTException e1) {
  e1.printStackTrace();
  }
 }
 }
 
 public static void main(String[] args) {
 new TestTray();
 }
}