Makeup on a zombie – Java Swing UX improvements

Even if they are outdated, GUI-based desktop applications won’t disappear anytime soon. But they should get improved user experience (UX) if possible. Some things are surprisingly easy to achieve. This is an example of Java Swing and keyboard handling.

When I learned Java programming in 1997, the AWT classes were the default way to create graphical user interfaces. The AWT widgets were not very sophisticated and really ugly, so it is no surprise they were replaced by a new widget toolkit, called “Swing”, as soon as possible. At the end of 1998, the Swing graphical API was the default way to develop GUIs for desktop applications on the Java platform.

Today, twenty years later, the Swing API is still part of the Java core SDK and ready for your adventures in GUI creation. But time has taken a toll on the technology. The widgets, once displayed with a state-of-the-art design, look really outdated. Swing introduced the concept of pluggable “Look-and-Feels” (L&F), so you could essentially re-skin your interface with a few lines of code, but all L&Fs look ugly and feel cumbersome now. You can say that Java Swing is a zombie: It is still available and in use in its latest development state, but makes no progress in regard of improvements. If software development follows one rule, it is that software that isn’t actively developed anymore is dead.

My personal date when Java Swing died was the day Chet Haase (author of the Java Swing book “Filthy Rich Clients”) left Sun Microsystems to work for Adobe. That was in 2008. The technology received several important updates since then, but soon after, JavaFX got on the stage (and left it, and went back on, left it again, and is now an optional download for the Java SDK). Desktop GUIs are even more dead than Java Swing, because “mobile first” and “web second” don’t leave much room for “desktop third”. Consequentially, Java FX will not receive support from Oracle after 2022.

But there are still plenty of desktop applications and they won’t go away anytime soon. There is a valid use case for a locally installed program with a graphical user interface on a physical computer. And there are still lots of “legacy systems” that need maintenance and improvements. Most of them are entangled with their UI toolkit of choice – a choice made before 2007, when “mobile first” wasn’t even available as an option.

Because those legacy systems still exist and are used, their users want to experience the look and feel of today’s applications. And this is where the fun begins: You apply makeup on a zombie to let it appear a little bit less ugly than it really is.

Recently, my task was to improve the keyboard handling of a Java Swing desktop application. It was surprisingly easy to add a tad of modern “feel”, and this gives me hope that the zombie might stay semi-alive longer than I thought. As you might already have guessed, StackOverflow is a goldmine for answers on ancient technology. Here are my first few improvements and their respective answer on StackOverflow:

  • Let’s suppose you want or need to interact with your application without a mouse or touchscreen. Your first attempt to start an interaction is to press the “menu” key in order to activate the application menu. This would be the “Alt” key on a windows system. For modern applications, your input focus is now at the menu bar. In Java Swing applications, nothing happens. You have to press “Alt” and a mnemonic character to enter a specific menu. If you want to reduce the initial hurdle to just one key, you need to teach all your Java Swing menus to react to the “Alt” key alone: https://stackoverflow.com/a/8659116
  • Speaking of focus, in modern applications you can move your focus by using the arrow keys. Java Swing still thinks that “Tab” and “Shift+Tab” is the pinnacle of focus control. If you want to improve the behavior (and therefore the “feel”) of your focus traversal, you can do it globally for your application: https://stackoverflow.com/a/8255423
  • And if you want to enable the Return/Enter key for button activation, you can do it with just one line: https://stackoverflow.com/a/440536

If you happen to work on a Java Swing application and want some cheap user experience upgrades, I’ve assembled all the knowledge above into a neat little class that you can use as an add-on utility class: https://github.com/dlindner/java-swing-ux/blob/master/src/com/schneide/swing/ux/KeyboardUX.java

What are your makeup tips for zombies?

Java Swing Layouting done right

A praise of the most developer-friendly Java Swing layout manager to date: DesignGridLayout.

Layout Managers were an huge benefit for Java Swing. They enabled software developers to program layout rather than to “drag and drop” it with some proprietary GUI builder. That’s nothing against a good GUI builder, but against the “source code” that gets generated as a result of using it. But after some time of playing and working with the layout managers given by Swing itself, we concluded that they weren’t up to the task. Since then, we were constantly on the lookout for new and better ways to tackle the layouting task.

