1 回答

TA貢獻1829條經驗 獲得超7個贊
正如我在評論中提到的,JavaFX 應用程序線程無法在仍在執行您的方法時安排下一幀渲染(即“脈沖”)。您使用Thread.sleepwhich阻塞FX 線程意味著它不能做任何事情,更不用說安排下一個脈沖了。被阻止的 FX 線程等于凍結的 UI,您的用戶將無法點擊更多卡片來嘗試獲得匹配。
您應該使用動畫 API在 FX 線程上“隨時間”執行操作。動畫是“異步”執行的(在 FX 線程上),這意味著可以在動畫運行時處理其他動作。啟動動畫的調用也會立即返回。這是一個示例,該示例將在一秒鐘內顯示矩形下方的形狀;但是,沒有邏輯來確定是否顯示了兩個匹配的形狀,一次只顯示了兩個形狀,等等。
import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
HBox box = new HBox(10, createCard(true), createCard(true), createCard(false));
box.setPadding(new Insets(100));
primaryStage.setScene(new Scene(box));
primaryStage.show();
}
private StackPane createCard(boolean circle) {
Shape shape;
if (circle) {
shape = new Circle(50, Color.FORESTGREEN);
} else {
// create triangle
shape = new Polygon(0, 0, 50, 100, -50, 100);
shape.setFill(Color.FIREBRICK);
}
Rectangle cover = new Rectangle(0, 0, 100, 150);
cover.mouseTransparentProperty()
.bind(cover.fillProperty().isEqualTo(Color.TRANSPARENT));
cover.setOnMouseClicked(event -> {
event.consume();
cover.setFill(Color.TRANSPARENT);
PauseTransition pt = new PauseTransition(Duration.seconds(1));
pt.setOnFinished(e -> cover.setFill(Color.BLACK));
pt.playFromStart();
});
return new StackPane(shape, cover);
}
}
添加回答
舉報