Monday, May 21, 2007

Mustang :- The Desktop bonus

One of the problems with java over the years is the lack on Desktop support. Sun has taken a major step with the release of Java 6.These changes have brought in a whole new flavour to the java desktop applications.

Java 6 now has system tray support.Now icons in the system tray can be added with menus and event handlers.Some applications that run in the background (eg mail client) can be seen in the system tray. Notifiers can also be provided to sent notification messages. The code demonstrates the use of the new functionality.
package com.sash.java6;

import java.awt.*;
import java.awt.TrayIcon.MessageType;
import java.awt.event.*;
import java.io.File;
import java.net.URI;

public class SystemTrayTest {

public SystemTrayTest() throws Exception {

if (SystemTray.isSupported()) {

SystemTray tray = SystemTray.getSystemTray();
//image for tray icon
Image image = Toolkit
.getDefaultToolkit().getImage("any_image.gif");

ActionListener exitListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}};

//pop menu for the tray
PopupMenu popup = new PopupMenu();
MenuItem alertItem = new MenuItem("Message");
popup.add(alertItem);

MenuItem defaultItem = new MenuItem("Exit");
defaultItem.addActionListener(exitListener);
popup.add(defaultItem);

final TrayIcon trayIcon = new TrayIcon(image, "Tray Demo", popup);

alertItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
trayIcon.displayMessage(
"Finally",
"Desktop support for Java",
MessageType.INFO);
}
});

trayIcon.setImageAutoSize(true);
trayIcon.setToolTip("Tooltip test");
tray.add(trayIcon);
} else {
System.err.println(
"System tray is currently not supported.");
}
}

public static void main(String[] args) throws Exception {

//the system tray icon test
new SystemTrayTest();
}
}


Other enhancements include, the introduction of the Desktop API. Using this API now its very easy to open the default email client etc. It also provides an API to open any given file with the default application associated in the OS.

Desktop d = Desktop.getDesktop();
//guess what?
//opens the application associated in your OS with the jpg file
d.browse(new URI("c:/text_file.txt"));

This code opens the default program associated with the text files, on my windows system it opens the file in notepad.

API enhancements have been made to the getTotalSpace, getUsableSpace and getFreeSpace methods have been added. These are very useful enhancements made.

Very nicely done by the sun guys, finally adding some much needed support for the desktop applications.
:)

No comments: