简体   繁体   中英

How to center a ImageView node within Region in JavaFx?

I'm having trouble with centering an ImageView node within the following Browser object. I have provided a snippet of the code below. My thought was to use setStyle("....."), but that didn't appear to have any influence on the placement of the image (It is still displayed top left corner). Any suggestions are greatly appreciated. Thanks!

class Browser extends Region {

    final WebView browser = new WebView();
    final WebEngine webEngine = browser.getEngine();
    File file;
    ImageView image;

    public Browser(String fileName, Image loaderImage) throws MalformedURLException {
        file = new File(fileName);

        //apply the styles
        getStyleClass().add("browser");

        //add the web view to the scene
        getChildren().add(browser);

        // load default image
        image = new ImageView();
        image.setImage(loaderImage);
        setStyle("-fx-background-position: CENTER;");
        getChildren().add(image);

    }

According to the Javadocs :

By default a Region inherits the layout behavior of its superclass, Parent , which means that it will resize any resizable child nodes to their preferred size, but will not reposition them. If an application needs more specific layout behavior, then it should use one of the Region subclasses: StackPane , HBox , VBox , TilePane , FlowPane , BorderPane , GridPane , or AnchorPane .

So will probably have better luck using one of these.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM