JPanel Layouts - potatoscript/JavaSwing GitHub Wiki

JPanel & Layout Managers

1️⃣ Introduction to JPanel

A JPanel is a container that holds and organizes multiple components inside a JFrame. It helps structure your GUI by grouping elements together.

Why Use JPanel?

✔️ Allows better component organization
✔️ Supports different layout managers
✔️ Enables nested layouts for complex UI designs


2️⃣ Creating a Simple JPanel

Example: Adding a JPanel to JFrame

import javax.swing.*;

public class JPanelExample {
    public static void main(String[] args) {
        // Create the frame
        JFrame frame = new JFrame("JPanel Example");
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Create a panel
        JPanel panel = new JPanel();

        // Add a label to the panel
        JLabel label = new JLabel("Hello, JPanel!");
        panel.add(label);

        // Add the panel to the frame
        frame.add(panel);

        // Make the frame visible
        frame.setVisible(true);
    }
}

Explanation

  • JPanel panel = new JPanel(); → Creates a panel.
  • panel.add(label); → Adds a label to the panel.
  • frame.add(panel); → Adds the panel to the frame.

🔹 By default, JPanel uses FlowLayout, which places components in a row.


3️⃣ Understanding Layout Managers

Swing provides different layout managers to arrange components inside a JPanel.

Layout Manager Description
FlowLayout Default layout; arranges components in a row.
BorderLayout Divides the panel into five regions: NORTH, SOUTH, EAST, WEST, CENTER.
GridLayout Arranges components in a grid (rows & columns).
BoxLayout Places components in a single row or column.
GridBagLayout Advanced flexible layout for precise component positioning.
CardLayout Stacks components like a deck of cards (switchable views).

4️⃣ FlowLayout (Default)

Example: Using FlowLayout

import javax.swing.*;
import java.awt.*;

public class FlowLayoutExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("FlowLayout Example");
        frame.setSize(400, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.LEFT)); // Align left

        // Add buttons
        panel.add(new JButton("Button 1"));
        panel.add(new JButton("Button 2"));
        panel.add(new JButton("Button 3"));

        frame.add(panel);
        frame.setVisible(true);
    }
}

Key Features

✔️ Places components horizontally in a row.
✔️ Wraps components if the row is full.
✔️ Align options: FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT.


5️⃣ BorderLayout

Example: Using BorderLayout

import javax.swing.*;
import java.awt.*;

public class BorderLayoutExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("BorderLayout Example");
        frame.setSize(500, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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

        panel.add(new JButton("North"), BorderLayout.NORTH);
        panel.add(new JButton("South"), BorderLayout.SOUTH);
        panel.add(new JButton("East"), BorderLayout.EAST);
        panel.add(new JButton("West"), BorderLayout.WEST);
        panel.add(new JButton("Center"), BorderLayout.CENTER);

        frame.add(panel);
        frame.setVisible(true);
    }
}

Key Features

✔️ Divides the panel into NORTH, SOUTH, EAST, WEST, CENTER.
✔️ CENTER takes the remaining space if other regions are used.


6️⃣ GridLayout

Example: Using GridLayout

import javax.swing.*;
import java.awt.*;

public class GridLayoutExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("GridLayout Example");
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(2, 2)); // 2 rows, 2 columns

        panel.add(new JButton("1"));
        panel.add(new JButton("2"));
        panel.add(new JButton("3"));
        panel.add(new JButton("4"));

        frame.add(panel);
        frame.setVisible(true);
    }
}

Key Features

✔️ Arranges components in a grid format (rows & columns).
✔️ Components get equal size within the grid.


7️⃣ BoxLayout

Example: Using BoxLayout (Vertical)

import javax.swing.*;
import java.awt.*;

public class BoxLayoutExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("BoxLayout Example");
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); // Vertical alignment

        panel.add(new JButton("Button 1"));
        panel.add(new JButton("Button 2"));
        panel.add(new JButton("Button 3"));

        frame.add(panel);
        frame.setVisible(true);
    }
}

Key Features

✔️ Arranges components vertically (Y_AXIS) or horizontally (X_AXIS).
✔️ Components retain their preferred size.


8️⃣ GridBagLayout (Advanced)

Example: Using GridBagLayout

import javax.swing.*;
import java.awt.*;

public class GridBagLayoutExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("GridBagLayout Example");
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        // Add button 1
        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(new JButton("Button 1"), gbc);

        // Add button 2
        gbc.gridx = 1;
        gbc.gridy = 0;
        panel.add(new JButton("Button 2"), gbc);

        // Add button 3 spanning 2 columns
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 2;
        panel.add(new JButton("Button 3"), gbc);

        frame.add(panel);
        frame.setVisible(true);
    }
}

Key Features

✔️ Most flexible layout, allowing precise component placement.
✔️ Supports row/column spanning (gridwidth, gridheight).
✔️ Used for complex, professional GUI designs.


9️⃣ CardLayout (Switchable Views)

Example: Using CardLayout

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CardLayoutExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("CardLayout Example");
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel(new CardLayout());

        JPanel panel1 = new JPanel();
        panel1.add(new JLabel("This is Panel 1"));
        JPanel panel2 = new JPanel();
        panel2.add(new JLabel("This is Panel 2"));

        panel.add(panel1, "Panel1");
        panel.add(panel2, "Panel2");

        JButton switchButton = new JButton("Switch");
        switchButton.addActionListener(e -> {
            CardLayout cl = (CardLayout) panel.getLayout();
            cl.next(panel);
        });

        frame.add(panel, BorderLayout.CENTER);
        frame.add(switchButton, BorderLayout.SOUTH);
        frame.setVisible(true);
    }
}

✔️ Used for tab-like interfaces or dynamic panels.
✔️ Switches between views using .next(), .previous(), .show().


🔥 Summary

JPanel organizes components efficiently.
Use layout managers to arrange UI elements properly.
Choose the right layout based on your UI needs.
CardLayout is great for switchable views.