2011-01-28 66 views
1

说,我有我的JTable以下栏目:格式JTable中单元格,如果非法格式,然后什么也不做

{"Item", "Price"} 

我想格式化价格列“0.00”格式。 但是,如果用户输入一个非法的字符串,然后保持单元格的原始值。当价格为“1.23”时,但当用户想要输入“abc”时,那么该单元应该仍然是“1.23”

我该怎么做?

谢谢

回答

2

让我们把你的大问题分解成小问题。

首先,你想有根据指定的格式,可以实现使用要显示你的Price列项的TableCellRenderer(其中,呈现数字时,将使用NumberFormat显示小数的正确数目) 。由于您的表格只有两列不同类型,因此最简单的解决方案是使用JTable#setDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer)。这样,您的号码将始终使用正确的小数位数显示。

其次,您的刊物的问题,同样的解决方案可以是相当优雅:打电话JTable#setDefaultEditor(java.lang.Class, javax.swing.table.TableCellEditor)并设置为编辑器的组件之一,将,commiting改变你的表型号之前,请确保新的值是一个有效号(当然根据你的规则有效)。

0

把格式化命令放到try/catch块中。如果操作失败,则返回NumberFormatException,取消编辑。

使用你原来的代码,做一些小的改动:

public void setValue(Object value) { 
    NumberFormat formatter = new DecimalFormat("0.00"); 
    String s = null; 
    try { 
     s = formatter.format(Integer.parseInt((String)value)); 
     if (null != s) setText(s); 
    } catch (NumberFormatException ex) { 
     // what could I do here? 
     // You could display a warning JOptionPane and/or output to System.out 
    } 
} 
+0

你能给出更详细的答案吗?我扩展了DefaultTableCellRenderer并重写了setText方法: – Leon 2011-01-28 15:32:08

+0

当然。首先发布你正在使用的代码来格式化你的问题中的单元格,然后我会提出一些改变的建议。别担心,这非常简单。 – 2011-01-28 15:34:15

+0

class DateRenderer extends DefaultTableCellRenderer public DateRenderer(){super(); } public void setValue(Object value){ NumberFormat formatter = new DecimalFormat(“0.00”); String s = null; 尝试{s = formatter.format(Integer.parseInt((String)value)); } catch(Exception ex){ //我能在这里做什么? } if(null!= s) setText(s); } } } – Leon 2011-01-28 15:35:49

1

JFormattedTextField工作你描述的那么只需要创建一个新的CellEditor延伸JFormattedTextField的方式。

2

JTable默认支持此功能。该表将根据每列中存储的数据选择渲染器/编辑器。因此,您只需重写getColumnClass(...)方法即可返回Double.class。然后当你编辑单元格时,编辑器将确保输入的值是一个有效的数字。

如果您想更多地控制数字的格式,可以使用Table Format Renderer