JList adding and removing items (Netbeans)

arnoutvh picture arnoutvh · May 20, 2014 · Viewed 24.6k times · Source

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!

Answer

Paul Samsotha picture Paul Samsotha · May 20, 2014

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)