// Fig. 12.13: ImageTest.java // Using JList to select an image to display. // The images are stored as byte arrays import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.io.*; public class ImageTest extends JFrame { private JList images; private JLabel label; private String names[] = { "Beard1.jpg", "Beard2.jpg", "Beard3.jpg", "Beard4.jpg", "Beard5.jpg" }; private byte icons[][] ; public ImageTest() { super( "Testing Images" ); try { icons = new byte[names.length][]; for (int i = 0; i < names.length; i++) { // access the requested file File file = new File(names[i]); // convert file to a byte array int numOfBytes = (int) file.length(); FileInputStream inFile = new FileInputStream (names[i]); icons[i] = new byte[numOfBytes]; inFile.read(icons[i]); } Container c = getContentPane(); c.setLayout( new FlowLayout() ); images = new JList( names ); images.setVisibleRowCount( 3 ); images.addListSelectionListener( new ListSelectionListener() { public void valueChanged( ListSelectionEvent e ) { Icon tempIcon = new ImageIcon (icons[ images.getSelectedIndex() ]); label.setIcon ( tempIcon ); } } ); c.add( new JScrollPane (images) ); Icon tempIcon = new ImageIcon (icons[0]); label = new JLabel( tempIcon ); c.add( label ); setSize( 350, 400 ); show(); } catch (Exception ex) { System.out.println (ex.getMessage()); } } public static void main( String args[] ) { ImageTest app = new ImageTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } } // This file is based on Fig. 12.13: ComboBoxTest.java from Deitel & Deitel // Java How to Program, @nd Ed. /************************************************************************** * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall. * * All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/