Java › Swing

Load thumbnails for visible rows in a Swing list

Request thumbnails for the rows you can see in a Swing list, share downloads across rows, and repaint each tile as its image arrives.

Load thumbnails for visible rows in a Swing list

In RSIS, you can read restaurant names and addresses and scroll before the photos arrive. I request thumbnails for visible rows and have the cell renderer draw the cached image or a placeholder.

The example uses Java 17, Swing JList, and the OkHttp image service in RSIS refactor-v2.

Show the list while photos load

Restaurant names and addresses come from the local database. The photos come from a remote server, so I let people browse as soon as the page of results is ready. Each row reserves room for a thumbnail and shows a storefront icon until the image arrives. When the photo replaces the icon, the text stays in place and the row keeps its height.

Swing asks the cell renderer for a component to paint each row. RSIS reuses the same renderer for several rows. A scroll, a resize, or a focus change can all repaint the list. If the renderer starts a download each time it paints, those routine events can trigger extra requests. Reading a photo synchronously in that code would also block the event dispatch thread (EDT). Java 17 JList

Subscribe to the URLs in the viewport

When the list opens, it listens for viewport changes. Several notifications can arrive before the EDT runs the next refresh. A flag keeps them from scheduling extra work. The refresh reads the first and last visible indices and gathers the URLs between them. If two visible rows share a URL, the list subscribes once.

When the visible range changes, I keep the existing subscriptions for URLs still in view. I close subscriptions for URLs that have scrolled out and start new ones for the URLs that have scrolled in. When the user leaves the list to open details, I close the image subscriptions and keep the list and its viewport for the return trip.

RestaurantList.refreshVisibleImages() registers a callback for each new URL. When an image arrives, the list looks up which visible rows currently use that URL. A row index captured at the start of the request could point to another restaurant by then.

1
2
3
4
5
6
urls.forEach(url -> visibleImages.computeIfAbsent(url,
        key -> images.loadAsync(key, IMAGE_PIXELS, IMAGE_PIXELS, ImageService.Priority.VISIBLE, result -> {
            if (result.isPresent()) {
                repaintImageRows(key);
            }
        })));

repaintImageRows() reads the current visible range, checks each row’s URL, and passes the bounds of each match to repaint(). At render time, each row reads the cached photo for the URL it currently displays. RSIS viewport and repaint code

Read thumbnails from the in-memory cache

The list paints a square tile 44 logical pixels wide and requests an 88×88 thumbnail. The image service downloads and decodes photos on worker threads, then stores the resized images in memory. The renderer uses getCachedSync() to look up the URL and dimensions. A cache miss leaves the storefront icon in the same tile.

A missing or invalid photo still leaves a usable row. You can read the address and open the restaurant details while the icon is in place. RSIS cell renderer · RSIS memory lookup

Share downloads and cache each rendered size

A single URL can serve the list and a larger tile in the detail view. I use the URL to look up a download that’s already in progress. A request for a second size can join that download. The service decodes both sizes from the bytes it received and caches each image under (URL, width, height). Each view can then find the thumbnail at the dimensions it asked for.

The callback runs on the service’s UI executor. RSIS supplies SwingUtilities::invokeLater to post that callback to the EDT. The service checks whether the subscription is still open when the callback runs, since the row may have scrolled out while it waited. A shared download continues as long as it has another subscriber. When the last subscription closes, the service removes queued work or attempts to cancel the active HTTP call. RSIS image service · Application wiring

Image sourceStrategyCost
A few small assets shipped with the appLoad once and reuseLittle benefit from tracking the viewport
Remote photos in a long listRequest images in the visible rangePlaceholders can appear during a fast scroll
Thumbnails should appear soon after scrollingPrefetch a few rows around the viewportBackground work uses bandwidth and cache capacity

I request images for the visible rows first. If you add prefetching, limit how many requests can queue so thumbnails already on screen still get priority. A few icons shipped with the app can be loaded once and reused without tracking which rows are visible.

Placeholder icons remain visible after scrolling while the thumbnail response is blocked Figure 1. I scrolled to the bottom of the list while the local test server held the thumbnail responses. The rows still show storefront icons.

The same visible rows now show thumbnails returned by the local server Figure 2. Once the server answered, the same rows showed thumbnails. The server received one request for the URL shared by the last two rows.

Verify the requests and then watch the list

An RSIS test holds one MockWebServer response open while two calls request the same URL at different sizes. It checks that the server receives one request and that both images have the requested dimensions. The test closes a third subscription before releasing the response and checks that it gets no callback.

1
./gradlew test --tests '*DefaultImageServiceTest'

To see the behavior in a window, point two list rows at the same image on a local server and hold the response. Check that the text appears, then scroll down while the photos are still loading. Let the server respond and watch the tiles currently on screen. Scroll back to see whether the list already has a cached thumbnail. The Explore gallery uses ImageService.NONE, so use an app or test window with the real image service wired in. RSIS image test · RSIS gallery setup

  • A missing image leaves a placeholder and preserves row size.
  • The renderer reads thumbnails from memory, with no network or disk I/O.
  • Viewport updates release stale subscriptions and repaint current rows.
  • Check how many times the shared URL was downloaded and whether each requested size is cached.
This post is licensed under CC BY 4.0 by the author.