A history of layout managers

Let’s reiterate our major path with different layout managers:

  • GridBagLayout – the most versatile layout manager included in the Java Swing core classes. It’s capable to handle virtually every layouting task, but the price is huge constraint setup code. Since the code bloats with even facile complexity in the dialog, it’s not maintainable once written. The advantages over GUI builders aren’t really present.
  • StringGridBagLayout – has the same power as GridBagLayout, but with much more concise constraint definitions. It uses a string based domain specific language that you have to learn. After a while, you begin to feel a clumsiness when inserting variables into the constraints.
  • TableLayout – was a new approach to layouting by applying a global grid to your panel. You define the grid by specifying row and column constraints. If you need special cell constraints afterwards, you can alter them, but it’s getting bloated again.
  • StringTableLayout – provided a string based domain specific language over the TableLayout. It had some nice additional features, but lacked versatility with dynamic GUIs.
  • FormLayout – was a great relief and a good companion for many full sized layouting tasks. By concentrating on a problem domain (form based layouts), it played out some advantages over general purpose layout managers. This layout is still in use here.
  • MigLayout – the bigger brother of all these layouts. MigLayout comes with several pages of cheat sheets and you’re soon lost without it. It combines the approaches of all layout managers listed (and many more) and blends them into a massively powerful and versatile product. If you learn this layout manager thoroughly, you’ll never have to look elsewhere. But the learning curve is steep and the complexity of your code scales with the complexity of the GUI (which isn’t a drawback).

All these layout managers added value to our GUIs and are in use until today, albeit seldom.

Keep it simple

Most of the time, your dialogs aren’t these super-fancy, highly dynamic full-page layouts every UI designer dreams about. If they are, pick one of the layout managers from the list and wade through the constraint setup. But let’s say you want to layout a rather plain dialog with some widgets, but you want to do it quick without sacrificing the looks. Here is a developer-friendly solution for this task: Use the DesignGridLayout manager.

Slick and easy layouts

The one thing that differentiates the DesignGridLayout from almost every other layout manager is that you use the layout manager instance itself (in a fluent interface style) to arrange the constraints of your grid. You do not add your widgets to the panel and hope for the layout manager to catch up with the layout, you add them to the layout manager (and hope for it to fill it into your panel, which it does nicely). Here is a little example of the API usage:

JPanel content = new JPanel();
DesignGridLayout layout = new DesignGridLayout(content);
JTextArea history = new JTextArea();
history.setRows(5);
JTextField message = new JTextField();
JButton sendNow = new JButton("Send");
layout.row().grid(new JLabel("History:")).add(new JScrollPane(history));
layout.row().grid(new JLabel("Message:")).add(message, 2).add(sendNow);
content.setLayout(layout);

If you are interested in the possibilities of the layout manager, you should read the usage introduction page of DesignGridLayout.

Developer-friendly approach

One big advantage of the fluent API when compared with the string based constraint definitions is the compiler and type system support. You can’t spell anything wrong and the code completion feature of your IDE guides you to the right method and parameter order. The other advantage is that you don’t need to mess with pixel sizes for spacing and such. It’s handled by the layout manager in the most comfortable manner.

And because an article about a layout manager isn’t of any worth without a picture, here’s one:

This is a frame with the panel we constructed in the example code above.

Prettier failures using Swing TaskDialog

An introduction to the Swing TaskDialog project, a fine little gem to spice up your (java swing) dialogs. Includes a real usage example.

The standard way to present graphical user interfaces (GUI) on a desktop machine in java is to use Swing. It’s a very flexible API with a steep learning curve and some oddities (e.g. EDT handling is cumbersome at least), beginning to show some age. There were several attempts to take the Swing experience to a new level, including the marvellous book “Filthy Rich Clients” by Chet Haase (we miss you in the Java camp!) and Romain Guy. So Swing isn’t dead or dying, it’s just getting old.

A pain point of Swing

One thing always bothered me with Swing: It is relatively easy to present a basic message or input dialog. But to add slightly more complexity to a dialog suddenly means substantially more effort. Dialogs don’t scale in Swing. If you ever “designed” an error dialog for your end user, presenting the essence of an exception that just occurred, you already know what I’m talking about. I have to make a confession: Our exception/error dialogs were nearly as nasty as the exception itself. But nobody wants to fail nasty.

