Java中如何,實作系統托盤功能.
範例圖
專案包結構圖
系統運行截圖
應用核心邏輯說明,隱藏到托盤實質就是講窗體隱藏.即setVisible(false),顯示窗體即就是講setVisible(true).
項目代碼如下:
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);
}
}