您最好將字段和控件(按鈕)分爲不同的面板,這樣可以爲每個面板提供不同的佈局管理器。
我會從一個基地JPanel
開始使用BorderLayout
。
爲此,我將在CENTER
位置添加「字段」面板,並在SOUTH
位置添加控件(按鈕)。
對於場,我會使用一個GridBagLayout
,但我很挑剔像,併爲控制面板我可能會使用一個FlowLayout
(除非你有機會獲得一個不錯的ButtonLayout
經理;))
這意味着你可以用一些落得像
使用代碼樣本來更新
public class FormPanel extends JPanel {
private JTextField fldFirstName;
private JTextField fldMiddleName;
private JTextField fldLastName;
private JTextField fldDateOfBirth;
private JTextField fldEMail;
private JButton okButton;
private JButton cancelButton;
public FormPanel() {
setLayout(new BorderLayout());
add(createFieldsPane());
add(createButtonsPane(), BorderLayout.SOUTH);
}
public JPanel createButtonsPane() {
JPanel panel = new JPanel(new FlowLayout());
panel.add((okButton = createButton("Ok")));
panel.add((cancelButton = createButton("Cancel")));
return panel;
}
protected JButton createButton(String text) {
return new JButton(text);
}
public JPanel createFieldsPane() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 2, 2);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
panel.add(createLabel("First Name:"), gbc);
gbc.gridy++;
panel.add(createLabel("Middle Name:"), gbc);
gbc.gridy++;
panel.add(createLabel("Last Name:"), gbc);
gbc.gridy++;
panel.add(createLabel("Date of Birth:"), gbc);
gbc.gridy++;
panel.add(createLabel("EMail:"), gbc);
gbc.gridy = 0;
gbc.gridx++;
gbc.weightx = 1;
panel.add((fldFirstName = createField()), gbc);
gbc.gridy++;
panel.add((fldLastName = createField()), gbc);
gbc.gridy++;
panel.add((fldMiddleName = createField()), gbc);
gbc.gridy++;
panel.add((fldDateOfBirth = createField()), gbc);
gbc.gridy++;
panel.add((fldEMail = createField()), gbc);
JPanel filler = new JPanel();
filler.setOpaque(false);
gbc.gridy++;
gbc.weightx = 1;
gbc.weighty = 1;
panel.add(filler, gbc);
return panel;
}
protected JLabel createLabel(String text) {
return new JLabel(text);
}
protected JTextField createField() {
JTextField field = new JTextField(12);
return field;
}
}
另請參閱(受到嚴重譴責的)'GroupLayout'。 –
對於窗體我的投票去(一如既往)的JGoodies的FormLayout – Robin
沒有人的建議MigLayout? – MadProgrammer