3

我将一个 CSV 文件导入一个DefaultTableModel,一列被格式化为双精度,到目前为止一切都很好。但是,如果我在 中编辑此列(双精度)中的一个单元格JTable,则该单元格不再是双精度。现在它是一个字符串。如何更改中已编辑单元格的类型TableModel?我知道我可以将字符串解析为 double with double value = Double.parseDouble(str);,但是如何确保在编辑单元格后发生这种情况?

我需要一个新的TableModel类吗:

class myTableModel extends DefaultTableModel { }

谢谢你的帮助。

4

1 回答 1

4

例如

    @Override
    public Class<?> getColumnClass(int c) {
        if (c == 1) {
            return Short.class;
        } else {
            return Integer.class;
        }
    }

或者

import javax.swing.*;
import javax.swing.table.*;

public class RemoveAddRows extends JFrame {

    private static final long serialVersionUID = 1L;
    private Object[] columnNames = {"Type", "Company", "Shares", "Price"};
    private Object[][] data = {
        {"Buy", "IBM", new Integer(1000), new Double(80.50)},
        {"Sell", "MicroSoft", new Integer(2000), new Double(6.25)},
        {"Sell", "Apple", new Integer(3000), new Double(7.35)},
        {"Buy", "Nortel", new Integer(4000), new Double(20.00)}
    };
    private JTable table;
    private DefaultTableModel model;
    private javax.swing.Timer timer = null;

    public RemoveAddRows() {
        model = new DefaultTableModel(data, columnNames) {

            private static final long serialVersionUID = 1L;

            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        table = new JTable(model);        
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);        
    }



    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                RemoveAddRows frame = new RemoveAddRows();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}
于 2012-11-28T13:38:10.627 回答