简体   繁体   English

当列类为float或double时如何使表单元格为空白

[英]How to make a table cell blank when the column class is float or double

I have a JTable which model was extended to AbstractTableModel . 我有一个JTable ,其模型已扩展为AbstractTableModel It has 4 columns. 它有4列。 First two columns hold string and last two columns hold double type data. 前两列保存字符串,后两列保存双精度类型数据。 The last 2 columns displays 0.0 when the data is Null; 当数据为Null时,最后两列显示0.0;

But I want to display it as blank when the value is null or 0; 但是我想在值为null或0时将其显示为空白; And when I will edit the cell and type any numerical value it will set double data type value with precision point. 当我编辑单元格并键入任何数值时,它将设置带有精度点的double数据类型值。

col1 || col2 || col3 || col4 
-----------------------------
aaa  || a1  || 250.00||
bb   || b1  ||       || 10.5
============================

A solution may be that to change in getValueAt(int rowIndex, int columnIndex) method and return " " when columnIndex is 3 and 4. But it creates another problem. 一种解决方案可能是更改getValueAt(int rowIndex, int columnIndex)方法,并在columnIndex为3和4时返回“”。但这会带来另一个问题。 When I edit the cell it return String value and required to parse the string value to double at setValueAt(Object value, int row, int col) method with Double.parseDouble(value.toString()); 当我编辑单元格时,它返回String值,并需要使用Double.parseDouble(value.toString());setValueAt(Object value, int row, int col)方法处将字符串值解析为两倍Double.parseDouble(value.toString());

But I think it is not wise or correct to parse the string value to Double ; 但是我认为将字符串值解析为Double是不明智或不正确的; I think setCellEditor may be a good solution. 我认为setCellEditor可能是一个很好的解决方案。 But I cant understand how to set a cell editor to double data type. 但是我不明白如何将单元格编辑器设置为双倍数据类型。

mytable.getColumnModel().getColumn(3).setCellEditor(???);

Could you give any solution. 您能提供任何解决方案吗?

You need to change the CellRenderer, not the CellEditor. 您需要更改CellRenderer,而不是CellEditor。

Read from "Concepts: Editors and Renderers" here: 在此处阅读“概念:编辑器和渲染器”:

http://docs.oracle.com/javase/tutorial/uiswing/components/table.html http://docs.oracle.com/javase/tutorial/uiswing/components/table.html

At last I could solve my problem using following codes. 最后,我可以使用以下代码解决我的问题。

@Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        setHorizontalAlignment(SwingConstants.RIGHT);
        if (value.equals(Double.valueOf(0))){
            super.setValue("");        
        }
        else {
            DecimalFormat numberFormat = new DecimalFormat("#,##0.00;(#,##0.00)");        
            Number num = (Number)value;
            super.setValue(numberFormat.format(num));
        }

        return c;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM