Allie Marie Allie Marie - 1 month ago 29
Java Question

Change ImageView image in code using JavaFX Scene Builder

I'm trying to change the image in an ImageView component on button click. I need it to be a local image. I keep getting a path error and I can't use an ImageIcon and convert it to an Image. Is there not a simple way to do this?

package tictactoesimulator_alliebeckman;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

/**
*
* @author Allie
*/
public class FXMLDocumentController implements Initializable {

// my components
@FXML
public Label lblWinLose;
@FXML
public Button btnNewGame;
@FXML
public ImageView ivOne;

// Event handle for button click
@FXML
public void handleButtonAction(ActionEvent event) {

// here is where I'm having the issue I have the image file in my src folder
// I've tried using a ImageIcon and it wont convert to an Image?
// All I need is the image to change to the local image on button click

lblWinLose.setText("Clicked");
Image image = new Image("o.png");
ivOne = new ImageView(image);
}

@Override
public void initialize(URL url, ResourceBundle rb) {

}
}


The project layout can be seen in this Eclipse screenshot:

enter image description here

Answer

From the screenshot in your question, the image is in the same package as the FXMLDocumentController class.

The Image constructor you are using is expecting the string version of a URL of the image: the best way to get such a URL is to use getClass().getResource(...) (as this will work whether you are loading from the file system or from a jar file). getClass().getResource(...) will resolve relative to the current class (or relative to the classpath if you begin the resource name with a leading /):

Image image = new Image(getClass().getResource("o.png").toExternalForm());

and then instead of creating a new ImageView you should do

ivOne.setImage(image);
Comments