我需要知道如何构建一个动态调整大小的java布局。布局设置有4个面板,从上到下堆叠:
顶部面板是GridLayout(4,2)。每个rown都是标签和文本字段 第二个面板是一个按钮 第三个面板是网格布局(n,2)。我会在一分钟内到达 底部面板也是一个按钮
n是动态变化的数字。第三个面板包含一个文本字段,然后是一个右侧有2个按钮的面板。我遇到的问题是我需要能够添加和删除这些行并让JFrame像我一样自动调整大小。我尝试将Frame设置为GridLayout(4,1),但是当我在actionPerformed()上更改大小时,它会均匀地扩展额外的空间。我想只在第三个面板中添加空格。
由于
编辑:ActionPerformed方法
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src == addTarget) {
targetChoosers.add(new JFileChooser(new File("C:\\")));
targets.add(new JTextField());
targetButtons.add(new JButton("Browse..."));
targetDeleters.add(new JButton("Delete"));
int numTargets = targets.size();
targetButtons.get(numTargets - 1).addActionListener(this);
targetDeleters.get(numTargets - 1).addActionListener(this);
bottomPanel.setLayout(new GridLayout(numTargets, 2));
bottomPanel.add(targets.get(numTargets - 1));
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
panel.add(targetButtons.get(numTargets - 1));
panel.add(targetDeleters.get(numTargets - 1));
bottomPanel.add(panel);
}
//...
else if (targetDeleters.contains(src)) {
int index = targetDeleters.indexOf(src);
targets.remove(index);
targetChoosers.remove(index);
targetButtons.remove(index);
targetDeleters.remove(index);
this.remove(submit);
this.remove(bottomPanel);
int numTargets = targets.size();
bottomPanel = new JPanel(new GridLayout(numTargets, 2));
for (int i = 0; i < targets.size(); i++) {
bottomPanel.add(targets.get(i));
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
panel.add(targetButtons.get(i));
panel.add(targetDeleters.get(i));
bottomPanel.add(panel);
}
this.add(bottomPanel);
this.add(submit);
}
//...
pack();
invalidate();
validate();
}