Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a lazy loading implementation of JList?

Tags:

java

swing

jlist

Is there a way to implement lazy loading with Swing's JList?

like image 278
user105413 Avatar asked Dec 02 '22 07:12

user105413


2 Answers

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; }
};
like image 143
Michael Myers Avatar answered Dec 03 '22 22:12

Michael Myers


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

like image 40
Un Homme Avatar answered Dec 03 '22 22:12

Un Homme