Java Graphics Tutorial II - Layouts

In the previous tutorial of Java Graphics, I explained about panels, frames and windows which we can put our items. But we didn't set the layout of the window , panel or frame in our last tutorial, what we did was we used the default layout.

Today in this tutorial we will be understanding about the different types on Layouts that are available for us to use and manipulate our GUI.

Container Layout :

The layout of each component in the container is governed by the Layout Manager. Each container (such as Panel or Frames) has a default layout manager associated with it, which we can change.

Layout Manager :

The following layout managers are included with the Java Programming Language :

  1. FlowLayout - The FlowLayout is the default layout manager for Panel  and Applet. The components when placed in the container having layout manager as FlowLayout will be placed next to each other making a flow (like students in a straight line)
  2. BorderLayout - The BorderLayout is the default layout manager of Window,Dialog and Frame. The BorderLayout is when applied will make the components appear on the borders i.e. WEST, SOUTH, NORTH, CENTER OR EAST depending upon what is the choice given.

  3. GridLayout - This layout manager provides the flexiblity for placing components on the container.

  4. CardLayout - It is something that uses two or more components which share the same display (as you can see below).

  5. GridBagLayout - The GridBagLayout is the most flexible and the most complex layout manager in the Java Environment. It places is components and rows and columns and thus allow us to do row span or column span in order to place over components.


By default, all Window classes use the BorderLayout manager and the Panel classes use the FlowLayout manager. A function called setLayout() is used to change the layout of the container (its shown below in the example).

A Simple  FlowLayout Example :

import java.awt.*;

public class GUI2 {

    private Frame f;
    private Button but1;
    private Button but2;
    public GUI2(){
        f = new Frame("CODE 2 LEARN");
        but1 = new Button("Like Code 2 Learn");
        but2 = new Button("Don't Like Code 2 Learn");
    public void generateGUI(){
        f.setLayout(new FlowLayout());
    public static void main(String[] args) {
        GUI2 launchgui= new GUI2();