I've gathered that in order to change the background color of a row,
one can either use the tablecellrenderer or can override the
prepareRenderer() method. I have chosen to override the
prepareRenderer() method. My question (and a reather silly one) is
exactly how to call this method to then color your rows.
I already have a jtable with is autogenerated by netbeans and all of
the code I've seen, the jtable is created programmatically.
Here is what I TRIED to do (any help is greatly appreciated):
public void updateGUI(String newValue){
DefaultTableModel errorTableModel = (DefaultTableModel)
parentScreen.jTableErrors.getModel();
int numRows = errorTableModel.getRowCount();
numRows++;
errorTableModel.setRowCount(numRows);
parentScreen.jTableErrors.setModel(errorTableModel);
Object newObjectError = (Object) newValue;
parentScreen.jTableErrors.setValueAt(newObjectError, numRows - 1, 0);
JTable coloredTable = new JTable( errorTableModel )
{
public Component prepareRenderer(
TableCellRenderer renderer, int row, int column)
{
Component c = super.prepareRenderer(renderer, row, column);
String message = (String) getValueAt(row, column);
String[] dividedMsg = message.split(":");
if(dividedMsg[0].equals("Error: ")){
this.setBackground(Color.RED);
}
else{
this.setBackground(Color.YELLOW);
}
return c;
}
};
parentScreen.jTableErrors = coloredTable;
}
Andrew McDonagh - 27 Jun 2006 20:53 GMT
> I've gathered that in order to change the background color of a row,
> one can either use the tablecellrenderer or can override the
> prepareRenderer() method. I have chosen to override the
> prepareRenderer() method. My question (and a reather silly one) is
> exactly how to call this method to then color your rows.
Snipped
Dont call it.
instead create a Derived class from JTable and over ride the
prepareRenderer() method.
However, the entire concept and design of Adding Customer Renderers has
been explicitly done so that you can create a well designed system
Using the internal methods like prepareRenderer() leave your design open
to fragile code that could break when ever Sun change the implementation
of JTable.
JTable's public API wont change, but its internals will.