如何使用 GridBagLayout 防止组件抖动?

问题描述

我有一个 GUI,其中四个组件使用 GridBagLayout 并排布置。当我向右调整窗口大小时,最左边的组件会抖动,当我向左调整大小时,最右边的组件会抖动。

这是一个例子:

import javax.swing.*;
import java.awt.*;

public class GBLShakeTest extends JPanel {
    public static void main(String[] args) {
        JFrame frame = new JFrame("GBLShakeTest");
        frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(500,500));
        frame.add(new GBLShaketest());
        frame.pack();
        frame.setLocationRelativeto(null);
        frame.setVisible(true);
    }

    public GBLShaketest() {
        super(new GridBagLayout());
        add(new JTextArea("component 1"),new GridBagConstraints(0,1,GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(0,0),0));
        add(new JTextArea("component 2"),new GridBagConstraints(1,0));
        add(new JTextArea("component 3"),new GridBagConstraints(2,0));
        add(new JTextArea("component 4"),new GridBagConstraints(3,0));
    }
}

它甚至发生在仅使用 JButton 的 GridBagLayout demo from oracle 上。向右调整大小没问题,但是当您向左放大窗口时,右侧的 Button 会抖动。 有谁知道如何解决这个问题?

解决方法

这绝对是 GridBagLayout 中的一个错误。我找不到解决方法,至少没有使用 GridBagLayout。

似乎发生的是,对于某些容器大小,GridBagLayout 将第一个组件的 X 坐标从 0 更改为 1。如果只有第一个组件的 weightx 非零,则不会出现问题(这让我怀疑这是浮点 weightx 值不准确的问题,但我还没有尝试深入研究 GridBagLayout 源以确认这一点) .

另一种选择是使用 SpringLayout。 SpringLayout 很难使用,但它可以做很多 GridBagLayout 可以做的事情,只需做一些工作。 (编写过使用 Motif 的 XmForm 小部件的代码的人会认识到其他组件的附件的使用,尽管 SpringLayout 的工作方式并不完全相同。)

SpringLayout layout = new SpringLayout();
setLayout(layout);

add(new JTextArea("component 1"));
add(new JTextArea("component 2"));
add(new JTextArea("component 3"));
add(new JTextArea("component 4"));

Component previous = null;
for (Component c : getComponents()) {
    // Attach component to top and bottom of container.
    layout.putConstraint(
        SpringLayout.NORTH,c,SpringLayout.NORTH,this);
    layout.putConstraint(
        SpringLayout.SOUTH,SpringLayout.SOUTH,this);

    if (previous != null) {
        // Attach component's left (west) edge to previous component's
        // right(east) edge.
        layout.putConstraint(
            SpringLayout.WEST,SpringLayout.EAST,previous);
    }

    previous = c;
}

// Bind this container's right (east) edge to the right (east) edge
// of the rightmost child component.
Component lastComponent = getComponent(getComponentCount() - 1);
layout.putConstraint(
    SpringLayout.EAST,this,lastComponent);