I've been trying to implement a timer to my program with no success. What I need is a timer that is able to count in seconds. My idea was to create a timer that added 1 to a variable every second, but I don't really know how to do that. The timer should start when button1 or button2 is clicked, and stop when button3 is clicked. I'll have to use a Swing timer by the way, since it concerns a GUI program.
It would be nice if somebody could point me in the right direction. I have looked up the syntax for timers in Java but I don't understand it (I'm new to coding).
This is the code (I left out some unimportant stuff):
public class ColoredWordsExperiment {
JFrame frame;
JButton button1;
JButton button2;
JButton button3;
ButtonHandler buttonHandler;
Timer timer;
ColoredWordsExperiment(){
frame = new JFrame("Colored Words Experiment");
button1 = new JButton("Matching");
button2 = new JButton("Non-matching");
button3 = new JButton("Finished");
buttonHandler = new ButtonHandler(this);
button1.addActionListener(buttonHandler);
button2.addActionListener(buttonHandler);
button3.addActionListener(buttonHandler);
timer = new Timer(1000, buttonHandler);
}
public static void main(String[] arg) {
new ColoredWordsExperiment();
}
}
-
class ButtonHandler implements ActionListener {
ColoredWordsExperiment coloredWords;
public ButtonHandler(ColoredWordsExperiment coloredWords) {
this.coloredWords = coloredWords;
}
@Override
public void actionPerformed(ActionEvent e){
//If button "Matching" is clicked
if (e.getActionCommand().equals("Matching")) {
generateMatching();
timer();
//If button "Non-Matching is clicked
} else if (e.getActionCommand().equals("Non-matching")) {
generateNonMatching();
timer();
//If button "Finished" is clicked
} else if (e.getActionCommand().equals("Finished")) {
//stop timer
}
}
public void timer(){
coloredWords.timer.start();
}
}