早期要將自己用Java寫的程式產生一個System Tray Icon掛在windows右下角工具列是非常麻煩的一件事,必須透過JNI來使用微軟提供的System Tray Icon相關API才能達成,沒想到Java在6.0也提供了相關功能(6.0好像到Update25了,太久沒用java,我的環境居然還是1.4.7)來解決這麻煩的過程。
System Tray主要由TrayIcon、PopupMenu和MenuItems組成,當然還需要至少一個的ActionListener來離開程式。簡單範例程式如下:
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;
public class SystemTrayTest {
public static void main(String[] args) {
try {
if (SystemTray.isSupported()) {
// get the SystemTray instance
final SystemTray tray = SystemTray.getSystemTray();
// load an image
Image img = Toolkit.getDefaultToolkit().getImage("D:/Study/java/bulb.gif");
// create a popup menu
final PopupMenu popMenu= new PopupMenu();
// create a tray icon
final TrayIcon trayIcon = new TrayIcon(img, "System Tray Test", popMenu);
// create menu item for the default action
MenuItem exitItem = new MenuItem("Exit");
popMenu.add(exitItem);
// create a action listener to listen for default action executed on the tray icon
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
tray.remove(trayIcon);
System.exit(0);
}
};
exitItem.addActionListener(listener);
tray.add(trayIcon);
} else {
System.out.println("SystemTray is not supported");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
閱讀全文...