【问题标题】:How do I make Thread.sleep() delay the execution time between two methods?如何让 Thread.sleep() 延迟两个方法之间的执行时间?
【发布时间】:2015-02-14 23:20:56
【问题描述】:

我正在做一个个人项目。理想情况下,我的程序应该将 jlabels 图标设置为某个 gif,等待 gif 结束,然后将其设置为空白 png。每次单击另一个标签时,我的程序都应该执行此操作(我使用事件侦听器使标签用作按钮,按钮很难看)。不幸的是,按下“按钮”后,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);
}

我很想将一些代码放入带有 int seconds 参数的方法中,然后在需要延迟时调用它。最简单的方法是什么?

编辑

所以我使用了充满鳗鱼的气垫船这样的方法

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);
}

每次用户在 GUI 中按下按钮时都会执行“battle()”方法。按下大约两次后,设置的gif和设置的png之间的延迟越来越小。这会导致 gif 动画在完成之前被切断。大约按四五次后,gif 似乎立即被切断了。

我玩过各种延迟时间,但没有一个能始终如一地播放 gif 直到完成。有没有办法获得一致的延迟?出于我的目的,gif 必须始终在每次按下按钮时播放完成。我该怎么做?

【问题讨论】:

    标签: java delay


    【解决方案1】:

    你问,

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

    最好的答案是,......你不知道。
    你的是一个 Swing GUI,所以不,不要使用Thread.sleep(...),尤其是在 Swing 事件线程上,因为你最终会让你的 GUI 完全进入睡眠状态,这不是你的目标。改用摇摆计时器。

    将延迟后运行的代码放入 Timer 的 ActionListener,在 Timer 和 bingo 上调用 start()

    例如,

    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();
             }
          });
       }
    }
    

    【讨论】:

      【解决方案2】:

      怎么样...

      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);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-17
        • 1970-01-01
        • 1970-01-01
        • 2016-03-18
        • 1970-01-01
        • 2020-07-15
        相关资源
        最近更新 更多