Programming user interfaces has many challenges. Fetching the data from remote service, populating the UI controls, tracking user input against the predefined set of validation rules, persisting the data back to the server, handling transitions between different application screens, supporting offline mode, handling error cases in the communication layer. All of these are just part of our daily programming tasks. While all of these relate directly to what the end user sees on the screen, there is a small subset that greatly affects the overall user experience.

The main two items in this subset are pixel perfection and application responsiveness. It is important to remember that the end user does not care about all of the wonderful underlying layers that take up a larger part of our day. As bad as analogies usually are, i would compare it to the vast majority of the drivers. I personally do not care how many people have worked on the specific model, how intricate are the internals of the engine and how many technical challenges had to be overcome during the development and testing. All i care about is that when i turn the key, the engine starts, when i turn the wheel / press the brake / turn on the AC, it responds correctly and immediately, and that it feels good to be sitting behind the wheel or in the passenger seat.

It is thus rather unfortunate that a lot of user interfaces are not implemented with these two main goals in mind. It would seem that programmers would rather enjoy letting the implementation complexity leaking into the UI layer – if it was hard to develop, it should at least look like that on the screen. There are multiple factors contributing to this. The farther you are from the target audience, the less you are able to judge the usability of the application, especially when you are immersed in its internals for long periods of time. When you operate at the level of data objects (with perhaps direct mapping to the optimized backend data storage), the users don’t. They see your application as a means to accomplish the specific flow that they have in mind. If you fail to crystallize the flows during the design stage, your users will see your application as unintuitive, time wasting and counter productive.

And even if you get the flows right – at least for your target audience – there is the issue of responsiveness. Imagine the following scenario. You’re in the kitchen, and want to heat that last slice of pizza from yesterday’s party. You put it in the microwave, press the button – and the entire kitchen freezes for one whole minute. You can look at the fridge, but you cannot open it. You remember that you pressed the microwave button, but the tray is not spinning and it does not make any noises. You step in your living room, and are not able to get back into the kitchen.

This is what happens when your code does I/O, database or any network operation on the UI thread. It does not really matter how small the operation is or how fast your machine is. If it locks the UI for even a fraction of a second, people will notice. You can say – well, this operation here that I’m doing is persisting the current screen state to the backend, so i cannot really let the user interact with the UI while i’m doing that. Or maybe it’s just not that important and the user can wait. Or maybe it’s just going to add to the development complexity of the UI layer.

Doing this right is hard. First, you need to understand what is right – and that varies depending on the specific scenario. Do you prevent the user from doing anything with the application? Or maybe let him browse some subparts of the screen while you’re running this long operation? Or maybe even let him change information elsewhere in the application? Do you show the progress of that operation? Do you allow canceling the operation? Do you allow creating dependencies between executing / scheduled operations?

And after you know what you want to do, the next step is actually implementing and testing it. At this point the word “multi-threading” will be your friend and nemesis. I cannot say that we are at a stage where doing multi-threading in UI is easy (although i certainly am not an expert in all the modern UI toolkits and libraries). It is certainly easier than it was a few years ago, but it’s still a mess. The words of Graham Hamilton from five years ago are still true today:

I believe you can program successfully with multi-threaded GUI toolkits if the toolkit is very carefully designed; if the toolkit exposes its locking methodology in gory detail; if you are very smart, very careful, and have a global understanding of the whole structure of the toolkit. If you get one of these things slightly wrong, things will mostly work, but you will get occasional hangs (due to deadlocks) or glitches (due to races). This multithreaded approach works best for people who have been intimately involved in the design of the toolkit.

Unfortunately I don’t think this set of characteristics scale to widespread commercial use. What you tend to end up with is normal smart programmers building apps that don’t quite work reliably for reasons that are not at all obvious. So the authors get very disgruntled and frustrated and use bad words on the poor innocent toolkit. (Like me when I first started using AWT. Sorry!)

I believe that any help we can get in writing correct multi-threaded code that deals with UI is welcome. This is why i continue enforcing the Swing threading rules in Substance. It is by far the biggest source of complaints ever since it was introduced about a year and a half ago in version 5.0. The original blog entry on the subject implied – rather unfortunately – that i wanted to make my job easier and not handle bugs that originate from UI threading violations. Allow me to clarify my position on the subject and repost my reply from one of Substance forum postings:

I do not intend to provide such API (disabling the threading checks) in the core Substance library. Once such an API exists, people will have little to no incentive to make their code more robust and compliant with the toolkit threading rules.

If the code you control violates the threading rules – and you *know* it – you should fix it. Does not matter if you’re using Substance or not.

