Reputation: 11
I am using GroupLayout to construct my frame in Java 7 on Windows 7 (64-bit). Following is the structure of layout that I have used seeing the Oracle example on GroupLayout.
Desired Layout:
+------------------------------------------+
| [Label1] [ComboBox1] |
| [Label2] [TextField1] [Button1] |
| [Label3] [TextField2] [Button2] |
| [Label4] [ComboBox2] |
+------------------------------------------+
My design in code:
layout.setHorizontalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING))
.addComponent(Label1)
.addComponent(Label2)
.addComponent(Label3)
.addComponent(Label4)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING))
.addComponent(ComboBox1)
.addComponent(TextField1)
.addComponent(TextField2)
.addComponent(ComboBox2)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING))
.addComponent(Button1)
.addComponent(Button2)
);
layout.linkSize(SwingConstants.HORIZONTAL, Button1, Button2);
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE))
.addComponent(Label1)
.addComponent(ComboBox1)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE))
.addComponent(Label2)
.addComponent(TextField1)
.addComponent(Button1)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE))
.addComponent(Label3)
.addComponent(TextField2)
.addComponent(Button2)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE))
.addComponent(Label4)
.addComponent(ComboBox2)
);
I need to get this checked by more experienced person. Currently, this code results in alignment problem with sizes ComboBox1, ComboBox2
and TextField2
reduced significantly.
What are your suggestions to remedy this?
Upvotes: 1
Views: 482
Reputation: 36601
For those type of layouts, I would almost always opt for the FormLayout
of JGoodies. Of course this is not included in the standard JDK, so not sure whether this is an option for you.
One of the main benefits (imo) of that layout is that it allows to easily align components in columns, with a decent and controllable resize behavior.
Upvotes: 2
Reputation: 347194
Firstly, I'd personally avoid GroupLayout
, its not really meant for hand coding.
I'd use a GridBagLayout instead
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(label1, gbc);
gbc.gridx++;
add(comboBox1, gbc);
gbc.gridx = 0;
gbc.gridy++;
add(label2, gbc);
gbc.gridx++;
add(textField1, gbc);
gbc.gridx++;
add(button1, gbc);
gbc.gridx = 0;
gbc.gridy++;
add(label3, gbc);
gbc.gridx++;
add(textField2, gbc);
gbc.gridx++;
add(button2, gbc);
gbc.gridx = 0;
gbc.gridy++;
add(label4, gbc);
gbc.gridx++;
add(comboBox2, gbc);
Upvotes: 2