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 putmyTable.setDefaultRenderer(String.class, new CustomRenderer());
If your data also consists of values with
BigDecimal
orInteger
as classes, you have to invoke that method several times for each class type (BigDecimal.class
orInteger.class
in each case).And finally, to change the background color you do this in your renderer:
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); c.setBackground(new java.awt.Color(255, 72, 72)); return c; } }
Josh Leitzel : This doesn't seem to work for me. The only thing I've done is invoke the setDefaultRenderer method and created the CustomRenderer class. Is there something else I need to be doing to get this to work?Camilo Díaz : Can you post your entire code here: http://www.rafb.net/paste/ ?Josh Leitzel : I got it working by using Object.class instead of String.class. Not sure why this was necessary, though, because all of my data were strings. Thank you for your help!Josh Leitzel : Am I not allowed to change the renderer inside a listener? I want to re-format the table when a button is pressed.KitsuneYMG : You need to use Object.class because you created a JTable w/o passing in a TableModel. The default table model created returns Object.class for each columns type. See: TableModel::getColumnClass(int col)pypmannetjies : Where do I use it? Say I now want to change a table cell's colour when I click on it? -
For brief code kindly to this site
http://apachejava.blogspot.com/2010/08/jtable-change-specific-complete-row.html
0 comments:
Post a Comment