Java,在TableModel中编辑单元格后,字符串而不是double [英] Java, string instead of double after editing cell in TableModel
问题描述
我将CSV文件导入到DefaultTableModel
中,其中一列的格式设置为double,到目前为止,效果很好.但是,如果我在JTable
的此列(双精度)中编辑一个单元格,则此单元格不再是双精度型.现在它是一个字符串.
如何更改TableModel
中已编辑单元格的类型?
我知道我可以使用double value = Double.parseDouble(str);
将字符串解析为两倍,但是如何确保在编辑单元格后会发生这种情况?
I import a CSV file into a DefaultTableModel
, one column is formatted as double, so far so good. But if I edit a cell from this column (double) in the JTable
, after that this cell is no longer a double. Now it is a string.
How can I change the type of the edited cell in the TableModel
?
I know that I can parse a string to double with double value = Double.parseDouble(str);
, but how can I ensure that this happens after editing a cell?
我需要一个新的TableModel
类吗?
class myTableModel extends DefaultTableModel { }
感谢您的帮助.
推荐答案
- 必须为所需的列覆盖getColumnClass
- have to override getColumnClass for required column(s)
例如
@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);
}
});
}
}
这篇关于Java,在TableModel中编辑单元格后,字符串而不是double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!