2012-12-02 45 views
-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++; 
    } 
    } 


} 
+5

嗯.... 1000毫秒等於1秒! –

+2

考慮刪除此問題。我認爲這對未來將有很大幫助。這不是一個真正的編程問題,但更多的是一個愚蠢的錯誤。 –

回答

3

敢肯定你需要將延遲設置爲1000不是100

+0

哎呀...感謝您的支持! – Zzz

相關問題