Skip to content
Advertisement

Uploading and displaing an image using JavaFX

I’m working with JavaFX, where I have written a code that contains display Image, through I want to display the image on my scene, but it’s not working. The image doesn’t display.
When I’m using the getAbsolutePath() it also displays an error. Although 70% of my coding is done, I’m just stuck with displaying images on the scene (without uploading it).
Here is the code I’m working with:

JavaScript

So, what I need, is to display images on my scene by clicking the button and selecting an image.

Advertisement

Answer

The Image() constructor expects a URI and not an Absolute path. There are two ways to approach this.

  1. Turn your absolutePath in a URI by adding the required prefix file://

  2. Use InputStream which holds the Image data and you don’t have to care about the Path after it has been created. I like this way better.

Example:

JavaScript

There are also some other problems with your code.

  1. Create your ImageView and initialize it. Not when the button is clicked but right at the beginning
  2. Add the ImageView to your Scene
  3. Do not create new ImageView every time the button is clicked, just change the Image.

This is my code based on yours:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement