Java JTabbedPane Example

In this section we will discuss about how to add the Tab pane in JFrame.

Java JTabbedPane Example

In this section we will discuss about how to add the Tab pane in JFrame.

Java JTabbedPane Example

Java JTabbedPane Example

In this section we will discuss about how to add the Tab pane in JFrame.

javax.swing.JTabbedPane provides the feature to add tabs onto the frame in Java. Using tab user can switch to one component to another.

Example

Here I am going to discuss about how to add tabs onto the frame. Through this example I will see you how to add tabs into the JFrame and how to add components on each tabs. For this I have created a Java Class named AddJTabbedPane.java into which I have created a method that describes the user interface. In this method I have instantiated various Jlabel,  JPanel. As well as instantiated JTabbedPane and JFrame. These labels are created for labeling the values which will be displayed with the associated tabs. Then created a JFrame and added two tabs named 'Fruit' and 'Vegetable' onto the JFrame.

Source Code

import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;

class AddJTabbedPane 
{
	JTabbedPane tp;
	JLabel lab1, lab2, lab3, lab4, lab5, lab6, lab7, lab8;
	JPanel fruit, vegetable;
	JFrame frame;
	public void createUI()
	{
		frame=new JFrame("JTabbedPane Example");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		fruit = new JPanel(new GridLayout(6,2));
		lab1=new JLabel("Apple");
		lab2=new JLabel("Orange");
		lab3=new JLabel("Papaya");
		lab4=new JLabel("Pine Apple");
		fruit.add(lab1);
		fruit.add(lab2);
		fruit.add(lab3);
		fruit.add(lab4);

		vegetable = new JPanel(new GridLayout(6,2));
		lab5=new JLabel("Cauliflower");
		lab6=new JLabel("Brinjal");
		lab7=new JLabel("Peas");
		lab8=new JLabel("Lady finger");
		vegetable.add(lab5);
		vegetable.add(lab6);
		vegetable.add(lab7);
		vegetable.add(lab8);
		
		tp=new JTabbedPane();
                Container pane = frame.getContentPane();
		pane.add(tp);
		tp.addTab("Fruit",fruit);
		tp.addTab("Vegetable",vegetable);

		frame.setSize(200,200);
		frame.setVisible(true);

	}	
	public static void main(String[] args) 
	{
		AddJTabbedPane tbp = new AddJTabbedPane();
		tbp.createUI();		
	}
}

Output

When you will execute the above example you will get the output as follows :

And the Frame will be look like as follows :

And when you will switch to Vegetable tab then the vegetable's name will be displayed.

Download Source Code