2012-07-03 70 views
1

嗯,我很抱歉發佈兩個以上的問題在很短的時間,但我想有這時間倒計時3至0 ...這裏是我的代碼添加一個計時器的Java Swing

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

public class ClickingGame extends JPanel implements ActionListener { 

    private static final long serialVersionUID = 1L; 
    static JFrame frame; 
    static JButton startbutton, clickingbutton, timerstop; 
    static JLabel timelabel, scorelabel; 
    static int time = 3; 
    static JTextField entertime; 
    static Timer clock; 
    static Timer countdown; 
    static int score = 0; 

    public ClickingGame() { 
     setLayout(new GridLayout(3, 2, 5, 5)); 
     startbutton = new JButton("Start CountDown"); 
     timelabel = new JLabel("Time Left = NULL", SwingConstants.CENTER); 
     entertime = new JTextField(); 
     clickingbutton = new JButton("Click Here!"); 
     scorelabel = new JLabel("Score = NULL", SwingConstants.CENTER); 
     timerstop = new JButton("Stop Timer!"); 
     clock = new Timer(1000, this); 
     countdown = new Timer(1000, this); 

     add(entertime); 
     add(startbutton); 
     add(timelabel); 
     add(scorelabel); 
     add(clickingbutton); 
     add(timerstop); 
     clickingbutton.setEnabled(false); 
     timerstop.setEnabled(false); 
     startbutton.addActionListener(this); 
     clickingbutton.addActionListener(this); 
    } 

    public static void openGUI() { 
     frame = new JFrame("Clicking Game"); 
     ClickingGame contentpane = new ClickingGame(); 
     frame.setContentPane(contentpane); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public void actionPerformed(ActionEvent e) { 

     if (e.getSource() == startbutton) { 
      startbutton.setEnabled(false); 
      clickingbutton.setEnabled(true); 
      time--; 
      if (time > 0) { 
       countdown.start(); 
       timelabel.setText("Starting In: " + time); 
      } else { 
       countdown.stop(); 
       time = 3; 
      } 
     } 

     if (e.getSource() == clickingbutton) { 
      score++; 
      scorelabel.setText("Score = " + score); 
     } 
    } 
} 

,你可以看到我有我的計時器「倒計時」樹立正確的,它只是倒計時以前......我試圖讓它倒計時一路3 ...

+3

另見本['ClockExample'(http://stackoverflow.com/a/5529043/230513)。 – trashgod

回答

3

您需要在您的actionPerformed中爲您的countdown對象添加一個案例作爲源。

編輯:

你可以嘗試這樣的事:

if (e.getSource() == startbutton) { 
     startbutton.setEnabled(false); 
     clickingbutton.setEnabled(true); 
     if (time > 0) { 
      countdown.start(); 
      timelabel.setText("Starting In: " + time); 
     } 
    } 
    if (e.getSource() == countdown){ 
     timelabel.setText("Starting In: " + time); 

     if (time == 0) { 
      countdown.stop(); 
      time = 3; 
     } else { 
      time--; 
     } 

    } 
+0

我該怎麼做呢? –