This is an example where you press a button and jList1 is refilled with items from a1 to a1000.:
//variable
private List<String> list = new ArrayList<>();
...
//main method
jList1.setModel(new DefaultListModel());
for(int i = 0; i < 1000; i++) {
list.add("a"+i);
}
...
//button action - jList1 refill
DefaultListModel dtm = (DefaultListModel)jList1.getModel();
dtm.removeAllElements();
for(String s : list) {
dtm.addElement(s);
}
If I fill the jList1
, then select (with mouse) 0 index (first element in jList) and then press the button the program freezes while refilling the list. If I select any other element or do not select any item in the list at all then it fills just fine.
P.S. This example is done without any swing or EWT threads, because the main reason was found using them.
SSCCE:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lt;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
/**
*
* @author Minutis
*/
public class Window {
public static void main(String[] args) {
final List<String> list = new ArrayList<>();
JFrame frame = new JFrame("BorderLayout Frame");
JPanel panel = new JPanel();
final JList jList1 = new JList();
JButton refill = new JButton("Refill");
jList1.setModel(new DefaultListModel());
for(int i = 0; i < 1000; i++) {
list.add("a"+i);
}
refill.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DefaultListModel dtm = (DefaultListModel)jList1.getModel();
dtm.removeAllElements();
for(String s : list) {
dtm.addElement(s);
}
}
});
frame.add(panel);
panel.setLayout(new BorderLayout());
panel.add(jList1, BorderLayout.CENTER);
panel.add(refill, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}