我想将 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);
最佳答案
使用此方法将 Region
的 Background
设置为以 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
大小的图像,使用 BackgroundFill
和 ImagePattern
:
region.setBackground(new Background(new BackgroundFill(new ImagePattern(image), CornerRadii.EMPTY, Insets.EMPTY)));
关于java - 使用 javafx 在运行时更改背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37750129/