如何使用FXML在Java FX中初始化场景后立即启动动画

时间:2013-04-14 13:14:53

标签: java animation javafx-2 fxml

我正在使用一些精美的动画在Java FX中编写应用程序。 我想在文本节点 text_1 中从左侧滑动到可用舞台宽度的20%。

public class SplashController implements Initializable {
public Democracy parent = null;

@FXML
public Text text1;
public Text text2;
public Text text3;

   public void animateIntro() {
       TranslateTransition t1_transl_1 = new TranslateTransition(new Duration(1500d),text1);
       t1_transl_1.setFromX(-100d);
       t1_transl_1.setByX((double)((20/100) * parent.getStage().getWidth()+100));
       // Here Democracy class has a static method to return its instance, which is assigned on class creation. I want to slide in the text_1 node to 20% of the total window width.
       //Here I am always getting **NaN**
       System.out.println((20d/100d) * parent.getStage().getWidth()); // Getting NaN
       System.out.println(parent.getStage().getScene().getWidth()); // Throwing Exception
       FadeTransition t1_fade_in = new FadeTransition(new Duration(1000d), text1);
       t1_fade_in.setFromValue(0);
       t1_fade_in.setToValue(100d);

       ParallelTransition t1_ptrans_1 = new ParallelTransition(text1,t1_fade_in,t1_transl_1);
       //With parallel transition I want to fade in and slide in the node at the same time.
       t1_ptrans_1.play();

    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        parent = Democracy.getInstance();
        animateIntro();
    }    


}

当我使用Netbeans内置的Debugger时,我发现parent的stage变量中的大多数值都是null。我认为这是因为该阶段没有完全初始化,我得到空值。是否有任何工作来检测完整的初始化?请帮帮我......

修改:即使我添加了

while(!parent.getStage().isShowing()) {
try{
    sleep(100);
} catch(Exception e){}

循环以确保只在舞台可见后调用animateIntro(),我仍然无法获得宽度。请帮我解决这个问题..

1 个答案:

答案 0 :(得分:0)

您可以尝试将侦听器绑定到阶段widthProperty,并等待实际包含数字的更改。