/*
* $Id: ClientTrayIcon.java,v 1.2 2007-10-16 11:44:58 tmfelser Exp $
* Created on 15.10.2007
*/
package jalk;
import java.awt.AWTException;
import java.awt.Frame;
import java.awt.Image;
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.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
/**
* This class creates a system tray icon.
* The system tray and tray icons are supported from Java 6 onwards.
* @author tmfelser
*
*/
public class ClientTrayIconJava6 implements ClientTrayIconInterface {
PopupMenu popup = null;
TrayIcon trayIcon = null;
private boolean trayIconAvailable = false;
public ClientTrayIconJava6() {
}
public final boolean init(final Frame parentFrame) {
if (!SystemTray.isSupported())
return false;
final SystemTray tray = SystemTray.getSystemTray();
Image icon = parentFrame.getIconImage();
if(icon == null)
icon = new BufferedImage(64,64, BufferedImage.TYPE_INT_RGB);
// create a popup menu
final ActionListener exitJalk = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(parentFrame != null) {
parentFrame.dispose();
}
}
};
popup = new PopupMenu();
final MenuItem exitItem = new MenuItem("Exit");
exitItem.addActionListener(exitJalk);
popup.add(exitItem);
// construct the TrayIcon
final ActionListener restoreParentFrame = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(parentFrame != null) {
parentFrame.setVisible(true);
parentFrame.setState(Frame.NORMAL);
parentFrame.toFront();
}
}
};
trayIcon = new TrayIcon(icon, "Jalk", popup);
trayIcon.addActionListener(restoreParentFrame);
try {
tray.add(trayIcon);
trayIconAvailable = true;
} catch (final AWTException e) {
System.err.println(e);
return false;
}
// add listener to parentWindow
if(trayIconAvailable && parentFrame != null) {
parentFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowIconified(final WindowEvent e) {
parentFrame.setVisible(false);
}
@Override
public void windowDeiconified(final WindowEvent e) {
parentFrame.setVisible(true);
}
});
}
return trayIconAvailable;
}
public final boolean isAvailable() {
return trayIconAvailable;
}
public final void exit() {
if(trayIcon != null && SystemTray.isSupported()) {
final SystemTray tray = SystemTray.getSystemTray();
tray.remove(trayIcon);
trayIcon = null;
}
}
}
//import org.jdesktop.jdic.tray.*;
//TF: this is for having a tray icon with the JDIC "library"
//private TrayIcon myTrayIcon = null;
//URL trayIconURL = this.getClass().getResource("/resources/trayicon.gif");
//javax.swing.ImageIcon icon = new javax.swing.ImageIcon(trayIconURL);
//myTrayIcon = new TrayIcon(icon);
//SystemTray.getDefaultSystemTray().addTrayIcon(myTrayIcon);
//...
//SystemTray.getDefaultSystemTray().removeTrayIcon(myTrayIcon);