Question

OK, I must be completely brainless but I can't seem to implement the code needed to set (permanently) the background color of the selected (clicked) cell in my JTable. I've read through most of the answers on this site but I'm still not getting it.

I'm using the preparedRenderer() method but I don't understand why it isn't working?

table.addMouseListener(
    new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent m) {
        row = table.getSelectedRow();
        column = table.getSelectedColumn();
        }
    }
);

table = new JTable(data, columnNames) {
        public Component prepareRenderer(TableCellRenderer rend, int r, int k) {
            Component g = super.prepareRenderer(rend, row, column);
            g.setBackground(Color.BLUE);
            return g;
        }
};

The way I'm understanding it is that prepareRenderer is taking a specific cell from the table as a Component and then allowing me to change the properties of that Component. But even if I write:

Component g = super.prepareRenderer(rend, 1, 1);
g.setBackground(Color.BLUE);
return g;

it just paints the whole table and not the cell at row=1, column=1??? I'm just not getting it...

Was it helpful?

Solution

it just paints the whole table and not the cell at row=1, column=1???

The prepareRenderer() method is called for every cell that gets repainted. This is done dynamically as the user selects a row or tabs to a new cell or clicks on a cell.

set (permanently) the background color of the selected (clicked) cell in my JTable.

Maybe you can create a Set of Point objects to represent the cells that you want to paint a different color. So when you click on the cell you create a Point object for the row/column and then add the Point to the set.

Then in the prepareRenderer(...) method you create a new Point representing the row/column you are about to renderer. If this Point is found in your Set then you change the background color.

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