代碼說明:
在桌面工具欄上顯示托盤
代碼片段:
- import Java.awt.AWTException;
- import Java.awt.Image;
- import Java.awt.MenuItem;
- import Java.awt.PopupMenu;
- import Java.awt.SystemTray;
- import Java.awt.Toolkit;
- import Java.awt.TrayIcon;
- import Java.awt.event.ActionEvent;
- import Java.awt.event.ActionListener;
- import Java.awt.event.MouseEvent;
- import Java.io.UnsupportedEncodingException;
- import Java.Net.URL;
- import Javax.swing.ImageIcon;
- import Javax.swing.JFrame;
- import Javax.swing.JLabel;
- public class SystemTrayDemo extends JFrame{
- private TrayIcon trayIcon = null;
- public SystemTrayDemo(){
- this.setTitle("系統托盤");
- jbInit();
- this.setSize(200, 250);
- this.setLocation(300, 300);
- }
- public void jbInit(){
- if(SystemTray.isSupported()){ //檢查當前系統是否支持系統托盤
- SystemTray tray = SystemTray.getSystemTray();//獲取表示桌面托盤區的 SystemTray 實例。
- Image image = Toolkit.getDefaultToolkit().getImage("newrobot1_256.png");
- PopupMenu popupMenu = new PopupMenu();
- MenuItem exitItem = new MenuItem("exit");
- System.out.println(exitItem.getFont());
- MenuItem menuItema = new MenuItem("menu a");
- MenuItem menuItemb = new MenuItem("menu b");
- MenuItem menuItemc = new MenuItem("menu c");
- MenuItem menuItemd = new MenuItem("menu d");
- exitItem.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent e) {
- try{
- System.exit(0);
- }catch(Exception ex) {
- ex.printStackTrace();
- }
- }
- });
- popupMenu.add(menuItema);
- popupMenu.add(menuItemb);
- popupMenu.add(menuItemc);
- popupMenu.add(menuItemd);
- popupMenu.add(exitItem);
- trayIcon = new TrayIcon(image, "系統托盤{thu}", popupMenu);
- trayIcon.addMouseListener(new Java.awt.event.MouseAdapter(){
- @Override
- public void mouseClicked(MouseEvent e) {
- if(e.getClickCount()==2){
- //注意下面的API調用,這個可以給用戶提示信息
- trayIcon.displayMessage("message", "double click",
- TrayIcon.MessageType.INFO);
- showIT(true);
- }
- }
- });
- //注意下面這個API調用,能夠保證使用的圖標被縮放到合適的比例
- trayIcon.setImageAutoSize(true);
- try{
- tray.add(trayIcon); // 將 TrayIcon 添加到 SystemTray。
- } catch (AWTException e) {
- System.err.println(e);
- }
- }else{
- System.out.println("你的系統不支持系統托盤");
- }
- //下面這個部分是具體的業務邏輯
- ImageIcon icon = new ImageIcon();
- try{
- URL url = new URL("newrobot1_256.png");
- icon = new ImageIcon(url);
- }catch(Exception e){
- }
- JLabel label = new JLabel();
- label.setIcon(icon);
- this.add(label);
- }
- public void showIT(boolean visable){
- if(this.isVisible() != visable)
- this.setVisible(visable);
- }
- public static void main(String[] args) {
- Javax.swing.SwingUtilitIEs.invokeLater(new Runnable(){
- public void run(){
- new SystemTrayDemo().setVisible(true);
- }
- });
- }
- }
【效果圖】
原文鏈接:http://www.oschina.Net/code/snippet_188162_8173