简体   繁体   English

从jtable中获取双精度值

[英]Getting double values out of a jtable

I found a few threads with a similar problem, but nothing worked for me. 我发现了几个存在类似问题的线程,但对我没有任何帮助。 I'm trying to get a double and a string value out of a jtable. 我正在尝试从jtable中获取双精度和字符串值。 I'm using the DefaultTableModel and did override the getCOlumnClass method: 我正在使用DefaultTableModel并覆盖了getCOlumnClass方法:

private void initTable()
{
    String tableColumns[] = { language.getTranslatedPhrase(MultilanguageUtil.Amount),
            language.getTranslatedPhrase(MultilanguageUtil.Ingredient),
            language.getTranslatedPhrase(MultilanguageUtil.Unit) };

    tableModel = new DefaultTableModel(tableColumns, 0) {
        private static final long serialVersionUID = 1L;  
         @Override
        public Class<?> getColumnClass(int column) {  
                switch (column) {  
                    case 0:
                        return Double.class;
                    case 1:  
                        return String.class;
                    case 2:  
                        return Units.class; 
                    default:
                        return String.class;
                }  
       }
    };


    table = new JTable(tableModel);

I'm expecting double values in the first column, but when i try to get a value with: 我期望第一栏中有双精度值,但是当我尝试通过以下方法获得一个值时:

int rowCount = tableModel.getRowCount();

for (int i = 1; i <= rowCount - 1; i++)
{
    double doubleValue = (Double) tableModel.getValueAt(i, 0);
}

I get this exception: 我得到这个例外:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double

I have also tried this: 我也尝试过这个:

Object objValue = tableModel.getValueAt(i, 0);
        double doubleValue = ((Double) objValue).doubleValue();

but i get the same exception. 但我得到同样的例外。

when i excecute 当我执行

System.out.println(table.getColumnClass(0));

it says 它说

class java.lang.Double

so, it seems to be right, but i still get the exception, which says that its an integer, and i can't cast it to a double... 因此,这似乎是正确的,但是我仍然遇到异常,它表示它是整数,并且我不能将其转换为双精度...

I hope someone could help me, and sorry for my bad english!(not my first language) 我希望有人能帮助我,并为我的英语不好对不起!(不是我的母语)

Well, to fix the error you should not put Integer s to the cell that you explicitly defined to have double values. 好了,要解决该错误,您不应将Integer放入您明确定义为具有double值的单元格中。 You can work around it like this: use String.valueOf() to make a String from your input. 您可以这样解决:使用String.valueOf()从输入中创建一个String This method accepts many variable types. 此方法接受许多变量类型。 Then from String , you can Double.parseDouble() . 然后从String ,可以Double.parseDouble() For example 例如

double doubleValue = Double.parseDouble(String.valueOf(tableModel.getValueAt(i, 0)));

Is a bit hackey but works. 有点hackey,但是可以用。

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

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