- Forward


Cell Renderers
in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Collection-Backed GUI Components:
    • Collection-backed GUI components (e.g., JComboBox, JList, JTable, JTree) can contain objects of any class but each must be rendered differently
  • The Default Renderer:
    • Calls the object's toString() method and renders the String
  • A Desirable Feature:
    • The ability to give the GUI component a renderer to use
Generic Renderers
Back SMYC Forward
  • What's Needed:
    • An object with a paint() method that can be passed an appropriately configured (i.e., with the correct bounds) Graphics object
  • What's Available:
    • Component and its descendants
  • How They Can Be Used:
    • As a "stamp"
Existing Hooks
Back SMYC Forward
  • JList/JComboBox:
    • Have a setCellRenderer()/setRenderer() method that is passed an object that implements the ListCellRenderer interface
  • JTable:
    • JTable has a setDefaultRenderer() method that is passed an object that implements the TableCellRenderer
    • TableColumn has a setCellRenderer() method that is passed an object that implements the TableCellRenderer
Creating a Renderer
Back SMYC Forward
  • Use an Existing Component:
    • Create a class that extends an appropriate existing GUI Component and implements the renderer interface
  • Use a Custom Container:
    • Create a class that extends a Container (e.g., JPanel), contains multiple appropriate components using an appropriate layout, and implements the renderer interface
  • Use a Custom Component:
    • Create a class that extends a Component (e.g., JComponent), implements the renderer interface, and overrides the paint method
Using an Existing Component
Back SMYC Forward

The Renderer

javaexamples/cellrenderer/ColorCellRenderer.java
 
Using an Existing Component (cont.)
Back SMYC Forward

An Application

javaexamples/cellrenderer/ColorCellRendererDemo.java
 
Using a Custom Container
Back SMYC Forward

A Supporting Class

javaexamples/cellrenderer/Fraction.java
 
Using a Custom Container (cont.)
Back SMYC Forward

The Component

javaexamples/cellrenderer/FractionLabel.java
 
Using a Custom Container (cont.)
Back SMYC Forward

The Renderer

javaexamples/cellrenderer/FractionCellRenderer.java
 
Using a Custom Container (cont.)
Back SMYC Forward

An Application

javaexamples/cellrenderer/FractionCellRendererDemo.java
 
Using a Custom Component
Back SMYC Forward

The Component

javaexamples/cellrenderer/ShapeLabel.java
 
Using a Custom Component (cont.)
Back SMYC Forward

The Renderer

javaexamples/cellrenderer/ShapeCellRenderer.java
 
Using a Custom Component (cont.)
Back SMYC Forward

An Application

javaexamples/cellrenderer/ShapeCellRendererDemo.java
 
There's Always More to Learn
Back -