Clean Code with Swing and Scala

I guess everybody who knows Java and Swing also knows the Swing Tutorial. It is a great source of information if you want to learn Swing. It is also a major catastrophy when it comes to structuring code. The problem is: Lots of people miss critical information contained in the tutorial like ‘Everything concerned with Swing must happen in the EDT’ but they seem to suck up the messy way to structure code like a sponge.

This might result in code like the one below. It is actually Scala code, but that shouldn’t matter much. The only piece that is a little special are the calls to Binder, which is a little Swing Binding Framework which I introduced a couple of weeks ago.

private def createPersonPanel(p : PersonEditor) = {
  1.         val panel = new JPanel()
  2.         val layout = new GridBagLayout()
  3.         val c = new GridBagConstraints()
  4.         c.gridx = 0
  5.         c.gridy = 0
  6.  
  7.         panel.setLayout(layout)
  8.  
  9.         c.fill = 0
  10.         panel.add(new JLabel("firstname"), c)
  11.  
  12.         c.fill = 1
  13.         c.gridx += 1
  14.         c.weightx = 1
  15.         val firstnameTF = new JTextField()
  16.         panel.add(firstnameTF, c)
  17.         Binder.bind(p.firstname, firstnameTF)
  18.  
  19.         c.fill = 0
  20.         c.weightx = 0
  21.         c.gridx = 0
  22.         c.gridy += 1
  23.  
  24.         panel.add(new JLabel("lastname"), c)
  25.         c.fill = 1
  26.  
  27.         c.gridx += 1
  28.         val lastnameTF = new JTextField()
  29.         Binder.bind(p.lastname, lastnameTF)
  30.         panel.add(lastnameTF, c)
  31.         c.fill = 0
  32.         c.weightx = 1
  33.         c.gridy += 1
  34.         c.anchor = GridBagConstraints.SOUTHEAST
  35.         val button = new JButton("save")
  36.         Binder.bind(p.save, button)
  37.         panel.add(button, c)
  38.         panel
  39.     }

What is so bad about this piece of crap … ähm … code?

The method is long. 38 lines is about 10 times longer than healthy for a method.

There is tons of code duplication.

The method does lots of different things: creating components, adding them to a panel, configuring the layout.

There is a strong dependency on the order of commands. We can’t just move stuff up or down in the method and still hope the result will be something reasonable, even if we stick to rearrangements allowed by the compiler.

All this together makes the method extremely hard to understand. How long does it take to understand what kind of GUI results? Don’t bother to much, I help. It looks like this:

and if you resize it, it looks like this

Arguably the result looks just as ugly as the code, but once the code is clean we might be able to improve on the visual design as well.

If you don’t see it in the code, you might see it in the images: There are three different ways JComponents are handled by the method: JLabels are in the left column and don’t resize. The JTextFields are in the right column and do resize and the JButton doesn’t resize and is in the buttom right. In the code this is completely hidden in the manipulation of the GridBagConstraint. So lets make it explicit in the code:

private def addToLabelColumn(
  1.         panel : JPanel,
  2.         component : JComponent,
  3.         row : Int) {
  4.         val c = new GridBagConstraints()
  5.         c.gridx = 0
  6.         c.gridy = row
  7.         c.weightx = 0
  8.         c.fill = 0
  9.         panel.add(component, c)
  10.     }
  11.  
  12.     private def addToComponentColumn(
  13.         panel : JPanel,
  14.         component : JComponent,
  15.         row : Int) {
  16.         val c = new GridBagConstraints()
  17.         c.gridx = 1
  18.         c.gridy = row
  19.         c.weightx = 1
  20.         c.fill = 1
  21.         panel.add(component, c)
  22.     }
  23.  
  24.     private def addButton(
  25.         panel : JPanel,
  26.         component : JButton,
  27.         row : Int) {
  28.         val c = new GridBagConstraints()
  29.  
  30.         c.weightx = 1
  31.         c.gridx = 1
  32.         c.gridy = row
  33.         c.fill = 0
  34.         c.anchor = GridBagConstraints.SOUTHEAST
  35.         panel.add(component, c)
  36.     }
  37.  
  38.     private def createPersonPanel(p : PersonEditor) = {
  39.         val panel = new JPanel()
  40.         val layout = new GridBagLayout()
  41.         panel.setLayout(layout)
  42.  
  43.         addToLabelColumn(panel, new JLabel("firstname"), 0)
  44.  
  45.         val firstnameTF = new JTextField()
  46.         Binder.bind(p.firstname, firstnameTF)
  47.         addToComponentColumn(panel, firstnameTF, 0)
  48.  
  49.         addToLabelColumn(panel, new JLabel("lastname"), 1)
  50.  
  51.         val lastnameTF = new JTextField()
  52.         Binder.bind(p.lastname, lastnameTF)
  53.         addToComponentColumn(panel, lastnameTF, 1)
  54.  
  55.         val button = new JButton("save")
  56.         Binder.bind(p.save, button)
  57.         addButton(panel, button, 2)
  58.         panel
  59.     }

