简体   繁体   English

在TableModel中编辑单元格后,Java,而不是double

[英]Java, string instead of double after editing cell in TableModel

I import a CSV file into a DefaultTableModel , one column is formatted as double, so far so good. 我将CSV文件导入DefaultTableModel ,一列格式为double,到目前为止一直很好。 But if I edit a cell from this column (double) in the JTable , after that this cell is no longer a double. 但是,如果我在JTable编辑此列中的单元格(double),那么此单元格不再是double。 Now it is a string. 现在它是一个字符串。 How can I change the type of the edited cell in the TableModel ? 如何更改TableModel中已编辑单元格的类型? I know that I can parse a string to double with double value = Double.parseDouble(str); 我知道我可以用double value = Double.parseDouble(str);解析一个字符串double value = Double.parseDouble(str); , but how can I ensure that this happens after editing a cell? ,但是如何确保在编辑单元格后发生这种情况?

Do I need a new TableModel -class like: 我需要一个新的TableModel类,如:

class myTableModel extends DefaultTableModel { }

Thanks for your help. 谢谢你的帮助。

for example 例如

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

or 要么

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);
            }
        });
    }
}

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

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