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.

You can use JList’s default cell renderer <strong>to</strong> display icons, as<br />

shown in Figure 39.22(b), using the following code:<br />

ImageIcon denmarkIcon = new ImageIcon(getClass().getResource(<br />

"image/denmarkIcon.gif"));<br />

...<br />

JList list = new JList(new ImageIcon[]{denmarkIcon, germanyIcon,<br />

chinaIcon, indiaIcon, norwayIcon, ukIcon, usIcon});<br />

How do you display a string along with an icon in one cell, as<br />

shown in Figure 39.22(c)? You need <strong>to</strong> create a cus<strong>to</strong>m renderer by<br />

implementing ListCellRenderer, as shown in Figure 39.23.<br />

JList<br />

«interface»<br />

javax.swing.ListCellRenderer<br />

+getListCellRendererComponent(list: JList,<br />

value: Object, index: int, isSelected: boolean,<br />

cellHasFocus: boolean): Component<br />

DefaultListCellRenderer<br />

YourCus<strong>to</strong>mListCellRenderer<br />

Figure 39.23<br />

ListCellRenderer defines how cells are rendered in a list.<br />

Suppose a list is created as follows:<br />

JList list = new JList(new Object[][]{{denmarkIcon, "Denmark"},<br />

{germanyIcon, "Germany"}, {chinaIcon, "China"},<br />

{indiaIcon, "India"}, {norwayIcon, "Norway"}, {ukIcon, "UK"},<br />

{usIcon, "US"}});<br />

Each item in the list is an array that consists of an icon and a<br />

string. You can create a cus<strong>to</strong>m cell renderer that retrieves an<br />

icon and a string from the list data model and display them in a<br />

label. The cus<strong>to</strong>m cell renderer class is given in Listing 39.9.<br />

Listing 39.9 MyListCellRenderer.java<br />

<br />

<br />

<br />

<br />

<br />

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

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

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

4<br />

5 public class MyListCellRenderer implements ListCellRenderer {<br />

6 private JLabel jlblCell = new JLabel(" ", JLabel.LEFT);<br />

7 private Border lineBorder =<br />

8 BorderFac<strong>to</strong>ry.createLineBorder(Color.black, 1);<br />

9 private Border emptyBorder =<br />

10 BorderFac<strong>to</strong>ry.createEmptyBorder(2, 2, 2, 2);<br />

11<br />

12 /** Implement this method in ListCellRenderer */<br />

13 public Component getListCellRendererComponent<br />

14 (JList list, Object value, int index, boolean isSelected,<br />

31

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

Saved successfully!

Ooh no, something went wrong!