I have a JTable
and I want a particular column to formatted as currency. If i put a number on that column like 3 it will show $3.00. i used TableCellRenderer
but i'm not getting into it. Can anyone help ?
Thanks in advance.
Here is a simple example. I don't know whether it works (if not - try to fix it).
import java.awt.Component;
import java.text.NumberFormat;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
public class CurrencyTableCellRenderer extends DefaultTableCellRenderer {
private static final NumberFormat FORMAT = NumberFormat.getCurrencyInstance();
@Override
public final Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
final Component result = super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
if (value instanceof Number) {
setHorizontalAlignment(JLabel.RIGHT);
setText(FORMAT.format(value));
} else {
setText("");
}
return result;
}
}
To add it:
table.getColumnModel().getColumn(column).setCellRenderer(new CurrencyTableCellRenderer());