next up previous
Next: Adding and removing list Up: Text In Swing Previous: Text areas

Combo boxes -- JComboBox

All of the components we have examined in this chapter have been derived from JTextComponent; however, there are other components in Swing which handle text.

These components are generally not parented by JTextComponent, they are usually composed of at least one JTextComponent child with the addition of some other functionality.

The combo box (also known as a pull-down list).

A combo box is the combination in a single component of

A JComboBox

The actions of the combo box are as follows:

When the use combo boxes? Use combo boxes to conserve GUI Space:

As simple example program, that produced the above combo box follows:

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

class CombBoxExample
		extends 	JFrame
		implements  ItemListener
{
	private	JComboBox	combo;

	final   String[]    sList =
	                    {
	                        "Canada",
	                        "USA",
	                        "Australia",
	                        "Bolivia",
	                        "Denmark",
	                        "Japan"
	                    };
	public CombBoxExample()
	{
		setTitle( "ComboBox Application" );
		setSize( 300, 110 );
		setBackground( Color.gray );
		getContentPane().setLayout( new BorderLayout() );

		JPanel topPanel = new JPanel();
		topPanel.setLayout( null );
		getContentPane().add( topPanel, BorderLayout.CENTER );

        // Create a combobox
		combo = new JComboBox();
		combo.setBounds( 20, 35, 260, 20 );
		topPanel.add( combo );

		// Populate the combobox list
		for( int iCtr = 0; iCtr < sList.length; iCtr++ )
		    combo.addItem( sList[iCtr] );

        // Allow edits
        combo.setEditable( true );

        // Watch for changes
        combo.addItemListener( this );
	}

	public void itemStateChanged( ItemEvent event )
	{
		if( event.getSource() == combo
				&& event.getStateChange() == ItemEvent.SELECTED )
		{
			System.out.println( "Change:"
							+ combo.getSelectedItem() );
		}
	}

	public static void main( String args[] )
	{
		// Create an instance of the test application
		CombBoxExample mainFrame	= new CombBoxExample();
		mainFrame.setVisible( true );
	}
}



 
next up previous
Next: Adding and removing list Up: Text In Swing Previous: Text areas
Dave Marshall
4/14/1999