How to Create a Pluggable Photo Album in Java
Join the DZone community and get the full member experience.
Join For FreeHere you see a simple photo album I created in Java Swing. It is, by no definition of the term, a great photo album. However, the point is that none of the photos you see are provided by the application itself. Nor do they come from the web. So... where do they come from and how did they end up in my photo album? Read on to find out...
Here's a clue. All that you would need to provide in order to add photos to my photo album is a Java application that is structured as follows:
The images "demo1.png" and "demo2.png" are two of the four photos you see in the first screenshot, i.e., the screenshot of my photo album. The other two photos you see there come from another Java application, which is structured in exactly the same way as the above. "Ah," you might now think. "This article is all about the Java SE 6 java.util.ServiceLoader class. I guess I'll need to be using Java SE 6 and then I'll be able to construct small applications structured like the above and then I'll be able to plug into your photo album."
Wrong. You don't need Java SE 6 at all. Although, you're close. Here's the definition of the VacPhotos class that you see in the illustration above:
package com.example.vacphotos;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import photoalbumapp.Photo;
public class VacPhotos implements Photo {
ImageIcon icon1 = new ImageIcon(getClass().getResource("/com/example/vacphotos/demo1.png"));
ImageIcon icon2 = new ImageIcon(getClass().getResource("/com/example/vacphotos/demo2.png"));
public VacPhotos() {
}
@Override
public Icon[] getPhoto() {
Icon[] icons = new Icon[]{icon1, icon2};
return icons;
}
@Override
public String[] getDescription() {
String[] descs = new String[]{"pic 1", "pic2"};
return descs;
}
}
In other words, you simply need to extend the photoalbumapp.Photo class, which the photo album itself makes available, meaning you need its JAR on your plugin's classpath. The photo album is an empty application shell that exposes the Photo class, with its two methods getPhoto and getDescription. You therefore need to create a Java class that implements those two methods, returning arrays of Icons and Strings for the photos you'd like to integrate into the photo album. Finally, you need to create a file in your META-INF.services folder, with the name of the class that you are implementing, which in this case is photoalbumapp.Photo. Within that file you need nothing more than one line, which is the FQN of your implementation class:
com.example.vacphotos.VacPhotos
And that's all. Now, when the JAR of your app is on the classpath of the photo album, your photos and descriptions will automatically be integrated with all the photos provided by all the other implementations of the same class. The cool thing is that the photo album is an implementation of JSR-296, the Swing Application Framework, so that lifecycle management and persistance, as well as other typical application services, are dealt with by the framework itself. For example, I don't need to provide any code for the user's resizings and repositionings to be saved across restarts.
The most important part, in this context, of my photo album application (i.e., this is a totally separate application to the VacationPhotos application above), is the code that defines my photo service:
package photoalbumapp;
import java.util.Collection;
import org.openide.util.Lookup;
import org.openide.util.Lookup.Result;
import org.openide.util.Lookup.Template;
public class PhotoService {
private static PhotoService service;
private Lookup photoLookup;
private Collectionphotos;
private Template photoTemplate;
private Result photoResults;
private PhotoService() {
photoLookup = Lookup.getDefault();
photoTemplate = new Template(Photo.class);
photoResults = photoLookup.lookup(photoTemplate);
photos = photoResults.allInstances();
}
public static synchronized PhotoService getInstance() {
if (service == null) {
service = new PhotoService();
}
return service;
}
public CollectiongetDefinitions() {
return photos;
}
}
The template lookup
method returns a Result
instance that contains multiple providers, if they exist. You can retrieve the entire collection of providers by calling the Result
instance's allInstances
method, which is exactly what is done above.
Here you see that we are not dealing with the Java SE 6 ServiceLoader class (nor its earlier incarnations, which have been in the JDK since JDK 1.3). Instead, we are dealing with the NetBeans Platform's org.openide.util.Lookup class. Above, I have provided the bridge between your VacationPhotos application and my own separate application that provides the photo album. The bridge is accessed by the photo album to retrieve photos and descriptions. The bridge, in its role as a "service", will, in turn, access all the classes that implement the Photo implementers, as defined in the small Java applications that exist for no other reason than to provide photos, such as the VacPhotos application shown earlier.
And how is the service used? The main JFrame constructor in the photo album is as follows, really simplistic as you can see:
...
...
...
private PhotoService photo;
public PhotoAlbum() {
photo = PhotoService.getInstance();
initComponents();
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
Collectioncoll = photo.getDefinitions(); photo
Iteratorit = coll.iterator();
while (it.hasNext()) {
Photo photo = it.next();
Icon[] icons =photo .getPhoto();
String[] strings =.getDescription();
for (int i = 0; i < icons.length; i++) {
JLabel imageLabel = new JLabel();
imageLabel.setBorder(BorderFactory.createLineBorder(Color.red));
Icon icon = icons[i];
String desc = strings[i];
imageLabel.setIcon(icon);
imageLabel.setText(desc);
content.add(imageLabel);
}
}
setContentPane(content);
}
...
...
...
And that's really all. Now, what are the benefits of using the NetBeans Platform's org.openide.util.Lookup class instead of the JDK's ServiceLoader class?
- Lookup is available in versions for older JDKs and thus you can use it as a replacement of ServiceLoader when running on JDKs older than 1.6.
- Lookup is ready to work inside of the NetBeans runtime container, so makes even more sense when you're working with NetBeans modules. It knows how to discover all the modules in the system, how to effectively read its defined services, and similar activities.
- Lookup supports listeners. Client code can attach a listener and observe changes in lookup content. This is a necessary improvement to adapt to the dynamic environment created by the NetBeans runtime container, where modules can be enabled or disabled at runtime, which in turn can affect the set of registered service providers.
- Lookup is extensible and replaceable. While the ServiceLoader class in JDK 1.6 is a final class with hard-coded behavior, the NetBeans Lookup class is an extensible class that allows various implementations. This can be useful while writing unit tests. Or you can write an enhanced version of lookup that not only reads META-INF/services but, for example, finds the requested service providers around the Internet.
- Lookup is a general purpose abstraction. While the JDK's ServiceLoader can de-facto have just one instance per classloader, there can be thousands of independent Lookup instances, each representing a single place to query services and interfaces. In fact this is exactly the way Lookup is used in NetBeans IDE—it represents the context of each dialog, window element, node in a tree, etc.
And now you know all that's needed for treating Java applications as plugins. (For further information, see John O'Conner's Creating Extensible Applications With the Java Platform.) In summary, by means of registration and discovery of classes and interfaces, loosely coupled photo albums, and similar applications, are clearly very easy to achieve.
Opinions expressed by DZone contributors are their own.
Comments