19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

652 Chapter 17 GUI Components<br />

JList inside<br />

a scroll<br />

pane<br />

JPanel with<br />

GridLayout<br />

An image is<br />

displayed on a<br />

Jlabel<br />

FIGURE 17.9<br />

When the countries in the list are selected, corresponding images of their flags are displayed in the labels.<br />

Here are the major steps in the program:<br />

1. Create the user interface.<br />

Create a list with nine country names as selection values, and place the list inside a<br />

scroll pane. Place the scroll pane in the west of the frame. Create nine labels <strong>to</strong> be used<br />

<strong>to</strong> display the countries’ flag images. Place the labels in the panel, and place the panel<br />

in the center of the frame.<br />

2. Process the event.<br />

Create a listener <strong>to</strong> implement the valueChanged method in the<br />

ListSelectionListener interface <strong>to</strong> set the selected countries’ flag images in the<br />

labels.<br />

LISTING 17.5<br />

ListDemo.java<br />

1 import java.awt.*;<br />

2 import javax.swing.*;<br />

3 import javax.swing.event.*;<br />

4<br />

5 public class ListDemo extends JFrame {<br />

6 final int NUMBER_OF_FLAGS = 9;<br />

7<br />

8 // Declare an array of Strings for flag titles<br />

9 private String[] flagTitles = {"Canada", "China", "Denmark",<br />

10 "France", "Germany", "India", "Norway", "United Kingdom",<br />

11 "United States of America"};<br />

12<br />

13 // The list for selecting countries<br />

14 private JList jlst = new JList(flagTitles);<br />

15<br />

16 // Declare an ImageIcon array for the national flags of 9 countries<br />

17 private ImageIcon[] imageIcons = {<br />

18 new ImageIcon("image/ca.gif"),<br />

19 new ImageIcon("image/china.gif"),<br />

20 new ImageIcon("image/denmark.gif"),<br />

21 new ImageIcon("image/fr.gif"),<br />

22 new ImageIcon("image/germany.gif"),<br />

23 new ImageIcon("image/india.gif"),<br />

24 new ImageIcon("image/norway.gif"),<br />

25 new ImageIcon("image/uk.gif"),<br />

26 new ImageIcon("image/us.gif")<br />

27 };<br />

28

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!