After much help from the generous users of this website, I've managed to make my timers function properly in a program I'm designing. Here is a small snippet of the code:
//Class represents what do when a button is pressed
private static class ButtonHandler implements ActionListener {
public void actionPerformed (ActionEvent e) {
them.setText("");
final JButton button = (JButton)e.getSource();
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
final String tc = random();
them.setText("They chose: " + tc + "!");
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (button == rock) {
whoWins("rock", tc);
} else if (button == paper) {
whoWins("paper", tc);
} else if (button == scissors) {
whoWins("scissors", tc);
}
yourWins.setText("Your wins: " + yw);
theirWins.setText("Their wins: " + tw);
}
});
timer.setRepeats(false);
timer.start();
}
});
timer.setRepeats(false);
timer.start();
}
}
What I would like to do is avoid having to define multiple timers just to get them to fire in succession. If it's possible to create a timer class that I call upon when I need to have a delay, that would be best. If I need to replace "new ActionListener()" with "this" or something, please notify me. I am new to java and I'd like to figure this out so I can continue working on various home projects.
ScheduledExecutorServiceand simply schedule a new task from the previous one. Don't forget to useSwingUtilites.invokeLaterto run the code - as otherwise you will violate Swing's threading policy. - Boris the Spider