0

I am having some problems getting the height of the top JPanel (this is essentially the top-most parent JPanel) to resize to the height of its child JPanel. As a result, when I place the top JPanel into a grid layout, there is extra gap below the child JPanel that is being occupied by the parent JPanel. What I want to do is to eliminate this gap such that the size of the top JPanel will be the same size as the child JPanel.

Essentially, the parent JPanel is a class that extends JPanel. I've tried to resize it to the size of the child JPanel using the size of the child JPanel, but the results are still the same.

this.setSize(childJPanel.getSize());

To clarify, I've used the Matisse visual editor to edit this top JPanel (set to GroupLayout), and I am placing this top JPanel into another JPanel with a GridLayout.

How to force top JPanel to resize to the height of its child JPanel?

CODE:

/*
 * 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
}

RESULT:

enter image description here

Justin
  • 742
  • 5
  • 17
  • 34
  • Try setting the preferred size instead of size. – Vlad Topala Jan 21 '13 at 16:27
  • 1
    @Vlad no: never call `setPreferredSize()`. Justin, you should never have to call either `setSize()/setPreferredSize()/setMinimumSize()/setMaximumSize()`. Let all this be handled by LayoutManager's, that is exactly what they are meant for. `GridLayout` is one of the lamest `LayoutManager` out there. `BorderLayout` and `GridBagLayout` are much more used. On some rare occasion, you may consider `FlowLayout`. `GroupLayout` is a layout for GUI-builders and produces unreadable and hard-to-debug code. – Guillaume Polet Jan 21 '13 at 16:31
  • @Vlad: I've tried setting the preferred size as well. The gap between the parent JPanel and the child JPanel is still there. This seems to be the result of the parent JPanel wanting to size its height to the size allotted by gridlayout, although I do not want this to happen. – Justin Jan 21 '13 at 16:48
  • See [this answer](http://stackoverflow.com/a/7181197/418556) for how to center a single component within a container, either stretched or preferred size. – Andrew Thompson Jan 21 '13 at 16:51
  • @Guillaume Polet: I've tried your suggestions for using a different layout manager, but that doesn't seem to solve the problem either. – Justin Jan 21 '13 at 16:52
  • @Justin I have not seen any parts of your code so comments is about the best you will get. Post code, you will get a better answer. – Guillaume Polet Jan 21 '13 at 16:56
  • @GuillaumePolet: I have just posted the code and the result. Basically, there is a wide gap created in between each child panel as indicated by the borders. I'm not exactly sure how to remove these gaps. They seem to result because the parent panel is resizing itself to fit the gridlayout formatted panel. – Justin Jan 21 '13 at 17:26
  • 1
    @Justin Like I said, GridLayout is a lame LayoutManager which sets equal size on all its children (based on the available space and the maximum preferred size of all its children). You could try a vertical BoxLayout with an additional "Glue" component at the end (`Box.createGlue()`), but I am not too big a fan of `BoxLayout` either. – Guillaume Polet Jan 21 '13 at 17:41
  • @Guillaume Polet: Thanks for your previous post. I just gave your suggestion about BoxLayout a try and it works perfectly. Now I was wondering how I could go about making your previous comment the answer to this post? – Justin Jan 21 '13 at 18:23
  • @GuillaumePolet: Would it be possible for you to repost this comment as an answer? I would like to accept it. – Justin Jan 21 '13 at 18:37

1 Answers1

2

As mentioned by Guillaume Polet above, it turns out that GridLayout "sets equal size on all its children (based on the available space and the maximum preferred size of all its children)". Using the BoxLayout manager (specifically PAGE_LAYOUT) will alleviate the issues described above. Specifically, BoxLayout will not set all its children to equal size. I found this page to be very useful for figuring out How to Use BoxLayout.

Glue and RigidArea can be used to space components when using BoxLayout.

Catalina Island
  • 7,027
  • 2
  • 23
  • 42
Justin
  • 742
  • 5
  • 17
  • 34