How do I arrange the swing component using BoxLayout?

This example demontrate how we can arrange component in row or column order using the BoxLayout layout manager. Instead of use the BoxLayout manager we can also use the Box component as our content pane to get the same effect as using the BoxLayout manager.

package org.kodejava.example.swing;

import javax.swing.*;

public class BoxLayoutDemo extends JFrame {
    public BoxLayoutDemo() {

    private void initialize() {
        setSize(400, 400);

        // Set the layout of the Content Pane to BoxLayout using BoxLayout.X_AXIS
        // will arrange the component left to right. If we want to arrange the
        // component top to bottom we can use the BoxLayout.Y_AXIS;
        setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));

        JLabel label = new JLabel("Username : ");
        JTextField textField = new JTextField();

        JLabel password = new JLabel("Password :");
        JPasswordField passwordField = new JPasswordField();



    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new BoxLayoutDemo().setVisible(true);


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me, buy me ☕ or 🍵

Leave a Reply