28.12.2012 Views

Core JFC Java Foundation Classes 2nd edition - Read

Core JFC Java Foundation Classes 2nd edition - Read

Core JFC Java Foundation Classes 2nd edition - Read

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

1402 Chapter I I The Table Control<br />

stored into. Since no column-based editors or Tenderers are installed, the<br />

getColumnClass method that is used here is critical, because the value it<br />

returns for each column determines which editor and renderer will be used.<br />

The first column, which contains strings, will be rendered and edited by<br />

the class-based renderer and editor for Object—a JLabel and a JText-<br />

Field, respectively. These are sufficient because they both work in terms of<br />

Strings, no matter what type of Object they are actually dealing with. The<br />

second column contains Color objects. There is no standard renderer or editor<br />

for Color, so the table would naturally use a JLabel to render and a<br />

JTextField to edit the result of applying the toString method to the<br />

Color object—which would produce a meaningless result. Here, however,<br />

our ColorRenderer and ColorEditor will be installed as class-based<br />

objects for the Color class so that they are used instead. If you run this<br />

example with the command:<br />

<strong>Java</strong> <strong>JFC</strong>Book.Chapter11.CustomEditorExample<br />

you get a result that looks like Figure 11-17. Although the gray-scale reproduction<br />

of this screen shot is not ideal, you can see that each persons name is<br />

accompanied by a small icon filled with that person s favorite color, or at least<br />

its gray-scale equivalent!<br />

Figure 11-17 A table with a custom renderer for colors.<br />

Implementing a Custom Color Renderer<br />

Next, lets look at the implementation of ColorRenderer. This renderer will<br />

be given a value from the table of type Color and will need to display a small<br />

Icon filled with that color. Like the other Tenderers that you've seen, this one<br />

is derived from Def aultTableCellRenderer and therefore uses a JLabel<br />

as the host component. JLabel is a good choice for this example because, as<br />

you know, it can display an Icon as well as, or instead of, text, so all the ren-

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

Saved successfully!

Ooh no, something went wrong!