Dise Dise - 3 months ago 7
Java Question

java.lang.ClassCastException: java.lang.String cannot be cast to Category type

i have a combobox.it has category name.so i need to pass string to category.
Category category = (Category)cmbCategory.getSelectedItem(); this line get error saying cant cast string to category type..

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

Answer

It looks like you are trying to convert and then assign a String to a Category.

Since String is not a Category obviously, nor implementing Category, you receive this exception.

You can add your Category class a string data member such as categoryNameand then set it as follows :

Category category = new Category().setCategoryName(cmbCategory.getSelectedItem());