Java Swing Tutorial - Java Swing Layout Managers








A container uses a layout manager to position all its components.

A layout manager computes four properties (x, y, width, and height) of all components in a container.

A layout manager is an object of a Java class that implements the LayoutManager interface or LayoutManager2 interface. LayoutManager2 interface inherits from the LayoutManager interface. Both interfaces are in the java.awt package.

The following list is layout managers we often use.

  • FlowLayout
  • BorderLayout
  • CardLayout
  • BoxLayout
  • GridLayout
  • GridBagLayout
  • GroupLayout
  • SpringLayout

Every container has a default layout manager. The default layout manager for the content pane of a JFrame is BorderLayout.

For a JPanel, the default layout manager is FlowLayout.

We can change the default layout manager of a container by using its setLayout() method.

To remove a layout manager, we can pass null to the setLayout() method.

The getLayout() method of a container returns the reference of the layout manager the container is currently using.

The following code shows how to set FlowLayout as the layout manager for the content pane of a JFrame

JFrame  frame  = new JFrame("Frame"); 
Container contentPane = frame.getContentPane(); 
contentPane.setLayout(new FlowLayout());

The following code shows how to set BorderLayout as the layout manager for a JPanel.

JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());

To get the layout manager for a container use the following code

LayoutManager  layoutManager = container.getLayout()




The null Layout Manager

To remove a layout manager, set the layout manager to null

myContainer.setLayout(null);

The following code sets the layout manager of a JFrame's content pane to null.

JFrame  frame  = new JFrame(""); 
Container contentPane = frame.getContentPane(); 
contentPane.setLayout(null);

"null layout manager" is also known as absolute positioning.

The following code shows how to use a null layout manager for the content pane of a JFrame. It layouts two buttons to it using the setBounds() method.

import java.awt.Container;
//from  w w w  . ja v a 2 s . c  om
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();
    contentPane.setLayout(null);

    JButton b1 = new JButton("Button");
    JButton b2 = new JButton("2");
    contentPane.add(b1);
    contentPane.add(b2);

    b1.setBounds(10, 10, 100, 20);
    b2.setBounds(120, 10, 150, 40);

    frame.setBounds(0, 0, 350, 100);
    frame.setVisible(true);
  }
}