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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With