If the code you do not control violates the threading rules – either put pressure on the respective developers to change it or stop using it.

It may be painful in the short term. I may lose potential users because of this. It may cause internal forks of the code base. I am aware of these issues. In my personal view, all of them are dwarfed by what is right in the long term interests of both Substance itself and Swing applications in general.

The followup posting by Adam Armistead provides a deeper look into why this matters – and i thank Adam for allowing me to repost it here:

I would just like to say I strongly support Kirill in this and I am very glad to see he is sticking to his guns on this. I feel that it is too easy to violate threading rules in UI code and that I run across entirely too much code that does. I feel that if someone doesn’t strictly enforce these threading rules then there is not enough pressure on developers to fix the problem. If there was enough pressure I wouldn’t see so damn much of this.

As for it causing problems due to 3rd party dependencies having bad UI code, there are tons of solutions for this. I have personally put pressure on developers to fix problems, submitted patches to open source projects to fix code myself, extended classes, forked codebases, used bytecode manipulation, proxy classes, and Spring and AspectJ method injection, method replacement, as well as adding before/after/around advice to methods. I have yet to encounter a situation where a little work or ingenuity on my part has not been able to overcome someone else’s crappy code. In the worst cases I have written my own libraries that don’t suck, but in most cases I didn’t have to go to this extreme.

I sincerely believe that having substance crash my applications has made MY applications as well as those I interact with better. I have seen people in comment sections in blog posts and on forums advise using Substance in order to assist developers in finding UI threading violations. I have fixed open source code and seen others do the same because Substance throws this exception. I can also say, I know may coders that if they had the choice to just log it, they would do so and just say, “aww, I’m busy, I’ll fix it later.” and likely never get around to it…

They’re always busy, so when one thing gets done there’s always half a dozen more that pop up. If it’s not crashing their code its not critical to fix. Besides, its too easy to violate these rules. I’m a Swing developer and I know the rules, and sometimes when I’m hammering out features I slip up and do things incorrectly. Personally, I am glad Substance catches it so I can fix it now.

What are the chances that Swing will start enforcing threading rules in the core? Zero. Between focusing all the client-side resources on JavaFX and sticking to binary compatibility (even when any reasonably sized Swing application needs code changes when it is ported between different JDKs), there is no chance. However, as SWT and Android show, a toolkit / library that aggressively enforces its own threading rules from the very beginning is not such a bad thing. And who knows, your users may even thank you for it.

Swing Puzzler #1

February 15th, 2010

I don’t like programming puzzles. If a small piece of code does not do what it appears to be doing after skimming through it, it is either the problem in the code itself, or the underlying libraries that it is using. Code should be easy to read, and easy to understand. This is why i didn’t enjoy any of the “Java puzzles” sessions during the last few JavaOne conferences. I have the original book and i’ve seen the presentation slides. Personally, i don’t think that i can learn much from them – except seeing that the puzzles originate from the intricacies of the language specification, unfortunate naming of the core APIs, or the artificial restrictions of binary compatibility that resulted in the mess that is core Java generics.

Unfortunately, all of these are still part of the platform – whether we want them or not. Which is why i’d like to present you with this simple Swing program based on the code from QStorm in one of the Substance forums. Note that the following code does not use Substance and runs under the default look-and-feel.

public class Puzzle1 {
   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            JFrame frame = new JFrame("Puzzle 1");
            frame.setSize(new Dimension(300, 200));
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            final JTable table = new JTable();
            table.getSelectionModel().addListSelectionListener(
                  new ListSelectionListener() {
                     @Override
                     public void valueChanged(ListSelectionEvent e) {
                        if (e.getValueIsAdjusting())
                           return;

                        System.out.println("Table: "
                              + table.getRowCount() + ", model: "
                              + table.getModel().getRowCount());
                     }
                  });
            table.setAutoCreateRowSorter(true);
            table.setModel(new DefaultTableModel(
                  new Object[][] { new Object[] { "Steven", 10 } },
                  new Object[] { "Name", "Value" }));
            frame.add(table, BorderLayout.CENTER);

            JPanel controls = new JPanel(
                  new FlowLayout(FlowLayout.TRAILING));

            JButton selectAllRowsBtn = new JButton("Select all rows");
            selectAllRowsBtn.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                  table.selectAll();
               }
            });
            controls.add(selectAllRowsBtn);

            JButton resetModelBtn = new JButton("Reset model");
            resetModelBtn.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                  table.setModel(new DefaultTableModel());
               }
            });
            controls.add(resetModelBtn);

            frame.add(controls, BorderLayout.SOUTH);

            frame.setVisible(true);
         }
      });
   }
}

