首页 文章

Swing:GridBagLayouts锚点不能嵌套在其他GridBagLayout中

提问于
浏览
0

我正在设置第一个 GridBagLayout 到主 JPanel . 在此面板中,添加了其他十个面板(outerConstraints) . 子面板包含一定数量的文本,应该将WEST放置在新布局和 innerConstraints 中 . 但他们居中 .

稍微测试一下后,我发现文本/图像被放置在WEST,但只有,如果 outerConstraints 没有水平填充白色面板 . 问题是,我无法删除此命令,因为我需要每个面板具有相同的宽度 .

是否有可能允许 outerConstraints 填充AND以使其嵌套 GridBagLayout 定位文本?

setLayout(new GridBagLayout());

GridBagConstraints outerConstraints = new GridBagConstraints();
outerConstraints.insets = new Insets(5, 5, 5, 5);
outerConstraints.fill = GridBagConstraints.HORIZONTAL;    // seems to be reason, but needed.

    for (int i = 0; i < 10; i++) {

        outerConstraints.gridx = i % 2;
        outerConstraints.gridy = i / 2;

        JPanel agentVisitCard = new JPanel();
        add(agentVisitCard, outerConstraints);

        GridBagConstraints innerConstraints = new GridBagConstraints();
        innerConstraints.anchor = GridBagConstraints.WEST;                 //fails
        innerConstraints.insets = new Insets(5, 5, 5, 5);

        GridBagLayout layout = new GridBagLayout();
        agentVisitCard.setLayout(layout);

        (...)

        JLabel label = new JLabel("Agent " + (i + 1) + ":");

        innerConstraints.gridx = 0;
        innerConstraints.gridy = 0;

        agentVisitCard.add(label, innerConstraints);

代理3未左对齐:
enter image description here

1 回答

  • 2

    锚没有工作的原因是因为组件没有重量 . 如果没有这个,给予组件的区域只是所需的最小尺寸,即组件本身的大小,而不是更大 .

    以下是swing tutorials(在 weightx, weighty 部分下)的引用解释:

    除非您为weightx或weighty指定至少一个非零值,否则所有组件在其容器的中心聚集在一起 . 这是因为当权重为0.0(默认值)时,GridBagLayout会在其单元格网格与容器边缘之间放置任何额外空间 .

    默认情况下,weightx和weighty为0,这就是为什么它不适合你 . 由于您只想水平锚定它,因此将weightx设置为非零值可以使其工作 . 如果你想要一个垂直锚,你也需要设置一个重量 .

    有关如何使用weightx和weighty值的说明如下:

    通常,权重指定为0.0和1.0作为极值:必要时使用其间的数字 . 较大的数字表示组件的行或列应该获得更多空间 .

    虽然他们建议使用0.0到1.0之间的值,但没有必要 . 任何 double 值都可以 . 重要的是组件重量之间的比例,如果你有几个组件 .

相关问题