Issue
I build a Java project at Netbeans. I have a Form and inside the Form i have a jList that is populated with an object (Favorite). I have also a Button and i want when i press the Button to Delete the selected item at jList.
I am trying the following code but i get an error.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int selectedIndex = jList1.getSelectedIndex();
ListModel lModel= jList1.getModel();
Favorite item = (Favorite)lModel.getElementAt(selectedIndex);
System.out.println("name= "+ item.getName());
}
I get the following error:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to model.FavoriteList at my.mymoviesamn.FavoriteTestForm.jButton1ActionPerformed(FavoriteTestForm.java:104) at my.mymoviesamn.FavoriteTestForm.access$000(FavoriteTestForm.java:15) at my.mymoviesamn.FavoriteTestForm$1.actionPerformed(FavoriteTestForm.java:51) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
What is the problem? When i select an item from the jList i want to get that object (Favorite) and Delete it. The problem is i can not get that object from jList.
Solution
Favorite item = (Favorite)lModel.getElementAt(selectedIndex);
You assume that your model contains Favorite
objects. It does not. It contains Strings.
So other parts of your code that fill that model are doing something wrong.
Answered By - GhostCat