Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

css - Set background image the same size as the window/screen in Java app

I would like to set a background image the same size as my window/screen.

I would prefer to do this in my CSS file, but I have NOT FOUND a way to accomplish this.

Must I do this in a javafx class file?

Thanks for every help ;)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You will have to determine the screen size in java code as demonstrated in JavaFX window sizing, there is no way to determine it in CSS.

For an Image, in your java code you can use something as

ImageView imageView = new ImageView(image);
imageView.setFitWidth(Screen.getPrimary().getVisualBounds().getWidth());
imageView.setFitHeight(Screen.getPrimary().getVisualBounds().getHeight());

If you want to set the background image to a scene then:

import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.*;

public class ScreenSizeImage extends Application {
    @Override public void start(final Stage stage) {
        // uncomment if you want the stage full screen.
        //stage.setFullScreen(true);

        Screen screen = Screen.getPrimary();
        Rectangle2D bounds = screen.getVisualBounds();

        stage.setX(bounds.getMinX());
        stage.setY(bounds.getMinY());
        stage.setWidth(bounds.getWidth());
        stage.setHeight(bounds.getHeight());

        StackPane root = new StackPane();
        root.setStyle(
            "-fx-background-image: url(" +
                "'http://icons.iconarchive.com/icons/iconka/meow/256/cat-box-icon.png'" +
            "); " +
            "-fx-background-size: cover;"
        );
        stage.setScene(new Scene(root));
        stage.show();
    }

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

Of course, rather than the inline setStyle call you are best off using a separate CSS stylesheet like below:

.root{
    -fx-background-image: url("background_image.jpg");
    -fx-background-size: cover;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...