首页 > 解决方案 > GridBagLayout 忽略锚点

问题描述

我的 GridBagLayout 有一些问题我想把按钮放在屏幕的左侧,就像现在一样。我知道我的体重为 0,但将其更改为 1 会破坏星座,我不知道如何将两者存档。

它看起来如何

如果这有帮助

public class CreatePanel extends JPanel {

    private static final Insets WEST_INSETS = new Insets(5, 0, 5, 1);;

    public CreatePanel(JPanel mainPanel) {
        setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
        this.mainPanel = mainPanel;
        setPreferredSize(new Dimension(400, 200));
        setBackground(Color.GRAY);

        add(Box.createVerticalGlue());
        add(createGameLabel());
        add(Box.createRigidArea(new Dimension(0,100)));
        add(createJPanel());
        add(Box.createVerticalGlue());
        add(Box.createVerticalGlue());
    }

    private GridBagConstraints createGbc(int x, int y) {

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridwidth = 1;
        gbc.gridheight = 1;

        gbc.anchor = GridBagConstraints.FIRST_LINE_START;

        gbc.insets = WEST_INSETS;
        gbc.weightx = 0.0;
        gbc.weighty = 0.0;
        return gbc;
    }

    private JPanel createJPanel() {
        bottemPanel = new JPanel();
        bottemPanel.setBackground(Color.ORANGE);
        bottemPanel.setLayout(new GridBagLayout());

        gbc = createGbc(0,0);
        gbc.gridwidth=2;
        bottemPanel.add(createRandomWordButton(),gbc);
        gbc = createGbc(0,1);
        bottemPanel.add(createWordTextField(),gbc);
        gbc = createGbc(1,1);
        bottemPanel.add(createUseWordButton(),gbc);

        return bottemPanel;
    }

    private JLabel createGameLabel() {...}

    private JButton createUseWordButton() {...}

    private JTextField createWordTextField() {...}
}

标签: javaswinglayout-managergridbaglayout

解决方案


我知道我的体重为 0,但将其更改为 1 休息...

看起来您正在使用 BoxLayout 将子面板垂直居中。但是,默认情况下,JPanel 在可用空间中水平居中。因此,在您的 createJPanel 方法中尝试添加:

bottom.setAlignmentX(0.0f);

如果这不起作用,您可能需要为底部面板使用包装面板:

//return bottemPanel;
JPanel wrapper = new JPanel(); // 
wrapper.setAlignmentX(0.0f);
wrapper.add(bottom);
return bottomPanel;

或者另一种解决方案是添加一个weightx值为 1.0f 的虚拟组件。

JLabel dummy = new JLabel(" "); 
gbc.gridx = ?;
gbc.weightx = 1.0f;
add(dummy, gbc);

推荐阅读