我使用javax.swing包中的Timer对象创建了一个秒表。当我实例化它时,我将延迟设置为100毫秒,但计时器似乎以毫秒而不是秒运行。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class StopWatch extends JApplet
{
private JPanel timePanel;
private JPanel buttonPanel;
private JTextField time;
private int seconds = 0;
boolean running = false;
private Timer timer;
public void init()
{
buildTimePanel();
buildButtonPanel();
setLayout(new GridLayout(3, 1));
add(timePanel);
add(buttonPanel);
}
private void buildTimePanel()
{
timePanel = new JPanel();
JLabel message1 =
new JLabel("Seconds: ");
time = new JTextField(10);
time.setEditable(false);
timePanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
timePanel.add(message1);
timePanel.add(time);
}
private void buildButtonPanel()
{
buttonPanel = new JPanel();
JButton startButton = new JButton("Start");
JButton stopButton = new JButton("Stop");
startButton.addActionListener(new StartButtonListner());
stopButton.addActionListener(new StopButtonListner());
buttonPanel.add(startButton);
buttonPanel.add(stopButton);
}
private class StartButtonListner implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if(running == false){
running = true;
if(timer == null){
timer = new Timer(100, new TimeActionListner());
timer.start();
} else {
timer.start();
}
}
}
}
private class StopButtonListner implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if(running == true){
running = false;
timer.stop();
}
}
}
private class TimeActionListner implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
time.setText(Integer.toString(seconds));
seconds++;
}
}
}
答案 0 :(得分:3)
非常确定您需要将延迟设置为1000而不是100