java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to change JTabbedPane tab placement position?

By default the tabs of the JTabbedPane is placed at the top. But you can actually places the tab at every side of the JTabbedPane, it can be on the top, right, left of bottom side.

To change this tab placement position you need to pass the tab placement constant when creating an instance of JTabbedPane. The placement can be the following values: JTabbedPane.TOP, JTabbedPane.RIGHT, JTabbedPane.LEFT and JTabbedPane.BOTTOM.

package com.javacoderanch.example.swing;

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

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

    private void initializeUI() {
        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(400, 200));

        //
        // Creates a JTabbedPane with tabs at the bottom.
        //
        JTabbedPane pane = new JTabbedPane(JTabbedPane.BOTTOM);
        pane.addTab("Tab 1", createPanel("Panel 1"));
        pane.addTab("Tab 1", createPanel("Panel 2"));
        pane.addTab("Tab 3", createPanel("Panel 3"));

        this.add(pane, BorderLayout.CENTER);
    }

    public JPanel createPanel(String title) {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.add(new JLabel(title), BorderLayout.NORTH);
        return panel;
    }

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

        JFrame frame = new JFrame("JTabbedPane Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

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