2010-04-06 87 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));