【发布时间】:2015-04-10 17:43:42
【问题描述】:
所以我有几个不同大小的Rectangle 对象,名为r1 和r2,最初出现在屏幕的死角。它们有不同的颜色(比如说一个是红色的,另一个是蓝色的),较小的放在较大的上面,所以即使它们堆叠在中心,两者仍然可以区分。我想让他们四处走动,回到原来的位置,因此使用TranslateTransition如下:
tt1 = new TranslateTransition(Duration.millis(20000), button1);
tt1.setByX(100); // moves 100 pixels to the right
tt1.setByY(-100); // moves 100 pixels down
tt1.setCycleCount(20); // oscillates 20 times
tt1.setAutoReverse(true);
tt2 = new TranslateTransition(Duration.millis(20000), button2);
tt2.setByX(-100); // moves 100 pixels to the left
tt2.setByY(100); // moves 100 pixels up
tt2.setCycleCount(20); // oscillates 20 times
tt2.setAutoReverse(true);
然而,在他们的移动过程中,如果r1 和r2 中的任何一个被MouseEvent 按下,我希望他们消失几秒钟(比如5 秒钟)然后重新活着。利用背景颜色完全黑色的事实,我使用FillTransition 来实现该效果:
FillTransition ft1 = new FillTransition(Duration.millis(5000), r1, Color.BLACK, Color.BLACK);
FillTransition ft2 = new FillTransition(Duration.millis(5000), r2, Color.BLACK, Color.BLACK);
通过将Rectangles 从Color.BLACK 转换为Color.BLACK 5 秒,它会产生按钮消失5 秒的效果。另外,我在r1 和r2 上有以下setOnMouseClicked,因此当用户输入时它们会消失:
r1.setOnMouseClicked((MouseEvent t) -> {
ft1.play();
});
r2.setOnMouseClicked((MouseEvent t) -> {
ft2.play();
});
在两个物体消失 5 秒后,它们必须重新出现在中心,就像它们在开始时所做的那样,并使用 tt1 和 tt2 重复相同的摆动运动,这是我在打开 setOnFinished 时实现的ft1 和 ft2:
ft1.setOnFinished((ActionEvent event) -> {
r1.setFill(color1); // restore the original color
tt1.play();
});
ft2.setOnFinished((ActionEvent event) -> {
r2.setFill(color2); // restore the original color
tt2.play();
});
然而,问题是,当r1和r2重新出现时,它们不是位于中心,而是位于它们上次消失的位置——换句话说,它们重生的位置就是它们所在的位置。在检测到用户的MouseEvent 时,在上一次TranslateTransition 期间。我试图通过使用r1.setX(centerX) 和r1.setY(centerY) 来修改它,其中centerX 和centerY 是一开始使用的原始中心坐标,但它无法解决问题。事实上,当我使用r1.getX() 时,返回值等于原始centerX 值,即使r1 没有放在中心很明显。这让我怀疑TranslateTransition 在不改变实际getX() 值的情况下履行其职责。我也想过在TranslateTransition和FillTransition上使用ParallelTransition,所以tt1可以在ft1生效时完成,但从那时起ft1将在tt1已经运行时开始运行有时,它不会提供可行的解决方案。
所以我的问题是,如果一个对象的TranslateTransition在中间被打断,我如何恢复对象的“原始”坐标,而不是TranslateTransition被打断时对象上次离开的位置?
附言我想避免在每次检测到MouseEvent 时创建新的Rectangle 对象,因为这意味着所有链接到r1 和r2 的TranslateTransition 和FillTransition 也必须重新创建。
【问题讨论】:
标签: javafx transition