I have a JTable in which I want to set different fore colors for different cells on mouse click.(Please note that not for rows or columns but for individual cells).
ie initially if the fore color is black, If I click on the cell it should turned to yellow. Again if I click it should be Green and so on.
Also I want to set two or 3 different colors for the text in a particular cell (The text is separated with space and each of these text should be of different color!!)
When changing the fore colors I don't want to change the backcolor.It is by default the white color itself.
You need to use a custom renderer. Read the JTable API and click in the link to the Swing tutorial titled "How to Use Tables" for more information.
If you want text of different colors then you need to either:
a) use HTML in the text
b) use a JTextPane as the renderer and set color attributes for the text.
To handle the background color, you would need to add a MouseListener to the table and store a Color object for the cell to indicate the background color of the cell. The renderer would then need to query this information when setting the color of the cell.
Rob Camick wrote:To handle the background color, you would need to add a MouseListener to the table and store a Color object for the cell to indicate the background color of the cell. The renderer would then need to query this information when setting the color of the cell.
I think it should also be possible to do this entirely through cell editors, in conjunction with getValue/setValue, without using MouseListeners. So this could be an alternate approach, though probably not an easier one (especially if the cells' text is not editable by the user—if it is editable then you probably be writing cell editors either way).
Rob Camick wrote: You need to use a custom renderer
Thank you Rob.
Yes, I tried to use a custom renderer like this
When I run this code the entire row becomes yellow. I want only the cell which I clicked should become Yellow.
Also if I click cell on first row and then click on 4 th row the whole 4 rows(from first to fourth) becomes yellow.
Initially if the fore color is black, If I click on the cell that cell should only turned to yellow. Again if I click on it , it should be Green and so on. All other cells should retain whatever color it has.
Joined: Jun 19, 2009
Thank you guys.
I handled it with simple html tags and MouseListener to the table.