Swing TaskDialog to the rescue

At late february this year, Eugene Ryzhikov published his Swing TaskDialog project on his blog. His release pace has been a new version once a week since then. So I’m writing on a moving target.

The TaskDialog project provides basic message, progress and input dialogs based on the operating system’s “User Experience Guidelines”. The visual content is very appealing as a result. But the project doesn’t stop here. The programming API is very understandable and to the point. You don’t have to hassle with big concepts to use it, just look at the examples and start from there.

It was a matter of minutes to replace our old, nasty error dialog with a much prettier one using TaskDialog. Here are two screenshots of it in action, with the detail section retracted (initial state) and flipped open.

Of course, this is only the Windows version of the dialog. You should head over to the TaskDialog examples page to get an idea how this might look on a Mac. This is a dialog that’s pretty enough to not scare the user away by sheer uglyness. The code for this dialog is something like:


TaskDialog dialog = new TaskDialog("Error during process execution");
 dialog.setIcon(TaskDialog.StandardIcon.ERROR);
 dialog.setInstruction("An error occurred during the execution of process 'DemoProcess':");

 Exception exception = new Exception("Because it's just a demo");
 StringBuilder detailMessage = new StringBuilder();
 for (StackTraceElement stackTraceElement : exception.getStackTrace()) {
 detailMessage.append(stackTraceElement.toString());
 detailMessage.append("\n");
 }
 dialog.setText("Error message: <b>" + exception.getMessage() + "</b>\n\n<i>This incident was traced and logged.</i>");
 dialog.getDetails().setExpandableComponent(
 new JLabel(Strings.toHtml(detailMessage.toString())));
 dialog.getDetails().setExpanded(false);

 JLabel waitLabel = new JLabel(Strings.toHtml("<i>This dialog closes automatically in 26s</i>"));
 dialog.setFixedComponent(waitLabel);

 dialog.show();

Notice the usage of Strings.toHtml() to convert plain Strings to HTML-rendered rich text elements.

Timed dialogs

If you look at the presented information, you’ll notice it’s just a demo presenting a fake exception. But you’ll notice another thing, too: This dialog is about to close itself automatically soon. This is a speciality of our project: The GUI runs unattended by users for long periods of time. If you encounter an error every ten minutes and an user returns to the screen after a week, the system isn’t accessable without closing a million dialogs first. You might argue why a system error lasts for a week, but that’s a reality in this project we cannot change. So we came up with timed dialogs that go away on their own after a while. The information of the dialog is persisted in the log files that get evaluated periodically.

The TaskDialog API provides easy integration for a GUI widget to be included in the dialog. In our timed dialog use case, it’s a JLabel, as highlighted in the code example at lines 16 and 17. A background thread periodically updates the text and closes the dialog when time runs out. But you’ll find examples with progress bars and other components on Eugene’s blog.

Conclusion

The Swing TaskDialog project is a fine little gem to spice up your application. It’s API is simple, yet powerful and has proven customizable to our special use case. Finally, effort for basic dialogs in Swing scales again.

JTable index madness

A coworker of mine recently stumbled upon a strange looking JTable:
A broken down JTable

This reminded me of an effect I have seen several times. Digging through the source code of the JTable we found an unusual handling of TableEvents:

    public void tableChanged(TableModelEvent e) {
        if (e == null || e.getFirstRow() == TableModelEvent.HEADER_ROW) {
            // The whole thing changed
            clearSelectionAndLeadAnchor();

            rowModel = null;

            if (getAutoCreateColumnsFromModel()) {
		// This will effect invalidation of the JTable and JTableHeader.
                createDefaultColumnsFromModel();
		return;
	    }

	    resizeAndRepaint();
            return;
        }
...

The hidden problem here is that the value of TableModelEvent.HEADER_ROW is -1. So sending a TableEvent to the table with a obviously wrong index causes the table to reset discarding all renderers, column sizes, etc. And this is regardless of the type of the event (INSERT, UPDATE and DELETE). Yes, it is a bug in our implementation of the table model but instead of throwing an exception like IndexOutOfBounds it causes another event which resets the table. Not an easy bug to hunt down…