package com.mindprod.example;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.util.List;
import static java.lang.System.*;
/**
* example use use of javax.swing.JList The code is quite different from AWT List.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2009-01-01 initial version
* @since 2009-01-01
*/
public final class TestJList
{
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 JList<String> flavour = new JList<>( new String[] {
"strawberry", "chocolate", "vanilla" } );
flavour.setForeground( FOREGROUND_FOR_LABEL );
flavour.setBackground( Color.WHITE );
flavour.setFont( new Font( "Dialog", Font.BOLD, 15 ) );
flavour.setSelectedIndex( 0 );
flavour.setSelectedValue( "chocolate", false);
flavour.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
flavour.setSelectedIndices( new int[] { 0, 2 } );
flavour.addListSelectionListener( new ListSelectionListener()
{
/**
* Called whenever the value of the selection changes.
* @param e the event that characterizes the change.
*/
public void valueChanged( ListSelectionEvent e )
{
out.println( "--selection--" );
String choice = flavour.getSelectedValue();
out.println( choice );
int which = flavour.getSelectedIndex();
out.println( which );
out.println( "--multiples--" );
List<String> choices = flavour.getSelectedValuesList();
for ( String aChoice : choices )
{
out.println( aChoice );
}
int[] indexes = flavour.getSelectedIndices();
for ( int index : indexes )
{
out.println( index );
}
}
} );
contentPane.add( flavour );
jFrame.setSize( 100, 100 );
jFrame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
jFrame.validate();
jFrame.setVisible( true );
}
} );
}
}