I am having an issue in my Swing app where I am creating a simple JList by passing it a model – and even though the model is demonstrably populated, the JList refuses to display it’s own model’s contents.
DefaultListModel dlm = new DefaultListModel();
String[] modelElems = {"Apple", "Orange", "Banana"};
for(int i = 0; i < modelElems.length; i++)
dlm.add(i, modelElems[i]);
JList lstFruitList = new JList(dlm);
lstFruitList.setVisible(true);
When my Swing app runs, I see the JList on screen, but it is completely empty! I’ve looked at countless examples, poured over the Swing tutorials, and cannot seem to figure out what is going on. Anybody ever had this happen to them before?!? Anything that is glaringly-obviously-wrong?!?
NOTE:
The following print statement indeed shows that my model has 3 elements:
// Prints "Fruit List model has a size of 3"
System.out.println("Fruit List model has a size of " + dlm.size());
However, if I try to loop through and print the names of the fruits in my model, by calling (String)dlm.get(i) at every iteration (where i is the iteration var), it prints each model element as null…
hmmmm
That code works fine for me. Some thoughts:
setVisibleon the JList, how exactly are you adding it to whatever you are displaying?lstFruitList.setBackground(Color.BLUE);For reference, here’s the code that I ran: