java - Set Background Color of a clicked table cell



I'm new to Java and I want to change the background color of a Specific cell, the one I clicked on, of a JTable.

I know that I have to use a MouseListener which I already did, also, the mousePressed. But at this point I am pretty lost.

EDIT: Forgot to add that the table is disabled, so you can't select a cell.

Can anyone help me? Thanks!

1 Answer: 

You must create a custom TableCellRenderer and pass it to the table

like this

public class ColorRenderer extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)  {
       // get the DefaultCellRenderer to give you the basic component
       Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
       // apply your rules
       if(table.isRowSelected(row) && table.isColumnSelected(col))

       return c;

in this class we check if the given cell if the selected cell (which is pretty much what happens when we click it) and paint it differently (in my case I paint it green) , else we paint with the default color or any color you like.

don't forget to set the custom renderer you just created

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

Edit 1

you must get the row and col of the clicked cell.

create 2 int variables that will hold the position

private int clickedRow=-1,clickedCol=-1;

add a mouse listener that updates the position variables

table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent event) {
                clickedRow= table.rowAtPoint(event.getPoint());
                clickedCol= table.columnAtPoint(event.getPoint());

after that you change the renderer so it paints only the clicked cell with the special color

if( clickedRow == row && clickedCol == col){