Domanda

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?

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top