Dea*_*per 3 java java-8 javafx-8
我正在搞乱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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
非常感谢能够提供帮助的任何人!
您想使用AnimationTimer或Timeline,而不是java.util.Timer.AnimationTimer或Timeline在JavaFX应用程序线程上执行它的代码,而java.util.Timer则不执行.使用java.util.Timer,您将遇到与线程争用条件相关的随机问题.您可以将Platform.runLater与java.util.Timer结合使用,但是,通常,使用AnimationTimer是处理此问题的首选方法.
查看相关问题:
| 归档时间: |
|
| 查看次数: |
1109 次 |
| 最近记录: |