Thursday, May 28, 2009

Simple Java Tray Example

I am just putting below a sample code to create a simple tray icon using java awt.
Also I will demonstrate how to show a Error, Warn or Info balloon message and opening a browser on click of the balloon message.

Following is the sample code:

SystemTray tray = SystemTray.getSystemTray();
TrayIcon ti;
PopupMenu menu = null;
menu = new PopupMenu();

MenuItem menuItem = new MenuItem("Quit");
menuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String s = ((MenuItem) (e.getSource())).getLabel();
if (s.equalsIgnoreCase("Quit") {
System.exit(1);
}
s = null;
}
});
menu.add(menuItem);

Image i = new ImageIcon("imagenage.gif").getImage();
ti = new TrayIcon(i, "Tool Tip to be displayed on mouse hover",
menu);


This should create a tray icon with the selected image. The tool tip message is displayed whenever the mouse hovers over the tray icon. On click of the tray icon the Menu created by PopUpMenu shows, in the above code it just shows an exit menu.

Below we will add a balloon message to the tray.


ti.displayMessage("Message Title",
"Actual Message", MessageType.INFO);


Note: The Message Types can be INFO, ERROR or WARNING Or NONE

Lets say we want to open a broswer on click of the balloon message. TO achieve this first we have to add a action listener to the tray icon, as shown below:

ti.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

}
});



Now that we have added an action listener, we will see how to open the browser and browse a site on click of the balloon message. To achieve this, add the following code to the actionPerformed method.


Desktop.getDesktop().browse((new URI("www.google.com"));


Voila Done.


On Second thoughts--- This Tray Icon API is in Java 1.6. Forgot to mention that :)

No comments:

Post a Comment