This is driving me absolutely insane.
I know that, to change the formatting of table cells with JTable, I have to use my own renderer. But I cannot seem to implement this properly.
This is my current setup:
public class MyClass
{
public static void main(String args[])
{
JTable myTable = new JTable(10, 10);
myTable.setDefaultRenderer ([I dont know what to put here], new CustomRenderer());
}
}
class CustomRenderer extends DefaultTableCellRenderer
{
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
// Formatting
return c;
}
}
What do I need to use for the first parameter of setDefaultRenderer? The API just says ‘class’. I have no idea what to put there.
Could someone just explain, in the simplest of terms, how I go about implementing this? Please provide an example of how I can change the formatting from within the main() method as well.
In the first parameter for
setDefaultRenderer, put the class literal for the Class that you want to override rendering. I.e., if your data consist all of strings, you can putIf your data also consists of values with
BigDecimalorIntegeras classes, you have to invoke that method several times for each class type (BigDecimal.classorInteger.classin each case).And finally, to change the background color you do this in your renderer:
If you write a renderer that should work for all classes of an interface, you will also need to modify the
getColumnClassfunction of your table model and let it return the interface class for all objects that implement this interface:With that one can register a renderer for IColorable.class and does not need to register a separate renderer for each implementation.