我有两个Java类:
GridBagLayout,这样我就可以将class2的实例添加到列表中。我的代码如下:
Class1
class2 one = new class2();
class2 two = new class2();
this.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(6,2,6,40);
gbc.gridx = 0;
this.add(new JLabel("Name"), gbc);
gbc.gridx = 1;
this.add(new JLabel("Surname"), gbc);
gbc.gridx = 2;
this.add(new JLabel("Age"), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
this.add(one, gbc);
gbc.gridy = 2;
this.add(two, gbc);Class2扩展JPanel
this.setLayout(new GridBagLayout());
GridBagConstraints gridBagCons = new GridBagConstraints();
gridBagCons.insets = new Insets(6,2,6,4);
gridBagCons.gridx = 0;
this.add(new JTextField(10), gridBagCons);
gridBagCons.gridx = 1;
this.add(new JTextField(10), gridBagCons);
gridBagCons.gridx = 2;
this.add(new JTextField(10), gridBagCons);因此,它不起作用,它显示标题:名称、姓氏和年龄,以及从class2导入的GridBagLayout of class1第一列中的其他两个面板。我希望标题与从class2导入的文本字段对齐。
拜托你能帮我看看吗。
发布于 2014-04-03 13:54:25
您需要在gridwidth上设置GridBagConstraints。您的示例创建了一个3x3网格。标题在第一行。在第二行中,第一个位置包含整个Class2面板,第2和第3列没有任何内容。第三排也是一样。
放
gbc.gridWidth = 3;
在添加Class2面板之前。
若要对齐文本字段,请将
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;对于“标头”的每个标签和第2类的每个文本字段,手动设置嵌体不会正确调整大小。
发布于 2014-04-03 14:13:03
您可以手动调整内嵌。
gbc.insets = new Insets(6,2,6,90);
gbc.gridx = 0;
this.add(new JLabel("Name"), gbc);
gbc.insets = new Insets(6,0,6,-20);
gbc.gridx = 1;
this.add(new JLabel("Surname"), gbc);
gbc.insets = new Insets(6,0,6,0);
gbc.gridx = 2;
this.add(new JLabel("Age"), gbc);
gbc.gridx = 0;
gbc.gridwidth = 3;
gbc.gridy = 1;
this.add(one, gbc);
gbc.gridy = 2;
this.add(two, gbc);不过,如果不使用第二个类并以另一种方式添加文本字段,可能会更好,这取决于您的实现。
编辑:这里的是一种使用GridLayout动态添加字段的方法
public class AddingFields {
static GridLayout gl = new GridLayout(2, 3, 20, 10);
static JFrame frame = new JFrame();
public static void main(String[] args) {
new AddingFields();
createAdderFrame();
}
AddingFields() {
frame.setLayout(gl);
frame.add(new JLabel("Name"));
frame.add(new JLabel("Surname"));
frame.add(new JLabel("Age"));
frame.add(new JTextField(10));
frame.add(new JTextField(10));
frame.add(new JTextField(10));
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
static void createAdderFrame() {
JFrame adder = new JFrame();
JButton addButton = new JButton("Add row");
adder.add(addButton);
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
gl.setRows(gl.getRows() + 1);
frame.add(new JTextField(10));
frame.add(new JTextField(10));
frame.add(new JTextField(10));
frame.pack();
}
});
adder.pack();
adder.setVisible(true);
}
}https://stackoverflow.com/questions/22839391
复制相似问题