好了,下面的代码显示了一个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