If this page does not print out automatically, select Print from the File menu.

Hands on: Building Java apps with Swing

The GUI builder in Netbeans 5.x makes light work of creating desktop applications

Tim Anderson, Personal Computer World 05 Oct 2006

The days when Java was just not good enough for graphical desktop applications are long gone.

Applications built with Swing, the Java GUI (graphical user interface) library, once had a reputation for slow performance and ugly appearance, but that’s not the case today.

It is true that Java applications are resource-hungry, but that is also the case with Microsoft’s .Net framework. If you want efficiency, native code still wins out by a large margin.

There is another factor in Java’s relative lack of popularity on the desktop, which is that creating a Java user interface is more challenging than it is in Visual Studio or Delphi.

There are a couple of reasons for this. First, Java uses layout managers to arrange widgets on a form, which is great for smooth-scaling on different platforms, but awkward when you need a quick result.

Second, the Swing library implements the Model-View-Controller architecture, which is good for more complex projects, but harder to learn.

The good news is that the latest versions of Netbeans, the Sun-sponsored free Java IDE (Integrated Development Environment), has a superb GUI builder called Matisse.

It uses a new library called Swing Layout Extensions library, which is better suited to the needs of a visual designer.

The Netbeans team also improved the usability of the IDE. Overall, Netbeans is now the best tool if you need to put together a quick Java GUI application.

Here is a step-by-step guide to creating the famous to-do list example with Netbeans 5.x.

A Netbeans to-do list
Start a new Java application in Netbeans, using the project wizard to name it PCWNetBeansExample.

Check the option to create a Main class, which is the entry point for the application, and click Finish. Next, right-click the package in the project explorer and choose New JFrame Form.

Call the new class MainForm, click Finish, and it will open in the Matisse GUI designer.

If you try to run the application now, no form will appear. To make it work, edit the main method in Main.java as follows:
MainForm f = new MainForm();
f.setVisible(true);

Now you can run the application and see a blank form, just like a new Visual Basic or Delphi project.

When you close the form, the application quits, because Netbeans automatically sets the JFrame’s defaultCloseOperation to EXIT_ON_CLOSE.

The next step is to lay out the form. Unlike most Java GUI builders, you don’t need to worry about layout managers.

Simply place a JList, a JLabel, a JTextField and two JButtons, aligning them using the form designer’s snap-to lines.

When you place the JList, Netbeans automatically places a JScrollPane as well, which is almost always what you want.

The GUI builder also makes commonly used properties easy to find. For example, right-click the first JButton, and choose Change Variable Name. This button will add an item to the list, so call it btnAdd.

Right-click again and choose Edit text, changing it to Add.

Right-click the JLabel and edit the text to say ‘New item’, noticing how other widgets shift right to accommodate the longer text. Using these techniques, call the JList lstItems, and the JTextField txtNewItem.

One complication of a JList is that its data is handled by a separate class implementing the ListModel interface.

Netbeans creates an instance of AbstractListModel automatically, but a DefaultListModel is more convenient.

Click the Source view and add the code:
import javax.swing.*;
below the package statement but above the class declaration. Then add:
private DefaultListModel dlm = new DefaultListModel();
in the body of the MainForm class.

Finally, view the properties of the JList, find the model property, and click the button to open the model editor.

Remove the existing model, and from the Select Mode button, choose Form Connection.

Select User Code and type dlm in the box. If you then look at the source, Netbeans has generated the following line:
lstItems.setModel(dlm);

This code is in a guarded section, which means you cannot type over it directly.

You will find many similar code snippet editors in Netbeans, allowing flexible customisation without losing the convenience of working through property editors.

All that remains is to wire up the events. Right-click the Add button, select Events, Action, ActionPerformed.

The code editor opens ready for you to type handling code. Here it is:
dlm.addElement(txtNewItem.getText());

Then do the same for the Delete button, adding this code:
int i = lstItems.getSelectedIndex();
if (i > -1) {
dlm.remove(i);
}

You can now run and test the application. There are plenty of refinements you can make, such as editing the JFrame’s title property to place some text in the window bar.

You can also have the JFrame appear in the centre of the screen.

To do this, right-click the JFrame, choose Properties, and then Code. Select Form Size Policy, and choose Generate Resize Code. Check Generate Center.

