A Table with Custom Editing and Rendering

Recall from the previous chapter that you can build your own editors and renderers for the cells in your table. One easy customization is altering the properties of the DefaultTableCellRenderer, which is an extension of JLabel. You can use icons, colors, text alignment, borders, and anything that can change the look of a label.

You don’t have to rely on JLabel, though. Developers come across all types of data. Some of that data is best represented as text—some isn’t. For data that requires (or at least enjoys the support of) alternate representations, your renderer can extend any component. To be more precise, it can extend Component, so your options are boundless. We look at one of those options next.

A Custom Renderer

Figure 16-3 shows a table containing audio tracks in a mixer format, using the default renderer. We have some track information, such as the track name, its start and stop times, and two volumes (left and right channels, both using integer values from to 100) to control.

A standard table with cells drawn by the DefaultTableCellRenderer

Figure 16-3. A standard table with cells drawn by the DefaultTableCellRenderer

We’d really like to show our volume entries as sliders. The sliders give us a better indication of the relative volumes. Figure 16-4 shows the application with a custom renderer for the volumes.

Figure 16-4. A standard table with the volume cells drawn by VolumeRenderer

The code for ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.