2

I am trying to add a different data types (to make JTable sort integer columns in a proper way) to my JTable and at the same time to render the table to see odd rows darker than even rows.

I have the following code of my TableCellRenderer:

public class MyCustomTableCellRenderer extends DefaultTableCellRenderer 
{
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean lected, boolean hasFocus, int row, int column) 
    {
        Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

        if (isSelected)
            cell.setBackground( new Color(180,180 ,255) );
        else
            if( row%2 == 0)
                cell.setBackground( new Color(220,220 ,255) );
            else
                cell.setBackground( Color.white );

        return cell;
    }
}

And the DataModel code is like this:

DefaultTableModel MydataModel = new DefaultTableModel()
{
    @Override
    public boolean isCellEditable(int row, int col)
    {
        return false;
    }

    @Override
    public Class getColumnClass(int c)  
    {
        String colname = getColumnName(c);

        if (colname.contains("INT")) return Integer.class;
        return String.class;
    }
};

I am adding new integer values using new Integer( some_integer ) to the table.

When running the code, the table is rendered in a proper way (odd and even rows have different colors), except columns with integer values. They are just white, like they were not affected by the Renderer.

Please, explain to me, how this problem can be solved. Thanks in advance. Max.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Max
  • 23
  • 1
  • 4

2 Answers2

2

It depend on how you set the renderer. Use the method

public void setDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer)

passing Integer class and your renderer.

StanislavL
  • 56,971
  • 9
  • 68
  • 98
2

By using prepareRenderer, you can eliminate the issue of synchronizing the table view with the table model via int modelRow = convertRowIndexToModel(row); this would also solve your issues with the broken stripped background. There's an example that you can see here, or the best example around is @camickr's Table Row Rendering.

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319