0

I recently learned that I can create a custom DefaultTableCellRenderer class for a JTable.

However, my code only colors the entire row but not the specific columns / cells I want to color based on a condition.

How can I specify the row and column in the DefaultTableCellRenderer class I created?

So here are the classes I created.

public class Schedule extends JPanel(){
    public Schedule(){
        schedulesJtbl.setDefaultRenderer(Object.class, new ScheduleTableCellRenderer());

    int startTime = 1230, endTime = 1330;
    int jtStartTime = scheduleJtbl.getValueAt(0,1);
    int jtEndTime = scheduleJtbl.getValueAt(0,2);
    int conflictCheck = 0;

    // duplicate startTime and endTime
    if((startTime == jtStartTime) && (endTime == jtEndTime)){
        conflictCheck++
        ScheduleTableCellRenderer.setConflict(conflictCheck);
    }
    //duplicate startTime
    else if(startTime == jtStartTime){
        conflictCheck++
        ScheduleTableCellRenderer.setConflict(conflictCheck);
    }  
}

and here's the ScheduleTableCellRenderer

public class ScheduleTableCellRenderer extends DefaultTableCellRenderer {

    static int conflict = 0;

    @Override
    public Component getTableCellRendererComponent(
            JTable table, Object value,
            boolean isSelected, boolean hasFocus,
            int row, int col) {

        Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);

        if (conflict > 0) {
            c.setBackground(Color.RED);
        } else if (conflict == 0) {
            c.setBackground(Color.GREEN);
        }

        return c;
    }

    public static void setConflict(int aConflict) {
        conflict = aConflict;
    }

}

If it's only startTime(as second condition on if) that duplicated, how can I color only column 2 but not the entire row just like what is happening right now on my JTable.

enter image description here

I hope you can help me.

Thank you.

heisenberg
  • 1,784
  • 4
  • 33
  • 62
  • Possible duplicate of http://stackoverflow.com/questions/17732005/trying-to-color-specific-cell-in-jtable-gettablecellrenderercomponent-overide – SomeDude Aug 22 '16 at 18:58
  • Have you tried adding condition on column also like: if (conflict > 0 && col == 1) – Ashwinee K Jha Aug 22 '16 at 19:08

1 Answers1

2
schedulesJtbl.setDefaultRenderer(Object.class, new ScheduleTableCellRenderer());

That sets the default renderer for all Objects in any row/column.

To set the renderer for a specific column you do:

table.getColumnModel().getColumn(???).setCellRenderer( ... );

You also need to reset the default background:

if (conflict > 0) {
    c.setBackground(Color.RED);
} else if (conflict == 0) {
    c.setBackground(Color.GREEN);
} else {
    c.setBackgrund( table.getBackground() );
}
camickr
  • 321,443
  • 19
  • 166
  • 288