使用 onMouseClicked 方法时如何获取 ImageView 的 ID?

我无法使用 onMouseClicked 方法获取我的 imageViews 的 ID。在这个应用程序中,我有 20 个 ImageView,当我单击其中一个时,它应该将图像更改为我文件中的图像。到目前为止,我有这个 imagePicker 方法,我用 imgViewOne 测试了图像更改,这是第一个 ImageView 的 ID,这工作正常。


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();

    }           

}

我在这里找到了一些关于获取文本字段或其他元素的 ID 的答案,但它们都有可以调用的事件处理程序event.getID().但是这里没有事件处理程序,所以我不知道如何获取 ID。我尝试将参数设置为 imagePicker,例如 imagePicker(ImageView v) 然后调用String id = v.getID();,但我无法更改此属性的图像。如果有人知道解决方案,请与我分享。提前致谢!


编辑:每个 ImageView 都有 id imagePicker 的 onMouseCliked 方法。所以每次点击时,它都会转到这个方法。


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



呼如林
浏览 227回答 1
1回答

ibeautiful

您正在使用控制器方法事件处理程序,这意味着您的方法可以并且通常应该具有相应子类的单个参数Event。在您的情况下,参数应该是 a MouseEvent,因为您正在设置onMouseClicked处理程序。然后,您可以获得相应的事件源ImageView(处理程序已添加到ImageView)。public void imagePicker(MouseEvent event) {&nbsp; &nbsp; event.consume();&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; File file = new File("/home/zoran/eclipse-workspace/Pogodi tko sam/bin/application/iks.png");&nbsp; &nbsp; &nbsp; &nbsp; String localUrl = file.toURI().toURL().toString();&nbsp; &nbsp; &nbsp; &nbsp; Image image = new Image(localUrl);&nbsp; &nbsp; &nbsp; &nbsp; ((ImageView) event.getSource()).setImage(image); // set image on clicked ImageView&nbsp; &nbsp; } catch (MalformedURLException e) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Malformed url ex");&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}请注意,getSource返回Object,因此您必须转换为适当的类型。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java