Swing Layout Managers

A layout manager is an object of a Java class that implements the Layout Manager interface. There is another interface called LayoutManager2 that inherits from the Layout Manager interface. A container uses a layout manager to compute the position and size of all its components. In other words, the job of a layout manager is to compute four properties (x, y, width, and height) of all components in a container. The x and y properties determine the position of a component within the container. The width and height properties determine the size of the component.

Some of the layout manager classes implement the LayoutManager2 interface. Both interfaces are in the java.awt package. There are many layout managers. Some layout managers are simple and easy to code by hand. Some are very complex to code by hand and they are meant to be used by GUI builder tools such as NetBeans. Some useful layout managers are available for free on the Internet. Sometimes we need to nest them to get the desired effects.

  • FlowLayout
  • BorderLayout
  • CardLayout
  • BoxLayout
  • GridLayout
  • GroupLayout
  • SpringLayout
Flow Layout

The FlowLayout is the simplest layout manager in Swing. It lays out the components horizontally, and then vertically. It lays the components in the order they are added to the container. When it is laying the components horizontally, it may lay them left to right, or right to left. The horizontal layout direction depends on the orientation of the container. We can set the orientation of a container by calling its setComponentOrientation() method. If we want to set the orientation of a container and all its children, than use the applyComponentOrientation() method instead.

Here is a snippet of code that sets the orientation of a container:

//Method – 1

//Set the orientation of the content pane of a frame to “right to left”

JFrame frame = new JFrame(“Test”);

Container pane = frame.getContentPane();

pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

//Method – 2

//Set the orientation of the content pane and all its children to “right to left”

JFrame frame = new JFrame(“Test”);

Container pane = frame.getContentPane();

pane.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

Example
		//FlowLayoutTest.java
		package com.jdojo.swing;
		import java.awt.Container;
		import java.awt.FlowLayout;
		import javax.swing.JButton;
		import javax.swing.JFrame;
		public class FlowLayoutTest {
		public static void main(String[] args) {
		JFrame frame = new JFrame("Flow Layout Test");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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

		for(int i = 1; i <= 3; i++) {
		contentPane.add(new JButton("Button " + i));
		}
		frame.pack();
		frame.setVisible(true);
		}
		}
	
swing-layout-managers

When we expand the frame horizontally, the buttons are displayed

swing-layout-managers

Border Layout

The Border Layout divides a container’s space into five areas: north, south, east, west, and center. When we add a component to a container with a Border Layout, we need to specify to which of the five areas we want to add the component. The Border Layout class defines five constants to identify each of the five areas. The constants are NORTH, SOUTH, EAST, WEST, and CENTER. For example, to add a button to the north area, then write

//Add a button to the north area of the container

JButton northButton = new JButton("North");

container.add(northButton, BorderLayout.NORTH);

The default layout for the content pane of a JFrame is a BorderLayout.

Example
		//BorderLayoutTest.java
		package com.jdojo.swing;

		import java.awt.BorderLayout;
		import javax.swing.JFrame;
		import java.awt.Container;
		import javax.swing.JButton;

		public class BorderLayoutTest {
		public static void main(String[] args) {
		JFrame frame = new JFrame("BorderLayout Test");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container container = frame.getContentPane();
		//Add a button to each of the five areas of the BorderLayout
		container.add(new JButton("North"), BorderLayout.NORTH);
		container.add(new JButton("South"), BorderLayout.SOUTH);
		container.add(new JButton("East"), BorderLayout.EAST);
		container.add(new JButton("West"), BorderLayout.WEST);
		container.add(new JButton("Center"), BorderLayout.CENTER);

		frame.pack();
		frame.setVisible(true);
		}
		}
	
swing-layout-managers
CardLayout

The CardLayout lays out components in a container as a stack of cards. Like a stack of cards, only one card (the card at the top) is visible in a CardLayout. It makes only one component visible at a time. You need to use the following steps to use a CardLayout for a container:

  • Create a container such as a JPanel.
  • JPanel cardPanel = new JPanel();

  • Create a CardLayout object.
  • CardLayout cardLayout = new CardLayout();

  • Set the layout manager for the container.
  • cardPanel.setLayout(cardLayout);

  • Add components to the container. You need to give a name to each component. To add a JButton to the cardPanel, use the following statement:
  • cardPanel.add(new JButton("Card 1"), "myLuckyCard");

    You have named your card myLuckyCard. This name can be used in the show() method of the CardLayout to make this card visible.

  • Call its next() method to show the next card.
  • cardLayout.next(cardPanel);

The CardLayout class provides several methods to flip through components.

Example
		//CardLayoutTest.java
		package com.jdojo.swing;

		import java.awt.Container;
		import javax.swing.JFrame;
		import java.awt.CardLayout;
		import javax.swing.JPanel;
		import javax.swing.JButton;
		import java.awt.Dimension;
		import java.awt.BorderLayout;
		public class CardLayoutTest {
		public static void main(String[] args) {
		JFrame frame = new JFrame("CardLayout Test");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container contentPane = frame.getContentPane();

		//Add a Next JButton in a JPanel to the content pane
		JPanel buttonPanel = new JPanel();
		JButton nextButton = new JButton("Next");
		buttonPanel.add(nextButton);
		contentPane.add(buttonPanel, BorderLayout.SOUTH);

		//Create a JPanel and set its layout to CardLayout
		final JPanel cardPanel = new JPanel();
		final CardLayout cardLayout = new CardLayout();
		cardPanel.setLayout(cardLayout);

		//Add five JButtons as cards to the cardPanel
		for(int i = 1; i <= 5; i++) {
		JButton card = new JButton("Card " + i);
		card.setPreferredSize(new Dimension(200, 200));
		String cardName = "card" + 1;
		cardPanel.add(card, cardName);
		}
		//Add the cardPanel to the content pane
		contentPane.add(cardPanel, BorderLayout.CENTER);
		//Add an action listener to the Next button
		nextButton.addActionListener(e -> cardLayout.next(cardPanel));

		frame.pack();
		frame.setVisible(true);
		}
		}
	
