java - 强制顶部 JPanel 调整大小至其子 JPanel 的高度

标签 java swing layout-manager matisse

我在将顶部 JPanel(这本质上是最顶部的父 JPanel)的高度调整为其子 JPanel 的高度时遇到一些问题。因此,当我将顶部 JPanel 放入网格布局中时,子 JPanel 下方会出现被父 JPanel 占用的额外间隙。我想要做的是消除这个间隙,使顶部 JPanel 的大小与子 JPanel 的大小相同。

本质上,父 JPanel 是一个扩展 JPanel 的类。我尝试使用子 JPanel 的大小将其调整为子 JPanel 的大小,但结果仍然相同。

this.setSize(childJPanel.getSize());

为了澄清,我使用 Matisse 可视化编辑器来编辑这个顶部 JPanel(设置为 GroupLayout),并且我将此顶部 JPanel 放置到另一个具有 GridLayout 的 JPanel 中。

如何强制顶部 JPanel 调整大小到其子 JPanel 的高度?

代码:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package helloworld;

/**
 *
 * @author Justin
 */
public class FooPanel extends javax.swing.JPanel {

    /**
     * Creates new form NewJPanel
     */
    public FooPanel() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabel2.setText("HELLOWORLD");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addContainerGap(122, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addContainerGap(45, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
    }// </editor-fold>
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package helloworld;

import java.awt.GridLayout;
import javax.swing.border.EmptyBorder;

/**
 *
 * @author Justin
 */
public class NewJApplet extends javax.swing.JApplet {

    /**
     * Initializes the applet NewJApplet
     */
    @Override
    public void init() {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the applet */
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    initComponents();
                    FooPanel panel1 = new FooPanel();
                    FooPanel panel2 = new FooPanel();
                    FooPanel panel3 = new FooPanel();
                    myPanel.setBorder(new EmptyBorder(5, 5, 5, 5) );
                    myPanel.setLayout(new GridLayout(0,1));
                    myPanel.add(panel1);
                    myPanel.add(panel2);
                    myPanel.add(panel3);

                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * This method is called from within the init() method to initialize the
     * form. WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        myPanel = new javax.swing.JPanel();

        javax.swing.GroupLayout myPanelLayout = new javax.swing.GroupLayout(myPanel);
        myPanel.setLayout(myPanelLayout);
        myPanelLayout.setHorizontalGroup(
            myPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 200, Short.MAX_VALUE)
        );
        myPanelLayout.setVerticalGroup(
            myPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(myPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 200, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(myPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
    }// </editor-fold>
    // Variables declaration - do not modify
    private javax.swing.JPanel myPanel;
    // End of variables declaration
}

结果:

enter image description here

最佳答案

正如 Guillaume Polet 上面提到的,事实证明 GridLayout“为其所有子级设置相同的大小(基于可用空间和所有子级的最大首选大小)”。使用 BoxLayout 管理器(特别是 PAGE_LAYOUT)将缓解上述问题。具体来说,BoxLayout 不会将其所有子项设置为相同的大小。我发现此页面对于弄清楚 How to Use BoxLayout 非常有用。 .

使用 BoxLayout 时,可以使用 Glue 和 RigidArea 来分隔组件。

关于java - 强制顶部 JPanel 调整大小至其子 JPanel 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14442940/

相关文章:

java - Apache Camel 传递参数

java - JAXB 和无命名空间的 XML

java - JTable 的复杂性

java - 如何在工具提示中使用换行符

java - 无法定位按钮或 JLabel

java - 为什么下面的代码只显示循环最后一圈的数组值?

java - 部署在 tomcat 中的 java 应用程序中的异常行为

java - 问题在面板数组中的 JButton 上设置约束

java - 使用或覆盖已弃用的 API

Java/斯卡拉 Swing : Make a component fill all available space in a row