(Java) JList displays an empty list occasionally on program start
My program reads in files from a given directory on program start (each one containing an object), and adds each object to a Vector. updateList() is then called which loops through each of these objects one by one, adding their names(String property) to a JList with a DefaultListModel.
The issue is that very rarely when the program starts, the list appears empty. I have performed many checks such as getting the number of entries in the list as reported by the list model and everything would appear to be correct.
Has anybody seen this before? Am I missing something important here?
Thanks, updateList() below:
private void updateList(){
for (int i=0; i < calculators.size(); i++){
开发者_如何学JAVA listModel.addElement(calculators.get(i).getName());
}
}
Has anybody seen this before?
Random errors generally happen because you are not updating Swing components on the Event Dispatch Thread. Read the section from the Swing tutorial on Concurrency for more information.
In particular you would use the invokeLater() method when starting your GUI. The Swing tutorial has plenty of examples. The basic structure the tutorial uses is like:
import java.awt.*;
import javax.swing.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
add( new JLabel("Label") );
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SSCCE() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
精彩评论