Search code examples
javaswingarraylistjlist

Update JList with Custom Arraylist


I have attempted to convert my program to a GUI. I have 2 custom Arraylists of type subject (b & m) I need to setListData to the custom object type b when the B button is pressed and m when the M button is pressed. So far my List looks like

LabelCoreSubs.setText("Core Subjects:");
        ListCoreSub.setModel(new AbstractListModel<String>() {
            String[] strings = {};

            public int getSize() {
                return strings.length;
            }

            public String getElementAt(int i) {
                return strings[i];
            }
        });
        jScrollPane1.setViewportView(ListCoreSub);

I can call this custom arraylist through ArrayList b = B.getCores(); how would i get this arraylist to display in my Jlist. I have also attempted to change the JList type to Subject but with no luck.

How do I update my JList to display each list on a button click event.


Solution

  • The setListData() method of JList only works for an Array or a Vector, so you can't use it with an ArrayList.

    So you can:

    1. Create a DefaultListModel.
    2. Use the addAll(...) method of the DefaultListModel to copy the items of the ArrayList into the model.
    3. Use the setModel(...) method of the JList.

    A better approach is to not create two ArrayLists to hold the initial data. Instead just create a DefaultListModel and add the data directly to the model. This way the data is only in one place. And to change the data displayed in the JList you just use the setModel(...) method.