Java Swing How to - Combine BorderLayout, GridLayout and FlowLayout








Question

We would like to know how to combine BorderLayout, GridLayout and FlowLayout.

Answer

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
/*from   w  w w .  ja v a2 s. c o  m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main {

  public static void main(String[] args) {
    JButton btnA = new JButton("A");
    JButton btnB = new JButton("B");

    btnA.setPreferredSize(new Dimension(50, 25));
    btnB.setPreferredSize(new Dimension(100, 25));

    JPanel btnAPanel = new JPanel();
    JPanel btnBPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    btnAPanel.add(btnA);
    btnBPanel.add(btnB);

    JPanel topPanel = new JPanel(new GridLayout(1, 0));
    topPanel.add(new JLabel("hi"));
    topPanel.add(btnAPanel);
    topPanel.add(btnBPanel);

    JPanel mainPanel = new JPanel(new BorderLayout());
    mainPanel.add(topPanel, BorderLayout.NORTH);

    mainPanel.setPreferredSize(new Dimension(400, 300));

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(mainPanel);
    frame.pack();
    frame.setVisible(true);
  }
}