0

I have been working on JList. I have created a DefaultListModel to add elements to the jList. Everything works fine when used normally, but, when I try to call a method from a thread to update list, it is stuck. Still don't know what's the problem. Below are the codes of jList, method and thread.

Code used for DefaultListModel and jList:

DefaultListModel<String> model = new DefaultListModel<>();
model.addElement("Element 1");
jList1.setModel(model);

Method to update jList in MainClass:

public void UpdateList()
{   
    DefaultListModel<String> model = new DefaultListModel<>();
    model.addElement("Element 1");
    jList1.setModel(model);
}

Thread for calling update method outside MainClass:

class Second extends Thread {
    public void run() {
        Thread.sleep(5000);
        MainClass a = new MainClass();
        a.UpdateList();
    }
}
Madhusudan Sharma
  • 403
  • 1
  • 3
  • 12
  • You're creating a completely **new** MainClass, and changing the state of the list in this new undisplayed object will have no effect on the currently displayed JList. You need to call the method on a reference to the displayed GUI, not a new instance (and don't even think about making things static for this purpose). Also use a Swing Timer if you want a delay, not a new thread otherwise you will be breaking Swing threading rules. – Hovercraft Full Of Eels Jun 19 '17 at 19:49
  • Wow..! That really works..! Thank you very much.! :) – Madhusudan Sharma Jun 19 '17 at 20:03
  • Some minor quibbles: 1. You usually don't want to extend Thread, but instead implement Runnable. 2. You will want to learn and follow Java naming conventions: methods begin with a lower case letter. 3. In the future if you have questions on code misbehavior, you'll want to create and post a valid [mcve]. – Hovercraft Full Of Eels Jun 19 '17 at 20:03
  • Yeah, actually I'm using this thread for another reason. This is the modified code just to show the JList problem. Thanks once again. – Madhusudan Sharma Jun 19 '17 at 20:07

0 Answers0