系統(tǒng)托盤(pán)也就是桌面右下角的圖標(biāo)。。
此程序?qū)崿F(xiàn)的功能是點(diǎn)擊窗體關(guān)閉按鈕不退出程序,而是隱藏到系統(tǒng)托盤(pán)里面。
實(shí)質(zhì)上也只是把窗體不可見(jiàn)了。。。
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);// 把窗體設(shè)置在屏幕中間 systemTray(); // 設(shè)置系統(tǒng)托盤(pán) // 添加關(guān)閉按鈕事件,關(guān)閉時(shí)候?qū)嵸|(zhì)是把窗體隱藏 this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { TestTray.this.setVisible(false); } }); this.setVisible(true); } /** * 處理系統(tǒng)托盤(pán) */ private void systemTray() { if (SystemTray.isSupported()) { // 判斷系統(tǒng)是否支持托盤(pán)功能. // 創(chuàng)建托盤(pán)右擊彈出菜單 PopupMenu popupMenu = new PopupMenu(); //創(chuàng)建彈出菜單中的退出項(xiàng) MenuItem itemExit = new MenuItem("退出系統(tǒng)"); itemExit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); popupMenu.add(itemExit); //創(chuàng)建托盤(pán)圖標(biāo) ImageIcon icon = new ImageIcon("img/icon.png"); // 創(chuàng)建圖片對(duì)象 TrayIcon trayIcon = new TrayIcon(icon.getImage(), "測(cè)試系統(tǒng)托盤(pán)", popupMenu); trayIcon.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TestTray.this.setVisible(true); } }); //把托盤(pán)圖標(biāo)添加到系統(tǒng)托盤(pán) //這個(gè)可以點(diǎn)擊關(guān)閉之后再放到托盤(pán)里面,在此是打開(kāi)程序直接顯示托盤(pán)圖標(biāo)了 try { SystemTray.getSystemTray().add(trayIcon); } catch (AWTException e1) { e1.printStackTrace(); } } } public static void main(String[] args) { new TestTray(); }}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注