LayoutManager of Swing

Hello everyone. This page is an English translation of a Japanese page. (The original Japanese has been slightly rewritten to make it easier to translate into English.)

In this article, we will deal with how to place labels in Swing. In this article, I wrote a program to place an instance of the JLabel class in the JFrame class. Basically, the placement of the components is determined automatically. In fact, the implementation class of the LayoutManager interface manages the placement of the components.

The class JLabel can handle short text strings and image display areas. We will create an instance of this class and add it to the JFrame.

In this article, I have tried to use some LayoutManager.

Sample program template

We will use the following program as a template.

Source
import javax.swing.JFrame;

public class Test extends JFrame {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(350, 250);

        init();

        setVisible(true);

    }

    private void init() {
        // Processing for installation
    }

}

Before displaying the frame in the setVisible method, we call our own init method. As a result of experimentation, the description process works well when the methods are called in this order.

BorderLayout

The JFrame’s LayoutManager is initially set to BorderLayout.

In the case of BorderLayout, the size of the component to be placed will be automatically adjusted to fit into the following five areas.

  • center (Center of the area)
  • east (Right edge of the region)
  • north (Top edge of the area)
  • south (Bottom edge of the area)
  • west (Left edge of the region)

The BorderLayout class defines the static fields CENTER, EAST, NORTH, SOUTH, and WEST corresponding to the above.

For the actual placement, use the add(Component comp, Object constraints) method. For the second argument, specify the location to be placed in the field above. Also, in the case of add(Component comp), it will be automatically placed in the center.

For example, the contents of the init method should be as follows. (There are some Japanese characters in the source code below, but please think of them as symbols.)

Source
import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;

public class Test2 extends JFrame {

    public static void main(String[] args) {
        new Test2();
    }

    public Test2() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(350, 250);

        init();

        setVisible(true);

    }

    private void init() {
        Border border = new LineBorder(Color.RED);

        JLabel label1 = new JLabel("ラベル1");
        label1.setBorder(border);
        add(label1);

        JLabel label2 = new JLabel("ラベル2");
        label2.setBorder(border);
        add(label2, BorderLayout.NORTH);

        JLabel label3 = new JLabel("ラベル3");
        label3.setBorder(border);
        add(label3, BorderLayout.SOUTH);

        JLabel label4 = new JLabel("ラベル4");
        label4.setBorder(border);
        add(label4, BorderLayout.EAST);

        JLabel label5 = new JLabel("ラベル5");
        label5.setBorder(border);
        add(label5, BorderLayout.WEST);
    }

}

The reason we are using the setBorder method is to draw the border. We will skip the details, but set the border in that section.

The following is the result of the display. The size of the image is automatically adjusted and placed.

swing_day003001_borderlayout_1

Note that changing the size of the screen does not change the placement. The size of each area will change.

As a reminder, the horizontal and vertical spacing between components is zero in the initial state. There are two ways to adjust this interval.

  • Use the constructor BorderLayout(int hgap, int vgap).
  • Use the setHgap and setVgap methods.

For example, the following is written at the beginning of the init method.

Source
setLayout(new BorderLayout(10, 20));
swing_day003001_borderlayout_2

As shown above, there are two constructors

  • BorderLayout()
  • BorderLayout(int hgap, int vgap)

In the case of using BorderLayout(), the spacing between components will be set to 0.

FlowLayout

With FlowLayout, the component will be wrapped and placed at the right edge. Initially, it will be centered. Also, to add a component, use the add(Component comp) method.

When using a JFrame, specify the FlowLayout object in the setLayout method. For example, you can write the following

Source
import java.awt.Color;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;

public class Test4 extends JFrame {

    public static void main(String[] args) {
        new Test4();
    }

    public Test4() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(350, 250);

        init();

        setVisible(true);

    }

    private void init() {
        setLayout(new FlowLayout());

        Border border = new LineBorder(Color.RED);

        JLabel label1 = new JLabel("ラベル1A");
        label1.setBorder(border);
        add(label1);

        JLabel label2 = new JLabel("ラベル2AB");
        label2.setBorder(border);
        add(label2);

        JLabel label3 = new JLabel("ラベル3ABC");
        label3.setBorder(border);
        add(label3);

        JLabel label4 = new JLabel("ラベル4ABCD");
        label4.setBorder(border);
        add(label4);

        JLabel label5 = new JLabel("ラベル5ABCDE");
        label5.setBorder(border);
        add(label5);
    }
}
swing_day003002_flowlayout_1

