문제

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);
}    
}
도움이 되었습니까?

해결책

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

    //...
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top