如何在 GridBagLayout 中调整 JPanel 的大小?

Posted

技术标签:

【中文标题】如何在 GridBagLayout 中调整 JPanel 的大小?【英文标题】:How to adjust size of JPanel in GridBagLayout? 【发布时间】:2015-11-17 20:26:26 【问题描述】:

我确信这个问题可能是重复的,但我仍然在发布,因为我无法找到解决方案/更正代码中的错误。我的 Java GUI 的一部分使用了 GridBagLayout。此布局将包含 3 个组件,2 个单选按钮将位于顶部(并排放置),其余空间应有一个 JPanel(从单选按钮下方的下一行开始,直到可用空间结束)。我在论坛和外部查看了不同的示例,但无法解决问题。

使用以下代码,我的 GUI 部分如下所示:

ImageDisplay = new JPanel(new GridBagLayout());
        GridBagConstraints g = new GridBagConstraints();
        g.insets = new Insets(5, 5, 5, 5); // insets for all components


        rawImage = new JRadioButton("Raw", true);
        peakPickedImage = new JRadioButton("Peak picked");
        radioButtonGroup.add(rawImage);
        radioButtonGroup.add(peakPickedImage);

        g.fill = GridBagConstraints.HORIZONTAL;
        g.gridx = 0;
        g.gridy = 0;
        g.gridwidth = 1;
        g.gridheight = 1;

        ImageDisplay.add(rawImage, g);

        g.gridx = 1;
        g.gridy = 0;
        g.gridwidth = 1;
        g.gridheight = 1;
        g.weightx = 0;
        g.weighty = 0;

        ImageDisplay.add(peakPickedImage, g);

        JPanel imagePanel = new JPanel();
        g.gridx = 0;
     //   g.gridy = 0;
        g.weightx = 1.0;
        g.weighty = 0.75;
        g.gridwidth = 3;
        g.gridheight = 3;
       // g.fill = GridBagConstraints.BOTH;

      //  g.fill = GridBagConstraints.SOUTH;

        imagePanel.setBorder(BorderFactory.createEtchedBorder());

        ImageDisplay.add(imagePanel, g);

并且,取消注释

g.fill = GridBagConstraints.BOTH;

我得到了 JPanel,其中包含两个单选按钮。如何解决这个问题?

【问题讨论】:

【参考方案1】:

试试这样:

JPanel ImageDisplay = new JPanel(new GridBagLayout());
GridBagConstraints g = new GridBagConstraints();
g.insets = new Insets(5, 5, 5, 5); // insets for all components
g.weightx = 0.0;
g.weighty = 0.0;

JRadioButton rawImage = new JRadioButton("Raw", true);
JRadioButton peakPickedImage = new JRadioButton("Peak picked");
ButtonGroup radioButtonGroup = new ButtonGroup();
radioButtonGroup.add(rawImage);
radioButtonGroup.add(peakPickedImage);

g.fill = GridBagConstraints.HORIZONTAL;
g.gridx = 0;
g.gridy = 0;
g.gridwidth = 1;
g.gridheight = 1;

ImageDisplay.add(rawImage, g);

g.gridx = 1;
g.gridy = 0;

ImageDisplay.add(peakPickedImage, g);

JPanel imagePanel = new JPanel();
g.gridx = 0;
g.gridy = 1;
g.gridwidth = 2;
g.weightx = 1.0; // fill the rest of the space
g.weighty = 1.0;
g.fill = GridBagConstraints.BOTH;

imagePanel.setBorder(BorderFactory.createEtchedBorder());

ImageDisplay.add(imagePanel, g);

【讨论】:

以上是关于如何在 GridBagLayout 中调整 JPanel 的大小?的主要内容,如果未能解决你的问题,请参考以下文章

如何让 GridBagLayout 尊重按钮或面板的最小尺寸?

在 java 中使用 GridBagLayout 时设置最大组件大小

如何在 GridBagLayout 中垂直对齐不同大小的按钮?

如何使用 GridBagLayout 在 JPanel 中对齐组件中心?

如何将 JPA 调整为 Criteriaquery

GridBagLayout:如何设置固定列宽?