user7569064
user7569064

Reputation:

Display an image with SceneBuilder

I created a small FXML file with SceneBuilder, 3 buttons and 2 ImageView.

What i want to do is :

  1. Run the app and display 2 images at start
  2. When pressing NEXT button, display 2 other images.

My problem is not for swiching images, but to display one as an ImageView created by scene builder.

Here's my Controller class:

public class Controller {
    private Button Next; //1st button
    private Button J2inc; //2nd button
    private Button J1inc; /3rd button
    private ImageView Img1;
    private ImageView Img2;

    void Inc2(ActionEvent event) {
        //nothing for the moment
    }
    void Inc1(ActionEvent event) {
        //nothing for the moment
    }
    void Nextimg(ActionEvent event) {
        //nothing for the moment
    }
}

And my start method:

public void start(Stage primaryStage) throws Exception {
    Parent root =  FXMLLoader.load(getClass().getResource("Css.fxml"));
    Scene scene = new Scene(root);
    primaryStage.setScene(scene);
    primaryStage.setTitle("P ");
    primaryStage.show();
}

I don't know how to initialize ImageView img1 so it loads something.

Failed to add the FXML here so i'll only add the ImageView line:

  <ImageView fx:id="Img1" fitHeight="750.0" fitWidth="450.0" layoutY="22.0" pickOnBounds="true" preserveRatio="true" AnchorPane.bottomAnchor="50.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="450.0" AnchorPane.topAnchor="25.0" />

Upvotes: 2

Views: 10762

Answers (1)

James_D
James_D

Reputation: 209438

To initialize it in the controller, make the variable accessible by annotating it @FXML, and initialize it in the controller's initialize() method:

public class Controller {
    private Button Next; //1st button
    private Button J2inc; //2nd button
    private Button J1inc; /3rd button

    @FXML
    private ImageView Img1;

    private ImageView Img2;

    public void initialize() {
        Img1.setImage(new Image(...));
    }

    void Inc2(ActionEvent event) {
        //nothing for the moment
    }

    void Inc1(ActionEvent event) {
        //nothing for the moment
    }

    void Nextimg(ActionEvent event) {
        //nothing for the moment
    }
}

If you prefer to initialize it directly in the FXML, provide a value for the image attribute. In Scene Builder, you can select the ImageView and type the Image's URL in the "Image" field in the top right (under "Properties"). Be sure to read the Image documentation for how the string representation of the URL is interpreted.

Upvotes: 3

Related Questions