-2

我使用 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++;
    }  
   }


}
4

1 回答 1

3

很确定您需要将延迟设置为 1000 而不是 100

于 2012-12-02T04:38:28.863 回答