1

I have a program designed as an MVC-pattern, where my model extends AbstractListModel. When i add a new user to my model is use following code:

public synchronized void addUser(User u) {
    if (!users.contains(u)) {
        users.add(u);
        Collections.sort(users);
        //fire
        fireIntervalAdded(ListDataEvent.INTERVAL_ADDED, getSize(), getSize());
    }
}

And it works fine, sometimes. But the JList isnt allways updating. Sometimes it works, and some times not... Any clue? And of course, the users im adding is always added to the model, but there is something wrong with the fireIntervalAdded/JList

EDIT: if i change the code to following:

public void addUser(final User u) {
    if (!users.contains(u)) {
        users.add(u);
        Collections.sort(users);
    }
    EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
        fireIntervalAdded(this, getSize(), getSize());
        }
    });
}

it works perfect. So the problem was that it wasnt the EDT that did the fire thing. Thx! Now i will rewrite it so it will be nice code aswell.

joxxe
  • 261
  • 1
  • 3
  • 13
  • Could it be a synchronization problem? Chances are there's nothing wrong with the `AbstractListModel` or `JList`. – Nate W. Oct 18 '11 at 18:12
  • EDIT: Hmm. I just removed every synchronized in the model. But still that random bug :( The method addUser is called from another thread (not a swing thread). – joxxe Oct 18 '11 at 18:22
  • 3
    The model should be updated from the EDT. – camickr Oct 18 '11 at 18:26
  • Se my edit for the answer :) thx! – joxxe Oct 18 '11 at 18:37
  • This [Q&A](http://stackoverflow.com/questions/7787998/how-to-generate-exceptions-from-repaintmanager) links to an article on techniques for finding such anomalies. – trashgod Oct 18 '11 at 23:40

1 Answers1

2

Aside from the EDT issue, you are firing the wrong index. Assuming users is already sorted you would need something like the following (all on the EDT, not just the firing of the event!):

int index = Collections.binarySearch(users, u);
if(index < 0) {
  int insertionPoint = -(index + 1);
  users.add(insertionPoint, u);
  fireIntervalAdded(this, insertionPoint, insertionPoint);
}
Walter Laan
  • 2,956
  • 17
  • 15