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 how to use a GUI to input enums with a javax.swing.JComboBox.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2010-04-03 initial version
* @since 2010-04-03
*/
public final class TestEnumJComboBox
{
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<GrapefruitVariety> variety = new JComboBox<>( GrapefruitVariety.values() );
variety.setMaximumRowCount( GrapefruitVariety.values().length );
variety.setForeground( FOREGROUND_FOR_LABEL );
variety.setBackground( Color.WHITE );
variety.setFont( new Font( "Dialog", Font.BOLD, 15 ) );
variety.setEditable( false );
variety.setSelectedIndex( 0 );
variety.setSelectedItem( GrapefruitVariety.GOLDEN );
variety.addItemListener( 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 )
{
String choice = variety.getSelectedItem().toString();
out.println( choice );
}
} );
contentPane.add( variety );
jFrame.setSize( 100, 100 );
jFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
jFrame.validate();
jFrame.setVisible( true );
}
} );
}
enum GrapefruitVariety
{
GOLDEN( "Golden" ),
MARSH( "Marsh Ruby" ),
RIO( "Rio Red" ),
RUBY( "Ruby" ),
STAR( "Star Ruby" ),
WHITE( "White" );
/**
* human name of variety
*/
private final String name;
/**
* constructor
*
* @param name human name of variety
*/
GrapefruitVariety( String name )
{
this.name = name;
}
/**
* override standard toString
*
* @return name of variety
*/
public String toString()
{
return name;
}
}
}