3

I'm trying to listen to the list view's scrollbar change. My first attempt is to do like this

listView.setOnScroll(new EventHandler<ScrollEvent>()
{ // Code ommited }

However it doesn't seem to be work. I try to use the debugger and found that the handle method in EventHandler hash't been called.

I have searched for other solution and found this one (https://gist.github.com/jewelsea/1684622) which is work, however it doesn't work if I move the for each loop to the position before primaryStage.show(). So this one is not the ideal solution for my use case since I've split my UI code into many subcomponent and I need to set the listener before calling primaryStage.show() (I don't won't to expose the listview instance to the main Application class).

I think that the problem is because the lookUpAll method work only if the node has already shown on the stage. I've think of some work around such as to do the foreach loop in a method which will be executed after the node is fully attached to the scene graph and is showed on to the screen, but still I don't know how to achieve this.

Thank you.

Nick Rippe
  • 6,465
  • 14
  • 30
Nuntipat Narkthong
  • 1,387
  • 2
  • 16
  • 24
  • Not an asnwer but related. Does [this](http://stackoverflow.com/a/16921731/682495) approach help you? Alternatively in Main Application class, get the controller of the listview fxml and call something controller.initCompnents() after stage.show(). – Uluk Biy Jun 05 '13 at 11:14

1 Answers1

3

Assuming you're passing the Stage to the method creating your ListView, you could use the onShown event to execute the code that attaches a listener to your scrollbars. Basically use a listener to set your other listeners. Example:

    ObservableList<String> names = FXCollections.observableArrayList("1","2","3","4","5","6","7");
    final ListView<String> listView = new ListView<String>(names);

    stage.setOnShown(new EventHandler<WindowEvent>(){
        boolean hasRun = false;
        @Override
        public void handle(WindowEvent arg0) {
            if(!hasRun){
                for (Node node: listView.lookupAll(".scroll-bar")) {
                    if (node instanceof ScrollBar) {
                        final ScrollBar bar = (ScrollBar) node;
                        bar.valueProperty().addListener(new ChangeListener<Number>() {
                            @Override public void changed(ObservableValue<? extends Number> value, Number oldValue, Number newValue) {
                                System.out.println(bar.getOrientation() + " " + newValue);
                            }
                        });
                    }
                }
                hasRun = true;
            }
        }});
Nick Rippe
  • 6,465
  • 14
  • 30
  • Yet another answer [here](http://stackoverflow.com/questions/26537548/javafx-listview-with-touch-events-for-scrolling-up-and-down/39304755#39304755). – Amin Sep 03 '16 at 08:15