如何在JavaFX中使两个ListView一起滚动

如何在JavaFX中使两个ListView一起滚动

本文介绍了如何在JavaFX中使两个ListView一起滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个ListViews并排放置,并且滚动条隐藏在其中之一上.有没有简单的方法可以使它滚动,如果我用滚动条滚动一个,另一个会自动跟随?

I have two ListViews side by side, and I have the scrollbar hidden on one of them. Is there any easy way to make it so that if I scroll the one with the scrollbar, the other one will automatically follow?

我以为我可以将这些属性绑定在一起,但是我似乎在ListViews上找不到任何滚动条位置类型的属性.

I thought I might be able to bind the properties together, but I can't seem to find any scrollbar-position type property on the ListViews.

推荐答案

您可以从ListView和 bind valueProperty中提取ScrollBar.

You can fetch the ScrollBar out of the both the ListViews and bind their valueProperty.

示例:

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);
    }
}

这篇关于如何在JavaFX中使两个ListView一起滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 21:23