JavaSwing GriBagLayout 放置问题

问题描述 投票:0回答:1

我尝试了很多方法将组件放在面板顶部,但它们始终站在面板中间。

private void setWestPanel() {
        westPanel = new JPanel();
        westPanel.setBackground(Color.GRAY);
        westPanel.setLayout(new GridBagLayout());
        westPanel.setPreferredSize(new Dimension(100, 100));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        JPanel westSubPanel = new JPanel();

        solveBtn = new JButton("Giải");
        resetBtn = new JButton("Xóa");
        exitBtn = new JButton("Thoát");

        solveBtn.setFocusable(false);
        resetBtn.setFocusable(false);
        exitBtn.setFocusable(false);

        solveBtn.setMnemonic('G');
        resetBtn.setMnemonic('X');
        exitBtn.setMnemonic('T');

        solveBtn.addActionListener(this);
        resetBtn.addActionListener(this);
        exitBtn.addActionListener(this);

        gbc.gridx = 0;
        gbc.gridy = 1;
        westPanel.add(solveBtn, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        westPanel.add(resetBtn, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridheight = GridBagConstraints.REMAINDER;
        westPanel.add(exitBtn, gbc);

        add(westPanel, BorderLayout.WEST);
    }

我希望组件位于面板的中间。我尝试过 gbc.anchor,但没有成功。

当前:

我的期待:

java swing
1个回答
0
投票

...但他们一直站在面板中间。

阅读 Swing 教程中关于如何使用 GridBagLayout 的部分,了解有关 GridBagLayout 使用的各种约束的信息。

weightx/weighty 约束控制此行为。默认情况下,组件将居中。如果您不希望这样,那么您需要一个具有非零约束的组件。

因此,在这种情况下,您需要创建一个虚拟组件并将其添加到面板的末尾:

JLabel dummy = new JLabel(" ");
gbc.gridy = 4;
gbc.weighty = 1.0;
westPanel.add(dummy, gbc);

现在所有额外的空间都进入最后一个组件。

或者另一种方法是使用“包装器”面板:

JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add(westPanel, BorderLayout.PAGE_START);
add(wrapper, BorderLayout.LINE_START);
//add(westPanel, BorderLayout.WEST);
© www.soinside.com 2019 - 2024. All rights reserved.