我有一个针对我的Java I类的秒表程序,它来自Java基础第3版第6.22页,我无法运行它。我不确定我哪里出错了。任何有助于破译该问题的帮助将不胜感激!该程序应该有一个3按钮设置和秒表计数秒,没什么花哨的。我有按钮本身的问题,我不能让他们启动,停止和重置计时器。我正在使用Jgrasp作为我的编译器,所有编译都很好。没有错误报告。我不确定我的if / else语句是否正确,或者我是否留下了一些不让计时器开始计数的东西。下面是作业的内容:设计并实现一个作为秒表的应用程序。包括显示以增量为单位的时间(以秒为单位)的显示。包括允许用户启动和停止时间的按钮,并将显示重置为零。
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Assignment_6_22_Panel extends JPanel
{
private JButton start, stop, reset;
private JLabel label;
private JPanel buttonPanel;
private Timer timer;
private int time = 0;
private final int DELAY = 1000;
public Assignment_6_22_Panel()
{
label = new JLabel("Time: " + time);
setBackground(Color.white);
start = new JButton("Start");
stop = new JButton("Stop");
reset = new JButton("Reset");
ButtonListener listener = new ButtonListener();
TimeListener watchListener = new TimeListener();
timer = new Timer(DELAY, watchListener);
start.addActionListener(listener);
stop.addActionListener(listener);
reset.addActionListener(listener);
buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(200, 150));
buttonPanel.setBackground(Color.white);
buttonPanel.add(start);
buttonPanel.add(stop);
buttonPanel.add(reset);
add(buttonPanel);
add(label);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == start)
timer.start();
else
if (event.getSource() == stop)
timer.stop();
else
time = 0;
}
}
private class TimeListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
label = new JLabel("Your Time: " + time);
}
}
}
这是相邻的代码
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Assignment_6_22
{
//-----------------------------------------------------------------
// Displays the main frame of the program.
//-----------------------------------------------------------------
public static void main(String[] args)
{
JFrame frame = new JFrame("Stop Watch");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Assignment_6_22_Panel());
frame.pack();
frame.setVisible(true);
}
}
答案 0 :(得分:1)
您的Timer
代码和ButtonListener
代码运行正常,问题出在TimerListener
...
private class TimeListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
label = new JLabel("Your Time: " + time);
}
}
每次JLabel
触发时,您都会创建Timer
的新实例,这与屏幕上显示的内容无关,而是需要设置现有的标签。
此外,您无法在何处实际更新time
的值以显示时间的推移......
private class TimeListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
time++;
label.setText("Your Time: " + time);
}
}
当您reset
Timer
时,您还应该确保更新label
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == start) {
timer.start();
} else if (event.getSource() == stop) {
timer.stop();
} else {
time = 0;
label.setText("Your Time: " + time);
}
}
}