Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
836 views
in Technique[技术] by (71.8m points)

javafx 2 - How to scroll to make a Node within the content of a ScrollPane visible?

Given that a huge AnchorPane with some subnodes is the content of a ScrollPane, how can i scroll to make one of the subnodes, that are outside of the current viewport, visible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

EDIT: code in the next example is more precise than mine: https://stackoverflow.com/a/23518314/1054140

You need to find a coordinates of this inner node inside content and adjust ScrollPane's vValue and hValue accordingly.

See ensureVisible() method in next small app:

public class ScrollPaneEnsureVisible extends Application {

    private static final Random random = new Random();

    private static void ensureVisible(ScrollPane pane, Node node) {
        double width = pane.getContent().getBoundsInLocal().getWidth();
        double height = pane.getContent().getBoundsInLocal().getHeight();

        double x = node.getBoundsInParent().getMaxX();
        double y = node.getBoundsInParent().getMaxY();

        // scrolling values range from 0 to 1
        pane.setVvalue(y/height);
        pane.setHvalue(x/width);

        // just for usability
        node.requestFocus();
    }

    @Override
    public void start(Stage primaryStage) {

        final ScrollPane root = new ScrollPane();
        final Pane content = new Pane();
        root.setContent(content);

        // put 10 buttons at random places with same handler
        final EventHandler<ActionEvent> handler = new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                int index = random.nextInt(10);
                System.out.println("Moving to button " + index);
                ensureVisible(root, content.getChildren().get(index));
            }
        };

        for (int i = 0; i < 10; i++) {
            Button btn = new Button("next " + i);
            btn.setOnAction(handler);
            content.getChildren().add(btn);
            btn.relocate(2000 * random.nextDouble(), 2000 * random.nextDouble());
        }

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

        // run once to don't search for a first button manually
        handler.handle(null);
    }

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...