Geertjan is a DZone Zone Leader and has posted 466 posts at DZone. You can read more from them at their website. View Full User Profile

How to Create Visual Applications in Java?

01.29.2008
| 133659 views |
  • submit to reddit
My excellent colleague Java evangelist Chuk Munn Lee wrote me an e-mail in response to my description yesterday of how to create JConsole plugins: "I did not know that the visual library can be used outside of NetBeans. Do you need a special build of the library? Do I need to build it myself or is there a standalone version that I can download?"

This is a good question and the answer is illustrative of how interwoven NetBeans IDE is with the NetBeans Platform. Look in your NetBeans installation folder and you'll find a folder called "platform7", with this content:

In other words, literally, the content of the folder above is the NetBeans Platform. Many of the JARs that make up the NetBeans Platform can be used outside a NetBeans Platform application. Last October I wrote about this, in a blog entry entitled NetBeans APIs Outside of the NetBeans Platform. Follow the steps in that tutorial and you'll have a standard Java application that makes use of some of the typical JARs from the NetBeans Platform.

In other words, several typical scenarios developed on the NetBeans Platform can also be developed outside of it. Another similar scenario is illustrated in the article I wrote yesterday, How to Get Started with JConsole Plugins, where the Visual Library API is used to inject some graph functionality into the JConsole. And so, in response to Chuk's questions "Do you need a special build of the library? Do I need to build it myself or is there a standalone version that I can download?", the answer is: "No, you don't." Download NetBeans IDE, take the two JARs that are highlighted in the screenshot above, put them on your app's classpath, and you're ready to create visual Java applications:

Let's get started for real now. To create visual applications, you need some kind of Swing container within which you need a JScrollPane. Then you create your visual "scene" within that JScrollPane. There are several interesting classes that you can extend to make your visual application. Have a look at the Javadoc or take a stroll through the tutorial, though not all of the tutorial is intended for use outside of the NetBeans Platform.

Now that you have a Swing container with a JScrollPane, create a new Java class that extends GraphScene. Fill it out as follows:

package demo;
import java.awt.Image; import java.awt.Point; import java.util.Random; import javax.swing.ImageIcon; import org.netbeans.api.visual.graph.GraphScene; import org.netbeans.api.visual.widget.LayerWidget; import org.netbeans.api.visual.widget.Widget; import org.netbeans.api.visual.widget.general.IconNodeWidget; import org.openide.util.Utilities; public class DemoGraphScene extends GraphScene {   private LayerWidget mainLayer;   private Image image;   private Random r = new Random();   public DemoGraphScene() {     mainLayer = new LayerWidget(this);     addChild(mainLayer);     image = Utilities.icon2Image(          new ImageIcon(getClass().getResource("/demo/chuk.png")));     addNode("Chuk");   } @Override
protected Widget attachNodeWidget(Object arg0) {
IconNodeWidget widget = new IconNodeWidget(this);
widget.setImage(image);
widget.setPreferredLocation(new Point(10, 20));
mainLayer.addChild(widget);
return widget;
}

@Override
protected Widget attachEdgeWidget(Object arg0) {
return null;
}

@Override
protected void attachEdgeSourceAnchor(Object arg0, Object arg1, Object arg2) {
}

@Override
protected void attachEdgeTargetAnchor(Object arg0, Object arg1, Object arg2) {
}

}

Most of the above code is self-explanatory, I believe. You have a LayerWidget which you add to the scene. Then you add an IconWidget, which you add to the layer. One interesting thing to note is how the icon is converted to an image, via a utility method from the NetBeans Utilities API, which you have already put on your classpath, together with the Visual Library API. In other words, there's a bunch of stuff that NetBeans Platform developers use that can also be used in your own smaller Java applications, as is the case here.

To wrap up, we need to instantiate the GraphScene class from our JFrame and then set the JScrollPane so that its port view will contain the "scene". Here's how we do that, nice and easy via the JFrame constructor:

private DemoGraphScene scene = new DemoGraphScene();

public DemoVisualFrame() {
initComponents();
jScrollPane1.setViewportView(scene.createView());
}

Next, I added a pic of Chuk to my app's source structure and then ran the application. And here's the result:

Next, let's turn Chuk into a movable object. The user should be able to drag and drop him with their mouse. Hmmm. That will mean a lot of coding, right? Wrong. Here's all I needed to add, i.e., just line 6 below:

protected Widget attachNodeWidget(Object arg0) {
IconNodeWidget widget = new IconNodeWidget(this);
widget.setImage(image);
widget.setPreferredLocation(new Point(10, 20));
//I only needed to add this line:
widget.getActions().addAction(ActionFactory.createMoveAction());
mainLayer.addChild(widget);
return widget;
}

And now, when I run my app, I can use my mouse to drag Chuk to a different location:

A MoveAction can only mean one thing, i.e., it can only mean that you want to move the widget. However, other actions could be implemented in a variety of ways, hence there is no default. You need to provide the content of the action yourself, as in the case of the LabelTextFieldEditor. Here, we begin by defining a class-level LabelTextFieldEditor:

private WidgetAction editorAction = ActionFactory.createInplaceEditorAction(new LabelTextFieldEditor());

Next, we define out LabelTextFieldEditor, extending the TextFieldInplaceEditor class:

private class LabelTextFieldEditor implements TextFieldInplaceEditor {
public boolean isEnabled(Widget widget) {
return true;
}

public String getText(Widget widget) {
return ((LabelWidget) widget).getLabel();
}

public void setText(Widget widget, String text) {
((LabelWidget) widget).setLabel(text);
}
}

Finally, we add a label to our widget. We also assign the editor action defined above to our widget. Here we go, just line 7 and 8 below:

@Override
protected Widget attachNodeWidget(Object arg0) {
IconNodeWidget widget = new IconNodeWidget(this);
widget.setImage(image);
widget.setPreferredLocation(new Point(10, 20));
//I added the following two lines:
widget.setLabel("Chuk");
widget.getLabelWidget().getActions().addAction(editorAction);
widget.getActions().addAction(ActionFactory.createMoveAction());
mainLayer.addChild(widget);
return widget;
}

That's it. Let's run our app again. You now have a label which you can click and then it is editable:

When you press Enter, the label is changed.

But what's the point of having just Chuk in our application? Let's add another evangelist, Gregg Sporar:

private Image CHUK = Utilities.icon2Image(new ImageIcon(getClass().getResource("/demo/chuk.png")));
private Image GREGG = Utilities.icon2Image(new ImageIcon(getClass().getResource("/demo/gregg.png")));

Next, we'll create a hash table, so that we can manipulate them more effectively:

private final Hashtable mapping;
{
mapping = new Hashtable();
mapping.put("Chuk", CHUK);
mapping.put("Gregg", GREGG);
}

Then, we'll add them both, rather than just one:

public DemoGraphScene() {
mainLayer = new LayerWidget(this);
addChild(mainLayer);
//Here we create our two evangelists:
addNode("Chuk");
addNode("Gregg");
getActions().addAction(editorAction);
}

We'll need to rewrite our earlier method just a bit, so that it is more generic, because now it will have to handle both Chuk and Gregg:

@Override
protected Widget attachNodeWidget(Object node) {
Image image = (Image) mapping.get(node);
if (image != null) {
return createNewWidget(node, image);
}
throw new IllegalArgumentException(node.toString());
}

And we move all the code from the previous implementation of the above method to a new one:

protected Widget createNewWidget(Object label, Image image) {
IconNodeWidget widget = new IconNodeWidget(this);
widget.setImage(image);
widget.setPreferredLocation(new Point(10, 20));
widget.setLabel(label.toString());
widget.getLabelWidget().getActions().addAction(editorAction);
widget.getActions().addAction(ActionFactory.createMoveAction());
mainLayer.addChild(widget);
return widget;
}

Run the app again and now you'll have two evangelists in your "scene", instead of just one, with the same properties because they're both the same widget, as you can see from the code above:

You might now think about connecting them together, which we can look at in a future article. In general, there's a lot more that can be done, of course, and the documentation on all of this goes into it all. Here's the homepage of the library. I also highly recommend Fabrizio Giudici's Creative use of the NetBeans Visual Library: the Light Table.

In summary, you don't even need to like NetBeans IDE to benefit from its graph library. Just download the IDE, get the two JARs specified above, and then add them to your classpath. That's all. And then code in whatever IDE has your preference.

Published at DZone with permission of its author, Geertjan Wielenga.

Comments

replied on Wed, 2008/01/30 - 3:13am

good

replied on Wed, 2008/01/30 - 3:13am

good

Musa Musa L replied on Wed, 2008/04/02 - 6:09am

This is excellent!! Can u post another tutorial on how to create the connections? better yet why don;t you make this a tutorial series?!!

Geertjan Wielenga replied on Wed, 2008/04/02 - 6:11am

Thanks. :-)

Part 2 was published sometime ago already:

http://java.dzone.com/news/how-add-resize-functionality-v 

naga jyothi replied on Fri, 2009/06/19 - 8:27pm

hi

I want more details reg how to develop a 3d(means embedding vrml/x3d) objects using netbeans .Can u please help me in this issue ,you r appreciated ....

Varun Nischal replied on Thu, 2009/07/09 - 6:50am

Tried this out today, its really cool. By the way, I tried to port this one to NetBeans Platform and I have 2 issues;

  1. Satellite view is not created.
  2. ImageIcon throws exception. 
Thanks.

ravi shekhar replied on Sat, 2009/08/08 - 12:54pm

Hi, Can some one help me please? I want to create a custom CircleWidget using visual library. This widget will draw a circle and will have all the properties of a widget. Later I will use this circle widget to create a circle using toggle button. An example code of CircleWidget will be highly appreciated. Ravi

Widi Cahya replied on Sun, 2011/01/30 - 11:18pm

hey,im just get this error when i run that code.

Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/openide/util/LookupListener

at org.openide.util.Utilities.loadImage(Utilities.java:2684)

at networktopologydrawer.DemoGraphScene.(DemoGraphScene.java:32) --> image = Utilities.icon2Image(new ImageIcon(getClass().getResource("print.png")));

at networktopologydrawer.DemoVisualFrame.(DemoVisualFrame.java:20)

at networktopologydrawer.DemoVisualFrame$1.run(DemoVisualFrame.java:67)

at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)

at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)

at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)

at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) Caused by: java.lang.ClassNotFoundException: org.openide.util.LookupListener

at java.net.URLClassLoader$1.run(URLClassLoader.java:202)

at java.security.AccessController.doPrivileged(Native Method)

at java.net.URLClassLoader.findClass(URLClassLoader.java:190)

at java.lang.ClassLoader.loadClass(ClassLoader.java:307)

at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:248)

... 12 more

can someone help me please??

Michael Je replied on Fri, 2013/04/05 - 7:43am

 Now I did not find the arguments in the FAQ particularly compelling or at all detailed. Sadly, you can babul-ilm.com find more compelling arguments in some of the TopLink public forums and random blogs. However, none so compelling that I feel the sudden need to switch.

Noel Padzinza replied on Thu, 2014/02/27 - 4:05am

Great tutorial. 2014 and its still relevant. Thanks for sharing. Noel - web design melbourne 

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.