使用JAVA开发系统托盘程序

 使用JAVA开发系统托盘程序

 

@for&ever 2009-11-27


参考文章《New System Tray Functionality in Java SE 6》,网址 http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/systemtray/ 。
JDK必须要在 1.6 版本。

最近项目中要实现定时任务常驻系统,能够同时有一个比较友好的操作方式提供给最终用户,于是考虑采用 System Tray 。刚好项目中使用的也是 JDK1.6 ,于是参考上面文章的例子,简单修改一下,增加自己需要的功能即可。

转帖代码如下:

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.awt.event.MouseListener; public class SystemTrayTest { public SystemTrayTest() { final TrayIcon trayIcon; if (SystemTray.isSupported()) { SystemTray tray = SystemTray.getSystemTray(); Image image = Toolkit.getDefaultToolkit().getImage("tray.gif"); MouseListener mouseListener = new MouseListener() { public void mouseClicked(MouseEvent e) { System.out.println("Tray Icon - Mouse clicked!"); } public void mouseEntered(MouseEvent e) { System.out.println("Tray Icon - Mouse entered!"); } public void mouseExited(MouseEvent e) { System.out.println("Tray Icon - Mouse exited!"); } public void mousePressed(MouseEvent e) { System.out.println("Tray Icon - Mouse pressed!"); } public void mouseReleased(MouseEvent e) { System.out.println("Tray Icon - Mouse released!"); } }; ActionListener exitListener = new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Exiting..."); System.exit(0); } }; PopupMenu popup = new PopupMenu(); MenuItem defaultItem = new MenuItem("Exit"); defaultItem.addActionListener(exitListener); popup.add(defaultItem); trayIcon = new TrayIcon(image, "Tray Demo", popup); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent e) { trayIcon.displayMessage("Action Event", "An Action Event Has Been Peformed!", TrayIcon.MessageType.INFO); } }; trayIcon.setImageAutoSize(true); trayIcon.addActionListener(actionListener); trayIcon.addMouseListener(mouseListener); // Depending on which Mustang build you have, you may need to uncomment // out the following code to check for an AWTException when you add // an image to the system tray. // try { try { tray.add(trayIcon); } catch (AWTException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // } catch (AWTException e) { // System.err.println("TrayIcon could not be added."); // } } else { System.err.println("System tray is currently not supported."); } } /** * @param args the command line arguments */ public static void main(String[] args) { SystemTrayTest main = new SystemTrayTest(); } }

 

 

 

一点小感想:
JAVA跨平台就是好!这个托盘程序在windows 和 linux平台都能运行的很好。

之前曾打算用C++ 做个既支持windows 又能支持Linux,发现很麻烦,放弃了。。。。


@forandever 2009-11-27

 

你可能感兴趣的:(java,windows,linux,image,System,action)