package com.mindprod.example;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import static java.lang.System.*;
/**
* Demonstrate the use of javax.swing.JComboBox.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.1 2009-04-27 demonstrate use of setMaximumRowCount
* @since 2009-01-01
*/
public final class TestJComboBox
{
private static final Color FOREGROUND_FOR_LABEL = new Color( 0x0000b0 );
/**
* Debugging harness for a Frame
*
* @param args command line arguments are ignored.
*/
public static void main( String args[] )
{
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
final JFrame jFrame = new JFrame();
final Container contentPane = jFrame.getContentPane();
contentPane.setLayout( new FlowLayout() );
final JComboBox<String> flavour = new JComboBox<>( new String[] {
"strawberry", "chocolate", "vanilla" } );
flavour.setMaximumRowCount( 3 );
flavour.setForeground( FOREGROUND_FOR_LABEL );
flavour.setBackground( Color.WHITE );
flavour.setFont( new Font( "Dialog", Font.BOLD, 15 ) );
flavour.setEditable( false );
flavour.setSelectedIndex( 0 );
flavour.setSelectedItem( "chocolate" );
final ItemListener theListener = new ItemListener()
{
/**
* Called whenever the value of the selection changes. Will
* be called twice for every change.
* @param e the event that characterizes the change.
*/
public void itemStateChanged( ItemEvent e )
{
final int selectedIndex = flavour.getSelectedIndex();
final String choice = ( String ) flavour.getSelectedItem();
out.println( selectedIndex + " " + choice + " " + e.toString() );
}
};
flavour.addItemListener( theListener );
contentPane.add( flavour );
jFrame.setSize( 100, 100 );
jFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
jFrame.validate();
jFrame.setVisible( true );
flavour.setSelectedIndex( 2 );
flavour.removeItemListener( theListener );
flavour.setSelectedIndex( 1 );
flavour.addItemListener( theListener );
flavour.setSelectedIndex( 0 );
}
} );
}
}