简体   繁体   中英

Java Thread.sleep() within a for loop

public void playPanel() throws IOException{

    for(int i = 0; i<listData.size(); i++){
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ascii.setText(listData.get(i));
    }

}

What I'm trying to do is play through the listData ArrayList type, which was copied from the ascii JTextArea. Its supposed to be an animation, so when they hit play the function displays the first slide, waits a second, then the next slide, etc.

When I run this the only thing that happens is a pause with nothing on the screen changing until it displays only the final slide. I'm not sure what's wrong with it

You should never call Thread.sleep(...) on the Swing event thread unless your goal is to put the entire application to sleep, rendering it useless. Instead, get rid of the for loop, and "loop" using a Swing Timer . Something like this should work, or be close to a functioning solution (caveat: code has not been compiled nor tested):

int delay = 1000;
new Timer(delay, new ActionListener() {
  private int i = 0;

  @Override
  public void actionPerformed(ActionEvent e) {
     if (i < listData.size()) {
       ascii.setText(listData.get(i));
     } else {
       ((Timer) e.getSource()).stop();
     }
     i++;
  }
}).start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM