简体   繁体   中英

Changing element location in DefaultListModel

I am working on DefaultListModel . I would require to move the selected item to first or to last(not up and down) location in list. How to move the selected item in a DefaultListModel at first or last location without swapping?

I'm guessing that the problem you're having is that when you hit your "up" or "down" button, the item moves, but because you removed it from the list and then added it again, it is no longer selected. The list selection model processes the "remove" event and clears its selection because the selected item was removed.

I know of two ways to fix this, both inelegant:

  1. Have your "move" action also update the selection model to keep the same item selected.
  2. Move the item by keeping it in the list and moving all the other items. So, if the list is [1, 2, 3, 4] and you want to move 3 to the start, first remove 1 and 2 to get [3, 4], then add them back in at index 1 to get [3, 1, 2, 4]. (This uses the fact that the selection model updates the selected index on add and remove events)

I've generally used (2), because although it is a bit more work, it allows the moving logic to deal only with the list model and not the selection 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