Java Swing How to - Align Multiple JPanel with different height








Question

We would like to know how to align Multiple JPanel with different height.

Answer

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
//from   w  w w  .j a v a  2s  . com
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {

  public static void main(String[] args) {
    final JFrame frame = new JFrame(Main.class.getSimpleName());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel btmPanel = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weighty = 1.0;
    gbc.weightx = 1.0;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.insets = new Insets(5, 5, 5, 5);
    gbc.anchor = GridBagConstraints.NORTH;
    JButton comp = new JButton("Panel-1");
    btmPanel.add(comp, gbc);
    JButton comp2 = new JButton("Panel-2");
    btmPanel.add(comp2, gbc);
    JButton comp3 = new JButton("Panel-3");
    comp3.setPreferredSize(new Dimension(comp.getPreferredSize().width, comp
        .getPreferredSize().height + 10));
    btmPanel.add(comp3, gbc);
    frame.add(btmPanel);
    frame.pack();
    frame.setVisible(true);
  }
}