Search code examples
javaindexingjlistdefaultlistmodel

JList behaves strange


I'm working with a JList in Java with a DefaultListModel. I'm trying to update the content of the list by changing place of the items. The problem is that DefaultListModel doesn't have any type of "update"-method so what I'm doing is removing the element I want to change the position of and then add it again on the index I want. This makes the list sometimes become very large with big gaps between the elements, and also it makes the elements text half, just like when a program crashes.

If I don't specify a position/index of the element to be added to and just remove it and then add it with the default add-method (which adds it to the bottom of the list), then this problem doesn't occur. Do you have any clue of how I can change the position of an element in a JList without causing this problem?

Thanks on advance!


Solution

  • This is the solution that @DanTemple gave me and it worked!

    1) Retrieve the data from the model. 2) Clear the data from the model. 3) Rearrange the data as desired. 4) Add the data back into the model.