1

How to change backgroung of selected cells in jTable?

I have already written table-rendering, but it allocates all row, and do not visible what kind of cell selected now.

public class MyTableRanderer extends DefaultTableCellHeaderRenderer{

    @Override
    public Component getTableCellRendererComponent(JTable jtable, Object obj,
            boolean isSelected, boolean hasFocus, int row, int col) {
        setText(obj.toString());

        if(isSelected){
            setBackground(Color.ORANGE);
            setForeground(Color.BLACK);
        } else {
            setBackground(Color.WHITE);
            setForeground(Color.BLACK);
        }

        return this;
    }

}

EDITED:

public class MyTableRanderer extends DefaultTableCellHeaderRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable jtable, Object obj,
            boolean isSelected, boolean hasFocus, int row, int col) {
        setText(obj.toString());

        Component cell = super.getTableCellRendererComponent(
                jtable, obj, isSelected, hasFocus, row, col);


        if (isSelected) {
            setBackground(Color.ORANGE);
            cell.setBackground(Color.green);
            setForeground(Color.BLACK);
        } else {
            setBackground(Color.WHITE);
            setForeground(Color.BLACK);
        }

        return this;
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Kholiavko
  • 334
  • 3
  • 11

2 Answers2

1

Try to insert this in your getTableCellRendererComponent function, to target a specific cell :

Component cell = super.getTableCellRendererComponent(
   table, obj, isSelected, hasFocus, row, column);
if (isSelected) {
   cell.setBackground(Color.green);
} 
Gauthier Boaglio
  • 10,054
  • 5
  • 48
  • 85
1

How to change backgroung of selected cells in jTable?

I have already written table-rendering, but it allocates all row, and do not visible what kind of cell selected now

then is required to test both methods if (isSelected & hasFocus) {

mKorbel
  • 109,525
  • 20
  • 134
  • 319