2

Basically this code gets called from a JButton(in another class) to move the cube by repainting it over and over again. I wish to create another JButton to stop the timer (timer.stop()) from another method. How would i do that

private ActionListener actionListener ;
public void moveCube()
{
    actionListener  = new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
            cube.moveBox(7,5);
    repaint();
        }
    };
    Timer timer = new Timer( 100, actionListener );
    timer.start();
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
user3249265
  • 113
  • 1
  • 5
  • 16

2 Answers2

1

You will have to make the Timer object available outside of the moveCube() method.

In other words: in your code, define Timer myTimer; at the top, and assign it in the moveCube() method: myTimer = new Timer( 100, actionListener );. Then, you can call the timer from your other button.

mvreijn
  • 2,807
  • 28
  • 40
0

Make a singleton for an object class that have Timer for that timer make get/set functions. After that get your instanceClass.getTimer().stop(); ofcource you have to set it in your first class....

Lucian Novac
  • 1,255
  • 12
  • 18