I have encountered a "strange" problem.
I'm doing a chat program in Java and it's designed in the way that your contacts are listen with a JList. When a message is received by any contact, the JList should still select the contact that was selected before the message was received. The contact that has sent the message to me should go to the top of the list but not be selected. I've solved this problem by saving the index of the currently selected contact and writing these two rows.
for updating the jlist with my defaultlistmodel
contactsJList.setModel(model);
for selecting the previously selected contact. I do this because the jlist "forgets" about the selection state after it's updated.
contactsJList.setSelectedIndex(selectedContactIndex);
The problem is that setSelectedIndex doesn't seem to select the specific object for real. It selects it and I can see it with my eyes, but somehow the selection is still where I last clicked with my mouse.
I will try to explain the problem with an example to make it clear.
When I send a message to a contact, say contact with the name Jay and index 5 on the list, this contact will move to the top of the list and get selected (this is because it's me that sends the message, I'm not receiving one). That means that Jay becomes index 0 and gets selected by writing:
contactsJList.setSelectedIndex(0);
Now when I receive a message from another contact eg with the name Ann, I still want Jay to be selected. Ann gets to the top of the list with index 0 and Jay is index 1 and second on the list. The problem now is that Jay does not get selected BECAUSE I havn't clicked on him personally with my mouse before getting the message from Ann, instead I wrote in code that Jay should be selected (and be the currently selected index). Now remember that Jay was index 5 in the first place before I sent him a message (that's also the index I clicked on with my mouse). So instead of Jay being selected after receiving the message from Ann, index number 5 gets selected.
Why does not setSelectedIndex() work properly? Am I not thinking right or something? How can I solve my problem? Maybe I should use ListSelectionModel?
Help would be really appreciated! Thank you very much in advance