【问题标题】:How to adjust size of JPanel in GridBagLayout?如何在 GridBagLayout 中调整 JPanel 的大小?
【发布时间】: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,其中包含两个单选按钮。如何解决这个问题?

【问题讨论】:

    标签: java user-interface layout jpanel gridbaglayout


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-20
      • 2012-09-01
      • 2013-08-04
      相关资源
      最近更新 更多