java ListTest
第一個檔名:ListFrame.java
import java.awt.FlowLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.ListSelectionModel;
public class ListFrame extends JFrame
{
private JList colorJList;
private final String colorNames[] = { "Black", "Blue" , "Pink", "Orange",
"Red", "White", "Yellow" } ;
private final Color colors[] = { Color.BLACK, Color.BLUE, Color.PINK, Color.ORANGE,
Color.RED, Color.WHITE, Color.YELLOW };
public ListFrame()
{
super("List Test");
setLayout( new FlowLayout() );
colorJList = new JList( colorNames );
colorJList.setVisibleRowCount( 5 );
colorJList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
add( new JScrollPane( colorJList ) );
colorJList.addListSelectionListener(
new ListSelectionListener()
{
public void valueChanged( ListSelectionEvent event )
{
getContentPane().setBackground( colors[ colorJList.getSelectedIndex() ] );
}
}
);
}
}
------------------------------------------------------------------------------------
第二個檔名:ListTest.java
import javax.swing.JFrame;
public class ListTest
{
public static void main ( String args[] )
{
ListFrame listFrame = new ListFrame();
listFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
listFrame.setSize( 350, 150 );
listFrame.setVisible( true );
}
}
留言列表