Reputation: 103
I am struggling a bit with this. After researching on Google I have created the following timer routine which works well when called
// play move method
public static void playMove() {
int delay = 1200; // delay for 1 sec.
int period = 1200; // repeat every sec.
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
private int count = history.getGameIndex();
public void run() {
count++;
if (count >= history.getTotalMoves() + 1) {
timer.cancel();
timer.purge();
return;
}
history.next();
}
}, delay, period);
}
However, the problem is that I can't figure how to integrate this code into a JToggleButton which is the correct place for it so that when I click play it plays a move and when I click stop is stops (or pauses) the routine. Here is my JToggleButton code:
ImageIcon playIcon = new ImageIcon(
JBoard.class.getResource("/images/menu/play.png"));
btnPlayMove = new JToggleButton(playIcon);
btnPlayMove.setToolTipText("Play");
btnPlayMove.setContentAreaFilled(true);
btnPlayMove.setMargin(new Insets(2, 2, 2, 2));
btnPlayMove.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if (isConnected()) {
showMessage("Engine disabled during network play...");
return;
} else if (btnPlayMove.isSelected()) {
// play
playMove();
ImageIcon playIcon = new ImageIcon(JBoard.class
.getResource("/images/menu/play.png"));
btnPlayMove.setIcon(playIcon);
} else {
// stop
ImageIcon stop = new ImageIcon(JBoard.class
.getResource("/images/menu/stop.png"));
btnPlayMove.setIcon(stop);
}
}
});
buttonPanel.add(btnPlayMove);
I am fairly new to Java and it would be great if someone could help
Upvotes: 0
Views: 263
Reputation: 347194
You could take advantage of the javax.swing.Timer
Timer timer = new Timer(1200, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
count++;
if (count >= history.getTotalMoves() + 1) {
timer.cancel();
timer.purge();
return;
}
history.next();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.setInitialDelay(1200);
Then in you button code you would simply call timer.start()
or timer.stop()
Upvotes: 1
Reputation: 159754
I would suggest you make the playMovie method non-static & declare History as a global variable & include in your swing class:
History history = new History(); // assuming this with no-args
public void playMove() {
int delay = 1200; // delay for 1 sec.
// etc.
// etc.
}
Also, you will need to programmatically stop playMove() if its TimerTask thread is still running.
Upvotes: 0