Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何设置方法的延迟_Java_Settimeout_Delay - Fatal编程技术网

Java 如何设置方法的延迟

Java 如何设置方法的延迟,java,settimeout,delay,Java,Settimeout,Delay,当我当前调用我的方法时 public void flip() { Image change = new ImageIcon(this.getClass().getResource(imageName[0])).getImage(); ImageIcon card = new ImageIcon(change); imagelbl.setIcon(card); } 当前,当调用该方法时,代码将运行并且该方法可以工作。这是完美的,但我需要有一个1秒的延迟之前,方法运行

当我当前调用我的方法时

public void flip() {
    Image change = new ImageIcon(this.getClass().getResource(imageName[0])).getImage();

    ImageIcon card = new ImageIcon(change);

    imagelbl.setIcon(card); 
}
当前,当调用该方法时,代码将运行并且该方法可以工作。这是完美的,但我需要有一个1秒的延迟之前,方法运行。
我尝试过使用setTimeout(),但没有成功。如何使此方法在运行前有1秒的延迟?

使用Timer类进行计时

public void callerMethod() {
    System.out.println("Start");
     Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            public void run() {
                delayedMethod();
            }
        }, 1000);
}


public void delayedMethod() {
    System.out.println("Test");
}

使用
Thread.sleep(1000)
作为
flip()
方法的第一行。

“我尝试过使用setTimeout()”-显示的代码不是JavaScript,而是
setTimeout()
是JavaScript。该方法在何处以及如何调用?Java和JavaScript不一样!只是一个提示:“超时”意味着“要等多久才能放弃”。所以这样一个方法,即使它存在于Swing中,也不会做您希望它做的事情;这不仅仅是个人不喜欢的问题。永远不要在EDT中使用睡眠。这将延迟整个GUI。此外,问题不是让线程睡眠,而是为另一种方法计时。使用Thread.sleep()时,您还必须处理异常。@pruntlar您能否详细说明为什么Thread.sleep()存在“个人”问题?由于OP使用的是swing(基于
ImageIcon
),因此最好使用
javax.swing.Timer
,而不是
java.util.Timer
,尤其是由于
flip
方法更改了GUI元素,这只能从EDT内部完成。