Pregunta

I'm trying to write some Java code to pull display a list of questions, obtained online. I have a working method called getQuestions, which pulls from my server and builds question objects off of that. I now want a JList that will automatically refresh every few seconds to be up to date on all the questions. If I run updateQuestions not inside the loop, it works fine, but as soon as I put it in the loop the list always shows up blank.

I have a method, called updateQuestions(), which gets the new array list of questions then sets them into the JList. If I run it once, it works fine. However, when I put it in my main as such:

listModel=new DefaultListModel();
questionList = new JList(listModel);
questionFeedFrame.add(questionList);
questionFeedFrame.pack();
questionFeedFrame.setVisible(true);
 while(true){
     try{
          updateQuestions(id);
          Thread.sleep(10000);
     }catch (Exception ee){
              ee.printStackTrace();
             }
           }


public static void updateQuestions(int id){
    listModel = (DefaultListModel) questionList.getModel();
    listModel.removeAllElements();
    ArrayList<Question> questions = getQuestions(id);
    for(Question q : questions){
       listModel.addElement(q.getQuestion());
    }
}

I've tried a bunch of things, including having everything repaint/validate. Any suggestions? Is there a better way to do this?

¿Fue útil?

Solución

Your problem is that your Thread.sleep(...) and while (true) loop are both tying up the Swing event thread preventing it from doing its two main jobs of drawing the GUI and interacting with the user. This will effectively freeze your GUI.

You could use a Swing Timer to do your loop without tying up the Swing event thread, but this won't fix problems with time needed to get online and download from a server. Thus I recommend that you instead use a background thread for this such as can be found with a SwingWorker, so as not to tie up and freeze the Swing event thread. Please check out Concurrency in Swing for more on this.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top