我最近遇到了类似的问题,我想要的东西用一个区间来执行(如果那是你的意思),直到用户触发的事件。我发现3种方式来做到这一点:
UPDATE
您应该使用的停止/取消方法自定义可运行和定时器或其他线程仍然会运行,当您退出应用程序。时间线似乎是自己做的。
使用定时器:
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Printed every second.");
}
};
timer.scheduleAtFixedRate(task, 0, 1000);
//timer.cancel();
有了时间表:
Timeline tl = new Timeline(new KeyFrame(Duration.millis(1000), e -> {
System.out.println("Timeline");
}));
tl.setCycleCount(Timeline.INDEFINITE);
tl.play();
//tl.stop();
或者使自己运行的类:
public class Runner implements Runnable {
private final Thread thread = new Thread(this);
private boolean run;
@Override
public void run() {
while(run) {
try {
System.out.println("Printed from loop");
Thread.sleep(1000);
} catch (InterruptedException e) {
run = false;
}
}
}
public void start() {
run = true;
thread.start();
}
public void stop() {
if(run) {
thread.interrupt();
System.out.print("Thread has stopped.");
}
}
}
然后当一个人点击fx。一个按钮的事件将停止使用James_D张贴的例子:
Button btn = new Button("Button");
btn.setOnAction(e -> {
timer.cancel();
tl.stop();
runner.stop();
});
您可能会发现有用的信息在一个快速复习[事件驱动的编程(http://en.wikipedia.org/wiki/Event- driven_programming)。注意:在JavaFX中,用于处理事件的主循环位于底层系统中,您的应用程序永远不需要编写事件循环 - 您只需提供系统将在适当时调用的事件处理程序。 – jewelsea 2015-03-31 21:29:21