문제

I have a JTable which model was extended to AbstractTableModel. It has 4 columns. 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;

But I want to display it as blank when the value is null or 0; And when I will edit the cell and type any numerical value it will set double data type value with precision point.

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. 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());

But I think it is not wise or correct to parse the string value toDouble; I think setCellEditor may be a good solution. 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.

Read from "Concepts: Editors and Renderers" here:

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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top