Danial Kosarifa
Danial Kosarifa

Reputation: 1074

how to set listener for image in FXML (Javafx Project)?

How to set an event handler for image inside the fxml. I've written the following which are 3 images and I want to click on them and they call the function I have already created in my controller class . I've already tried onMouseClick and onAction neither of them would work .

   <ImageView fitHeight="31.0" fitWidth="29.0"  pickOnBounds="true" preserveRatio="true" GridPane.columnIndex="1" GridPane.rowIndex="0" >
            <image >
       <Image url="@/views/add.png" />
        </image>
        </ImageView>
     <ImageView fitHeight="31.0" fitWidth="29.0"  pickOnBounds="true" preserveRatio="true" GridPane.columnIndex="1" GridPane.rowIndex="1">
            <image>
       <Image url="@/views/remove.png" />
        </image>
        </ImageView>
     <ImageView fitHeight="31.0" fitWidth="29.0"  pickOnBounds="true" preserveRatio="true" GridPane.columnIndex="1" GridPane.rowIndex="2">
            <image>
       <Image url="@/views/edit.png" />
        </image>
        </ImageView>

I've also checked out other post as well but they all say how to do it when the image is defined pragmatically . Any suggestion is appreciated .

Upvotes: 1

Views: 1497

Answers (1)

Dth
Dth

Reputation: 1976

There's no onAction because ImageView, is not really a clickable component, but nothing stops you from listening to its mouse events, so you can use onMousePressed or orMouseClicked. Additionally, settings pickOnBounds to true ensures that events will be fired even if you click on the transparent part of the image. Here is an example FXML file:

<ImageView onMousePressed="#imageClicked" pickOnBounds="true">
    <image>
        <Image url="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png"/>
    </image>
</ImageView>

And the corresponding method in its controller:

@FXML
public void imageClicked(MouseEvent event) {
    System.out.println("Clicked: "+event.getSource());
}

Result:

Clicked: ImageView@7bf40ff6[styleClass=image-view]

Upvotes: 5

Related Questions