How to center the content of a javafx 8 scrollpane

后端 未结 4 1888
渐次进展
渐次进展 2021-01-04 20:21

I have a ScrollPane, which contains a GridPane, which contains an ImageView, which contains an Image. What I want is for the Image to be centered in the GridPane.

W

4条回答
  •  隐瞒了意图╮
    2021-01-04 20:35

    Better solution via viewportBoundsProperty:

    import javafx.application.Application;
    import javafx.geometry.Bounds;
    import javafx.scene.Node;
    import javafx.scene.Scene;
    import javafx.scene.control.ScrollPane;
    import javafx.scene.image.Image;
    import javafx.scene.image.ImageView;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.GridPane;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Rectangle;
    import javafx.stage.Stage;
    
    public class ImageDB extends Application {
        final static int WIDTH = 400;
        final static int HEIGHT = 200;
    
        @Override
        public void start(Stage root) {
            // Image image = new Image("0.jpg");
            Image image = this.createImage();
            ImageView view = new ImageView();
            view.setImage(image);
            GridPane grid = new GridPane();
            grid.getChildren().add(view);
    
            ScrollPane scroll = new ScrollPane();
            scroll.setContent(grid);
    
            BorderPane border = new BorderPane();
            border.setCenter(scroll);
    
            this.center(scroll.getViewportBounds(), grid);
            scroll.viewportBoundsProperty().addListener((observable, oldValue, newValue) -> {
                this.center(newValue, grid);
            });
    
            root.setScene(new Scene(border));
            root.setMaximized(true);
            root.show();
        }
    
        private Image createImage() {
            return new Rectangle(ImageDB.WIDTH, ImageDB.HEIGHT, Color.CORNFLOWERBLUE).snapshot(null, null);
        }
    
        public static void main(String[] args) {
            Application.launch(args);
        }
    
        private void center(Bounds viewPortBounds, Node centeredNode) {
            double width = viewPortBounds.getWidth();
            double height = viewPortBounds.getHeight();
            if (width > ImageDB.WIDTH) {
                centeredNode.setTranslateX((width - ImageDB.WIDTH) / 2);
            } else {
                centeredNode.setTranslateX(0);
            }
            if (height > ImageDB.HEIGHT) {
                centeredNode.setTranslateY((height - ImageDB.HEIGHT) / 2);
            } else {
                centeredNode.setTranslateY(0);
            }
    
        }
    
    }
    

提交回复
热议问题