/* * File: ListTest.java * * Create a scrolling list that allows only one item to be selected. * Uses ListSelectionEvents when an item is selected. * Also demonstrates the Toolkit class to get Font information from * the browser. * * Copyright: Northeast Parallel Architectures Center * */ import javax.swing.*; import javax.swing.JComponent.*; import java.awt.Color; import java.awt.Toolkit; import java.awt.Font; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; public class ListTest extends JApplet implements ListSelectionListener{//ItemListener, // Allow five visible items in the list, but // disallow multiple selections: private JList fontList; //No default scrolling .SO scrollPane must be added private JScrollPane scrollPane ; private String fontString; private JLabel fontLabel; private Font f = new Font ("Dialog", Font.PLAIN, 18); public void init() { getContentPane().setLayout(new FlowLayout()); setBackground( Color.white ); setFont (f); // Color the scrolling list: Color lightBlue = new Color( 0xB0, 0xE0, 0xE6 ); Color navyBlue = new Color( 0x19, 0x19, 0x70 ); // Get list of system fonts: Toolkit toolkit = Toolkit.getDefaultToolkit(); String fonts[] = toolkit.getFontList(); fontList = new JList(fonts); scrollPane = new JScrollPane(fontList); fontList.setBackground( lightBlue ); fontList.setForeground( navyBlue ); //Row count that will be visible fontList.setVisibleRowCount(3); //Single selection only allowed fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Construct a text label: fontString = " Once in a galaxy "; fontString += "far, far away! "; fontLabel = new JLabel( fontString, JLabel.CENTER ); getContentPane().add(scrollPane); getContentPane().add(fontLabel); // Determine default font: String defaultFontName = fontLabel.getFont().getName(); // Select default font in scrolling list: for ( int i = 0; i < fonts.length; i++ ) { if ( defaultFontName.equals( fonts[i] ) ) { fontList.setSelectedIndex(i); break; } } // Register the applet to listen for events: fontList.addListSelectionListener(this); } public void valueChanged(ListSelectionEvent event){ String fontName = (String)fontList.getSelectedValue(); int style = Font.BOLD; int size = fontLabel.getFont().getSize(); fontLabel.setFont( new Font( fontName, style, size ) ); fontLabel.setText(fontString ); update(this.getGraphics()); showStatus( "You chose " + fontName + "!" ); } }