I'm trying to make a stopwatch in java.
My first problem is that on line 46 I should start timerMethod in a new thread but I couldn't figure out how to do that.
The second problem is that lines 44, 45 and 53 have errors that say "Local variable isTiming defined in an enclosing scope must be final or effectively final".
Code:
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Stopwatch {
public static void main(String[] args) {
windowMethod();
}
public static void windowMethod() {
//create frame
JFrame frame = new JFrame();
frame.setSize(900, 600);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//create panel
JPanel panel = new JPanel();
frame.add(panel);
panel.setLayout(null);
//create time label
JLabel timeLabel = new JLabel("00:00:00");
panel.add(timeLabel);
timeLabel.setFont(new Font("Tahoma",Font.PLAIN, 32));
Dimension timeLabelSize = timeLabel.getPreferredSize();
int timeLabelx = (450-(timeLabelSize.width/2));
timeLabel.setBounds(timeLabelx, 50, timeLabelSize.width, timeLabelSize.height);
//create start/stop button
JButton startStopButton = new JButton("Start Timer");
panel.add(startStopButton);
startStopButton.setFont(new Font("Tahoma",Font.PLAIN, 32));
Dimension startStopButtonSize = startStopButton.getPreferredSize();
int startStopButtonx = (450-(startStopButtonSize.width/2));
startStopButton.setBounds(startStopButtonx, 150, startStopButtonSize.width, startStopButtonSize.height);
boolean isTiming = false;
startStopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (isTiming = false) { //This runs if the button is clicked to start the timer
isTiming = true;
timerMethod(isTiming); //runs the timerMethod in a new thread?
startStopButton.setText("Stop Timer");
Dimension startStopButtonSize = startStopButton.getPreferredSize();
int startStopButtonx = (450-(startStopButtonSize.width/2));
startStopButton.setBounds(startStopButtonx, 150, startStopButtonSize.width, startStopButtonSize.height);
}
else { //This runs if the button is clicked to stop the timer
isTiming = false;
startStopButton.setText("Start Timer");
Dimension startStopButtonSize = startStopButton.getPreferredSize();
int startStopButtonx = (450-(startStopButtonSize.width/2));
startStopButton.setBounds(startStopButtonx, 150, startStopButtonSize.width, startStopButtonSize.height);
}
}
});
}
public static String timerMethod(boolean isTiming) {
int milliseconds = 0;
int seconds = 0;
int minutes = 0;
while(isTiming = true) {
milliseconds++;
if (milliseconds > 999) {
milliseconds = 0;
seconds++;
if (seconds > 59) {
seconds = 0;
minutes++;
}
}
}
String outputTime = (minutes + ":" + seconds + ":" + milliseconds);
return outputTime;
}
}