Miles Jordan
Miles Jordan

Reputation: 3

How to actively update a JList in Java

I'm working on a project where one of the parameters is that either a table or a list needs to display multiple names it's reading from a text file. Im using Swing and JList for this, but I'm having a lot of trouble actually updating the list with the new information.

public void selectTable(ArrayList<String> select) {
    DefaultListModel model = new DefaultListModel();
    model.addElement(select);
    selectList = new JList(model);
    selectList.setPreferredSize(new Dimension(690, 230));   
}

I keep reading that you're supposed to use the Default List Model to update it, but everytime I try theres no change on the GUI side of things, the JList stays blank. Looking through the debugger, the array list I have goes into the add element method, but nothing changes

Upvotes: 0

Views: 861

Answers (1)

camickr
camickr

Reputation: 324128

Edit:

In JDK 11 you can create a DefaultListModel and then add the ArrayList to the model using the addAll(...) method of the DefaultListModel:

    ArrayList<String> items = new ArrayList<>();
    items.add("one");
    items.add("two");

    DefaultListModel<String> model = new DefaultListModel<>();
    model.addAll( items );

    JList<String> list = new JList<>(model);

Original answer (when I was using JDK8):

You can't add an ArrayList to the DefaultListModel.

You need to add each item of the ArrayList to the DefaultListModel separately.

So you need to iterate through the ArrayList and add each item in the ArrayList to the model by using the addElement(...) method.

Also, you don't show in your code where you add the JList to a JScrollPane and then add the JScrollPane to the frame.

Upvotes: 5

Related Questions