Reputation: 1319
I am using the following DefaultTableCellRenderer
to display currency in my tables. It works fine too, only problem I have is, the numbers in the columns I set this renderer on are aligned left, everything else is aligned right. I´d like to know why.
public class DecimalFormatRenderer extends DefaultTableCellRenderer {
public static final DecimalFormat formatter = new DecimalFormat("#.00");
@Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
value = formatter.format((Number) value);
return super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
}
}
Upvotes: 0
Views: 1626
Reputation: 347194
The default cell renderer used by JTable
to render numbers set's it horizontal alignment to JLabel.RIGHT
...
static class NumberRenderer extends DefaultTableCellRenderer.UIResource {
public NumberRenderer() {
super();
setHorizontalAlignment(JLabel.RIGHT);
}
}
You render will be using JLabel.LEADING
by default (being based on a JLabel
).
If you change your renderer to set the horizontal alignment in constructor, it should align to where you want it to go...
public class DecimalFormatRenderer extends DefaultTableCellRenderer {
//...
public DecimalFormatRenderer() {
super();
setHorizontalAlignment(JLabel.RIGHT);
}
//...
}
Upvotes: 2