Reputation: 47
I have a Jtable with some values [all are Strings] in it. Some values have " * "in front of them which I need to color. I'm able to color those cells which have a " * " using the Cell Renderer. But after I color the cell, I need to remove the " * " without changing the cell color. When I try to edit the cell value, the color changes back to WHITE. What am I missing in here. Here's the code
public SimpleTable()
{
JPanel panel = new JPanel();
setTitle("Colored JTable");
setBounds(400, 400, 400, 250);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
JTable table = new JTable(this.getRows(), this.getHeaders());
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setDefaultRenderer(Object.class, new MyTableRenderer());
this.scrollPane = new JScrollPane(table);
panel.add(scrollPane);
getContentPane().add(panel);
}
This is my cell renderer
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(table.getValueAt(row, column).toString().contains("*"))
{
String v = table.getValueAt(row, column).toString().replace("*", "");
table.setValueAt(v, row, column);
cellComponent.setBackground(Color.YELLOW);
}
else
{
cellComponent.setBackground(Color.WHITE);
}
return cellComponent;
Upvotes: 0
Views: 636
Reputation: 285403
Options:
I favor the latter as a cleaner more OOP solution. Note your cell renderer should be involved with rendering only. It should never change the data held by the table, ever.
For an example of the first:
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if(value != null && value.toString().contains("*")) {
value = value.toString().replace("*", "");
setBackground(Color.YELLOW);
} else {
setBackground(Color.WHITE);
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
Upvotes: 3