Fast way to find visible components in JScrollPane

2019-07-28 10:50发布

Given a JScrollPane containing a thousand components using some LayoutManager. Each component can be either in a loaded or unloaded state. There are not enough resources for all to be loaded.

I'd like to have only the visible components load()ed in memory, and the invisible components unload()ed. When the user scrolls, a listener needs to keep updating the components' states: unload() the previously visible, and load() the newly visible.

  1. At any given moment, how do I know which components are visible?
  2. Can I know this without iterating the whole thousand? (as if an efficient viewPort.getVisibleComponents())

I was going to have a prepared sorted list of all component Ys, then in runtime binary search the ViewPort's Y to reach an index which may guide me to the visible ones. This failed as component Ys all returned 0 during list preparation time. This needs to be efficient.

1条回答
别忘想泡老子
2楼-- · 2019-07-28 11:06

For concreteness, I will assume 1000's of records, each represented by an instance of class Record. Each such Record should contain a unique, meaningful key of type Key.

  • Obtain the List<Key>, possibly in a background task.

  • Construct a one-column TableModel of the key values.

  • Use this model to construct a JTable, table.

  • Add the table to a JScrollPane on the left side of a suitable layout.

  • On the right, add a panel that can Display the details of a single, selected Record.

  • Let Display contain a ListSelectionListener, seen here, that updates the details for whichever Record is currently selected in the table.

  • Add each selected Record to a cache, retrieving the Record from storage, possibly in a background task, only if not already present in the cache.

查看更多
登录 后发表回答