Skip to content

Instantly share code, notes, and snippets.

@yblee85
Created May 8, 2014 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yblee85/906790e3f09aac2b1595 to your computer and use it in GitHub Desktop.
Save yblee85/906790e3f09aac2b1595 to your computer and use it in GitHub Desktop.
JAVA JTable cell color
/** GET TABLE COLUMN MODEL AND SET CELL RENDERER **/
Color LIGHT_BLUE = new Color(176, 196, 222);
EmployeeDetailScheduleTableCellRenderer cellRenderer = new EmployeeDetailScheduleTableCellRenderer(LIGHT_BLUE);
TableColumnModel tcm =tableListDetailSchedule.getColumnModel();
for(int i=2; i<=8; i++) {
TableColumn tm = tcm.getColumn(i);
tm.setCellRenderer(cellRenderer);
}
/** CREATE CELL RENDERER **/
private class EmployeeDetailScheduleTableCellRenderer extends DefaultTableCellRenderer {
private Color color;
public EmployeeDetailScheduleTableCellRenderer(Color color) {
this.color = color;
}
public Component getTableCellRendererComponent (JTable table, Object value, boolean selected, boolean focused, int row, int column) {
setEnabled(table == null || table.isEnabled()); // see question above
boolean isToBeColored = false;
if(column>=2 && column<=8) {
Object val = table.getModel().getValueAt(row, column);
String txtVal = val.toString();
String strPrefix = "<html><center>";
String strPostfix = "<br>";
if(txtVal.contains(strPrefix)) {
String work_hour_part = txtVal.substring(txtVal.indexOf(strPrefix)+strPrefix.length(), txtVal.indexOf(strPostfix));
System.out.println(work_hour_part);
if(!work_hour_part.equals("0.00")) {
isToBeColored = true;
}
}
}
if(isToBeColored) {
setBackground(color);
} else {
setBackground(null);
}
super.getTableCellRendererComponent(table, value, selected, focused, row, column);
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment