简体   繁体   English

JTable单元格中的对齐

[英]Alignment in a JTable cell

I am using the following DefaultTableCellRenderer to display currency in my tables. 我使用以下DefaultTableCellRenderer在我的表中显示货币。 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 ... JTable用于渲染数字的默认单元格渲染器将其水平对齐设置为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 ). 默认情况下,渲染将使用JLabel.LEADING (基于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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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