Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 661
arnoutvh Avatar asked Mar 19 '23 13:03

arnoutvh


2 Answers

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)

like image 197
Paul Samsotha Avatar answered Apr 02 '23 00:04

Paul Samsotha


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.

like image 25
camickr Avatar answered Apr 02 '23 00:04

camickr