Group java components
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!
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.
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.
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.
精彩评论