Building GUI apps faster


Last time, we looked at the fundamentals of Java’s graphical user interface (GUI) armoury, its Layout Managers and explored the three basic options: BorderLayout, FlowLayout and GridLayout.

But hand-coding isn’t the only way to build GUI designs. Most of the major IDEs now support drag-and-drop style GUI builders — NetBeans comes with Swing GUI Builder, while Eclipse now has a plug-in option called WindowBuilder.

But as we’ve been using NetBeans exclusively through this series, we thought that, this time, we’d take a look at how GUI Builder works and compares with a practical example.

Get NetBeans, Java & Source Code

To follow along, download the NetBeans IDE and Java SE SDK bundle from Oracle’s website. Alternatively, you can install them separately, but just make sure you install the Java SE SDK first as NetBeans will look for it during installation.

Download the source code for this project from our website and compare how it works with the previous version.

Unzip the downloaded zip file and on NetBeans, select File > Import Project > From ZIP and choose the inner zip file from the unzipped download. NetBeans will do the rest.

Create a new project

Our original Mortgage Calculator app with GUI coded by hand.

Our original Mortgage Calculator app with GUI coded by hand.

Our last project was a Mortgage Calculator, in which, we created the GUI from scratch by hand. It’s a pretty simple app as far as GUIs go, but it provides the perfect baseline to compare building the same interface using the GUI Builder.

Right-click on your new app, select New and JFrame Form to begin.

Right-click on your new app, select New and JFrame Form to begin.

To start, fire up NetBeans and from the main menu, select File > New Project. On the New Projects window, you should see “Java” highlighted in the Categories list and “Java Application” in the Projects list. If not, make any necessary changes. Otherwise, press Next.

On the New Java Application window, change the Project Name entry to something appropriate (we’ve used “MortgageCalc2”) and un-tick the checkbox next to “Create Main Class”. Now press Finish.

After project initialisation is completed, right-click on the project root folder and select New, JFrame Form from the context menus. On the New JFrame Form window, change the Class Name and Package entries (we’ve used “NewInterface” and “apcmortgagecalc2”, respectively).

You can use whatever you think is appropriate, but we suggest using capitals for former and lowercase for the latter. When you’re done, press the Finish button.

GUI designer window

If you want to see Nimbus LaF in preview mode, use the right-click menu.

If you want to see Nimbus LaF in preview mode, use the right-click menu.

As soon as you do that, NetBeans will open up the IDE with the GUI Builder window. Depending on if and how you’ve modified the IDE layout, you should have four area sections — the Navigator window down the left side, the design window upper-middle, the runtime output box below and the Swing and AWT GUI component palette down the right-hand side.

You’ll also see a second toolbar row at the top of the design frame, showing Source, Design and History buttons. To the right of those buttons, the first two icon buttons toggle between selection and connection mode, while the third is a preview button.

This gives you a centre-screen preview of what your GUI design will look like, but be aware, it’s a quick preview and uses the default OS system theme, or “look and feel” (LaF) as Java calls it.

When you actually come to run the app, the user interface will feature Java’s default Nimbus LaF provided you’re using the default setup.

To see Nimbus LaF in preview mode, head to the Navigator window, right-click on the “[JDialog]” entry, select Preview Design and choose Nimbus from the context menu (feel free to try any other options
as well).

Drag and drop

To start building up your user interface, click on a component from the palette and drag it onto the JFrame. If you were with us last time, you might remember that each of the Layout Manager options uses auto-placement (within reason) and auto-arranges components should you change the size of the frame.

The GUI Builder on the other hand uses the newer GroupLayout manager, which basically locks a component’s position to wherever you drop it, although if you resize the JFrame, GUI components on the right-side will expand to fill the space.

But to help you create a clean design where components line up and are positioned with regular spacing, the GUI Builder will also offer you automatic alignment guideline suggestions to snap your components to. You set the location of the first component and GUI Builder will use that to baseline its future suggestions as you near that original component with your next.

Bottom line, for simple layouts like our Mortgage Calculator app, it means a GUI layout can be completed in a fraction of the time it takes to build by hand.

To complete the app GUI, we’ll start by loading up the JLabel and JTextField components into the JFrame, followed by a JButton. Underneath, we add a full-width JTable and JScrollPane. Finally, we add in three more JLabels and JTextFields.

Click and drag

Once you’ve added a new component to the JFrame, you can resize it by simply clicking one of the eight corner/side handles and dragging it to change its size. Pull the component towards the edge of the JFrame and you’ll see the alignment guidelines — these allow you to create a clean, uniform look.

GUI Builder also provides a bucketload of short-cut options. For example, with JLabels, double-click on the component to activate label editing and you can change the text on the spot.

However, for all text-based components, you can also just right-click on the component and choose Edit Text from top of the context menu.

Component properties

The right-side Properties window lets you modify your GUI components.

The right-side Properties window lets you modify your GUI components.

There’s one other section of the default GUI Builder frame in NetBeans — the Properties window. If you can’t see it, it’s probably a tab to the right of the Palette window, running down the far-right border.

Click-and-drag that tab into the main IDE window and you can add it permanently to the GUI Builder frame.

As you click on each GUI component, the Properties window displays that component’s properties in four group options: Properties, Binding, Events and Code.

