Ошибка выполнения IllegalArgumentException при настройке изображения javafx
Я получаю эту ошибку
Caused by: java.lang.IllegalArgumentException: Invalid URL: unknown
protocol: c at javafx.scene.image.Image.validateUrl(Image.java:1097)
at javafx.scene.image.Image.<init>(Image.java:598)
at javafx.scene.image.ImageView.<init>(ImageView.java:164)
at fileshare_client.fx.pkg1.UploadappUI_1Controller.iconimagebuttonAction(UploadappUI_1Controller.java:355)" java:355
который
imageview=new ImageView(iconimage.getAbsolutePath());"
вот мой код:
@FXML
private AnchorPane mainAnchorpane;
@FXML
private ImageView imageview;
private File iconimage;
@FXML
public void iconimagebuttonAction(ActionEvent event) {
FileChooser filechooser = new FileChooser();
iconimage = filechooser.showOpenDialog(mainAnchorpane.getScene().getWindow());
System.out.println(iconimage.getName());
if (iconimage != null) {
String iconimagepath = iconimage.getAbsolutePath();
System.out.println(iconimagepath);
**imageview=new ImageView(iconimage.getAbsolutePath());**// error
}
}
3 ответа
Решение
С помощью
iconimage.getAbsolutePath()
дает вам абсолютный путь к файлу, где конструктор ожидает file URL
Попробуйте использовать
iconimage.toURI().toString()
или добавить file:
на абсолютный путь
"file:" + iconimage.getAbsolutePath()
Вот фрагмент кода, который я использую.
File imageFile = new File("mountains001.jpg");
System.out.println(imageFile.getAbsolutePath());
if (imageFile.exists()) {
ImageView imageView = new ImageView();
Image image = new Image(imageFile.toURI().toString());
imageView.setImage(image);
root.getChildren().add(imageView);
}
Здесь URL должен быть предоставлен в конструкторе ImageView
поэтому предлагаемый код будет:
@FXML
public void iconimagebuttonAction(ActionEvent event) {
FileChooser filechooser = new FileChooser();
iconimage = filechooser.showOpenDialog(mainAnchorpane.getScene().getWindow());
System.out.println(iconimage.getName());
if (iconimage != null) {
try {
String iconimagepath = iconimage.getAbsolutePath();
System.out.println(iconimagepath);
imageview=new ImageView(iconimage.toURI().toURL().toExternalForm());
} catch (MalformedURLException ex) {
Logger.getLogger(UploadappUI_1Controller.class.getName()).log(Level.SEVERE, null, ex);
}
}
}