JavaFX change the image in an imageView
Your Issue
If you have a member node in your controller which you inject using @FXML
, you should never create a new object instance using a new
constructor and assign that new object to your existing reference. Instead just use the object which FXML created for you.
You have:
@FXML
private ImageView img_1;
That's fine.
Then in loadImg, you have:
img_1 = new ImageView();
img_1.setImage(newImg);
That is bad.
You already have an ImageView which the FXMLLoader created for you when you loaded your FXML document. The FXML Loader then assigned that ImageView to your img_1
reference because you used an @FXML
annotation.
How to Fix it
So all you need to do is to stop creating new ImageViews and only write:
img_1.setImage(newImg);
And you are done.
Why it works
The Image property of ImageView is an observable property. The JavaFX system observes the Image property for any changes and if it changes, automatically updates the image displayed on the screen for the ImageView. You don't need to perform any repaint call (there is no such repaint routine to call in any case).
Background Reading
If you want to understand the JavaFX scene graph architecture better, read the Oracle tutorial on it:
- Working with the JavaFX Scene Graph.
Some Tips
- You can create a JavaFX image directly from an InputStream, you don't need to use ImageIO and SwingFXUtils for this task.
- You can use a Task to communicate with a database and your application may be more responsive.
- It is probably simpler to read the image from a file or over http rather than from a database.
Disclaimer
Besides the issue pointed out here, there may be other errors in code you have not provided which may prevent you from getting your application to work as you wish.