首页 > 解决方案 > JPanel 中 GridBagLayout 中的 JButton

问题描述

我从上周开始学习摇摆,我对 GridBagConstraints 有一些问题,将一个按钮放在左上角,但所有其他按钮都默认放在 GridBagConstraints 中?

我正在使用类似于非原创但说明问题的代码

import java.awt.*;
import javax.swing.*;

@SuppressWarnings("serial")
class MyPanel extends JPanel
{
    JButton menu = new JButton("Menu"), button = new JButton("Puzzle");

    GridBagConstraints gbc1 = new GridBagConstraints(), gbc2 = new GridBagConstraints();

    private void setup()
    {
        gbc1.anchor   = GridBagConstraints.FIRST_LINE_START;
        gbc2.anchor   = GridBagConstraints.CENTER;
        gbc2.weightx  = 1.0;
        gbc2.weighty  = 1.0;
    }

    public MyPanel()
    {
        this.setLayout(new GridBagLayout());
        this.setup();
        this.button.setPreferredSize(new Dimension(250, 140));
        this.add(menu, gbc1);
        this.add(button, gbc2);
    }
}

@SuppressWarnings("serial")
public class Test extends JFrame
{
    public Test()
    {
        this.setTitle("Test");
        this.setContentPane(new MyPanel());
        this.setResizable(false);
        this.setSize(800, 600);
        this.setVisible(true);
    }

    public static void main(String args[])
    {
        SwingUtilities.invokeLater(() -> new Test());
    }
}

输出

输出

我想要菜单是顶角。

我从这里读到,但我不明白这个你能解释一下 GridBagConstraints 如何做到这一点。

我希望这个问题很清楚,如果没有,请在评论中告诉我。

编辑:

@camickr 建议有效,但有点问题,拼图按钮不在提取中心。

谢谢。

标签: javaswinglayout-managergridbaglayout

解决方案


默认情况下,GridBagLayout 将显示所有水平和垂直居中的组件,除非其中一个组件的 weightx/weighty 值不等于 0。然后该组件将填充框架中的额外空间。

因此,如果您想要一个组件位于“顶部/左侧”,一个组件位于“中心”,您需要:

  1. 使用“锚”约束。这两个组件会有所不同。
  2. 中心的组件将需要使用“weightx/weighty”约束。

但是,更简单的解决方案可能是使用具有不同布局管理器的面板组合。

例如:

JPanel menuPanel = new JPanel( new FlowLayout(FlowLayout.LEFT) );
menuPanel.add(menuButton);

JPanel centerPanel = new JPanel( new GridBagLayout() );
centerPanel.add(puzzle, new GridBagConstraints());

frame.add(menuPanel, BorderLayout.PAGE_START);
frame.add(centerPanel, BorderLayout.CENTER);

所以现在框架的“顶部”将包含一个面板,该面板从左侧显示组件,框架的“中心”将包含您的拼图,位于框架的剩余空间的中心。

编辑:

我解决了它,但在中心组件中将 gridx 和 gridy 设置为 0,但我没有完全理解设置

好吧,我提到您需要使用 gridx/gridy 约束。您应该始终使用这些约束,因为您要将组件添加到哪个网格非常明显。本教程中的示例始终指定这些值。

使用 gridx/gridy 都等于 0,并没有真正的意义。效果是您有两个组件试图共享同一个网格。

删除 setResizable(false) 语句并缩小框架的大小以查看按钮如何重新定位自身。

两个组件共享同一个网格是不正常的。通常你会在第一行有菜单,在第二行有按钮。这将使按钮在框架中水平居中,在菜单下方的空间中垂直居中。你是做什么的


推荐阅读