JList adds and removes elements (Netbeans)

I am trying to add and remove elements from jList (jList1), but this will not work. I searched stackoverflow for other people with the same problem, but when their problem is resolved, I keep getting errors. So this is how I declared 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 tried so many things, but they do not work! Can anybody help me?

Thank!

+4
source share
2 answers

AbstractListModel. DefaultListModel. ClassCastException. , DefaultListModel.

jList1.setModel(new DefaultListModel());

, , DefaultListModel#addElement(element) add(2, element)

+6

jList:

ListModel? DefaultListModel. , String.

Swing , , , "" "".

+1

Source: https://habr.com/ru/post/1541326/


All Articles