首页 > 解决方案 > JavaFX 缩放 ScrollPane 内容居中

问题描述

我的目标是让带有一些内容的 ScrollPane(带有一些控件的 vbox)可缩放,这样当缩放的内容达到可见边界时,ScrollPane 会显示水平和垂直滚动条。但是有一个问题 - 为了做到这一点,我必须将我的内容包装在一个组中,这样做,缩放不是从中心,而是从 ScrollPane 的左上角 (0,0),而没有换行Group 的内容从中心进行缩放,但不显示滚动条。这是测试应用程序:

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Slider;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;


public class ZoomScrollExample extends Application {

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

  @Override
  public void start(Stage stage) throws Exception {
    Pane root = new Pane();
    Scene scene = new Scene(root, 450, 450, Color.WHITE);
    stage.setScene(scene);

    VBox layout = new VBox();
    layout.setMinHeight(400);
    layout.setMinWidth(400);
    Rectangle r = new Rectangle(200, 200);
    r.setStroke(Color.RED);
    r.setFill(Color.WHITE);
    layout.getChildren().add(r);
    layout.setAlignment(Pos.CENTER);
    ScrollPane sp = new ScrollPane();

    //comment this to get no scroll bars but scaling is centered
    Group g = new Group(layout);
    sp.setContent(g);

    //uncomment this
    //sp.setContent(layout);

    sp.setPrefSize(450, 450);
    Slider s = new Slider();
    root.getChildren().add(sp);
    root.getChildren().add(s);
    s.setMin(100);
    s.setMax(200);

    // actual scaling
    layout.scaleXProperty()
        .bind(s.valueProperty().divide(100));
    layout.scaleYProperty()
        .bind(s.valueProperty().divide(100));

    stage.show();
  }
}

有没有(简单的)方法可以同时拥有滚动条和居中缩放?

标签: javafxzoomingscalescalingscrollpane

解决方案


推荐阅读