0

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 Answers1

1

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);
    }
});
Braj
  • 46,415
  • 5
  • 60
  • 76
  • This still generates the continuous repeating on the timer. I Know this because "CLICK" string is repeated when inserted into "msgPaneDoc" – user3633639 Jun 08 '14 at 16:07
  • Try with sample code that I shared you that prints `Hello` single time. – Braj Jun 08 '14 at 16:07
  • It's the same outcome – user3633639 Jun 08 '14 at 16:17
  • Don't know what are you doing. It prints `Hello` single time for me. Just update your question as EDIT section to show what are you doing now. – Braj Jun 08 '14 at 16:19
  • Right now, i've just put that code u sent in an If Statement so that when i click a button, it will start the timer. I placed the exact code u have up there but still the hello is repeating. – user3633639 Jun 08 '14 at 16:33
  • When I tried then there is no button, no listener, Just a simple standalone program with above lines in `main()` method. There is something wrong in your code. If you need then share complete reproducible code. – Braj Jun 08 '14 at 16:35
  • So can anything be done to initial attempt to help solve this repetition problem? – user3633639 Jun 08 '14 at 16:44