2015-07-12 56 views
1

我有兩個並排的ListViews,並且我在其中之一上隱藏了滾動條。有沒有簡單的方法可以使它如果我用滾動條滾動,另一個會自動跟隨?我如何使兩個ListViews在JavaFX中滾動到一起

我想我可能能夠將屬性綁定在一起,但我似乎無法在ListViews上找到任何滾動條位置類型屬性。

回答

3

您可以從兩個ListViews和綁定他們的valueProperty中獲取ScrollBar

實施例:

import javafx.application.Application; 
import javafx.collections.FXCollections; 
import javafx.collections.ObservableList; 
import javafx.scene.Node; 
import javafx.scene.Scene; 
import javafx.scene.control.ListView; 
import javafx.scene.control.ScrollBar; 
import javafx.scene.layout.HBox; 
import javafx.stage.Stage; 

public class Main extends Application { 
    @Override 
    public void start(Stage primaryStage) throws Exception { 

     HBox root = new HBox(); 

     // Declare ListView's 
     ListView listView1 = new ListView<String>(); 
     ListView listView2 = new ListView<String>(); 

     // Fill Data inside ListView 
     ObservableList<String> list = FXCollections.observableArrayList(); 
     for (int i = 0; i < 100; i++) { 
      list.add("Value " + i); 
     } 
     listView1.setItems(list); 
     listView2.setItems(list); 

     root.getChildren().addAll(listView1, listView2); 

     Scene scene = new Scene(root, 400, 400); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 

     // Bind the ListView scroll property 
     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()); 
      } 
     } 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 
相關問題