Why do cell handlers often extend JLabel?

I noticed that this is common. For example, DefaultListCellRenderer, DefaultTableCellRenderer, and DefaultTreeCellRenderer use it. In addition, many custom cell renderings that I see on the Internet also use this. I want to use a custom TableCellRenderer in my code, but I'm confused about whether I really need JLabel subclasses. What is the use of the JLabel subclass?

+8
java swing subclassing jlabel
source share
3 answers

The API for DefaultTableCellRenderer states:

The table class defines a single cell renderer and uses it as a stamp to render all cells in a table; it displays the first cell, changes the contents of this cell renderer, transfers the origin to a new location, re-draws it, etc. The standard JLabel component was not intended to be used this way, and we want to avoid running revalidate every time a cell is drawn. This will significantly reduce performance, as the revalidate message will be passed to the container hierarchy to determine if any other components will be affected. Since rendering is the only parent for the life of the drawing operation, we also want to avoid the overhead associated with walking through the hierarchy for the drawing operation. Thus, this class overrides the validate , invalidate , revalidate , repaint and firePropertyChange , which are not op-ops, and override the isOpaque method solely for performance isOpaque . If you are writing your own renderer, consider this performance consideration.

+10
source share

JLabel has all the necessary firepower, and then it processes the text and icons, it can center itself, by default it has an opaque background ... and I could go on and on ...

+5
source share

Because everyone - even the early Swing team - has the right to do things the wrong way :-)

It is wrong to expand the component instead of implementing the visualizer interface and allow this implementation to delegate the component (which may be a specially implemented JLabel with all the whistles that they consider necessary, I’m not personally convinced). We are still suffering from this poor implementation decision - ominous "color memory "DefaultTableCellRenderer is a direct result.

So: Do-not-subclass-someComponent-to-implement-someRenderer. Especially not for someComponent == DefaultTableCellRenderer, it is broken!

BTW, SwingX does it right :-)

+4
source share

All Articles