Bizarro Swing JList Model Behavior
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:
- I see that you call the
setVisible
on the JList, how exactly are you adding it to whatever you are displaying? - Are you adding the elements after you display your JFrame? If I remember correctly, that won't work well, I think you have to repaint everything.
- Make sure that you're not messing around with the list model at some point; Maybe at some point later in the code, you're changing it?
- Ensure that you are actually looking at the right element; maybe your list is hidden behind something else?(try setting the background color, i.e.
lstFruitList.setBackground(Color.BLUE);
- Final thought, are you sure that you've compiled it properly? I've sometimes accidentally forgotten to compile, or had messed up something and was running an older version of the code and was confused as to why something didn't work.
For reference, here's the code that I ran:
import java.awt.*;
import javax.swing.*;
public class javatest{
public static void main(String[] args){
JFrame f = new JFrame("HELLO");
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);
JPanel p = new JPanel();
p.add( lstFruitList );
f.add( p );
f.setLocation(0,0);
f.setSize(400,400);
f.setVisible(true);
}
}
精彩评论