Muhammad Musharaf
Muhammad Musharaf

Reputation: 21

How to add ImageView Component in javaFX on runtime

Actually i working on a project where i am stuck in a problemi have need to add a ImageView Component by cliking on a button on the runtime, Any Help? it would be anEventful act of YOur's for helping me.

MainClass

public class See extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

Controller

public class FXMLDocumentController implements Initializable {

    @FXML
    private Button button;

    @FXML
    private void handleButtonAction(ActionEvent event) {
        File fil=new File("src\\see\\unshadedLaptop.png");
        Image im=new Image(fil.toURI().toString());
        ImageView view=new ImageView(im);
        view.prefHeight(200);
        view.prefWidth(200);
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        File fil=new File("src\\see\\unshadedLaptop.png");
        Image im=new Image(fil.toURI().toString());
        ImageView view=new ImageView(im);

    }

}

Upvotes: 0

Views: 440

Answers (1)

SedJ601
SedJ601

Reputation: 13859

One approach is to give the Node an fx:id in your FXML. Then Do @FXML YourNodeType yourNodeFxId;. Then in the Button event handler do yourNodeFxId.getChildren().add(theImageViewHere);.

Using your code to show an example:

public class FXMLDocumentController implements Initializable {

    @FXML
    private Button button;
    @FXML 
    private Pane pane;//This is just an example. Make sure you have a  Pane with an fx:id="pane" in your FXML.

    @FXML
    private void handleButtonAction(ActionEvent event) {
        File fil=new File("src\\see\\unshadedLaptop.png");
        Image im=new Image(fil.toURI().toString());
        ImageView view=new ImageView(im);
        pane.getChildren().add(view);//This is the added code.
    }

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

Upvotes: 1

Related Questions