I'm trying to make a stopwatch with three buttons, "Start", "Pause", and "Stop". My instructor only taught us how to set Action Listeners to two buttons. How do I set up Action Listeners to three buttons? Here is my coding so far
JButton startButton = new JButton("Start");
JButton stopButton = new JButton("Stop");
JButton pauseButton = new JButton("Pause");
startButton.addActionListener(this);
stopButton.addActionListener(this);
public void actionPerformed(ActionEvent actionEvent) {
Calendar aCalendar = Calendar.getInstance();
if (actionEvent.getActionCommand().equals("Start")){
start = aCalendar.getTimeInMillis();
aJLabel.setText("Stopwatch is running...");
} else {
aJLabel.setText("Elapsed time is: " +
(double) (aCalendar.getTimeInMillis() - start) / 1000 );
}
}
I haven't made any Action Listeners for my "Pause" feature yet because I don't know how to pause the timer anyway. But I wanted to link the action to the button before I figured out how to pause.
What you are looking for is a
if-then-else if-thenstatement.Basically, add the
ActionListenerto all three buttons as you have been doing...Then supply a
if-else-ifseries of conditions to test for each possible occurrence (you are expecting)Take a closer look at The if-then and if-then-else Statements for more details
Instead of trying to use the reference to the buttons, you might consider using the
actionCommandproperty of theAcionEventinstead, this means you won't need to be able to reference the original buttons...It also means that you could re-use the
ActionListenerfor things likeJMenuItems, so long as they had the sameactionCommand...Now, having said that, I would encourage you not to follow this paradigm. Normally, I would encourage you to use the
Actions API, but that might be a little too advanced for where you're up to right now, instead, I would encourage you to take advantage of Java's anonymous class support, for example....This isolates the responsibility for each button to a single
ActionListener, which makes it easier to see what's going on and when required, modify them without fear or affecting the others.It also does away with the need to maintain a reference to the button (as it can be obtained via the
ActionEventgetSourceproperty)