在场景渲染之前调用Initialize中的查找

时间:2016-01-12 02:12:40

标签: java javafx

我想使用下面的代码来同步滚动条。

Node n1 = listView1.lookup(".scroll-bar");
if (n1 instanceof ScrollBar) {
    final ScrollBar bar1 = (ScrollBar) n1;
    Node n2 = listView2.lookup(".scroll-bar");
    if (n2 instanceof ScrollBar) {
        final ScrollBar bar2 = (ScrollBar) n2;
        bar1.valueProperty().bindBidirectional(bar2.valueProperty());
    }
}

我想在场景的Initialize()方法中运行这些代码行。 不幸的是,这些代码行要求渲染场景。 有没有办法在没有任何用户输入的情况下渲染场景后运行这些线?

1 个答案:

答案 0 :(得分:1)

这个丑陋的黑客似乎有效:

public class Controller {

    @FXML
    private ListView<String> listView1 ;
    @FXML
    private ListView<String> listView2 ;

    @FXML
    private Parent root ;

    public void initialize() {
        root.sceneProperty().addListener((obs, oldScene, newScene)  -> {
           if (newScene != null) {
               root.applyCss();
               Node n1 = listView1.lookup(".scroll-bar");
               System.out.println(n1);
               if (n1 instanceof ScrollBar) {
                   final ScrollBar bar1 = (ScrollBar) n1;
                   Node n2 = listView2.lookup(".scroll-bar");
                   System.out.println(n2);
                   if (n2 instanceof ScrollBar) {
                       final ScrollBar bar2 = (ScrollBar) n2;
                       bar1.valueProperty().bindBidirectional(bar2.valueProperty());
                   }
               }

           }
        });

    }
}