Is there a way to implement lazy loading with Swing's JList?
In a way, yes. You can create a custom ListModel
which uses the getElementAt(int index)
method to load the correct value if it hasn't already been loaded. See the example in the Javadocs for JList
:
// This list model has about 2^16 elements. Enjoy scrolling.
ListModel bigData = new AbstractListModel() {
public int getSize() { return Short.MAX_VALUE; }
public Object getElementAt(int index) { return "Index " + index; }
};
I solved it. I had missed the solution discussed at the top of the JList API documentation.
In the example source code I posted in another answer on this topic, add this line (and comment) after creating the JList:
// Tell JList to test rendered size using this one value rather
// than every item in ListModel. (Much faster initialization)
myList.setPrototypeCellValue("Index " + Short.MAX_VALUE);
The problem is that JList, by default, is accessing every item in the entire ListModel to determine at runtime the necessary display size. The line added above overrides that default, and tells JList to examine just the one value as passed. That one value acts as a template (prototype) for sizing the display of the JList.
See:
http://java.sun.com/javase/6/docs/api/javax/swing/JList.html#prototype_example
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