How do I create a simple JTabbedPane?

In this example you will learn how to use JTabbedPane to arrange some components in tabbed view. The JTabbedPane component of the Swing API allows some components such as panels to share the same view. By selecting the corresponding tab, the panel will be displayed on the user’s screen. To add tabs to the JTabbedPane class you can use the addTab() method.

To the addTab() method accept two arguments, the title of the tab and the component you wish to display as the content of the tab. In the code snippet below we will use a simple panel as the content of the tab. You can also define an image icon for the tab which makes the program looks better. You can read it in this example:

Now, let’s create a simple example of JTabbedPane which has three tabs and the corresponding content, they are the Dashboard, Transaction and Account tabs. Below is an image that show how the screen will looks.

Simple Tabbed Pane Demo

Simple Tabbed Pane Demo

package org.kodejava.examples.swing.tabbedpane;

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

public class SimpleTabbedPane extends JPanel {
    public SimpleTabbedPane() {
        initializeUI();
    }

    public static void showFrame() {
        JPanel panel = new SimpleTabbedPane();
        panel.setOpaque(true);

        JFrame frame = new JFrame("Simple Tabbed Pane Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                SimpleTabbedPane.showFrame();
            }
        });
    }

    private void initializeUI() {
        JTabbedPane tabbedPane = new JTabbedPane();

        JPanel dashboardPanel = new JPanel();
        dashboardPanel.add(new JLabel("Dashboard"));
        //
        // Add Dashboard Tab
        //
        tabbedPane.addTab("Dashboard", dashboardPanel);

        JPanel transactionPanel = new JPanel();
        transactionPanel.add(new JLabel("Transaction"));
        //
        // Add Transactions Tab
        //
        tabbedPane.addTab("Transaction", transactionPanel);

        JPanel accountPanel = new JPanel();
        accountPanel.add(new JLabel("Account"));
        //
        // Add Account Tab
        //
        tabbedPane.addTab("Account", accountPanel);

        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(400, 200));
        this.add(tabbedPane, BorderLayout.CENTER);
    }
}

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply