获取时间线后 int 的值



我有一个应用程序,其目标是掷骰子,我使用时间线,但我不知道如何在另一个类中获取骰子结束时的值。这是我的代码:在课堂上骰子

private List <Image> listeFaceDice;
private int randomNum;
private ImageView imageView;
public void dropDice(){
    Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.5), event -> {
        setRandomNum(rand.nextInt(6);
        imageView.setImage(listeFaceDice.get(randomNum-1));
    }));
    timeline.setCycleCount(6);
    timeline.play();
    timeline.setOnFinished(e -> {
        setRandomNum(randomNum);
    });
}

课堂游戏

public Button getBtnDropDice() {
    if(btnDropDice == null) {
        btnDropDice = new Button("Drop dice");
        btnDropDice.setOnAction(new EventHandler<ActionEvent>(){
            public void handle(ActionEvent arg0) {
                // TODO Auto-generated method stub
                Dice dice = new Dice();
                    dice.dropDice();
                    System.out.println(dice.getRandomNum());
            }
        });
    }
    return btnDropDice;
}

一旦掷骰子完成,您实际上已经访问了该值:您只是不对它执行任何操作(除了调用setRandomNum(...),当您传递已经设置的值时,它不会执行任何操作(。

如果将该处理程序替换为System.out.println(...)您将在控制台中看到该值:

timeline.setOnFinished(e -> {
    System.out.println(randomNum);
});

如果你想在调用类中对它做一些事情,首先当然要注意dropDice()方法将立即退出(即在动画完成之前(。您可以做的一件事是向dropDice()方法传递一个处理结果的函数:

public void dropDice(IntConsumer valueProcessor){
    Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.5), event -> {
        setRandomNum(rand.nextInt(6);
        imageView.setImage(listeFaceDice.get(randomNum-1));
    }));
    timeline.setCycleCount(6);
    timeline.play();
    timeline.setOnFinished(e -> {
        valueProcessor.accept(randomNum);
    });
}

现在您可以执行以下操作:

Dice dice = new Dice();
dice.dropDice(diceValue -> {
    // do whatever you need to do with diceValue here. 
    // Just as a demo:
    System.out.println("Value rolled was "+diceValue);
});

掷骰子完成后,您传递给dropDice()的函数(更准确地说,IntConsumer中的accept(...)方法(将在FX应用程序线程上调用(因此可以安全地更新UI(。

最新更新