0

I created desktop application with Netbeans, and I want to change a particular cell color if it has string value of "on Process". I tried

class CustomTableCellRenderer extends DefaultTableCellRenderer{
    public Component getTableCellRendererComponent (JTable table, Object obj,
            boolean isSelected, boolean hasFocus, int row, int column) {
        Component cell = super.getTableCellRendererComponent(
            table, obj, isSelected, hasFocus, row, column);
        if (obj=="on Process") {
            cell.setBackground(Color.green);
        } 
        return cell;
    }
}

but it is not changing my tableI used

table.getColumnModel().getColumn(7).setCellRenderer(new CustomTableCellRenderer());

I`m getting values from database and using

for(int i=0; i<arraylist.size(); i++) {
    table.setValueAt(status, i, 7);
}

here status is String, if I type manually like:

table.setValueAt("on Process", i, 7);

it changes the color, it is fine, but I can not type it like that, I need to set value from variable. I tried String, Object, no use! I tried toString(), I tried ""+status, ... it is just ignoring what I assign to it. Inside forloop if I type "on Process" it works, but outside forloop I can assign from variable, it changes color. I am confused, don`t know what to do. Please help me.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Jamol
  • 3,768
  • 8
  • 45
  • 68

2 Answers2

4

You need this:

if(obj.toString().equals("on Process"))

instead of:

if(obj=="on Process")
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
1

@Eng.Fouad is right about distinguishing between equals() and ==. You'll also need to verify that your TableModel returns the desired type token for your specified column, as shown in this example. The DefaultTableModel simply returns Object.class.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • columnClasss often is the culprit - shouldn't in this context as the OP is using a per-column renderer. Which might be the problem, if the update from the database triggers a structureChanged. @user1290988, does it? – kleopatra Apr 14 '12 at 09:10
  • @kleopatra is right: `getCellRenderer()` should find the `TableColumn`'s renderer first. A `fireTableStructureChanged()` may cause the "types of the new columns may be different." No change would explain why `setValueAt()` with a `String` literal finds the column renderer. – trashgod Apr 14 '12 at 17:18