微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

GridBagLayout 忽略锚点

如何解决GridBagLayout 忽略锚点

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

How it looks atm

If that helps

public class CreatePanel extends JPanel {

    private static final Insets WEST_INSETS = new Insets(5,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() {...}
}

解决方法

我知道我的体重为 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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。