java.lang.ClassCastException:java.lang.String无法强制转换为Category类型

时间:2016-09-08 18:35:15

标签: java

我有一个combobox.it有类别名称。所以我需要将字符串传递给类别。 类别类别=(类别)cmbCategory.getSelectedItem();这一行得到错误,说不能将字符串转换为类别类型..

private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
    double amount = Double.parseDouble(txtAmount.getText());
    Expense expense = new Expense();
    expense.setReason(txtReason.getText());
    expense.setAmount(amount);
    DateFormat format = new SimpleDateFormat("MMMM d, yyyy");

    Category category = (Category)cmbCategory.getSelectedItem();
    String startDate = ((JTextField)txtDate.getDateEditor().getUiComponent()).getText();

    try {
        Date date = format.parse(startDate);
        expense.setDate(date);
    } catch (ParseException ex) {
        Logger.getLogger(ExpenseView.class.getName()).log(Level.SEVERE, null, ex);
    }

    expense.setCategory(category);
    ExpenseController.saveExpense(expense);
}          

2 个答案:

答案 0 :(得分:1)

Category.getSelectedItem ();返回String

除非将其分配给类Category的属性,例如name,且类型为string

category.setName(cmbCategory.getSelectedItem());

答案 1 :(得分:1)

您似乎正在尝试转换,然后将Category分配给String

由于Category显然不是Category,也没有实施Category,因此您会收到此例外。

您可以为categoryName类添加一个字符串数据成员,例如Category category = new Category().setCategoryName(cmbCategory.getSelectedItem()); ,然后按如下所示进行设置:

$('#datepicker2').datepicker('setDate', new Date('<?=$value->fecha_final?>'));