2010-04-06 91 views
1

嗨,我是JTable中的編輯器問題。Java Swing jtable單元格編輯器使E編號翻倍

我有一列顯示數據爲26,687,489,800.00即:Double。

當用戶單擊單元格以編輯數據時,它顯示爲-2.66874908E10。

我想作爲時即顯示它出現的數據進行編輯:26,687,489,800.00 - 沒有E10等等

任何幫助,將不勝感激。

邁克

回答

2

您應該正確使用一個DecimalFormat例如格式化你的價值,當你設置你的編輯器。

+0

您好我已創建的文本字段,它使用已經格式化: DecimalFormat的DF =新的DecimalFormat(「#,###, ###,###,###,###,## 0 ######「); df.format(d); 我已經爲我的列指定了JTextField作爲編輯器,但是我仍然遇到同樣的問題? 任何想法?我錯過了什麼 Mike – Michael 2010-04-06 13:50:53

2

用作編輯器的組件與用於顯示數據的組件(渲染器)完全不同。這就是爲什麼你在他們兩個之間有不同的格式。

我建議你閱讀這個part of the Java tutorial,關於添加你自己的單元格編輯器。你應該添加一個Formatted text field,你會put the number format you need

例子:

DecimalFormat df = new DecimalFormat ("#,##0.######"); //you shouldn't need more "#" to the left 
JFormattedTextField fmtTxtField = new JFormattedTextField(df); 
TableCellEditor cellEditor = new DefaultCellEditor(fmtTxtField); 

//This depends on how you manage your cell editors. This is for the whole table, not column specific 
table.setCellEditor(cellEditor); 
+0

嗨我創建了一個文本字段並使用格式: DecimalFormat df = new DecimalFormat(「#,###,###,###,###,###, ## 0 ######「); df.format(d); 我已經爲我的列指定了JTextField作爲編輯器,但是我仍然遇到同樣的問題? 任何想法?我錯過了什麼 Mike – Michael 2010-04-06 13:49:37

+0

@Michael - 我認爲你應該使用JFormattedTextField來完成這個任務。我不確定你對常規JTextField和DecimalFormat做了什麼,但正常使用應該是創建一個JformattedTextField並將DecimalFormat作爲參數:http://java.sun.com/javase/7/docs /api/javax/swing/JFormattedTextField.html#JFormattedTextField(java.text.Format) – Gnoupi 2010-04-06 13:55:35

1

如果我們認爲您的列級雙,你可以做到以下幾點:

DecimalFormat df = new DecimalFormat ("#,##0.######"); 
JFormattedTextField fmtTxtField = new JFormattedTextField(df); 
TableCellEditor cellEditor = new DefaultCellEditor(fmtTxtField); 
table.setDefaultEditor(Double.class, new DefaultCellEditor(fmtTxtField)); 

但你需要覆蓋DefaultCellEditor的默認委託執行。 (至少在的Java6)

//DEFAULT IMPLEMENTATION INSIDE THE CONSTRUCTOR 
.... 
public DefaultCellEditor(final JTextField textField) { 
    editorComponent = textField; 
    this.clickCountToStart = 2; 
    delegate = new EditorDelegate() { 
     public void setValue(Object value) { 
      textField.setText((value != null) ? value.toString() : ""); 
     } 

     public Object getCellEditorValue() { 
      return textField.getText(); 
     } 
    }; 
textField.addActionListener(delegate); 
} 
.... 

//YOUR IMPLEMENTATION 
public class DoublesCellEditor extends DefaultCellEditor { 

    private JFormattedTextField textField; 

    public DoublesCellEditor(JFormattedTextField jft) { 
     super(jft); 
     this.textField = jft; 
     super.delegate = new EditorDelegate() { 
      public void setValue(Object value) { 
       textField.setValue(value != null ? ((Number) value).doubleValue() : value); 
      } 

      public Object getCellEditorValue() { 
       Object value = textField.getValue(); 
       return value != null ? ((Number) value).doubleValue() : value; 
      } 
     }; 
    } 
} 

,而使用:

table.setDefaultEditor(Double.class, new DoublesCellEditor(fmtTxtField));