我在一个对话框中有4个JPanel,它们使用GridBagLayout垂直排列。所有这些都应该有理想的长度。
除了Panel 2之外,每个东西都可以正常工作,其内容根据组合框的选择动态添加和删除,该组合框也包含在同一个Panel中且不是固定大小。由于内容的性质,我也为Panel 2本身使用了GridBagLayout,并且最初设置Min。,Max。 Panel的PreferredSize和内容的最大可能尺寸,并希望此面板坚持这个尺寸。但是这不起作用,因为Panel2也受Panel1和Panel2内容的影响(它们的内容也被添加和删除但总是具有相同的大小)
有什么建议吗?由于这里施加了奇怪的限制,他们想要添加面板的照片,但是由于这些特殊的限制
确定查看问题的评论后,我将在这里添加一些代码片段
JPanel dataPanel=new JPanel();
dataPanel.setLayout(new GridBagLayout());
final GridBagConstraints constraintAmpliaciones = new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0);
//dataPanel.add(panelIdOrigen, constraintAmpliaciones);
constraintAmpliaciones.gridy++;
dataPanel.add(panel1,constraintAmpliaciones );
constraintAmpliaciones.gridy++;
dataPanel.add(panel2,constraintAmpliaciones);
constraintAmpliaciones.gridy++;
dataPanel.add(panel3, constraintAmpliaciones);
constraintAmpliaciones.gridy++;
dataPanel.add(panel4,constraintAmpliaciones);
Panel2(有问题的)是这样的:
void initComponents() {
panelGeneral = new JPanel();
panelGeneral.setLayout(new GridBagLayout());
panelGeneral.add(panelLarger, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
/**
* here for dimension,I have tried different sizes including the fixed size in pixels of panelLarger
*/
Dimension dimension = new Dimension((int) panelGeneral.getPreferredSize().getWidth(), (int) panelGeneral.getPreferredSize().getHeight());
panelGeneral.setMaximumSize(dimension);
panelGeneral.setPreferredSize(dimension);
panelGeneral.setMinimumSize(dimension);
this.add(panelGeneral);
}
/**
* is called upon combox selection
*/
void updateComponents() {
if (selection1) {
panelGeneral.remove(panelLarger);
panelGeneral.add(panelSmaller, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
} else {
panelGeneral.remove(panelSmaller);
panelGeneral.add(panelLarger, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
}
}
答案 0 :(得分:0)
我不确定我是否理解正确,但你可以试试这个:
将Panel2中的JLabel放在Panel2中的所有其他组件下面(我假设Panel2在它没有所有可能的组件时垂直地太小)。确保Jlabel文本设置为""所以它对用户来说似乎是不可见的。
在此之后,您希望将JLabel的GridBagConstraints设置为fill = VERTICAL和weighty = 1.0。
这应该将所有其他组件推送到Panel2的顶部,因为JLabel在它们下面垂直扩展,它应该保留Panel的大小并防止它收缩。我想如果你确切地知道每次图像的大小,你可以放入一个这样大小的JLabel,而不是让它垂直缩放。
Swing可能很棘手,因为我无法看到你的所有代码,但我经常在我的GUI中使用隐藏的JLabel来使面板按照我想要的方式进行扩展。