Initially, the horizontal and vertical spacing between components is 5. To adjust this interval, write, for example, the following (Instead of “setLayout(new FlowLayout();").

Source
FlowLayout flowLayout = new FlowLayout();
flowLayout.setHgap(10);
flowLayout.setVgap(20);
setLayout(flowLayout);
swing_day003002_flowlayout_2

The placement of the components can be adjusted with the following constructor.

  • FlowLayout(int align)
  • FlowLayout(int align, int hgap, int vgap)

The FlowLayout class defines the following fields as values for the first argument: FlowLayout.LEFT, FlowLayout.RIGHT, FlowLayout.CENTER, FlowLayout.LADING, FlowLayout.TRAILING.

For example, to set it to left-justified, write the following (Instead of “setLayout(new FlowLayout());")

Source
setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));
swing_day003002_flowlayout_3

If you look at the alignment of the components in the second row, you can see that they are left-aligned.

As shown above, there are three constructors as follows.

  • FlowLayout()
  • FlowLayout(int align)
  • FlowLayout(int align, int hgap, int vgap)

It is important to note that FlowLayout() sets the center alignment, horizontal and vertical spacing to 5.

CardLayout

CardLayout allows you to place cards on top of each other. You can use CardLayout#next method to display the next card.

There are two constructors as follows.

  • CardLayout()
  • CardLayout(int hgap, int vgap)

In this section, we will only show an example using CardLayout().

In the following sample program, clicking on the display area will change the display of the card.

Source
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;

public class Test7 extends JFrame {

    public static void main(String[] args) {
        new Test7();
    }

    public Test7() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(350, 250);

        init();

        setVisible(true);

    }

    private void init() {
        CardLayout cardLayout = new CardLayout();
        setLayout(cardLayout);

        Border border = new LineBorder(Color.RED);

        JLabel label1 = new JLabel("ラベル1A");
        label1.setBorder(border);
        add(label1);

        JLabel label2 = new JLabel("ラベル2AB");
        label2.setBorder(border);
        add(label2);

        JLabel label3 = new JLabel("ラベル3ABC");
        label3.setBorder(border);
        add(label3);

        JLabel label4 = new JLabel("ラベル4ABCD");
        label4.setBorder(border);
        add(label4);

        JLabel label5 = new JLabel("ラベル5ABCDE");
        label5.setBorder(border);
        add(label5);

        JLabel[] labels = { label1, label2, label3, label4, label5 };
        for (JLabel label : labels) {
            label.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    cardLayout.next(getContentPane());
                }
            });
        }
    }

}

The MouseAdapter is registered in the addMouseListener method of each label. Clicking on a label with the mouse will change the display to the next label.

Initial display
swing_day003003_cardlayout_1
After clicking
swing_day003003_cardlayout_2

The size of the component has been automatically extended to the entire area.

GridLayout

GridLayout allows you to arrange components in a grid. The placed components will be of equal size.

There are three constructors as follows.

  • GridLayout()
  • GridLayout(int rows, int cols)
  • GridLayout(int rows, int cols, int hgap, int vgap)

GridLayout() creates a single-row layout.

Source
import java.awt.Color;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;

public class Test8 extends JFrame {

    public static void main(String[] args) {
        new Test8();
    }

    public Test8() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(350, 250);

        init();

        setVisible(true);

    }

    private void init() {
        setLayout(new GridLayout());

        Border border = new LineBorder(Color.RED);

        JLabel label1 = new JLabel("ラベル1A");
        label1.setBorder(border);
        add(label1);

        JLabel label2 = new JLabel("ラベル2AB");
        label2.setBorder(border);
        add(label2);

        JLabel label3 = new JLabel("ラベル3ABC");
        label3.setBorder(border);
        add(label3);

        JLabel label4 = new JLabel("ラベル4ABCD");
        label4.setBorder(border);
        add(label4);

        JLabel label5 = new JLabel("ラベル5ABCDE");
        label5.setBorder(border);
        add(label5);
    }

}
swing_day003004_gridlayout_1

In GridLayout(int rows, int cols), the components are placed according to the specified rows and columns.

For example, you can specify the following (Instead of “setLayout(new GridLayout();").

Source
setLayout(new GridLayout(2, 3));
swing_day003004_gridlayout_2

GridLayout(int rows, int cols, int hgap, int vgap) allows you to specify horizontal spacing and vertical spacing.

For example, you can specify the following.

Source
setLayout(new GridLayout(2, 3, 10, 20));
swing_day003004_gridlayout_3

Components of equal size were placed with a horizontal spacing of 10 and a vertical spacing of 20.

That’s all. I hope this is helpful to you.

Articles next and previous in the same category