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

时间:2015-08-24 12:04:02

标签: java user-interface layout jpanel gridbaglayout

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

使用以下代码,我的GUI部分看起来像这样:

enter image description here

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 个答案:

答案 0 :(得分: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);

祝你好运,   卓然