简体   繁体   中英

JList adding and removing items (Netbeans)

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.

In order to keep the existing items in the JList and add new ones, I had to get the model ListModel and then add the items to DefaultListModel as the ListModel does not have an addElement method. This is how I implemented:

   DefaultListModel<String> model = new  DefaultListModel<String>();
   ListModel model2 = jList.getModel();
   for (int i=0; i< model2.getSize();i++){
        model.addElement(model2.getElementAt(i).toString());              
        }
   model.addElement("new element");
   jList.setModel(model);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM