简体   繁体   中英

Displaying items in a JList

I want to display a list of n elements in a JList. 3 Items of the list are shown. One item should be selected and dependent on this selected item, the last shown element should be the selected one.

For example, the items 1, 2, 3, 4, 5, 6, 7 are in the list. By default, the first shown item is the selected one: If item 3 is selected, items 3, 4, 5 are shown - if item 5 is selected, items 5, 6, 7 are shown.

What I want is the following behavior: Item 3 is selected: Items 1, 2, 3 are shown. Item 5 is selected: Items 3, 4, 5 are shown.

Any idea how this can be implemented?

From the documentation of JList:

A ListModel can be supplied directly to a JList by way of a constructor or the setModel method. The contents need not be static - the number of items, and the values of items can change over time.

This can be used to change which values are in the List. And here is how you listen for the selection events:

The preferred way to listen for changes in list selection is to add ListSelectionListeners directly to the JList. JList then takes care of listening to the the selection model and notifying your listeners of change.

So, implement a ListModel and a ListSelectionListener which changes said model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM