I noticed this is common. For example DefaultListCellRenderer, DefaultTableCellRenderer, and DefaultTreeCellRenderer all use it. Also a lot of the custom cell renderers I see online use this as well. I want to use a custom TableCellRenderer in my code, but I'm confused about whether I really need to subclass JLabel. What's the benefit of subclassing JLabel?
The API for the DefaultTableCellRenderer states:
The table class defines a single cell renderer and uses it as a as a rubber-stamp for rendering all cells in the table; it renders the first cell, changes the contents of that cell renderer, shifts the origin to the new location, re-draws it, and so on. The standard
JLabel
component was not designed to be used this way and we want to avoid triggering arevalidate
each time the cell is drawn. This would greatly decrease performance because therevalidate
message would be passed up the hierarchy of the container to determine whether any other components would be affected. As the renderer is only parented for the lifetime of a painting operation we similarly want to avoid the overhead associated with walking the hierarchy for painting operations. So this class overrides thevalidate
,invalidate
,revalidate
,repaint
, andfirePropertyChange
methods to be no-ops and override theisOpaque
method solely to improve performance. If you write your own renderer, please keep this performance consideration in mind.