java - 使用 javafx 在运行时更改背景图像

标签 java javafx background runtime

我想将 Pane 的背景图像设置为用户通过 javafx 中的文件选择器选择的图像。有谁知道如何做到这一点? 这是我的代码:

ImageView backgroundImageView = new ImageView();
backgroundImageView.setId("backgroundImageView");
FileChooser fileChooser = new FileChooser();
fileChooser.setInitialDirectory(new File(new File("src\\backgrounds").getAbsolutePath()));
fileChooser.setTitle("select background image");
Button openButton = new Button("select background image...");
openButton.setOnAction(
        e -> {
            File file = fileChooser.showOpenDialog(main.getPrimaryStage());
            if (file != null) {
                try {
                    root.setStyle("-fx-background-image: url(\'" + file.toURI().toURL().toString() + "\');-fx-background-position: center center;-fx-background-repeat: stretch;");
                    //root.setBackground(new Background(new BackgroundImage(new Image(file.toURI().toURL().toString()))));//terrible errors!
                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                }
            }
        });
vBox.getChildren().add(openButton);

最佳答案

使用此方法将 RegionBackground 设置为以 File 形式给出的图像:

static void setBackgroundImage(File file, Region region) throws MalformedURLException {
    Image image = new Image(file.toURI().toURL().toExternalForm());
    region.setBackground(new Background(new BackgroundImage(
            image,
            BackgroundRepeat.NO_REPEAT,
            BackgroundRepeat.NO_REPEAT,
            BackgroundPosition.CENTER,
            BackgroundSize.DEFAULT
    )));

}

或者,对于拉伸(stretch)到 Region 大小的图像,使用 BackgroundFillImagePattern:

region.setBackground(new Background(new BackgroundFill(new ImagePattern(image), CornerRadii.EMPTY, Insets.EMPTY)));

关于java - 使用 javafx 在运行时更改背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37750129/

相关文章:

由于单独的线程,Javafx 无法附加上下文菜单

css - 将样式应用于 javaFX 中的 TreeView 子节点

javafx - 如何在 JavaFX 2.1 中创建模式窗口

image - Outlook HTML 电子邮件中的 VML 表格单元格背景图像仅在单击或调整大小时可见

html - 背景重复不适用于移动设备

javascript - 一天中不同时间的不同背景?

java - 无法使用 jvisualvm 分析 JBoss 5

java - 我对 abiFilters 配置有疑问

java - 根据另一个 ArrayList 在 ArrayList 中查找特定条目?

java - 如何在 hibernate 中调用程序?