19 May 2011

JTabbedPane Tutorial




 JTabbedPane Tutorial
Hello Friends,

Nice to see you again.
Today we will learn JTabbed Pane in Java Swing.

JTabbedPane is very important Swing Component.

         We can use it in our Swing Application when we have less space to display much items in it. In these type of situation rather than use any simple JPanel , we can display in one JTabbedPane with many tab in it.

         So be ready to learn this simple exmaple of JTabbedPane.
After apply this code in action, you will be capable of using JTabbedPane in your Swing Applications.

         This simple example of JTabbedPane gives you the basic idea of JTabbedPane and you will be familiar for using JTabbedPane.

Output will be like this:










OK For this you have to create one class called JTabbedPaneDemo.java and paste the below code in it.
And run it....Simple right..?


-----------------------------------------------------------------------------------------------------------------------------------

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

public class JTabbedPaneDemo extends JFrame{
public JTabbedPaneDemo()
{
super("JTabbedPane Demo");
setLayout(new BorderLayout());
// This panel will contain all components
// and then it will add in JFrame to show.
JPanel mainPanel = new JPanel();
// Different Panel for display in 
//   all Tab in JTabbedPane.
JPanel panelOne=new JPanel();
JPanel panelTwo=new JPanel();
JPanel panelThree=new JPanel();
JTabbedPane tab=new JTabbedPane();
JLabel lblOne=new JLabel("This is First Tab");
JLabel lblTwo=new JLabel("This is Second Tab");
JLabel lblThree=new JLabel("This is Third Tab");
Dimension lblSize=new Dimension(300, 300);
lblOne.setPreferredSize(lblSize);
lblTwo.setPreferredSize(lblSize);
lblThree.setPreferredSize(lblSize);
panelOne.add(lblOne);
panelTwo.add(lblTwo);
panelThree.add(lblThree);
// Here all panel will add in JTabbedPane with title.
tab.add("Tab 1",panelOne);
tab.add("Tab 2",panelTwo);
tab.add("Tab 3",panelThree);
// Adding JtabbedPane in mainPanel.
mainPanel.add(tab);
// Adding Main Panel to JFrame.
add(mainPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
pack();
}
public static void main(String s[])
{
new JTabbedPaneDemo();
}
}

-----------------------------------------------------------------------------------------------------------------

So I hope this code is helpful in understanding the working of JTabbedPane.

Feel free to ask me if you have any dought regarding this.
You can also give me suggessions to improve this tutorial.

Leave comments if you like this post...!

Thank you.
Nirav Raval

3 comments:

Leave Comment If You Like This...Thank You..!