Java触发动作事件
我以前看过这样的帖子,但是问题或答案都不清楚,所以如果你以前听过,请耐心听我说。我有一个计时器,我希望在计时器启动时发生ActionEvent。我不想使用javax.swing.Timer方法。如何做到这一点?没有必要解释,但这会有所帮助。我正在寻找类似ActionEvent.do()方法的东西 我的代码:Java触发动作事件,java,timer,actionevent,Java,Timer,Actionevent,我以前看过这样的帖子,但是问题或答案都不清楚,所以如果你以前听过,请耐心听我说。我有一个计时器,我希望在计时器启动时发生ActionEvent。我不想使用javax.swing.Timer方法。如何做到这一点?没有必要解释,但这会有所帮助。我正在寻找类似ActionEvent.do()方法的东西 我的代码: /** * * @param millisec time in milliseconds * @param ae action to occur when time is compl
/**
*
* @param millisec time in milliseconds
* @param ae action to occur when time is complete
*/
public BasicTimer(int millisec, ActionEvent ae){
this.millisec = millisec;
this.ae = ae;
}
public void start(){
millisec += System.currentTimeMillis();
do{
current = System.currentTimeMillis();
}while(current < millisec);
}
/**
*
*@param毫秒时间(毫秒)
*@param ae在时间结束时执行的操作
*/
公共基本计数器(整数毫秒,动作事件ae){
此值为0.毫秒=毫秒;
这个.ae=ae;
}
公开作废开始(){
毫秒+=System.currentTimeMillis();
做{
current=System.currentTimeMillis();
}而(电流<毫秒);
}
谢谢!Dando18这里有一些简单的计时器实现。你为什么不检查其他计时器的工作方式
public class AnotherTimerImpl {
long milisecondsInterval;
private ActionListener listener;
private boolean shouldRun = true;
private final Object sync = new Object();
public AnotherTimerImpl(long interval, ActionListener listener) {
milisecondsInterval = interval;
this.listener = listener;
}
public void start() {
setShouldRun(true);
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() {
@Override
public void run() {
while (isShouldRun()) {
listener.actionPerformed(null);
try {
Thread.sleep(milisecondsInterval);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}
});
}
public void stop() {
setShouldRun(false);
}
public boolean isShouldRun() {
synchronized (sync) {
return shouldRun;
}
}
public void setShouldRun(boolean shouldRun) {
synchronized (sync) {
this.shouldRun = shouldRun;
}
}
}
“我以前见过这样的帖子,但他们问得不好”。。。真是巧合……只要用
定时器就行了。您的实现似乎是单线程的。@SotiriosDelimanolis我想知道一种不使用计时器的方法。我正在寻找类似ActionEvent.do()方法的方法
-这就是Swing计时器的工作方式。每当计时器触发时,它都会创建一个ActionEvent,然后使用此ActionEvent调用ActionListener的actionPeformed()方法。为什么不使用Swing计时器呢?