好了,下面的代碼顯示了一個JTextArea和一個JButton的JFrame。當按鈕被點擊時,Timer重複發送事件(在它們之間有第二個延遲)到與按鈕相關的actionListener,該按鈕用當前時間附加一行。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.Timer;
public class TimerTest extends JFrame implements ActionListener{
private static final long serialVersionUID = 7416567620110237028L;
JTextArea area;
Timer timer;
int count; // Counts the number of sendings done by the timer
boolean running; // Indicates if the timer is started (true) or stopped (false)
public TimerTest() {
super("Test");
setBounds(30,30,500,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null);
area = new JTextArea();
area.setBounds(0, 0, 500, 400);
add(area);
JButton button = new JButton("Click Me!");
button.addActionListener(this);
button.setBounds(200, 400, 100, 40);
add(button);
// Initialization of the timer. 1 second delay and this class as ActionListener
timer = new Timer(1000, this);
timer.setRepeats(true); // Send events until someone stops it
count = 0; // in the beginning, 0 events sended by timer
running = false;
System.out.println(timer.isRepeats());
setVisible(true); // Shows the frame
}
public void actionPerformed(ActionEvent e) {
if (! running) {
timer.start();
running = true;
}
// Writing the current time and increasing the cont times
area.append(Calendar.getInstance().getTime().toString()+"\n");
count++;
if (count == 10) {
timer.stop();
count = 0;
running = false;
}
}
public static void main(String[] args) {
// Executing the frame with its Timer
new TimerTest();
}
}
那麼,這段代碼是一個如何使用javax.swig.Timer對象的例子。關於這個問題的具體情況。 if語句停止定時器必須改變,顯然,actionPerformed的動作。下面的片段是解決方案的骨架的actionPerformed:
public void actionPerformed(ActionEvent e) {
if (e.getComponent() == myDealerComponent()) {
// I do this if statement because the actionPerformed can treat more components
if (! running) {
timer.start();
runnig = true;
}
// Hit a card if it must be hitted
switch (getJBTable(JB.total, JB.aces > 0)) {
case 0:
JB.hit();
break;
case 1:
break done;
case 2:
JB.hit();
JB.bet *= 2;
break done;
}
if (JB.total >= 21) { // In this case we don't need count the number of times, only check the JB.total 21 reached
timer.stop()
running = false;
}
}
}
恕我直言,這樣可以解決問題,現在@ user920769必須考慮放在哪裏的ActionListener和啓動/停止條件......
@kleopatra:謝謝爲表明我這個定時器類的存在,我不知道任何關於它和它的神奇,讓可能有很多的任務東西放到一個Swing應用程序:)
非常感謝你的例子,但是我得到這些行的錯誤:timer = new Timer(1000,this); timer.setRepeats(真);說它無法分別找到合適的構造函數或方法。他們是否被棄用? – Fractaly
你導入Timer類嗎?這些方法即使在上一個版本中也不會被棄用,因此這似乎是您的錯誤。 [這裏是Java7 ApiDoc](http://download.oracle.com/javase/7/docs/api/javax/swing/Timer.html) – Charliemops