Java:计时器(等待 x 秒)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27281781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:33:10  来源:igfitidea点击:

Java: Timer (wait x seconds)

javatimer

提问by Casper TL

I have a simple GUI that can save and get some data out of an .doc file.

我有一个简单的 GUI,可以从 .doc 文件中保存和获取一些数据。

When i press a save button, i have a label that says "Succes" or "Error" via label.setText();

当我按下保存按钮时,我有一个标签,通过 label.setText() 显示“成功”或“错误”;

Update: The code is meant to be ran in a FXMLDocumentController (built p? SceneBuilder)

更新:该代码旨在在 FXMLDocumentController(内置 p?SceneBuilder)中运行

I want the label to go back to being empty ("") after 3 seconds..

我希望标签在 3 秒后恢复为空(“”)。

I have tried:

我努力了:

try {
    Thread.sleep(1000);               
    } 
 catch(InterruptedException ex) {
Thread.currentThread().interrupt();

}

}

but is it like, that the sleep-function freezes the whole GUI so i can't interact with it while it's sleeping. How do i set up an timer that does not affect usability? :)

但是,睡眠功能是否会冻结整个 GUI,因此我无法在它睡觉时与其进行交互。如何设置不影响可用性的计时器?:)

回答by maimArt

Create a TimerTask which is started after 3 seconds. This TimerTask has to execute the code which uses gui components via Platform.runLater(new Runnable())

创建一个在 3 秒后启动的 TimerTask。此 TimerTask 必须通过 Platform.runLater(new Runnable()) 执行使用 gui 组件的代码

Timer timer = new Timer();
timer.schedule(new TimerTask() {

        @Override
        public void run() {
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    label.setText("");
                }
            });

        }
    }, 3000);

回答by brso05

class runnable implements Runnable {
    private Object obj;
    public runnable(Object obj)
    {
        this.obj = obj;
    }
    public void run() {
        try {
            Thread.sleep(3000);
            this.obj.setText("");//right here just execute your method
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Hello from a thread!"); //your code here
    }

}

public class Test {

    public static void main(String[] args){
        Object myObject;
        (new Thread(new runnable(myObject))).start();
    }
}

You could launch another thread to handle this. Just do your processing in the other thread. Sleep for 3 seconds then clear the lbl.

您可以启动另一个线程来处理此问题。只需在另一个线程中进行处理即可。休眠 3 秒,然后清除 lbl。

Here is an example showing how it works:

这是一个显示其工作原理的示例:

class runnable implements Runnable {
    Test test;
    public runnable(Test test)
    {
        this.test = test;
    }
    public void run() {
        try {
            Thread.sleep(3000);
            this.test.test = "test2";
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Hello from a thread!");
    }

}

public class Test {
    public String test = "test";
    public static void main(String[] args) throws InterruptedException{
        Test test = new Test();
        System.out.println(test.test);
        (new Thread(new runnable(test))).start();
        Thread.sleep(4000);
        System.out.println(test.test);
    }
}

************************************************************UPDATE*************************************************************

****************************************************** **********更新*************************************** **********************

class runnable implements Runnable {
    Test test;
    public runnable(Test test)
    {
        this.test = test;
    }
    public void run() {
        try {
            Thread.sleep(3000);
            this.test.label.setText("This is a test.");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Hello from a thread!");
    }

}

public class Test {
    public String test = "test";
    JLabel label = new JLabel("Test");
    JFrame frame = new JFrame();
    JButton button = new JButton();
    public static void main(String[] args) throws InterruptedException{
        Test test = new Test();
        test.label.setText("Test");
        test.button.setText("Test Button");
        test.button.setSize(50, 50);
        test.frame.setSize(500, 500);
        test.frame.add(test.button);
        test.frame.add(test.label);
        test.frame.setVisible(true);
        test.button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                System.exit(0);
            }

        });
        (new Thread(new runnable(test))).start();
    }
}

回答by MeetTitan

Your problem is your are blocking the UI thread. It cannot update anything and the main loop breaks. You can accomplish your goal with a timerobject as others have answered, or if you don't want to you could implement your own thread to do the same.

您的问题是您正在阻止 UI 线程。它无法更新任何内容并且主循环中断。您可以使用timer其他人回答的对象来实现您的目标,或者如果您不想这样做,您可以实现自己的线程来做同样的事情。

回答by ps-aux

You cannot interact with GUI because the code is sleeping in event dispatch thread which is responsible for handling GUI events and so it's blocked. Use this Swing Timerinstead.

您无法与 GUI 交互,因为代码在负责处理 GUI 事件的事件调度线程中休眠,因此它被阻塞。请改用此摇摆计时器

The given example there is simple. I include the comments.

给出的例子很简单。我包括评论。

  int delay = 1000; //milliseconds

  //Create action listener which listens for the event generated by the timer
  ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
          Place here code to execute when the time runs out.
      }
  };
  //Simply create a timer with the created listener and start it.
  new Timer(delay, taskPerformer).start();

回答by Epiglottal Axolotl

Don't use Thread.sleep(). Instantiate a javax.swing.Timerand have it do an event callback. If you want to keep it in the same method, call wait(), and then have the event handler call notify(), which will resume the program. However, you probably don't need to do that; you can just remove the text directly using the event handler.

不要使用Thread.sleep(). 实例化 ajavax.swing.Timer并让它做一个事件回调。如果您想将其保留在相同的方法中,请调用wait(),然后让事件处理程序调用notify(),这将恢复程序。但是,您可能不需要这样做;您可以直接使用事件处理程序删除文本。

回答by TheDutchDevil

To do this you will have to use threading. In case you are using Swing you can use a Swing Timer. The code will look something like this. Put this code where you are 'saving' the file.

为此,您必须使用线程。如果您使用的是 Swing,则可以使用 Swing Timer。代码看起来像这样。将此代码放在您“保存”文件的位置。

  int delay = 3000; 
  ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
          //Empty the label here. This code will be called once the timeout of three seconds has been passed
      }
  };
  new Timer(delay, taskPerformer).start();