John O'really
John O'really

Reputation: 11

How to make CardLayout inside JTabbedPane

I am working on a project with JTabbedPane

When I click TAB2, it shows the PANEL 2. Done

PANEL 2 consist of a JButton "Next" that will switch to PANEL 2.1 and JButton "Previous" to

switch it back to PANEL 2 while still in the TAB 2.

So, it is a Card Layout inside Tab2?

Thanks for helping!

-----------------------------
TAB 1  |  TAB 2 |  TAB 3 |  
-----------------------------
                             -
                             -
          PANEL  2           -
                             -
                             -
                             -
                             -
      "Previous" "NEXT"      -
==========================   =

Upvotes: 1

Views: 2508

Answers (1)

davidbuzatto
davidbuzatto

Reputation: 9424

You just need to insert a JPanel in the tab and set its layout as CardLayout. So, inside each "card" you will insert a new JPanel. Here is an example:

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

public class Foo extends JFrame {

    public Foo() {

        setTitle( "Tabs and Cards" );
        setSize( 400, 400 );
        setDefaultCloseOperation( EXIT_ON_CLOSE );

        JTabbedPane tabbedPane = new JTabbedPane();

        // needs to be final to be accessed inside the event handlers
        final JPanel tab1 = new JPanel();
        final JPanel tab2 = new JPanel();
        tab2.setLayout( new CardLayout() );

        tabbedPane.addTab( "Tab 1", tab1 );
        tabbedPane.addTab( "Tab 2", tab2 );


        JPanel tab21 = new JPanel();
        tab21.add( new JLabel( "2.1" ) );

        JPanel tab22 = new JPanel();
        tab22.add( new JLabel( "2.2" ) );

        JPanel tab23 = new JPanel();
        tab23.add( new JLabel( "2.3" ) );

        tab2.add( tab21 );
        tab2.add( tab22 );
        tab2.add( tab23 );


        JButton btnToTab22 = new JButton( "Next!" );
        btnToTab22.addActionListener( new ActionListener(){
            @Override
            public void actionPerformed( ActionEvent evt ) {
                // gets the layout, casts it and call next to go to the next card
                ( ( CardLayout ) tab2.getLayout() ).next( tab2 );
            }
        });
        tab21.add( btnToTab22 );

        JButton btnToTab23 = new JButton( "Next!" );
        btnToTab23.addActionListener( new ActionListener(){
            @Override
            public void actionPerformed( ActionEvent evt ) {
                ( ( CardLayout ) tab2.getLayout() ).next( tab2 );
            }
        });
        tab22.add( btnToTab23 );

        add( tabbedPane, BorderLayout.CENTER );

        setVisible( true );

    }

    public static void main( String[] args ) {
        new Foo();
    }

}

I didn't commented the code because is not so complicated, but I think that you will understand easily. Take a look at the documentation.

Upvotes: 3

Related Questions