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.

This method signature is very similar <strong>to</strong> the<br />

getListCellRendererComponent() method used <strong>to</strong> create cus<strong>to</strong>m list<br />

cell renderers.<br />

This method is passed with a JTable, the value associated with<br />

the cell, information regarding whether the value is selected and<br />

whether the cell has the focus, and the row and column indices of<br />

the value. The <strong>com</strong>ponent returned from the method is painted on<br />

the cell in the table. The class in Listing 40.9,<br />

MyImageCellRenderer, defines a renderer for displaying image<br />

icons in a panel.<br />

Listing 40.9 MyImageCellRenderer.java<br />

<br />

<br />

<br />

<br />

import javax.swing.*;<br />

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

import java.awt.*;<br />

public class MyImageCellRenderer extends DefaultTableCellRenderer {<br />

/** Override this method in DefaultTableCellRenderer */<br />

public Component getTableCellRendererComponent<br />

(JTable table, Object value, boolean isSelected,<br />

boolean isFocused, int row, int column) {<br />

Image image = ((ImageIcon)value).getImage();<br />

ImageViewer imageViewer = new ImageViewer(image);<br />

}<br />

}<br />

return imageViewer;<br />

You can also create a cus<strong>to</strong>m edi<strong>to</strong>r. JTable provides the<br />

DefaultCellEdi<strong>to</strong>r class, which can be used <strong>to</strong> edit a cell in a<br />

text field, a check box, or a <strong>com</strong>bo box. To use it, simply create<br />

a text field, a check box, or a <strong>com</strong>bo box, and pass it <strong>to</strong><br />

DefaultCellEdi<strong>to</strong>r's construc<strong>to</strong>r <strong>to</strong> create an edi<strong>to</strong>r.<br />

Using a cus<strong>to</strong>m renderer and edi<strong>to</strong>r, the preceding example can be<br />

revised <strong>to</strong> display scaled images and <strong>to</strong> use a cus<strong>to</strong>m <strong>com</strong>bo edi<strong>to</strong>r<br />

<strong>to</strong> edit the cells in the Publisher column, as shown in Figure<br />

40.16. The program is given in Listing 40.10.<br />

Figure 40.16<br />

A cus<strong>to</strong>m renderer displays a scaled image, and a cus<strong>to</strong>m edi<strong>to</strong>r<br />

edits the Publisher column using a <strong>com</strong>bo box.<br />

Listing 40.10 Cus<strong>to</strong>mTableCellRendererEdi<strong>to</strong>rDemo.java<br />

<br />

24

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

Saved successfully!

Ooh no, something went wrong!