Brought to you by EarthWeb
ITKnowledge Logo Login Graphic Click Here!
Click Here!
ITKnowledge
Search this book:
 
Search the site:
 
EXPERT SEARCH ----- nav

EarthWeb Direct

EarthWeb Direct

EarthWeb sites: other sites

Previous Table of Contents Next


A Complete JTabbedPane Sample Application

Listing 14.3 shows the DynamicTabbedPaneTest application that allows tabs to be dynamically added and removed from the test tabbed pane. The application consists of two view areas: the tabbed pane to the left and the control panel to the right. Upon application initialization, three tabs are added to the tabbed pane. After that, clicking the Add Tab button will add a new tab to the tabbed pane. Clicking the Remove Selected button will remove the selected tab from the tabbed pane. The Select None button will clear the selection in the tabbed pane when chosen. The final component in the control panel displays the selected tab in the tabbed pane. Notice that the selected tab is counted from 0.

Each tab contains a JLabel instance and a JTextField instance. The label displays the number of the tab. Tabs are numbered sequentially from the start of the application beginning with zero. The JTextField instance contains the text of the tab’s title. This text can be edited, and will update the tab’s title to the string entered in the text field when the enter key is typed in the text field. The initial title for the tab is its number.

The DynamicTabbedPaneTest application is shown in Figure 14.4 after some tabs have been added and removed. The titles of some of the tabs have also been edited. In this example, the location of the tabs is not explicitly set, so the tabs are placed on top of the components, in their default locations.


Figure 14.4  The complete DynamicTabbedPane-Test application.

Listing 14.3 The DynamicTabbedPaneTest Application

package com.foley.test;

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

import javax.swing.*;
import javax.swing.event.*;

import com.foley.utility.JBox;
import com.foley.utility.ApplicationFrame;


/**
 * An application that displays a JTabbedPane in a frame.
 * New tabs may be added to the tab by pressing a button.
 * The title of a tab may be updated by hitting enter in the
 * textField contained in the tab.
 *
 * @author Mike Foley
 **/
public class DynamicTabbedPaneTest extends Object {
    private JBox jBox;
    private JTabbedPane tabbedPane;
    private JLabel selectedLabel;

    private int addedTabCount;
    

    /**
     * Create the panel for the test application.
     * This panel contains a JTabbedPane to the left,
     * and some configuration controls to the right.
     **/
    public DynamicTabbedPaneTest() {

        //
        // No tabs have been added yet.
        //
        addedTabCount = 0;

        tabbedPane = createTabbedPane();
        tabbedPane.setBorder( BorderFactory.createLoweredBevelBorder()  );

        jBox = JBox.createHorizontalJBox();
        jBox.add( tabbedPane );

        jBox.add( Box.createRigidArea( new Dimension( 10, 10 ) ) );

        JPanel controlPanel = createControlPanel();
        jBox.add( controlPanel );
    }

    /**
     * Create the tabbed pane used in the application.
     * Add a few interesting tabs.
     * <p>
     * @return The tab pane instance for this application.
     **/
    protected JTabbedPane createTabbedPane() {
        JTabbedPane tabbedPane = new JTabbedPane();

        addTab( tabbedPane );
        addTab( tabbedPane );
        addTab( tabbedPane );

        tabbedPane.setForegroundAt( 0, Color.red );
        tabbedPane.setBackgroundAt( 0, Color.yellow );
        tabbedPane.setForegroundAt( 1, Color.yellow );
        tabbedPane.setBackgroundAt( 1, Color.red );
        return( tabbedPane );
    }
    

    /**
     * Create the controls for adding and removing tabs.
     * <p>
     * @return The control panel.
     **/
    protected JPanel createControlPanel() {
        JPanel controlPanel = new JPanel();
        BoxLayout boxLayout = new BoxLayout( controlPanel,
                                             BoxLayout.Y_AXIS );

        controlPanel.setLayout( boxLayout );

        JButton addButton = new JButton( “add tab” );
        controlPanel.add( addButton );
        controlPanel.add( Box.createRigidArea( new Dimension(10,10) ) );
        addButton.addActionListener( new ActionListener() {
            public void actionPerformed( ActionEvent event ) {
                addTab( tabbedPane );
                getCenter().repaint();
            }
        } );

        JButton removeButton = new JButton( “remove selected” );
        controlPanel.add( removeButton );
        controlPanel.add( Box.createRigidArea( new Dimension(10,10) ) );
        removeButton.addActionListener( new ActionListener() {
            public void actionPerformed( ActionEvent event ) {
                removeSelectedTab();
            }
        } );
        
        JButton noneButton = new JButton( “select none” );
        controlPanel.add( noneButton );
        controlPanel.add( Box.createRigidArea( new Dimension(10,10) ) );
        noneButton.addActionListener( new ActionListener() {
            public void actionPerformed( ActionEvent event ) {
                tabbedPane.getModel().clearSelection();
            }
        } );

        selectedLabel = new JLabel();
        setSelectedLabel();
        controlPanel.add( selectedLabel );
        controlPanel.add( Box.createRigidArea( new Dimension(10,10) ) );
        tabbedPane.addChangeListener( new ChangeListener() {
            public void stateChanged( ChangeEvent event ) {
                setSelectedLabel();
            }
        } );
        return( controlPanel );
    }
    