When you run the application, you will find that it does a reasonable job of resizing intelligently, but you may need to do some fine-tuning.

For example, by default the JList stretches horizontally but not vertically.

Go back to the designer, right-click the JList, choose Auto Resizing, and select Vertical as well as Horizontal.

Now it stretches in both directions, and the other controls shuffle down helpfully as it does.

Another neat touch is that the IDE tells you how to run your application. When you build the project, check the console output, which includes the command line to use when running outside Netbeans.

Netbeans versus Eclipse
The big rival to Netbeans is Eclipse, another free Java IDE sponsored originally by IBM, but now adopted by many other big names including Adobe, BEA, Borland and Compuware.

Eclipse also has a visual editor, recently updated as part of the Summer 2006 release codenamed Callisto. How does it compare to Netbeans?

Eclipse has a ton of good features, but its Swing Visual Editor is a long way behind Netbeans.

The visual designer is better than nothing, but less smooth than Netbeans, and with fewer productivity features.

It also lacks the Swing Layout Extensions library, so you have to use the old Swing layout managers.

Even building a simple to-do list application can be surprisingly awkward.

For example, if someone comes to the Eclipse Visual Editor straight from Visual Basic, and places a JButton on a JFrame, they are unlikely to be happy with the result.

By default, the JFrame has a BorderLayout, which means the button will either fill one edge, or go in the centre and fill the entire form.

The button also has no default text, so if you place it north or south it turns into a narrow band.

A solution is to place a container, such as a JPanel, dock it south, and then place the buttons on the container using FlowLayout to line them up, left to right.

This works, although the Eclipse Visual Editor gives JPanel a GridBagLayout by default.

Now you can add a JScrollPane and JList to the centre of the JFrame but, annoyingly, the left side of the JScrollPane does not align perfectly with the button JPanel, because the JPanel’s horizontal gap property which separates the buttons also adds a margin before the first button. And so it goes on.

If you are skilled with Swing layout managers you can fix these issues easily, but it is a turn-off for beginners.

These comments are only in reference to the Swing Visual Editor, one small part of the wider Eclipse project.

For a long time Eclipse was successful with no GUI designer at all, so it is not an essential part of a Java toolkit; and the current Visual Editor is a big improvement on earlier versions.

As a code editor, Eclipse is equal or ahead of Netbeans, and thanks to its wide adoption and easy extensibility, Eclipse is excellent for a wide variety of tasks, including work with C++, Ruby, PHP and other languages.

Eclipse also gives you a choice of GUI toolkits, with support for the SWT (Standard Widget Toolkit) as well as Swing.

If you want to blend in perfectly with the operating system, or access native features, such as COM on Windows, SWT has advantages. There is also talk of implementing a Matisse designer in Eclipse.

The Netbeans GUI designer is a breakthrough for Java. You can put together a desktop user interface easily without losing the benefit of layout management, smooth resizing and cross-platform capability.

Memory usage in .Net and Java
Runtime environments, such as .Net and Java, bring productivity benefits, but at what cost?

The screen below shows memory usage for the same to-do list application created in Java, .Net, and Delphi 2006 for Win32.

The measurement is Private Bytes, which is memory allocated to the process that cannot be shared with other processes, and a good indication of the real memory cost of running the application.

It is apparent that native code is far more efficient in this instance. How much it matters is moot.

Have a look at the Performance tab in Windows’ Task Manager for some clues. Two useful clues are the amount of Available Physical Memory and the Total Commit Charge.

If available physical memory is low, or the total committed is more than the amount of free physical memory, then your system is making heavy use of memory paged to disk which means poor performance.

On the other hand, you may have plenty. For example, with 1GB or more of Ram, a few 23MB Java processes can be accommodated easily.

Of course, it all depends on how many you have to run. As both Java and .Net become more popular, the demands on our system memory can only increase.

For more articles on visual programming, click the tag below.

www.pcw.co.uk/2165762
This article was printed from the Personal Computer World web site
© Incisive Media Ltd. 2008
Incisive Media Limited, Haymarket House, 28-29 Haymarket, London SW1Y 4RX, is a company registered in the United Kingdom with company registration number 04038503
Close this window to return to the website