Custom header renderer in JXTable?

271 views Asked by At

I was using JTable#setDefaultRenderer to set custom rendered in Swing.

As I understood, in SwingX this method should be passed an instance of DefaultTableRenderer. If I need a very custom drawing, I can initialize DefaultTableRenderer with my custom ComponentProvider

I.e. renderer functions were moved to provider's.

Now what to do with header?

In Swing I was doing

getTableHeader().setDefaultRenderer(new MyHeaderRenderer());

What should I do in SwingX? Use DefaultTableRenderer again?

1

There are 1 answers

0
dic19 On

As I understood, in SwingX this method should be passed an instance of DefaultTableRenderer

I wouldn't say you should / must / have to use DefaultTableRenderer, because the contract is inherited from JTable and it requires a TableCellRenderer interface compliant object.

It can be a DefaultTableRenderer and we can take advantage of ComponentProvider<?> to delegate the renderer component creation based on a CellContext, as explained here. But it also can be a DefaultTableCellRenderer as well or any implementation that meets the interface (for example).

It is true that setDefaultRenderer(Class class, TableCellRenderer renderer) method is overriden, not to make the renderer be a DefaultTableRenderer instance but to synchronize the the string representation in case the renderer is a StringValue interface compliant object. We can see that in the source code:

public class JXTable extends JTable implements TableColumnModelExtListener {

    ...

    /**
     * {@inheritDoc} <p>
     * 
     * Overridden to synchronize the string representation. If the renderer is of type
     * StringValue a mapping it will be used as converter for the class type. If not, 
     * the mapping is reset to default.
     */
    @Override
    public void setDefaultRenderer(Class<?> columnClass,
            TableCellRenderer renderer) {
        super.setDefaultRenderer(columnClass, renderer);
        getStringValueRegistry().setStringValue(
                (renderer instanceof StringValue) ? (StringValue) renderer : null, 
                        columnClass);
    }

    ...
}

So having said all this, I don't think you have the obligation to use DefaultTableRenderer in the table header either. The table header remains a JTableHeader (getTableHeader() method wasn't overridden as far as I know) and it still requires a TableCellRenderer compliant object to be set as the default renderer.