Question

I'm cleary doing something wrong. My guess would be the component, but here's the problem. This is my cell renderer:

public class WildcardCellRenderer implements TableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {

        JTextField c = new JTextField();
        c.setBorder(javax.swing.BorderFactory.createEmptyBorder());

        if(vColIndex == 2){
            if((Integer)value == 0) c.setText("No") ;
            else c.setText("Si");
        } else c.setText(value.toString());

        return c;
    }

}

and this is how I set up the thing in my panel:

    this.table.setDefaultRenderer(Object.class, new WildcardCellRenderer() );

The problem is that when I set up this renderer the rows become unselectable. Should I use a different Component to display what I need to display? Basically I'm displaying a 0/1 value as a No/Yes value.

Was it helpful?

Solution

You need to take the "isSelected" value into account and set up the background color accordingly like this:

 if (isSelected) {
        c.setBackground(table.getSelectionBackground());
        c.setForeground(table.getSelectionForeground());
    }
    else {
        c.setBackground(table.getBackground());
        c.setForeground(table.getForeground());
    }

I took this from one of my ListCellRenderers but i assume it works the same with the TableCellRenderers.

Oh and BTW, you can reuse the text field, there is no need to create a new textfield for each cell, so you could make the text field a member of your class and inside the method just change something in your text field like content/color and return it. That way you don't end up with a million textfield instances on a large table.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top