They allow you to change how the component looks, (foreground/background colours, font type, style, size etc), but also how it interacts with other variables, other events and most stops in between.

GUI Builder Shortcuts

Change the component name by right-clicking it in the Navigator menu.

Change the component name by right-clicking it in the Navigator menu.

Another thing you’ll want to do quick-sticks is change the default names NetBeans gives your GUI components.

The fact NetBeans automatically names them gives you one less thing to do if you’re in a hurry to create your design, but names like “jTextField1”, “jTextField2” and so on aren’t terribly descriptive, particularly when, later, you’re trying to remember what their roles are in your code.

Click anywhere in your design window and the Navigator window on the left will give you a full list of all the GUI components in your design. Right-click on any component in the list, choose Change Variable Name and you can change the component name to something more useful.

Removing ActionPerformed methods

Use the Properties’ window Events tab to remove default methods.

Use the Properties’ window Events tab to remove default methods.

Double-clicking on a user-action component such as a JTextField or JButton in the design window will automatically create an “ActionPerformed” method in your source code and take you to it.

It’s an easy way to start building the activity functionality into your GUI and linking it to your code. The only problem with it is once the method has been created, getting rid of it can be a bit tricky.

In fact, the only way to delete these auto-generated methods in the most recent releases of NetBeans is to go back to the design window and click on the GUI component whose method you want to delete. Next, go to the Properties window, click on the Event tab button and you should see ActionPerformed at the top of the Event list with a link to the method you want to remove.

Go to the end of this row, click on the ellipsis (…) button and this brings up the Handlers window. Click on the ActionPerformed handler in the new window and press the Remove button. Now go back to your source code and the offending method should have disappeared.

Binding data model to JTable

Use the Code Customiser to use your own table model with a JTable.

Use the Code Customiser to use your own table model with a JTable.

You may also remember last time that, in order to get our mortgage payment schedule data to appear in the JTable, we created a TableModel, bound that to the JTable and put the JTable inside a JScrollPane to allow scrolling beyond the visible window.

Then as we created the schedule data, we added it row by row to the TableModel (which we called “dataModel”). But when you add a JTable via the GUI Builder, the Builder creates the new instance, but also creates its own table model.

For many applications, having this done automatically for you helps speed up coding. But if you want to use a custom TableModel, you have to tell the GUI Builder to back off its auto-gen code to allow yours to work.

To do this, you must right-click on the JTable in the left-side Navigator window and select Customise Code from the context menu.

In the Initialisation Code window, look for the “table.setModel” codeline, change the dropbox on the left from “default code” to “custom property” and inside the braces, type in the name of your TableModel you want bound to this table (here, our TableModel is”‘dataModel”). Click the OK button.

If you look at the NewInterface class in the source code, we manually add five columns to the dataModel object, one each for Date, Payment, Amount Interest, Amount Principal, Current Balance. These initialise the columns and provide the column headers at the same time. Without them, no payment schedule data will be displayed in the table.

Launch the app

Run the app, compare it with our original version and it should perform almost identically. You’ll also see that we’ve brought over the two main engine room methods, calculateLoan() and getStartDate() — there’s no need to reinvent the wheel if we don’t need to.

So hand-code or GUI builder?

This is one of the most common questions around this topic — should I hand-code my GUI designs or use a GUI builder framework instead? In a way, there are two issues here — using a GUI builder to save from having to learn how to hand-code plus the suitability of GUI builders for every app.

When I was a kid, we couldn’t wait to get our hands on a calculator, so we could rip through our homework and do something more enjoyable. Thankfully, we weren’t allowed anywhere near one until we’d learn how to do mathematical calculations by hand.

The moral behind that analogy fits here as well — GUI builders can save time, but knowing how to hand-code a GUI should help you make better use of GUI builders, by understanding how basic Java GUI design works.

But using a GUI builder for every app? This one depends on who you talk to. Some developers won’t touch GUI builders and prefer to do every job by hand, others will say life’s too short, there’s too much to learn, so cut corners whenever possible. Still others again are more pragmatic, choosing on a case-by-case basis.

Personally, I think you can make it a bit simpler. GUI builders allow you to drag-n-drop your GUI components into position and they generate the corresponding Java code for you.

The key here is if you understand the code the GUI builder creates, there’s probably no reason not to use it. But chances are, you’ll have to maintain the code in the future and that will be much easier to do if you understand what that code actually does.

Still, GUI builders are often thought to save coding time, but the time you save by drag-and-dropping your GUI components could be later spent trying to figure out the code the GUI builder just generated. Why? Look at the number of code lines for the two versions of our Mortgage Calculator — the hand-coded version is 210; the GUI Builder version is 400 — and 201 lines of that comes from the GUI Builder itself.

My experience is that using GUI designers almost always create more code than hand-coding the GUI yourself.

Let’s say you need to come up with a simple GUI design fast for a meeting to get a project off the ground. In that case, something like NetBean’s GUI Builder is a no-brainer. But it’s just worth remembering that wandering through the GUI code may well take you longer than code you’ve created yourself.

That’s why I’m a fan of learning how to create GUI apps both ways. There might be short-cuts to coding, but there are no short-cuts to learning and the more you learn, the better a coder you’ll be.