GridBagLayout 控制 Swing 中的对齐方式

GridBagLayout controls alignment in Swing

我有这个 window,上面几乎全是 JScrollPane。我正在向它添加大按钮(附有图像)并且我希望它们继续向下添加,这就是为什么我使用 GridBagLayout 并且每次添加按钮时我都设置 gbc.gridx, gbc.gridy .

滚动的东西工作正常:

但问题是,当我添加少于 4 个按钮时,它们会对齐到行的中心,而不是像我希望的那样对齐到左侧。像这样

知道如何将它们左对齐吗?我尝试了 gbc.anchorgbc.fill 但没有成功。谢谢

这是我的 JScrollPane

中的面板
private JPanel imagesPanel() {
        JPanel panel = new JPanel(new GridBagLayout());

        int x = 0;
        int y = 0;

        GridBagConstraints c = new GridBagConstraints();
        //c.anchor = GridBagConstraints.NORTHWEST;

        //add all images as buttons
        List<PuzzleImage> imageList = _imageLoader.getImageCollection().getAllImages();
        for(PuzzleImage puzzleImage : imageList) {
            for(int i = 0; i < 1; i++) { //ignore this, just for debugging. i add 3 images
                ImageIcon imageIcon = new ImageIcon(puzzleImage.getLowScaleImage());

                c.gridx = x;
                c.gridy = y;
                c.weightx = 1.0;

                JButton btn = new JButton(imageIcon);
                btn.setPreferredSize(new Dimension(ImageLoader.LOW_SCALE_IMAGE_SIZE, ImageLoader.LOW_SCALE_IMAGE_SIZE));
                panel.add(btn, c);

                x++;
                if(x>=4) {
                    x = 0;
                    y++;
                }
            }
        }

        return panel;
    }

没有您的代码很难给出准确的答案,但这里有一个可能的解决方案:

您可以将包含所有图片的 JPanel 嵌套在另一个 JPanel 中,使其锚定在左侧,如下所示:

JPanel pictures = /* already defined */;
JPanel container = new JPanel(new BorderLayout());

container.add(pictures, BorderLayout.WEST);
//add container to your scroll container

but the problem is, when I add less than 4 buttons, they align to the center of the row, instead to the left side as I want them to

至少有一个组件需要具有大于 0 的 weightx 约束。

阅读 How to Use GridBagLayout 上的 Swing 教程部分。解释约束如何工作的部分将提供更多信息。

你为什么还要使用 GridBagLayout?你的最后一个问题得到了一个简单的解决方案:FlowLayout in Swing doesn't move to the next line。那么你甚至不需要担心约束。

或者您可以使用 GridLayout 您只需定义您希望 4 列和组件自动换行。您可能需要嵌套面板,这样组件就不会 shrink/grow,具体取决于框架的大小。

基本代码为:

JPanel wrapper = new JPanel();
JPanel buttons = new JPanel( new GridLayout(0, 4) );

for (...)
{
    JButton button = new JButton(...);
    buttons.add( button );
}

frame.add(wrapper);