« Surface 2.6, Fabric 2.6 and Colorspace 1.1 out now | Main | JSlider is stupid »

SystemTray and Swing

An attempt to merge SystemTray with a Swing JPopupMenu. If you like problems, try this code.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.teppefall.ds.console.Console;
import com.teppefall.ds.util.View;

public class TestSystemTray {

	static JFrame owner;
	static JPopupMenu jfcPopup;
	
	public static void main(String[] args) {
		TrayIcon trayIcon = null;
		if (SystemTray.isSupported()) {
		    SystemTray tray = SystemTray.getSystemTray();
		    Image image = new ImageIcon(TestSystemTray.class.getResource("/images/teppefall.png")).getImage();
		    owner = View.asApplication("JFC/SystemTray bug", new JLabel("Press here after popup"));
		    jfcPopup = new JPopupMenu("JFC");
		    jfcPopup.add(new JMenuItem("Exit") {{
		    	addActionListener(new ActionListener() {
		    		public void actionPerformed(ActionEvent e) {
			        	Console.info(this, e);
			        	System.exit(0);
		    		}
		    	}
	    		);
		    }});
		    trayIcon = new TrayIcon(image, "Tray Icon");
		    trayIcon.setImageAutoSize(true);
		    trayIcon.addActionListener(new ActionListener() {
		        public void actionPerformed(ActionEvent e) {
		        	Console.info(this, e);
		        	//System.exit(0);
		        	jfcPopup.setVisible(false);
		        }
		    });
		    trayIcon.addMouseListener(new MouseAdapter() {
		    	public void mouseReleased(MouseEvent e) {
		    		jfcPopup.setVisible(false);
		    		if(e.isPopupTrigger()) {
		    			jfcPopup.setInvoker(owner);
		    			jfcPopup.setLocation(e.getX(), e.getY());
		                jfcPopup.setVisible(true);
		    		}
		    	}
		    	public void mousePressed(MouseEvent e) {
		    		mouseReleased(e);
		    	}
		    });
		    try {
		        tray.add(trayIcon);
			    //trayIcon.displayMessage("Teppefall", "Says hi !", MessageType.INFO);
		    } catch (AWTException e) {
		    	Console.warn(TestSystemTray.class, e);
		    }
		} else {
		}
	}
}

The setInvoker idea I got from this:
http://weblogs.java.net/blog/ixmal/archive/2006/05/using_jpopupmen.html

Don't know if makes any difference though. The custom imports are from Darkstar:

Other implementations.
http://jeans.studentenweb.org/java/trayicon/trayicon.html
http://www.jpackages.com/jtray/
https://jdic.dev.java.net/

Check out Jan Erik Paulsen on Twitter.



TrackBack

TrackBack URL for this entry:
http://labs.teppefall.com/movabletype/mt-tb.cgi/138