简体   繁体   English

Java中的计时器问题-设置setRepeat(false)时时间未停止

[英]Timer Issue in Java - Time not Stopping when setRepeat(false) is set

I'm hoping someone could help me fix this issue that I'm having with timers. 我希望有人可以帮助我解决计时器方面的问题。 When timer.start() is run, the timer starts. 运行timer.start()时,计时器启动。 however, it seems to repeat endlessly. 然而,它似乎无休止地重复着。

I just need the timer to execute once. 我只需要计时器执行一次即可。 How can I achieve this if timer.setRepeats(false) is not working? 如果timer.setRepeats(false)无法正常运作,该如何实现?

     ActionListener updatePane = new ActionListener() {

     public void actionPerformed(ActionEvent ae) {

     try {
            msgPaneDoc.insertString(msgPaneDoc.getLength(), "CLICK",  
                    msgPaneDoc.getStyle("bold_style")); 
         } catch (BadLocationException ex) {    
           }}}; 

        Timer timer = new Timer(3000,updatePane); 

         timer.start();
         timer.setRepeats(false);

You have call it from inside the The Event Dispatch Thread . 您已经从“事件调度线程”内部调用了它。

Try with SwingUtilities.invokeLater() or EventQueue.invokeLater() 尝试使用SwingUtilities.invokeLater()EventQueue.invokeLater()

Sample code: 样例代码:

SwingUtilities.invokeLater(new Runnable() {

    @Override
    public void run() {
        ActionListener actionListener = new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                System.out.println("Hello");
            }
        };
        Timer timer = new Timer(1000, actionListener);
        timer.start();
        timer.setRepeats(false);
    }
});

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

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