I'm trying to add and remove items from my jList (jList1), but It doesn't work. I've searched on stackoverflow for other people with the same problem, but when their problem is solved, I keep getting errors. So this is how I declared the jList:
jList1.setModel(new javax.swing.AbstractListModel() {
String [] strings = lijstItems;
public int getSize() {
return strings.length;
}
public Object getElementAt (int i) {
return strings[i];
}
});
So now I made these buttons to add and remove items from the list:
private void addHostActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
DefaultListModel model = (DefaultListModel) jList1.getModel();
model.add(2, "item");
// THIS DOES NOT WORK...
}
And
private void deleteHostActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
I've tried so many things, but they don't work! Can anyone help me please?
Thanks!
You set the model of the list to an AbstractListModel
. You can't cast the model to a DefaultListModel
. Trying to do so will give you a ClassCastException
So set the model to a DefaultListModel
instead.
jList1.setModel(new DefaultListModel());
And you probably want to use DefaultListModel#addElement(element)
instead of adding the element to same index every time, with add(2, element)
this is how I declared the jList:
Why are you creating a custom ListModel? Just use the DefaultListModel. There is no need for you to create a custom model to simply store String data.
Then you can read the section from the Swing tutorial on How to Use Lists for a working example that does exactly what you want by using the "Hire" and "Fire" buttons.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With