我试图在java中制作秒表。
我的第一个问题是,在第46行,我应该在一个新线程中启动timerMethod,但我无法弄清楚如何做到这一点。
第二个问题是第44,45和53行有错误表示"在封闭范围内定义的局部变量isTiming必须是最终的或有效的最终"。
代码:
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;
}
}
答案 0 :(得分:0)
timerMethod
实际上应该是扩展Thread类的类的run()
方法,它应该有一种从另一个线程停止的方法。
我建议您仔细阅读Oracle网站https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html上的并发课程吗?