After managing to get my columns to sort by defining the Column Classes - my Cell Render now only applies to Columns that contain String values and not applied to the Integer columns?
This shows you Column class definitions for String and Integer Classes:
JTable compTable5 = new JTable();
compTable5.setEnabled(false);
DefaultTableModel model5 = new DefaultTableModel(){
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return Integer.class;
default:
return String.class;
}
}
};
This is the Renderer
compTable5.setDefaultRenderer(Object.class, new DefaultTableCellRenderer(){
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row, int col) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
int status = (int)table.getValueAt(row, 1);
String status2 = (String)table.getValueAt(row, 5);
if ("Not Used".equals(status2)) {setBackground(Color.lightGray);setForeground(Color.black);}
else if (status2.equals("Priority 1")) {setBackground(scaleRed);}
else if ( status == 0 && !status2.equals("Working") && !status2.equals("Not Used") && !status2.equals("Priority 1")) {setBackground(pink);setForeground(Color.black);}
else if (status < 20) {setBackground(scaleRed);}
else if (status >= 20 && status < 40) {setBackground(scaleOrange);setForeground(Color.black);}
else if (status >= 40 && status < 60) {setBackground(scaleYellow);setForeground(Color.black);}
else if (status >= 60 && status < 80) {setBackground(scaleGreen1);setForeground(Color.black);}
else if (status >= 80 && status < 100) {setBackground(scaleGreen2);setForeground(Color.black);}
else if (status > 100) {setBackground(scaleBlue);setForeground(Color.white);}
else {
setBackground(table.getBackground());
setForeground(table.getForeground());
}
return this;
}
});
I am a java noob and this is my first stackoverflow post, thanks for all the help you all have given already given me on this forum!
JTable
most likely uses a special TableCellRenderer
for Integers (and Doubles, Floats, Longs) to display the values right-aligned instead of the default left-aligned.
You bind your DefaultTableCellRenderer
for Object.class
, which is a fall-back if no more specialized TableCellRenderer is found.
Try to bind your DefaultTableCellRenderer both to Object.class
and to Integer.class
, like this:
DefaultTableCellRenderer myRenderer = new DefaultTableCellRenderer() {
// all your code for the cell renderer, as in your example
}
compTable5.setDefaultRenderer(Object.class, myRenderer);
compTable5.setDefaultRenderer(Integer.class, myRenderer);