我试图实现的是在动画结束后返回一个整数值。
我有这个代码:
public void spin(){
symbol = queue.poll();
this.setImage(symbol);
queue.add(symbol);
}
private int randomize(int min, int max){
long seed = System.nanoTime();
Random rand = new Random(seed);
return rand.nextInt((max - min) + 1) + min;
}
public int getKey() {
return this.queue.peek().getKey();
}
public int play() {
KeyFrame kf = new KeyFrame(Duration.millis(20), e -> spin());
Timeline tl = new Timeline(kf);
tl.setCycleCount(randomize(10,50));
tl.play();
tl.setOnFinished(e -> { // Incompatible types: unexpected return value
return this.queue.peek().getKey(); // Incompatible types: bad return type in lambda expression
});
return e;
}
我正在开发一款吃角子老虎机游戏,以提高我的java编程技能。我有一个Symbol类,它有两个属性(符号的ImageView和整数键)。然后我有一个Reel类,它包含一个符号对象队列。(上面的代码来自我的Reel类)。单击将调用play方法,该方法会触发一个动画,该动画会多次调用spin()方法。spin方法基本上是从队列中轮询符号,然后再次将其添加到队列中。(这会不断旋转队列最前面的符号)。然后简单地使用getKey()方法,该方法返回一个整数值(当前是队列头的符号对象的键属性)。我希望能够在动画完成后立即从play()方法返回后者。但是我在setOnFinished中有语法错误:"不兼容的类型:意外的返回值"。有人能帮我理解我的代码出了什么问题,以及我应该如何处理吗?提前谢谢。
这根本不是动画API的设计方式:它遵循事件驱动的模型。Timeline.play()
方法会立即退出(即在动画完成之前),因此执行会在动画完成很久之前到达方法的末尾。显然,此时onFinished
处理程序没有可用的值。
相反,您应该将onFinished
处理程序视为在动画完成时提供要执行的代码。所以你应该做一些类似的事情:
public void play() {
KeyFrame kf = new KeyFrame(Duration.millis(20), e -> spin());
Timeline tl = new Timeline(kf);
tl.setCycleCount(randomize(10,50));
tl.play();
tl.setOnFinished(e -> {
int x = this.queue.peek().getKey();
// do whatever you need to do with x here....
});
}