简体   繁体   中英

Alignment in a JTable cell

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

    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM