Java:计时器(等待x秒)

时间:2014-12-03 21:15:51

标签: java timer

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

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

更新:代码应在FXMLDocumentController中运行(由SceneBuilder构建)

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

我试过了:

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

}

但就像睡眠功能冻结了整个GUI,所以我在睡觉时无法与它交互。如何设置不影响可用性的计时器? :)

6 个答案:

答案 0 :(得分:7)

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

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

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

        }
    }, 3000);

答案 1 :(得分:1)

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

你可以启动另一个线程来处理这个问题。只需在另一个线程中进行处理。睡3秒然后清除lbl。

以下是一个展示其工作原理的示例:

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

答案 2 :(得分:0)

您无法与GUI进行交互,因为代码在事件调度线程中处于休眠状态,该线程负责处理GUI事件,因此被阻止。请改用这个Swing Timer

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

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

答案 3 :(得分:0)

不要使用Thread.sleep()。实例化javax.swing.Timer并让它进行事件回调。如果要将其保留在同一方法中,请调用wait(),然后让事件处理程序调用{​​{1}},这将恢复该程序。但是,你可能不需要这样做;你可以直接使用事件处理程序删除文本。

答案 4 :(得分:0)

为此,您必须使用threading。如果您使用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();

答案 5 :(得分:0)

您的问题是您正在阻止UI线程。它无法更新任何内容和主循环中断。您可以使用timer对象完成目标,因为其他人已经回答,或者如果您不想,您可以实现自己的线程来执行相同的操作。