I introduced three methods. One for adding a JLabel, one for adding a JComponent and one for adding JButtons. These handle the arrangement of components on a JPanel. The total length of the code increased because we create the GridBagConstraints insided the methods and have to set all properties and don’t rely anymore on the previous step to leave the constraint in a specific state.

If we now look at the createPersonPanel we’ll get a strong fealing of repetition in various places:

  • each call to add* methods takes the same JPanel as an argument. We can improve on this by creating a Builder wich crates the panel, contains the add* methods and can return the fully configured panel at the end.
  • for each property we create a JLabel, a JTextField, bind the property to the later and add both to the JPanel. We can fix this by encapsulating it in a seperate method.

The result might look like this:

  1.     case class PanelBuilder() {
  2.         val panel = new JPanel()
  3.         val layout = new GridBagLayout()
  4.         panel.setLayout(layout)
  5.  
  6.         def add(components : (JLabel, JComponent), row : Int) {
  7.             addToLabelColumn(components._1, row)
  8.             addToComponentColumn(components._2, row)
  9.         }
  10.  
  11.         def add(
  12.             component : JButton,
  13.             row : Int) {
  14.             val c = new GridBagConstraints()
  15.  
  16.             c.weightx = 1
  17.             c.gridx = 1
  18.             c.gridy = row
  19.             c.fill = 0
  20.             c.anchor = GridBagConstraints.SOUTHEAST
  21.             panel.add(component, c)
  22.         }
  23.  
  24.         private def addToLabelColumn(
  25.             component : JComponent,
  26.             row : Int) {
  27.             val c = new GridBagConstraints()
  28.             c.gridx = 0
  29.             c.gridy = row
  30.             c.weightx = 0
  31.             c.fill = 0
  32.             panel.add(component, c)
  33.         }
  34.  
  35.         private def addToComponentColumn(
  36.             component : JComponent,
  37.             row : Int) {
  38.             val c = new GridBagConstraints()
  39.             c.gridx = 1
  40.             c.gridy = row
  41.             c.weightx = 1
  42.             c.fill = 1
  43.             panel.add(component, c)
  44.         }
  45.  
  46.     }
  47.  
  48.     private def create(name : String, property : Property[String]) : (JLabel, JComponent) = {
  49.         val textField = new JTextField()
  50.         Binder.bind(property, textField)
  51.         (new JLabel(name), textField)
  52.     }
  53.  
  54.     private def create(name : String, action : => Unit) = {
  55.         val button = new JButton("save")
  56.         Binder.bind(action, button)
  57.         button
  58.     }
  59.  
  60.     private def createPersonPanel(p : PersonEditor) = {
  61.         val builder = PanelBuilder()
  62.  
  63.         builder.add(create("firstname", p.firstname), 0)
  64.         builder.add(create("lastname", p.lastname), 1)
  65.         builder.add(create("save", p.save), 2)
  66.  
  67.         builder.panel
  68.     }

The PanelBuilder has now two simple public add methods. In order to imitate the method signitures in Java we would have to create a couple of helper classes and interfaces. It would make the code less compact but this shouldn’t be a serious problem. Creation of the various components is just as the binding extracted in two create Methods. The createPersonPanel has now only 5 lines of code. Adding another property to the form should be trivial. Changing the extremely simplistic layout should be trivial and is at least limited to a single small class. I think this is pretty much OK for a first step toward clean swing code. So I leave it like it is right now. Although I do have further plans for this.

I hope most of you agree that the code is much easier to understand and maintain in the form it is right now. But is it really worth the effort? Some might say no. If the whole application would consist of only this little panel. I would agree. But a Swing application typically does not have a single panel with two textfields and a button. But tens or even hundreds of panels. Many consisting of large collections of components. If you have to maintain such a monster, would you prefer createPersonPanel methods like the last one, or would you prefer the first version? What if the customer if finally fed up with your crappy layout and insists on proper spacing between the labels and the JTextFields or other components?

All this is pretty nice when you start a new Swing application. But what if you have an existing Swing application? One with convoluted code just as the Swing Tutorial taught you? Well … start changing it now. Don’t sit down for two months and rewrite all your code, but find pieces of code duplication and extract them. It will be a long way, but you wont reach the end if you don’t start walking.

But what if you are not using Swing, but writing a web application? Well it really shouldn’t matter much. Your PanelBuilder might be written in JavaScript, or create HTML, but the principle is the same: Seperate creation of components, layout of components and binding of components to properties and actions.

Share:
  • DZone
  • Digg
  • del.icio.us
  • Reddit
  • Facebook
  • Twitter