【发布时间】:2020-06-16 02:30:39
【问题描述】:
我已经在这个秒表应用程序上工作了很长时间,但我遇到了一些问题。
问题
- 秒表未正常启动可能是由于时钟逻辑
- 秒表未在我的 Java 程序中正确显示数字
如果有人能帮助解释我的程序中的缺陷并告诉我为什么它没有按照我希望的方式工作,那就太好了。需要很多帮助和赞赏,所以这是我的代码。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Clock {
private static void createWindow() {
// Important
final int windowWidth = 800; // Window width
final int windowHeight = 300; // Window height
// Clock variables
boolean clockRunning = true; // When clock is running, this will be true
int milliseconds = 0;
int seconds = 0;
int minutes = 0;
int hours = 0;
// Create JFrame
JFrame frame = new JFrame(); // JFrame object
// Create timer text
JLabel timer = new JLabel("00:00:00");
timer.setText("00:00:00");
timer.setBounds(355, 100, 100, 40); // Button position
// JButtons
JButton startTimer = new JButton("Start the timer"); // Start timer button
JButton stopTimer = new JButton("Stop the timer"); // Stop timer button
// Event listeners
startTimer.addActionListener(new ActionListener() // Start timer
{
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("Timer has started");
}
});
stopTimer.addActionListener(new ActionListener() // Stop timer
{
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("Timer has stoped");
}
});
// Clock logic
if (clockRunning = true) {
milliseconds = 0;
seconds++;
}
if(milliseconds > 1000) {
milliseconds=0;
seconds++;
}
if(seconds > 60) {
milliseconds=0;
seconds=0;
minutes++;
}
if(minutes > 60) {
milliseconds=0;
minutes=0;
hours++;
}
timer.setText(" : " + seconds); // Milliseconds
timer.setText(" : " + milliseconds); // Seconds
timer.setText(" : " + minutes); // Minutes
timer.setText("" + hours); // Hours
// JButton Settings
startTimer.setBounds(10, 100, 200, 30); // Button position
stopTimer.setBounds(570, 100, 200, 30); // Button position
// Frame Settings
frame.setSize(windowWidth, windowHeight); // Window size
frame.setLayout(null); // Frame position
// Add
frame.add(startTimer);
frame.add(stopTimer);
frame.add(timer);
// Frame settings
frame.setVisible(true); // Make frame visible
frame.setResizable(false); // Disables maximize
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Allows the window to be closed
}
public static void main(String[] args) {
createWindow();
}
}
【问题讨论】:
-
创建一个 Swing
Timer增加毫秒数,然后检查计数并更新标签。从已经定义的动作监听器中启动和停止Timer。 -
if (clockRunning = true)← 这不是你认为的那样。布尔值是离散类型,所以你永远不应该使用相等来检查它们。if (clockRunning)就足够了(并且不会冒您所犯错误的风险)。 -
@Andrew Thompson “毫秒数”是什么意思
-
“不”是指“数字”。
标签: java swing timer stopwatch