This is how the UI looks like – it has a table with one row, and two buttons on the bottom:

When the “Select all rows” button is clicked, the JTable.selectAll() is called:

When the “Reset model” is called, the table model is reset to an empty model (no rows):

After the table is created, a selection listener is added to it. It prints the number of table rows as returned by JTable.getRowCount() and as returned by JTable.getModel().getRowCount().

What is the last line printed to the console after the two buttons have been activated?

  • Table: 0, model: 0
  • Table: 1, model: 0
  • Table: 1, model: 1
  • None of the above

The core Substance look-and-feel library is in the feature freeze state, and it’s time to tie the loose ends. Over the next couple of weeks i will be updating documentation, fixing bugs and perhaps adding a few new skins. Along with that, i will polish the visuals of third-party components covered by the Substance plugins that i maintain, and today it’s time to talk about the date picker component from SwingX.

The ever-changing plans for Swing in JDK 7 (which went from grandiose to acceptable to almost non-existent) at one time included a new date picker component available in the core Swing library. While the fate of such a component has not been addressed in the five-hour press conference today, there are a number of open-source and commercial date picker components available for use in Swing applications. One of them comes from SwingX – a library that is supported by the matching Substance SwingX plugin.

The latest 6.0dev drop of Substance SwingX plugin aligns the visuals of the JXDatePicker component with those of editable comboboxes. The inset look, double border and flat button that responds to the mouse rollover – all of these add up to a consistent and polished appearance of your UI running under Substance 6.0. Let’s see a few screenshots.

Here is the date picker component under the Business skin in the latest 6.0dev drop:

https://substance.dev.java.net/release-info/6.0/date-pickers-business.png

Here, you can see four date pickers in different areas of the application – toolbar, sidebar, status bar and the general area. While under the Business sin there is not much visual difference, it becomes more evident under the Business Blue Steel skin:

https://substance.dev.java.net/release-info/6.0/date-pickers-business-bluesteel.png

Here, the toolbar has a darker shade of blue used on its controls, and sidebar / status bar use a lighter shade of blue. Notice how the component automatically picks up the colors for the background and the border based on the decoration area that hosts it.

Next up the Gemini skin:

https://substance.dev.java.net/release-info/6.0/date-pickers-gemini.png

Here, note how the date picker in the toolbar has picked up not only the lighter color for the border, but also the correct light color for the foreground and the arrow icon. The same can be seen under the Magellan skin:

https://substance.dev.java.net/release-info/6.0/date-pickers-magellan.png

with date pickers in different decoration areas picking the matching foreground / background colors. Finally, the date pickers under the Dust skin:

https://substance.dev.java.net/release-info/6.0/date-pickers-dust.png

You are more than welcome to take the latest 6.0dev drops of Substance and its plugins for a spin and report bugs / visual artifacts to the project mailing lists or forums:

After taking a deep dive into the intricacies of aligning text components, comboboxes, spinners and buttons in the latest 6.0dev drops of Substance look-and-feel, it’s time to talk about supporting different font settings.

As with precise micro-design, Karsten has pioneered the Swing work on matching the desktop font settings in his JGoodies Looks collection of look-and-feels. Along with the native font rasterizer (at least on Windows Vista and its Segoe UI 12 font), this is by far the most important part in creating an application that is visually consistent with the user desktop. Personally, i think that one of the biggest mistakes in Java 6 was staying with Tahoma 11 as the default font for the native Windows look-and-feel, followed closely by an equally baffling font choice in Nimbus.

After the JGoodies font policy layer has been adopted in Substance, it was extended to provide font policies for Mac, KDE and Gnome desktops. When you run a Substance-powered application under one of these (or Windows), it will query the desktop font settings, and adopt them for all the controls and title panes. While this may cause a form designed for Windows XP (Tahoma 11) to have controls overflowing the form bounds on Gnome (DejaVu Sans 13), it is a small price to pay – in my personal view.

Given the wide choice of fonts that Substance must support, the micro-design layer in Substance needs cannot use hard-coded pixel values for control insets, margins, gaps and strokes. This functionality has been present for quite some time, and now is extended to support the new alignment requirements.

Here is a screenshot of the relevant controls under the different Tahoma font sizes:

https://substance.dev.java.net/release-info/6.0/tahoma-no-guiders.png

and the same controls with guider lines showing the alignment of perceived vertical bounds and text baselines:

https://substance.dev.java.net/release-info/6.0/tahoma-guiders.png

If you’re interested to see what Substance 6.0dev can bring to your application, take it for a spin. You can also click the button below to launch a WebStart demo – switch to the “Alignment” tab and see the control alignment in action: