Java 6 introduced basic integration with the host OS desktop. It now has the SystemTray and TrayIcon classes. So, how do we minimize an application to system tray using them?
The idea is quite simple - when the window is iconified, for example, we make it invisible, and add a tray icon. The tray icon has an ActionListener attached to it and when the user double-click on it the application’s previous state is restored. Quite simple. Let’s look at the code to do that:
package com.anydoby.minimize;
import static java.awt.SystemTray.getSystemTray;
import java.awt.AWTException;
import java.awt.Image;
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.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URL;
import javax.swing.JFrame;
/**
*
* @author SergeyZ
*
*/
public class MainWindow extends JFrame {
private static final long serialVersionUID = 4570679418654300776L;
public MainWindow() {
super("Minimizer");
setDefaultCloseOperation(EXIT_ON_CLOSE);
URL resource = getClass().getResource("/icon.gif");
Image image = Toolkit.getDefaultToolkit().getImage(resource);
setIconImage(image);
if (SystemTray.isSupported()) {
final TrayIcon icon = new TrayIcon(image);
icon.setToolTip("Task Logger");
icon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainWindow.this.setVisible(true);
MainWindow.this.setExtendedState(MainWindow.NORMAL);
getSystemTray().remove(icon);
}
});
addWindowListener(new WindowAdapter() {
@Override
public void windowIconified(WindowEvent e) {
MainWindow.this.setVisible(false);
try {
getSystemTray().add(icon);
} catch (AWTException e1) {
e1.printStackTrace();
}
}
});
}
setSize(100, 100);
}
public static void main(String[] args) {
MainWindow window = new MainWindow();
window.setVisible(true);
}
}You can download an eclipse project with working example here.
PS: tested this on my home laptop with Zenwalk installed - does not work - see this bug. As an alternative you can try jdesktop, which as seems to be working better (quite strange, as JDIC was the predecessor of desktop integration implementation for Mustang).
First published on the old anydoby.com blog on 2008-03-15.