I'm making an applet which has two buttons: step back and step forward. I have the same timer in every button to execute an animation. If I push step forward it works fine, and the animation runs, but if i push step back, the animation doesn't run or is bad runned (in a wrong position and velocity). I guess the problem is the timer doesn't stop correctly and is running when start the timer again, but I don´t know how to solve it.
This is the code of the step forward button:
//Code of the button "Paso a Paso"
this.botonPasoAPaso = new JButton("Paso a paso");
this.botonPasoAPaso.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Avoid timer to accelerate
if (timer != null && timer.isRunning()) {
timer.stop();
}
//Code of the timer, makes an animation
timer = new Timer(35, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (pasoAPaso <= listaPaquetes.size()) {
Paquete p = listaPaquetes.get(pasoAPaso);
p.animar();
panelGrafo.removeAll();
panelGrafo.updateUI();
panelGrafo.setPaquete(p);
panelGrafo.setAnimar(true);
panelGrafo.repaint();
}
}
});
timer.start();
pasoAPaso++;
}
});
This is the code of the step back button:
this.botonAtras.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (timer != null && timer.isRunning()) {
timer.stop();
}
timer = new Timer(35, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (pasoAPaso < listaPaquetes.size() && pasoAPaso>=0) {
Paquete p = listaPaquetes.get(pasoAPaso);
p.animar();
panelGrafo.removeAll();
panelGrafo.updateUI();
panelGrafo.setPaquete(p);
panelGrafo.setPasoAPaso(pasoAPaso);
panelGrafo.setAnimar(true);
panelGrafo.repaint();
//Actualizar matriz del render para pintar celdas
RenderTabla.matrizTotal = new Cuadrado[pasos.get(pasoAPaso).length][pasos.get(pasoAPaso)[0].length];
RenderTabla.matrizTotal = pasos.get(pasoAPaso);
tabla.introducirDatos(pasos.get(pasoAPaso),false);
}
}
});
timer.start();
pasoAPaso--;
}
});
This is a video of the applet to see what's happening If you see the video, when I click the "Paso a Paso" (Step forward) button, a truck is animated, but when I click the "rewind" (Step back) button, it doesn't work (appears a truck but is not correctly animated), and if i click again nothing happens.
Thanks.