swing-layout-managers
BoxLayout

The BoxLayout arranges components in a container either horizontally in one row or vertically in one column. We need to use the following steps to use a BoxLayout in your program:

  • • Create a container, for example, a JPanel.
  • JPanel hPanel = new JPanel();

  • • Create an object of the BoxLayout class. Unlike other layout managers, you need to pass the container to the constructor of the class. You also need to pass the type of box you are creating (horizontal or vertical) to its constructor. The class has four constants: X_AXIS, Y_AXIS, LINE_AXIS, and PAGE_AXIS. The constant X_AXIS is used to create a horizontal BoxLayout that lays out all components from left to right. The constant Y_AXIS is used to create a vertical BoxLayout that lays out all components from top to bottom. The other two constants, LINE_AXIS and PAGE_AXIS, are similar to X_AXIS and Y_AXIS. However, they use the orientation of the container in laying out the components.
  • //Create a BoxLayout for hPanel to lay out

    //components from left to right

    BoxLayout boxLayout = new BoxLayout(hPanel, BoxLayout.X_AXIS);

  • • Set the layout for the container.
  • hPanel.setLayout(boxLayout);

  • • Add the components to the container.
  • hPanel.add(new JButton("Button 1"));

    hPanel.add(new JButton("Button 2"));

Example
		//BoxLayoutTest.java
		package com.jdojo.swing;
		import java.awt.Container;
		import javax.swing.JFrame;
		import javax.swing.JButton;
		import javax.swing.JPanel;
		import javax.swing.BoxLayout;
		import java.awt.BorderLayout;

		public class BoxLayoutTest {
		public static void main(String[] args) {
		JFrame frame = new JFrame("BoxLayout Test");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container contentPane = frame.getContentPane();

		JPanel hPanel = new JPanel();
		BoxLayout boxLayout = new BoxLayout(hPanel, BoxLayout.X_AXIS);
		hPanel.setLayout(boxLayout);
		for(int i = 1; i <= 3; i++) {
		hPanel.add(new JButton("Button " + i));
		}
		contentPane.add(hPanel, BorderLayout.SOUTH);
		frame.pack();
		frame.setVisible(true);
		}
		}
	
swing-layout-managers
GridLayout

A GridLayout arranges components in a rectangular grid of equally sized cells. Each component is placed in exactly one cell. It does not respect the preferred size of the component. It divides the available space into equally sized cells and resizes each component to the cell’s size.

We can specify either the number of rows or the number of columns in the grid. If we specify both, only the number of rows is used, and the number of columns is computed. Suppose ncomponents is the number of components added to the container, and nrows and ncols are the specified number of rows and columns. If nrows is greater than zero, the number of columns in the grid is computed using the following formula:

ncols = (ncomponents + nrows - 1)/nrows

If nrows is zero, the number of rows in the grid is computed using the following formula:

nrows = (ncomponents + ncols - 1)/ncols

We cannot specify a negative number for nrows or ncols, and at least one of them must be greater than zero. Otherwise, a runtime exception is thrown.

We can create a GridLayout using one of the following three constructors of the GridLayout class:

  • GridLayout()
  • GridLayout(int rows, int cols)
  • GridLayout(int rows, int cols, int hgap, int vgap)
Example
		// GridLayoutTest.java
		package com.jdojo.swing;

		import java.awt.GridLayout;
		import javax.swing.JPanel;
		import java.awt.BorderLayout;
		import javax.swing.JFrame;
		import java.awt.Container;
		import javax.swing.JButton;
		public class GridLayoutTest {
			public static void main(String[] args) {
				JFrame frame = new JFrame("GridLayout Test");
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				Container contentPane = frame.getContentPane();

				JPanel buttonPanel = new JPanel();
				buttonPanel.setLayout(new GridLayout(3,0));

				for(int i = 1; i <= 9 ; i++) {
					buttonPanel.add(new JButton("Button " + i));
				}
				contentPane.add(buttonPanel, BorderLayout.CENTER);
				frame.pack();
				frame.setVisible(true);
			}
		}
	
swing-layout-managers
SpringLayout

An instance of the SpringLayout class in the javax.swing package represents a SpringLayout manager. Recall that the job of a layout manager is to compute four properties (x, y, width, and height) of components in a container. In other words, it is responsible for positioning the components inside the container and computing their size. A SpringLayout manager represents these four properties of a component in terms of springs. It is cumbersome to code by hand. It is meant for GUI builder tools.

What is a spring?

In the context of a SpringLayout manager, you can think of a spring the same way as a mechanical spring, which can be stretched, compressed, or stay in its normal state. An object of the spring class represents a spring in a SpringLayout. A spring object has four properties: minimum, preferred, maximum, and current value. You can think of these four properties as its four types of length. A spring has its minimum value when it is most compressed. In its normal state (neither compressed nor stretched), it has its preferred value. In its most stretched state, it has its maximum value. Its value at any given point in time is its current value. When the minimum, preferred, and maximum values of a spring are the same, it is known as a strut.

The Spring class has no public constructors. It contains factory methods to create springs. To create a spring or strut from scratch, you can use its overloaded constant() static method.

Copyright 1999- Ducat Creative, All rights reserved.