views:

104

answers:

3

I'm creating a GUI in Java using the GridBagLayout. Is there any way for me to create a component group so that I can pass the reference to the group and have access to all of them?

I've considered creating a panel and grouping the components that way, but I was wondering if there was another way that makes use of the complexity of the GridBagLayout.

Thanks so much!

A: 

The usual way is to use the JPanel as you suggested. Remember that the JPanel itself may have its own independent layout manager. So you may use a GridBagLayout on the JPanel to position the elements on the panel.

Vincent Ramdhanie
the only problem with this solution is that you can have an hard time to align outer and inner panels' components together...
Guillaume
@Guillaume It will take some careful planning to create an effective layout. But the way the components are grouped in the panels and how the panels are placed next to each other will affect the appearance of the alignment that you mention.
Vincent Ramdhanie
+2  A: 

You should think of panels as write-only. You bung your components on there, all set up and with the correct layout constraints. You (almost) never go and search through for components.

Instead, add the components to a Set (or similar) as you set up. Then you can do a very clean posh for loop over the collection to perform the appropriate task. A more advanced technique would be to have individual observers (listeners) refreshing the components from a model.

Tom Hawtin - tackline
I would never consider panels to be write-only. You must have some pretty static UIs. I quite frequently add and remove components, e.g. I might use the decoration pattern to add/remove things to a widget to indicate an error or indicate something. Also, many applications generate their views dynamically based on data or may populate a manually created UI from data using bean properties or reflection.
vickirk
"add" and "remove" are write/not-read operations. (I'd actually tend to hide/show rather that add/remove, although add/remove is useful for non-table tables.)
Tom Hawtin - tackline
Sorry, I misunderstood your comment, when you said write-only I assumed you meant whack the stuff on the panel and thats it, I apologies. I like gridbags and find replacing what is it there already and replacing it gives required results.
vickirk
+3  A: 

Well, if you can't create a bean with JLabel, JTextField and JButton for containing your group, you can always use Map in your main ui panel to register the elements while you add them. Some structure like

Map<K, List<Component>>

might work, where K is a identifier for a group. This way you dissociate the components from the way they are placed in ui.

Taisin