【发布时间】:2012-10-29 05:14:00
【问题描述】:
我必须在 JTable 中创建我的一列,它是 double 类型,以仅获取数字并以精度 2 舍入所有列。不仅以这种精度显示它们,而且以精度 2 将数字写入数据。在事实上,如果我写 2.456 它应该在单元格和数据中写 2.46。最好的方法是如何做到这一点?使用自定义单元格渲染器还是使用自定义单元格编辑器? 我有这段代码,但它不会更改数据,它只会在单元格上显示正确的数据
public class DoubleCellRenderer extends DefaultTableCellRenderer {
int precision = 0;
Number numberValue;
NumberFormat nf;
public DoubleCellRenderer(int aPrecision) {
super();
precision = aPrecision;
setHorizontalAlignment(SwingConstants.RIGHT);
nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(aPrecision);
nf.setMaximumFractionDigits(aPrecision);
}
@Override
public void setValue(Object value) {
if ((value != null) && (value instanceof Number)) {
numberValue = (Number) value;
value = nf.format(numberValue.doubleValue());
}
super.setValue(value);
}
}
【问题讨论】:
-
JTable 有两种状态,渲染器和编辑器,渲染器是关于在 XxxTableModel 中格式化值存储,仅此而已,编辑器是关于在 XxxModel 中添加、主题、删除值存储,而 CellEditor 没有存在,然后add,motity,remove值存储在XxxTableModel中
标签: java swing jtable tablecellrenderer tablecelleditor