How to create tabbed panes in Java Swing?

Tabbed pane is used to show the component from a group of same components if one of the tab of a pane is selected. i.e. When the tab is selected it shows corresponding component and so on. Extended portion of tab may have a title, an icon or both together. Tab may get highlighted when selection is made.
Tabbed panes are generally used to save the space by having multiple components separated by a tab.

In Java Swing we can create tabbed panes using JTabbedPane. JTabbedPane comes with three constructor flavours.

JTabbedPane() 


Above constructor constructs an empty tabbed pane with default tab placement which is at the tab and denoted by JTabbedPane.TOP.

JTabbedPane( int tabPlacement )


In above constructor we can specify the tab placement which is specified by either JTabbedPane.TOP, JTabbedPane.BOTTOM , JTabbedPane.RIGHT, JTabbedPane.LEFT.

JTabbedPane ( int tabPlacement, int tabLayoutPolicy )

In above constructor with tab placement option we can also specify the tab layout policy which is the policy which decides how to layout the panes when all tabs do not fit on the go.

Now lets see how we can create the tabbed panes using JTabbedPane.
JFrame tabbedFrame = new JFrame("Tabbed Pane Example");
tabbedFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabEx = new JTabbedPane();
tabbedFrame.add( tabEx, BorderLayout.CENTER );
JButton button = new JButton( "1st tab selected" );
tabEx.add( "1st Tab", button );
button = new JButton( "2nd tab selected" );
tabEx.add("2nd Tab", button);
tabbedFrame.setSize( 300,200 );
tabbedFrame.setVisible( true );

Output:



In above example we have used add method which adds a component to JTabbedPane with a specified title. Here we have used method with two arguments, first is the title which is the title to be displayed for the tab and second argument is the component which need to be shown up when we select the tab.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment