GridBagLayout 忽略锚点

GridBagLayout ignores anchor

我的 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() {...}
}

I know I have my weight to 0 but changing it to 1 breaks...

您似乎在使用 BoxLayout 使子面板垂直居中。但是默认情况下,JPanel 在可用的 space 中水平居中。所以在你的 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);