Java JTabbedPane class example

Beginner java tutorial site is rehosted with updated content and useful information under the domain name javabeginner.com

 

JTabbedPane

 
Java Swing Tutorial Explaining the JTabbedPane Component. A JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text and an image.

 

 

 

The shape of a tab and the way in which the selected tab is displayed varies by Look and Feel.

JTabbedPane Source Code

Sept 18, 2006 by Hemanth

Swing JTabbedPane API Constructors

import javax.swing.JTabbedPane;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;

import java.awt.*;
import java.awt.event.*;

public class JTabbedPaneDemo extends JPanel {
    public JTabbedPaneDemo() {
        ImageIcon icon = new ImageIcon("java-swing-tutorial.JPG");
        JTabbedPane jtbExample = new JTabbedPane();

        JPanel jplInnerPanel1 = createInnerPanel("Tab 1 Contains Tooltip and Icon");
        jtbExample.addTab("One", icon, jplInnerPanel1, "Tab 1");
        jtbExample.setSelectedIndex(0);

        JPanel jplInnerPanel2 = createInnerPanel("Tab 2 Contains Icon only");
        jtbExample.addTab("Two", icon, jplInnerPanel2);

        JPanel jplInnerPanel3  = createInnerPanel("Tab 3 Contains Tooltip and Icon");
        jtbExample.addTab("Three", icon, jplInnerPanel3, "Tab 3");

        JPanel jplInnerPanel4 = createInnerPanel("Tab 4 Contains Text only");
        jtbExample.addTab("Four", jplInnerPanel4);

        //Add the tabbed pane to this panel.
        setLayout(new GridLayout(1, 1)); 
        add(jtbExample);
    }

    protected JPanel createInnerPanel(String text) {
        JPanel jplPanel = new JPanel();
        JLabel jlbDisplay = new JLabel(text);
        jlbDisplay.setHorizontalAlignment(JLabel.CENTER);
        jplPanel.setLayout(new GridLayout(1, 1));
        jplPanel.add(jlbDisplay);
        return jplPanel;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("TabbedPane Source Demo");
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
            	System.exit(0);}
        });

        frame.getContentPane().add(new JTabbedPaneDemo(), 
                                   BorderLayout.CENTER);
        frame.setSize(400, 125);
        frame.setVisible(true);
    }
}

 
        

Output

JTabbedPane

		
        
 

Download JTabbedPane Source Code

 

JTabbedPane question

When I use a JTabbedPane and want to listen to which tab is being clicked, which listerner should I use?

Answer: ChangeListener