我想将窗格的背景图像设置为用户通过javafx中的filechooser选择的图像。有谁知道如何做到这一点? 这是我的代码:
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);
答案 0 :(得分:1)
使用此方法将Background
的{{1}}设置为Region
的图像:
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
)));
}
大小的图片,使用带有Region
的{{1}}:
BackgroundFill