Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding items to a JList from ArrayList using DefaultListModel

I'm trying to add items that are in an ArrayList to a JList which is working when I use the following code:

private void UpdateJList(){
    DefaultListModel<String> model = new DefaultListModel<String>();
    for(Person p : personList){
        model.addElement(p.ToString());
    }
    clientJList.setModel(model);
    clientJList.setSelectedIndex(0);
}

However, If I declare the DefaultListModel outside of the method, the adding increments each item, IE instead of adding one of each item, it adds multiple items. I was just wondering why this happens?

like image 765
Ari Avatar asked Nov 24 '11 05:11

Ari


People also ask

How do you add items to JList?

However, JList has no method to add or delete items once it is initialized. Instead, if you need to do this, you must use the ListModel class with a JList. Think of the ListModel as the object which holds the items and the JList as the displayer.

How do I add a border to a JList?

You can use a custom ListCellRender . Then in the if (isSelected) just add the border. Then instantiate the render. MyListCellRenderer renderer = new MyListCellRenderer(); JList list = new JList(); list.

What is DefaultListModel in Java?

DefaultListModel provides a simple implementation of a list model, which can be used to manage items displayed by a JList control. For more information, see JList Class. Constructor. Constructor.

How do I make my JList scrollable?

JList doesn't support scrolling directly. To create a scrolling list you make the JList the viewport view of a JScrollPane. For example: JScrollPane scrollPane = new JScrollPane(dataList); // Or in two steps: JScrollPane scrollPane = new JScrollPane(); scrollPane.


1 Answers

If you define DefaultListModel outside your update method then it becomes Instance variable so it will be having same value for one instance. Thus if you call this method over and over from same instance it will simply add more values to the existing list. Thus it shows multiple items.

NOTE : declaring DefaultListModel outside function does not cause any problem, making its object outside function is the problem. You can do the following without any problem :

DefaultListModel<String> model;

private void UpdateJList(){
    model = new DefaultListModel<String>();
    for(Person p : personList){
         model.addElement(p.ToString());
    }    
    clientJList.setModel(model);     
    clientJList.setSelectedIndex(0);
}

or you can try clearing the previous values from your model and then adding new values.

like image 116
gprathour Avatar answered Sep 27 '22 17:09

gprathour