|
Apr
15
|
Rendering of table cells is handled by instances of TableCellRenderer. By default JTable uses a DefaultTableCellRenderer to render all of its cells.
To control the number of decimal places used we just need to subclass DefaultTableCellRenderer and format the cell double value before passing the (formatted) value to to the parent (DefaultTableCellRenderer) class.
To get the table to use that class we tell the JTable to use it for a given column.
Following example illustrates what is required.
import java.awt.*;
import java.text.DecimalFormat;
import javax.swing.*;
import javax.swing.table.*;
public class DecimalPlacesInTable extends JFrame {
public static void main( String[] args ) {
DecimalPlacesInTable frame = new DecimalPlacesInTable();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
}
public DecimalPlacesInTable() {
Object[] columnNames = { "A", "B", "C" };
Object[][] data = {
{ "abc", new Double( 850.503 ), 5 },
{ "def", new Double( 36.23254 ), 6 },
{ "ghi", new Double( 8.3 ), 7 },
{ "jkl", new Double( 246.0943 ), 23 }};
JTable table = new JTable(data, columnNames);
// Tell the table what to use to render our column of doubles
table.getColumnModel().getColumn(1).setCellRenderer(new DecimalFormatRenderer() );
getContentPane().add(new JScrollPane(table));
}
/**
Here is our class to handle the formatting of the double values
*/
static class DecimalFormatRenderer extends DefaultTableCellRenderer {
private static final DecimalFormat formatter = new DecimalFormat( "#.00" );
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
// First format the cell value as required
value = formatter.format((Number)value);
// And pass it on to parent class
return super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column );
}
}
}



April 26th, 2011 at 8:02 am
Compiling and running, that code results an error : CANNOT FORMAT GIVEN OBJECT AS A NUMBER.
What do I do?
April 26th, 2011 at 9:47 am
Have updated the code, let me know if there is still a problem
May 14th, 2011 at 4:08 am
Now, error resulting is :
java.lang.String cannot be cast to java.lang.Number
May 14th, 2011 at 3:03 pm
That suggests theres a String in the column you are trying to format.
The renderer expects the table to contain Number’s in that column.