If you have a JTable where the values displayed in a particular column
are Integer objects, it will display the Integer values with commas
(e.g. 98765432 is displayed as 98,765,432) if these two conditions are
true:
1. The getColumnClass(int columnIndex) method of the JTable's
TableModel returns Integer.class for the column in which the Integer
objects are displayed.
2. The JTable is using an instance of
javax.swing.table.DefaultTableCellRenderer to display the Integer
values.
Under normal circumstances, the second condition is usually true. As
its name implies, DefaultTableCellRenderer is the default renderer a
JTable uses to display values if another rendederer is not explicitly
specified.
The first condition may or may not be true, depending on the
TableModel used by the JTable. If an instance of DefaultTableModel is
being used, its getColumnClass() method will always return
Object.class, and the DefaultTableCellRenderer, having no way of
knowing that the Objects it is displaying are actually numeric values,
will simply display those objects by calling their toString() method.
For Integer objects, toString() returns a String representation of the
Integer's value that does not include commas.
Sometimes, the desired behavior might be for the TableModel's
getColumnClass() method to return Integer.classthis is important if the table is to be sorted on an Integer columnbut the JTable should display Integers
without commas. The way to do this is to tell the JTable to use something other than DefaultTableCellRenderer for displaying Integers.
Writing a custom implementation of the TableCellRenderer interface is
not trivial, however. The easy solution is to create a subclass of
DefaultTableCellRenderer that displays Integers without commas, and
lets its parent class handle details like cell background colors,
borders, etc. This small class fills the bill:
import javax.swing.table.*;
import javax.swing.*;
public class NoCommaIntegerRenderer extends DefaultTableCellRenderer {
public NoCommaIntegerRenderer() {
// make sure numbers are displayed right-justified
setHorizontalAlignment(JLabel.RIGHT);
}
// this overrides setValue() in the parent class.
public void setValue(Object value) {
if(value == null) setText("");
else setText(value.toString());
}
}
A JTable named "jtable" can use this class to display Integers by
adding the following line of code:
jtable.setDefaultRenderer(Integer.class,
new NoCommaIntegerRenderer());
By using this solution, a sortable JTable can still sort properly on
an Integer column100 will appear
after 20 in an ascending
sort, instead of before, which is the case if the values are treated
as Objects or Stringswhile at the same time, the undesired
behaviorthe formatting of Integer values with commasis eliminated.