0

我遇到了 GridBagLayouts 的问题。

我有一些组件如下图所示:

在此处输入图像描述

如果“顶部”组件收缩得足够小,我希望“中心”组件能够移动到“右上角”的底部边缘上方。但是,这显然会导致问题,因为它必须在网格中的不同行中才能这样做。

为了解决这个问题 - 我将整个右列定义为其自己的容器,并具有自己的布局管理器。我希望这两列能够独立运行,但是我遇到了同样的问题!我看不出这两个布局管理器是如何交互的。谁能解释我的问题是什么?

这是相关代码(在我的类扩展Applet):

public void init(){
    addComponents();
}

private void addComponents(){
    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    Left left = new Left();
    Top top = new Top();
    Center center = new Center();
    TopRight topRight = new TopRight();
    BottomRight bottomRight = new BottomRight();
    Bottom bottom = new Bottom();

    topRight.setPreferredSize(new Dimension(200,200));
    top.setPreferredSize(new Dimension(0,200));
    center.setPreferredSize(new Dimension(0,100));
    container.setPreferredSize(new Dimension(200,200));

    c.fill = GridBagConstraints.BOTH;

    c.gridx = 0; c.gridy = 0;
    c.gridwidth = 1; c.gridheight = 3;
    c.weightx = 0.2; c.weighty = 1.0;
    this.add(left,c);

    c.gridx = 1; c.gridy = 0;
    c.gridwidth = 1; c.gridheight = 1;
    c.weightx = 0.8; c.weighty = 0.8;
    this.add(top,c);

    c.gridx = 1; c.gridy = 1;
    c.gridwidth = 1; c.gridheight = 1;
    c.weightx = 0.8; c.weighty = 0.0;
    this.add(center,c);

    c.gridx = 1; c.gridy = 2;
    c.gridwidth = 1; c.gridheight = 1;
    c.weightx = 0.8; c.weighty = 0.2;
    this.add(bottom,c);

    JPanel container = new JPanel();
    container.setLayout(new GridBagLayout());

    c.gridx = 2; c.gridy = 0;
    c.gridwidth = 1; c.gridheight = 3;
    c.weightx = 0.0; c.weighty = 1.0;
    this.add(container,c);

    GridBagConstraints c2 = new GridBagConstraints();
    c2.fill = GridBagConstraints.BOTH;

    c2.gridx = 0; c2.gridy = 0;
    c2.gridwidth = 1; c2.gridheight = 1;
    c2.weightx = 0.0; c2.weighty = 0.0;
    container.add(topRight,c2);

    c2.gridx = 0; c2.gridy = 1;
    c2.gridwidth = 1; c2.gridheight = 1;
    c2.weightx = 0.0; c2.weighty = 1.0;
    container.add(bottomRight,c2);
}

注意:显示的每个组件(左、上等)都是 JPanel 的扩展 - 每个组件都覆盖了它的 paint(Graphics g) 方法以用一些颜色填充它。

在此先感谢,并为长期阅读感到抱歉,

乔纳森

4

1 回答 1

0

我解决了这个问题。它与我不必要地设置 Top 组件的首选高度有关 - 当我删除该行时,它就像我想要的那样工作。

于 2012-11-06T04:16:12.547 回答