Question

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);
}    
}
Was it helpful?

Solution

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);
    }

    //...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top