jastrachan | 8 Jul 10:14 2004
Picon

Re: JTree in GroovySwing

On 8 Jul 2004, at 08:13, Jeremy Aston wrote:
> Hi,
>
> I am new to Groovy and cannot work out how to get a JTree object added 
> to a scroll panel.  I have set the JTree object up, assigning it to a 
> variable eg:
>
> 	topNode = new DefaultMutableTreeNode( "Projects" )
> 	projectTree = new JTree( topNode )
>
> I then assumed I would be able to do something like (within a 
> swingbuilder):
>
>   	scrollPane( constraints:BorderLayout.CENTER, 
> border:BorderFactory.createRaisedBevelBorder() ) {
> 		projectTree
> 	}
>
> But this does not produce anything in the scroll pane.
>
> If I do:
>
>   	scrollPane( constraints:BorderLayout.CENTER, 
> border:BorderFactory.createRaisedBevelBorder() ) {
> 		tree()
> 	}

There are 2 approaches. One is to use the normal Java APIs to add to 
your scroll pane...

     s = scrollPane(...) {
     }
     s.add(tree)

Or to create the tree using the swing builder

   	scrollPane( constraints:BorderLayout.CENTER, 
border:BorderFactory.createRaisedBevelBorder() ) {
		tree = tree(model: new DefaultTreeModel(topNode))
	}

(we could maybe make things easier by adding a pseudo property called 
'root' or something to avoid having to wrap the root node in a 
TreeModel

> I get the default sample tree in the scroll pane therefore I have also 
> tried:
>
>   	scrollPane( constraints:BorderLayout.CENTER, 
> border:BorderFactory.createRaisedBevelBorder() ) {
> 		projectTree = tree( topNode )
> 	}
>
> But that does not produce anything in the scroll pane either.

That sounds like a bug in the SwingBuilder - we should be able to get 
that to work

> Also once I have the JTree how do I assign a double click action to it 
> (or for that matter to a JList?)  The Sun recommended way in Swing is 
> to use an anonymous inner MouseAdapter class but obviously I cannot do 
> that in groovy.  I can write a separate Java class but is there a 
> better way that uses say action{} or something similar?

You can do this in groovy using a magic property of the listener's 
method name.

e.g.

widget.mouseClicked = { event | println "I've just been clicked with 
event ${event}" }

or in markup this would be...

     tree(model: whatever, mouseClicked: { event | println "I've just 
been clicked with event ${event}" })

James
-------
http://radio.weblogs.com/0112098/


Gmane