我正在摆弄 JavaFX API,由于某种原因,这个应用程序似乎在(看似)随机的时间后冻结了。
它是一个制作红绿渐变图案的应用程序,并且有一个很酷的动画与之配合。当应用程序运行时,按 Enter 键,动画就会开始。一段时间后(就像我之前所说的那样,似乎是随机的)它将停止更新,但计时器继续运行,循环也是如此,并且仍然使用正确的参数调用 setColor 方法,这让我认为要么PixelWriter 被冻结或窗口未更新。
我所做的代码如下:
package me.dean;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.PixelWriter;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.Timer;
import java.util.TimerTask;
public class DeansApp extends Application {
CoolAnimation canvas;
@Override
public void start(Stage primaryStage) throws Exception {
canvas = new CoolAnimation();
canvas.setWidth(255);
canvas.setHeight(255);
primaryStage.setScene(new Scene(new Pane(canvas)));
canvas.getScene().setOnKeyPressed(event -> {
if(event.getCode().equals(KeyCode.ENTER)) {
canvas.play ^= true;
}
});
primaryStage.setOnCloseRequest(event -> System.exit(0));
primaryStage.show();
}
private class CoolAnimation extends Canvas {
boolean play;
int column = 0;
boolean coloring = true;
public CoolAnimation() {
super();
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if(CoolAnimation.this.play) {
GraphicsContext g = getGraphicsContext2D();
if(g != null) {
PixelWriter writer = g.getPixelWriter();
if(writer != null) {
for (int x = Math.min(255, column),
y = Math.max(0, column - (int) CoolAnimation.this.getWidth());
x >= 0 && y<=255;
x--, y++) {
writer.setColor(x, y, coloring ? Color.rgb(x, y, 0) : Color.WHITE);
}
}
}
column++;
if(column >= CoolAnimation.this.getWidth() * 2) {
coloring ^= true;
column = 0;
}
}
}
}, 0L, 10L);
}
}
}
非常感谢任何能够提供帮助的人!
你想使用一个动画定时器 http://blog.netopyr.com/2012/06/14/using-the-javafx-animationtimer/ or Timeline https://docs.oracle.com/javase/8/javafx/api/javafx/animation/Timeline.html, not a java.util.Timer https://docs.oracle.com/javase/8/docs/api/java/util/Timer.html。 AnimationTimer 或 Timeline 在 JavaFX 应用程序线程上执行其代码,而 java.util.Timer 则不会。使用 java.util.Timer 您将遇到与线程竞争条件相关的随机问题。您可以使用平台.runLater https://docs.oracle.com/javase/8/javafx/api/javafx/application/Platform.html#runLater-java.lang.Runnable-与 java.util.Timer 结合使用,但一般来说,使用 AnimationTimer 是处理此问题的首选方法。
查看相关问题:
- javafx动画循环 https://stackoverflow.com/questions/13029920/javafx-animation-looping
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)