2013-09-27 118 views
0

我正在使用以下DefaultTableCellRenderer在我的表格中顯示貨幣。它也可以正常工作,只有我遇到的問題是,我設置此渲染器的列中的數字左對齊,其他所有對齊都正確。我想知道爲什麼。在JTable單元格中對齊

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

回答

2

使用JTable渲染號碼默認單元格渲染器設置的IT水平對齊到JLabel.RIGHT ...

static class NumberRenderer extends DefaultTableCellRenderer.UIResource { 
    public NumberRenderer() { 
     super(); 
     setHorizontalAlignment(JLabel.RIGHT); 
    } 
} 

渲染將使用默認JLabel.LEADING(是基於一個JLabel)。

如果你改變你的渲染器設置在構造函數中的水平對齊方式,它應該對準您想要它去......

public class DecimalFormatRenderer extends DefaultTableCellRenderer { 

    //... 

    public DecimalFormatRenderer() { 
     super(); 
     setHorizontalAlignment(JLabel.RIGHT); 
    } 

    //... 
} 
+0

完美,謝謝。 –