我有一个包含 2 列的 JTable。第一个仅包含一周中各天的名称,第二个包含一个 double
值。
共有三个按钮:
使用此方法自动生成用于测试的
double
值:private void autoGenerate(java.awt.event.ActionEvent evt) { for (int a=0; a<Config.n; a++){ tabla.setValueAt(a - a*0.5, a, 1);} }
绘图。
将表的值保存在BD中
当我在使用 autoGenerate
按钮生成值后尝试将数据保存到 BD 中时,一切正常。
但是,当我手动输入值后尝试将数据保存到 BD 时,会发生错误:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
at project.Graph.jButton5ActionPerformed(Graph.java:286)
保存数据的按钮执行以下操作:
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt,Patient p) {
try {
for (int k = 0; k < Config.n; k++) {
DBManager.save(p, k+1,(double)this.table.getValueAt(k, 1));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
最佳答案
However when I try to save the data into the BD after having typed the values manually an error occurs:
无需对列类或 CellEditor
进行任何其他修改,通过 JTable
UI 编辑值将导致存储 String
对象在模型中。因此,在检索值并尝试转换为 double
时会出现 ClassCastException
。考虑通过 TableModel
显式定义列类 - 这不仅会导致 Double
对象存储在模型中,还会影响 CellEditor(避免在输入非数字数据)。
DefaultTableModel model = new DefaultTableModel(){
@Override
public Class<?> getColumnClass(int col){
if ( col == 1 ){
return Double.class;
}
return String.class;
}
@Override
public int getColumnCount(){
return 2;
}
};
JTable table = new JTable(model);
关于java - JTable 中的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38335914/