我正在使用Java Swing在eclipse中编写联系人列表应用程序.
如何获得仅包含列和行的简单表格布局?
我不想要行或列标签.
像这样的东西:
first name: john
middle name: franklin
last name: doe
@H_403_11@
名称可编辑的文本框等.
什么是最好的组件?
我还会在文本字段下面有按钮.
目前我有一个正确运行的JFrame.它拉出一个窗口,我的菜单选项正确.但是当我尝试这样做时:
myFrame.setLayout(new GridLayout(6,2));
@H_403_11@
我收到一个错误.我想有一个两列五行(可能是6)的网格布局.
我想在左栏上有一个标签,在右栏上有一个文本框.
然后在底部的两个按钮,居中.
最佳答案
您最好将字段和控件(按钮)分成单独的面板,这样您就可以为每个面板提供不同的布局管理器.
原文链接:https://www.f2er.com/java/438175.html我将使用BorderLayout从基础JPanel开始.
在此,我将在CENTER位置添加“fields”面板,在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);
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;
}
}
@H_403_11@