應用Java完成體系托盤功效的引見(附源碼和截圖)。本站提示廣大學習愛好者:(應用Java完成體系托盤功效的引見(附源碼和截圖))文章只能為提供參考,不一定能成為您想要的結果。以下是應用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);
}
}