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

570 views Asked by At

I'm hoping someone could help me fix this issue that I'm having with timers. When timer.start() is run, the timer starts. 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?

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

There are 1 answers

7
Braj On

You have call it from inside the The Event Dispatch Thread.

Try with SwingUtilities.invokeLater() or 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);
    }
});