How to call the same task more than 1 time

Asked

Viewed 62 times

-1

I have the following task:

Timer tempovolta1 = new Timer();
TimerTask tarefavolta1 = new TimerTask() {
    @Override
    public void run() {
        jButton1.setBackground(Color.BLUE);
    }
};

I want to call her several times:

tempo1.schedule(tarefa1, 2000 );

Then to a longer time I’ll call her and give ERROR:

Exception in thread "AWT-Eventqueue-0" java.lang.Illegalstateexception: Task already scheduled or cancelled

  • I removed the other question

  • Diogo sees a certain resistance of yours in relation to the construction of questions according to the site. Recreating a question will not cause you to get answers if the question does not conform to a pre established standard for the site. Take a little time and read [Ask] and [help/dont-Ask] and then edit your question according to the hints of these links. And at all times as possible, add a [mcve]. If you follow the tips of these links, your questions will improve in quality and the answers will come in the same proportion.

1 answer

0

From what I understand you want or need to actually use the Swing timer.

Set a constant for example

private static final int TIMER_DELAY = 50;

Your Timer

new javax.swing.Timer(TIMER_DELAY, new ActionListener() {
     public void actionPerformed(ActionEvent e) {
        loopTeste();
     }
  }).start();

And his method

public void loopTeste() {
      button.setLocation(button.getLocation().x + 5, button.getLocation().y);
      getContentPane().repaint();
   }
  • I didn’t understand, I thought I had to use something like mult-timer or cancel the task after running, it would work ?

  • @Diogocipriano the code worked?

  • i used timer to give an interval between running a for

  • I need to call the same timer over and over again

  • I don’t know where and how to use what you wrote

Browser other questions tagged

You are not signed in. Login or sign up in order to post.