I'm tryin to pick a file and read it into an imageView. I'm using java fx.

Here's my code:

   public void changeImage() {

    try {

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Choose Image");

        fileChooser.getExtensionFilters().addAll(
                new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"),
                new ExtensionFilter("All Files", "*.*"));
        File selectedFile = fileChooser.showOpenDialog(ScreenController.stage);

        if (selectedFile != null) {
            File file = selectedFile;
            File desc = new File("/" + file.getName());
            FileUtils.copyFile(file, desc);
            Image img = new Image(desc.getPath());
            profileImage.setImage(img);
        }
    } catch (Exception e) {
        System.err.println(e);
    }

}

The problem seems to be Image img = new Image (desc.getPath()); getting an error that the file does not exist. But it does and it is a image. // Alex

有帮助吗?

解决方案

The Image constructor needs a String representation of a URL, not a filesystem path.

Replace

Image img = new Image(desc.getPath());

with

Image img = new Image(desc.toURI().toURL().toExternalForm());
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top