What are the best practices of Java Swing development

swing

While doing my pre-research for this question, I found that there isn't much well-organized information about Java Swing best practices out there on the Internet. So I figure I'll give Stack Exchange a shot at building that One Great List.

What are the best practices of Java Swing development? What have you found to work for you, and why?

Best Answer

I can only answer for what's worked for me. Other commentors have pointed out that Java GUIs in general fall into the 'uncanny valley' of not-quite-native look and feel, and I don't dispute this.

Make good use of the Action API. It lets you better encapsulate different actions your user will perform and allow you to wire them up to shortcuts, accelerator keys, buttons and other input objects much more easily.

Use an appropriate layout manager. GridBagLayout is extremely powerful, but I would go so far as to say it is unmaintainable without an excessive amount of comments. When I run static code analysis tools such as Sonar over an older GUI app I maintain, it always points out the massive amounts of magic numbers to make the GridBags layout just right. I've had plenty of success with GroupLayout, which avoids having to specify pixel-perfect alignment.

If you think you need a JDialog... you probably don't. Dialog boxes are horrible, in terms of user experience -- this application decided to use them for every menu and form, and to enforce always-on-top rules in bizarre ways. This turned into a maintenance nightmare when we actually did need to alert something over the menu. Cue frustrated clicking on unfocusable -- and thus undismissable -- dialogs.

Use SwingWorker instead of rolling your own multithreading, where appropriate. It's very easy to extend SwingWorker and do some longrunning task while providing regular updates back to the GUI. Think downloading a client update. It'll handle the worker thread scheduling for you and let you publish download percentages back to the view, so you can update your ProgressBar or what have you.

That's all I can suggest, in my admittedly limited experience.