Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Programmatically scroll to bottom in ScrollPane

cshApr 12 2012 — edited Apr 13 2012
I am trying to auto scroll to bottom in a ScrollPane. I add items to a VBox, like in a chat window. Therefore I need to scroll to bottom.

However, I only can scroll to the last item, I previously added.
I think the reason is, that the VBox doesn't has its new height, after I added the item.

I tried it with autosize() and layout() but it doesn't work.

Any ideas?

Run this code, to see what I mean. Click "add", height is 0.0. Add enough items, so that scrollbars appear. It doesnt scroll to bottom. Only when I click the other button.
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;

public class TestApp3 extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    public void start(final Stage stage) throws Exception {

        final VBox root = new VBox();

        final ScrollPane scrollPane = new ScrollPane();

        final VBox vBox = new VBox();
        vBox.setAlignment(Pos.BOTTOM_CENTER);

        scrollPane.setContent(vBox);

        scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);

        Button button = new Button("add");
        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                vBox.getChildren().add(new Label("hallo"));
                vBox.autosize();
                vBox.layout();
                System.out.println(vBox.getHeight());
                scrollPane.setVvalue(Double.MAX_VALUE);
            }
        });

        Button button2 = new Button("scroll");
        button2.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                scrollPane.setVvalue(Double.MAX_VALUE);
            }
        });

        root.getChildren().addAll(scrollPane, button, button2);
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 11 2012
Added on Apr 12 2012
3 comments
6,672 views