繁体   English   中英

JPanel 中 GridBagLayout 中的 JButton

[英]JButton in GridBagLayout in a JPanel

我从上周开始学习 Swing,我对 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 建议有效,但有点问题,拼图按钮不在提取中心。

谢谢。

默认情况下,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) 语句并缩小框架的大小以查看按钮如何重新定位自身。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM