Dise Dise - 6 months ago 36
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();
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);
} catch (ParseException ex) {
Logger.getLogger(ExpenseView.class.getName()).log(Level.SEVERE, null, ex);



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