【发布时间】:2011-11-13 20:56:24
【问题描述】:
我需要知道如何构建一个可以动态调整大小的 java 布局。布局设置为 4 个面板,从上到下堆叠:
顶部面板是一个 GridLayout(4,2)。每行是一个标签和一个文本字段 第二个面板是一个按钮 第三个面板是网格布局 (n,2)。我会在一分钟内到达 n 底部面板也是一个按钮
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();
}
【问题讨论】:
-
请提供一个sscce,显示您如何在按钮侦听器中调用
pack()。 -
@trashgod 我已经发布了 actionperformed 方法(无论如何都是相关部分)。我不确定 pack() 会有什么帮助,因为 GridLayout 会自动将组件的大小设置为均匀分布在整个框架中
-
@ewok 然后在此处发布基于 SSCCE 的可运行代码,然后您会看到布局的许多奇迹 :-)
-
@mKorbel 我完全可运行的代码约为 45 kloc。我不相信我可以发布它。
-
请注意,SSCCE 不是您的“完全可运行代码”。请真正阅读 SSCCE 上的文件。