user8616404
user8616404

Reputation:

How to get ID of ImageView when using onMouseClicked method?

I am having trouble with getting ID of my imageViews using onMouseClicked method. In this app I have 20 ImageViews and when I click on one of them, it should change image to image from my file. So far I have this imagePicker method where I tested image change with imgViewOne, which is ID of first ImageView and this works fine.

public void imagePicker() {
    try {
        File file = new File("/home/zoran/eclipse-workspace/Pogodi tko sam/bin/application/iks.png");
        String localUrl = file.toURI().toURL().toString();
        Image image = new Image(localUrl);
        //imgViewOne.setImage(image);
    } catch (MalformedURLException e) {
        System.out.println("Malformed url ex");
        e.printStackTrace();
    }           
}

I have found some answers here about getting ID of text fields or some else elements, but all of them have event handlers on which can be called event.getID(). But here, there is no event handler so I do not know how to get ID. I tried to set argument into imagePicker, like imagePicker(ImageView v) and then call String id = v.getID(); but I could not change image on this attribute. If anyone knows the solution, please share with me. Thanks in advance!

Edit: Every ImageView has onMouseCliked method by id imagePicker.So every time clicked, it goes to this method.

      <ImageView fx:id="trinaesta" onMouseClicked="#imagePicker" fitHeight="150.0" fitWidth="200.0" pickOnBounds="true" preserveRatio="true" GridPane.rowIndex="3">

Upvotes: 0

Views: 363

Answers (1)

Slaw
Slaw

Reputation: 45806

You are using a controller method event handler which means your method can, and typically should, have a single parameter of the appropriate Event subclass. In your case, the parameter should be a MouseEvent as you are setting the onMouseClicked handler. You can then get the source of the event which will be the corresponding ImageView (the handler was added to the ImageView).

public void imagePicker(MouseEvent event) {
    event.consume();
    try {
        File file = new File("/home/zoran/eclipse-workspace/Pogodi tko sam/bin/application/iks.png");
        String localUrl = file.toURI().toURL().toString();
        Image image = new Image(localUrl);
        ((ImageView) event.getSource()).setImage(image); // set image on clicked ImageView
    } catch (MalformedURLException e) {
        System.out.println("Malformed url ex");
        e.printStackTrace();
    }           
}

Note that getSource returns Object so you'll have to cast to the appropriate type.

Upvotes: 3

Related Questions