简体   繁体   English

如何使Thread.sleep()延迟两个方法之间的执行时间?

[英]How do I make Thread.sleep() delay the execution time between two methods?

I'm working on a personal project. 我正在做一个个人项目。 Ideally, my program should set a jlabels icon to a certain gif, wait for the gif to end, then set it to a blank png. 理想情况下,我的程序应将jlabels图标设置为某个gif,等待gif结束,然后将其设置为空白png。 My program should do this every time another label is clicked (I've used event listeners to make labels function as buttons, buttons are ugly). 我的程序应该在每次单击另一个标签时执行此操作(我已经使用事件侦听器使标签用作按钮,按钮却很丑陋)。 Unfortunately, upon "button" press, the gif is instantly replaced with the blank png, because there is no delay or waiting. 不幸的是,按下“按钮”后,由于没有延迟或等待,因此gif立即替换为空白png。

public void battle() {

ImageIcon active = new  ImageIcon(getClass().getClassLoader().getResource("resource/attacks/Animation-attackbasic_DEFAULT.gif"));
ImageIcon blank = new ImageIcon(getClass().getClassLoader().getResource("resource/attacks/Animation-blank_DEFAULT.png"));

playerAttackDisplay.setIcon(active); //This sets the Jlabel icon to the gif

try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(aqGUI.class.getName()).log(Level.SEVERE, null, ex);}

playerAttackDisplay.setIcon(blank);
}

I'd love to just put some code in a method with an int seconds parameter, then just call it whenever I need a delay. 我很想将一些代码放入带有int seconds参数的方法中,然后在需要延迟时才调用它。 What is the most simple way to do this? 最简单的方法是什么?

EDIT 编辑

So I've used Hovercraft Full of Eels's approach like so 所以我像这样使用了Hovercraft Full of Eels的方法

public void delay(int time) {
final ImageIcon blank = new ImageIcon(getClass().getClassLoader().getResource("resource/attacks/Animation-blank_DEFAULT.png"));
new Timer(time, new ActionListener() {

public void actionPerformed(ActionEvent arg0) 
     {playerAttackDisplay.setIcon(blank);}
      }).start();}

public void battle() {
final ImageIcon I = new ImageIcon(getClass().getClassLoader().getResource("resource/attacks/Animation-attackbasic_DEFAULT.gif"));

    playerAttackDisplay.setIcon(I);
    delay(500);
}

The "battle()" method is executed every time the user presses a button in the GUI. 每次用户在GUI中按下按钮时,都会执行“ battle()”方法。 After pressing it about twice, there is a smaller and smaller delay between the gif being set and the png being set. 大约按两次后,设置的gif和设置的png之间的延迟越来越小。 This results in the gif animation being cut off before it finishes. 这导致gif动画在完成之前被截断。 After about four or five presses, the gif is seemingly instantly cut off. 大约四五次按下后,gif似乎立即被切断。

I've played around with various delay times, none of them are consistent in ALWAYS playing the gif to completion. 我玩过各种延迟时间,但始终无法播放gif来完成它们。 Is there no way to get a consistent delay? 没有办法获得一致的延迟吗? For my purposes, the gif must ALWAYS play to completion at EVERY button press. 就我而言,每次按下按钮时,gif都必须始终播放到完成。 How can I do this? 我怎样才能做到这一点?

You ask, 你问,

How do I make Thread.sleep() delay the execution time between two methods? 如何使Thread.sleep()延迟两个方法之间的执行时间?

And the best answer is,.... you don't. 最好的答案是……。
Yours is a Swing GUI, so no, don't use Thread.sleep(...) especially on the Swing event thread as you'll end up putting your GUI entirely to sleep, which is not your goal. 您的是一个Swing GUI,所以不,尤其是在Swing事件线程上,请不要使用Thread.sleep(...) ,因为您最终会使GUI完全进入睡眠状态,这不是您的目标。 Use a Swing Timer instead. 请改用Swing计时器。

Put your code to run after the delay into the Timer's ActionListener, call start() on your Timer and bingo. 将延迟后要运行的代码放入Timer的ActionListener中,在Timer和Bingo上调用start()

For example, 例如,

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

public class TimerImageSwapper {
   public static final String[] IMAGE_URLS = {
      "http://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/"
      + "600px_Amaranto_con_cavallo_rampante.png/120px-600px_Amaranto_con_cavallo_rampante.png",
      "http://upload.wikimedia.org/wikipedia/commons/thumb/2/2b/"
      + "600px_Blu_con_Croce_del_Sud.png/120px-600px_Blu_con_Croce_del_Sud.png",
      "http://upload.wikimedia.org/wikipedia/commons/thumb/1/10/"
      + "600px-Flag_of_Portugal_and_Angola_v1.png/120px-600px-Flag_of_Portugal_and_Angola_v1.png",
      "http://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/"
      + "Flag_of_Meskhetian_Turks_1.svg/120px-Flag_of_Meskhetian_Turks_1.svg.png",
      "http://upload.wikimedia.org/wikipedia/commons/thumb/b/b8/"
      + "Greece_flag_300.png/120px-Greece_flag_300.png",
      "http://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/"
      + "National_Flag_Kingdom_of_Italy.png/120px-National_Flag_Kingdom_of_Italy.png",
      "http://upload.wikimedia.org/wikipedia/commons/thumb/9/98/"
      + "Flag_of_the_Kumukh_people.png/120px-Flag_of_the_Kumukh_people.png" };


   private ImageIcon[] icons = new ImageIcon[IMAGE_URLS.length];
   private JLabel mainLabel = new JLabel();

   private int iconIndex = 0;;

   public TimerImageSwapper(int timerDelay) throws IOException {
      for (int i = 0; i < icons.length; i++) {
         URL imgUrl = new URL(IMAGE_URLS[i]);
         BufferedImage image = ImageIO.read(imgUrl);
         icons[i] = new ImageIcon(image);
      }
      int gap = 25;
      mainLabel.setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));

      mainLabel.setIcon(icons[iconIndex]);

      new Timer(timerDelay, new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            iconIndex++;
            iconIndex %= IMAGE_URLS.length;
            mainLabel.setIcon(icons[iconIndex]);
         }
      }).start();
   }

   public Component getMainComponent() {
      return mainLabel;
   }

   private static void createAndShowGui() {
      TimerImageSwapper timerImageSwapper;
      try {
         timerImageSwapper = new TimerImageSwapper(1000);
         JFrame frame = new JFrame("Timer Image Swapper");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.getContentPane().add(timerImageSwapper.getMainComponent());
         frame.pack();
         frame.setLocationByPlatform(true);
         frame.setVisible(true);

      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }

   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

How about... 怎么样...

public void battle() {

ImageIcon active = new  ImageIcon(getClass().getClassLoader().getResource("resource/attacks/Animation-attackbasic_DEFAULT.gif"));
ImageIcon blank = new ImageIcon(getClass().getClassLoader().getResource("resource/attacks/Animation-blank_DEFAULT.png"));

playerAttackDisplay.setIcon(active,Long timeToWait); //This sets the Jlabel icon to the gif

try {
Thread.sleep(timeToWait);
} catch (InterruptedException ex) {
Logger.getLogger(aqGUI.class.getName()).log(Level.SEVERE, null, ex);}

playerAttackDisplay.setIcon(blank);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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