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

How to adjust size of JPanel in GridBagLayout?

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

使用以下代码,我的 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,其中包含两个单选按钮。如何解决这个问题?

这样试试:

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);