    /**
     * Update the text on the selectedLabel to the currently
     * selected tab in the tabbedPane.
     **/
    private void setSelectedLabel() {
        if( tabbedPane.getModel().isSelected() )
            selectedLabel.setText( “Selected Index: “ +
                                   tabbedPane.getSelectedIndex() );
        else
            selectedLabel.setText( “None Selected” );
    }


    /**
     * Create a JLabel and add it to the tabbed pane.
     * The text of the label matches the tab’s text, and
     * is simply the number of tabs created during this
     * run of the application.
     * <p>
     * @return The index of the newly added tab.
     **/
    private int addTab( final JTabbedPane tabbedPane ) {
        String name = “Tab “ + addedTabCount;
        final JPanel panel = new JPanel();
        panel.setLayout( new BorderLayout() );
        
        panel.add( new JLabel( name ), BorderLayout.NORTH );
        final JTextField textField = new JTextField( name );
        textField.addActionListener( new ActionListener() {
            public void actionPerformed( ActionEvent event ) {
                //
                // Update the title of our tab to that entered.
                //
                String newTitle = textField.getText();
                int index = tabbedPane.indexOfComponent( panel );
                tabbedPane.setTitleAt( index, newTitle );
                //
                // validate and paint the tabs to display properly.
                //
                tabbedPane.revalidate();
                tabbedPane.repaint();
            }
        } );

        panel.add( textField, BorderLayout.SOUTH );

        tabbedPane.add( panel, name );
        tabbedPane.revalidate();

        //
        // Bump the number of tabs added.
        //
        addedTabCount += 1;

        return( tabbedPane.getTabCount() - 1 );
    }
    

    /**
     * Remove the currently selected tab from the tabbed pane.
     **/
    private void removeSelectedTab() {
        if( tabbedPane.getModel().isSelected() ) {
            int selectedIndex = tabbedPane.getSelectedIndex();
            tabbedPane.removeTabAt( selectedIndex );
            tabbedPane.revalidate();
            getCenter().repaint();
        }
    }

    /**
     * @return The center component in this object.
     **/
    public JComponent getCenter() {
        return( jBox );
    }


    /**
     * Application entry point.
     * Create the frame, and display a tabbed pane in it.
     *
     * @param args Command line parameter. Not used.
     **/
    public static void main( String args[] ) {

        JFrame frame = new ApplicationFrame( “DynamicTabbedPaneTest” );
        JTabbedPaneTest test = new JTabbedPaneTest();

        frame.getContentPane().add( test.getCenter(),
                                    BorderLayout.CENTER );
        frame.pack();
        frame.setVisible( true );

    } // main

} // DynamicTabbedPaneTest

Summary

The JTabbedPane class provides a container that shows one component in a set of components at a given time. Tabs are provided to allow the user to switch the currently visible component. The tabs can be placed on any side of the component display area. Methods are provided to set the foreground and background colors of the tabs. The component added to the tabbed pane itself controls its colors. The class employs a SingleSelectionModel to track which component is selected. If there is not a component selected, the tabbed pane displays empty.

Methods are provided to dynamically alter the components in the tabbed pane. You can insert a component at any given position or append it to the end of the existing components in the tabbed pane. A component can be removed dynamically from the tabbed pane, or all components can be removed with a single method call. Each of the add and remove types of methods can operate on a given component or index. Methods are also provided to convert from index to component, and vice versa.

Components and tabs already in the tabbed pane can be changed. The component can be replaced, as well as the text and icon in the tab.

To demonstrate the use of the JTabbedPane class, a complete example using many of the methods in the JTabbedPane class was presented. In this application, tabs can be added and removed interactively from the tabbed pane. The title for the tab also can be edited.


Previous Table of Contents Next
HomeAbout UsSearchSubscribeAdvertising InfoContact UsFAQs
Use of this site is subject to certain Terms & Conditions.
Copyright (c) 1996-1999 EarthWeb Inc. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.