Using TableCellRenderer and getColumnClass together

后端 未结 2 1981
忘了有多久
忘了有多久 2021-01-24 20:49

when i add getcolumn class to my abstracttablemodel, i couldnt use my custom TableCellRenderer to set background color. (i use this for sorting,alignment numeric columns)

<
相关标签:
2条回答
  • 2021-01-24 21:05

    Your getColumnClass() method will return: String.class, Double.class and Integer.class for columns 0, 1, 2.

    JTable will provide the default renderer for the Double and Integer columns.

    If you want to use your custom renderer for all your columns then you need to do:

    MyCustomTableCellRenderer renderer = new MyCustomTableCellRenderer();
    table.setDefaultRenderer(Object.class, renderer); // or you could use "String.class"
    table.setDefaultRenderer(Double.class, renderer);
    table.setDefaultRenderer(Integer.class, renderer);
    

    When you use "Object.class" it means use the Object renderer as a last resort renderer, only if no other custom renderer for the specific class has been added to the table.

    0 讨论(0)
  • 2021-01-24 21:16

    Use TableColumn#setCellRenderer() to draw individual values for each column.

    Just add below lines in your code

    MyCustomTableCellRenderer cellRenderer = new MyCustomTableCellRenderer();
    for (int i = 0; i < table.getColumnCount(); i++) {
        table.getColumnModel().getColumn(i).setCellRenderer(cellRenderer);
    }
    

    instead of

    table.setDefaultRenderer(Object.class, new MyCustomTableCellRenderer());
    

    and your problem will be solved.

    Note: You are using DefaultTableCellRenderer that will apply on cell hence use setCellRenderer() instead of setDefaultRenderer().

    screenshot: (one row is selected)

    enter image description here

    0 讨论(0)
提交回复
热议问题