在将 GridBagLayout 添加到框架后更改组件的约束

Changing the constraints of a component in a GridBagLayout after they've been added to the frame

我在 Whosebug 上看过另外两篇关于这个的帖子,在这两篇文章中,解决方案都使用了 setConstraints(myComponent, anotherConstraint),当我尝试在 java 中使用它。

want to change an Inset in a gridbag layout dynamically

Change the component weight dynamically in GridBagLayout

我还能如何在按下按钮后更改组件的 weightx

实际问题是我在屏幕底部有两个组件,我需要将其中一个组件设置为按下按钮后屏幕的最大宽度。

I couldn't get setConstraints() to work..

那么好像密码是错误的。从红色面板的 RHS 与 Articuno 标签的 LHS 整齐对齐的事实来看,我怀疑包含红色面板的网格包单元格不会跨越超过一列,并且目前完全填满了该列。

可能还有其他原因,但总之minimal reproducible example我不会进一步推测。

这里是一个简单的例子,展示了如何做到这一点。请注意,必须调用 revalidate() 才能看到更改。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.image.BufferedImage;

public class FullWidthToggle {

    private JComponent ui = null;

    FullWidthToggle() {
        initUI();
    }

    public final void initUI() {
        if (ui != null) {
            return;
        }

        GridBagConstraints gbc = new GridBagConstraints();
        GridBagLayout gbl = new GridBagLayout();
        ui = new JPanel(gbl);
        ui.setBorder(new EmptyBorder(4, 4, 4, 4));

        BufferedImage image = new BufferedImage(
                160, 20, BufferedImage.TYPE_INT_RGB);
        gbc.insets = new Insets(5, 5, 5, 5);
        ui.add(new JLabel(new ImageIcon(image)), gbc);

        final JCheckBox checkBox = new JCheckBox("Full Width");
        gbc.gridx = 1;
        gbc.anchor = GridBagConstraints.LINE_START;
        ui.add(checkBox, gbc);

        final JLabel label = new JLabel("Am I full width?");
        label.setBorder(new LineBorder(Color.RED, 2));
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 2;
        ui.add(label, gbc);

        ActionListener actionListener = (ActionEvent e) -> {
            if (checkBox.isSelected()) {
                gbc.fill = GridBagConstraints.HORIZONTAL;
            } else {
                gbc.fill = GridBagConstraints.NONE;
            }
            gbl.setConstraints(label, gbc);
            ui.revalidate(); // <- important! 
        };
        checkBox.addActionListener(actionListener);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception useDefault) {
            }
            FullWidthToggle o = new FullWidthToggle();

            JFrame f = new JFrame(o.getClass().getSimpleName());
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setLocationByPlatform(true);

            f.setContentPane(o.getUI());
            f.pack();
            f.setMinimumSize(f.getSize());

            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}