Skip to content

How show or hide images in condition with javafx

I need help to program a windows based application with JavaFX. I simply want to show or hide some images with if/else condition. what I exactly want is something like this: if x=1 then show image1 if x=2 them show image2

I tried setvisible() and setDisable() methodes to do this, but it doesn’t work.

public class BoardSelection implements Initializable {
    @FXML
    public ImageView image1= new ImageView();
    @FXML
    public ImageView image2 = new ImageView();

    public int batteryVariation(int x){

        if(x=1){
            image1.setVisible(true);
            image2.setVisible(false);
        }
        if(x=2){
            image2.setVisible(false);
            image2.setVisible(true);
        }
        return x;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }

and my .fxml file codes are:

<ImageView fx:id="image1" fitHeight="60.0" fitWidth="30.0" layoutX="118.0" layoutY="227.0">
      <image>
        <Image url="@../img/image1.png" />
      </image>
    </ImageView>
    <ImageView fx:id="image2" fitHeight="60.0" fitWidth="30.0" layoutX="191.0" layoutY="227.0" pickOnBounds="true" preserveRatio="true">
      <image>
        <Image url="@../img/image2.png" />
      </image>
    </ImageView>

Answer

In the if statement you used the assignment operator (=) instead of comparison operator == .

public int batteryVariation(int x) {
    if (x == 1) {
        image1.setVisible(true);
        image2.setVisible(false);
    }
    if (x == 2) {
        image1.setVisible(false);
        image2.setVisible(true);
    }
    return x;
}

Example of working code:

public class PicturesTestController implements Initializable {

    @FXML
    private TextField tf_testInput;

    @FXML
    private ImageView image1;

    @FXML
    private ImageView image2;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        image2.setVisible(false);
        tf_testInput.setOnAction(actionEvent -> batteryVariation(Integer.parseInt(tf_testInput.getText())));
    }

    public int batteryVariation(int x) {
        if (x == 1) {
            image1.setVisible(true);
            image2.setVisible(false);
        }
        if (x == 2) {
            image1.setVisible(false);
            image2.setVisible(true);
        }
        return x;
    }
}

Anyway, is better use the setImage() method to set/change pictures in a ImageView.

https://docs.oracle.com/javase/8/javafx/api/javafx/scene/image/ImageView.html