views:

41

answers:

2

Is there a library that makes it possible to write Swing based GUIs similar to the manner done by SwingBuilder in Groovy?

I am hoping to develop a Java GUI application without embedding Groovy or another complete programming language in Java, and I find the standard Java syntax rather tedious.

+1  A: 

I'm not aware of such a library, though something similar would be possible (without named parameters, though, which reduces readability). Someone may have converted SwingBuilder to java.

[Looks like you can get java source for SwingBuilder at http://kickjava.com/src/groovy/swing/SwingBuilder.java.htm. I don't know how current that is]

About the closest you can come in plain java is to use the "double curly trick" (which isn't really a trick, just an anonymous inner class definition).

The SwingBuilder example on your referenced page:

new SwingBuilder().edt {
    frame(title:'Frame', size:[300,300], show: true) {
    borderLayout()
    textlabel = label(text:"Click the button!", constraints: BL.NORTH) 
    button(text:'Click Me',
           actionPerformed: {
               count++;
               textlabel.text = "Clicked  ${count} time(s).";
               println "clicked"},
               constraints:BL.SOUTH)
    }
}

could be written something like the following in Java

new JFrame() {{
    setTitle("Frame");
    setSize(300,300);
    setLayout(new BorderLayout());
    textlabel = new JLabel("Click the button!");
    add(textlabel, BorderLayout.NORTH);
    add(new JButton("Click Me") {{
        addActionListener(new ActionListener() {
            @Override public void actionPerformed(ActionEvent e) {
                count++;
                textlabel.setText("Clicked " + count + " time(s).");
                System.out.println("clicked");
        }});
    }}, BorderLayout.SOUTH);
    setVisible(true);
}};

NOTE: The problem here is that when you use

new SomeClass() {{ ... }}

it's actually creating a new class definition. I wouldn't recommend doing it very often because of this.

Scott Stanchfield
A: 

I went down this path at one point, then I found MiGLayout - unless I'm using a split pane, I can generally lay out each of my views in a single panel, with a minimum of hassle. There is a tad of a learning curve, but once you are over the hump, you can knock out a really nice looking GUI in almost no time.

The whole paradigm of nesting panels inside other panels isn't clean for a lot of designs - you wind up fighting the layout manager.

Kevin Day
Looks good to me. Thanks.
Muhammad Alkarouri