JavaFX为ImageView提供了许多类似的鼠标事件

JavaFX为ImageView提供了许多类似的鼠标事件,java,javafx,Java,Javafx,您好,我有大量类似的图像拖放事件的问题,我用标签移动到其他图像视图 代码示例: //drag and drope for imageview01 @FXML private void handleDragDetected1(MouseEvent event) { Dragboard db = imageview01.startDragAndDrop(TransferMode.ANY); ClipboardContent cb = new ClipboardContent(

您好,我有大量类似的图像拖放事件的问题,我用标签移动到其他图像视图

代码示例:

//drag and drope for imageview01
@FXML
private void handleDragDetected1(MouseEvent event) {
      Dragboard db = imageview01.startDragAndDrop(TransferMode.ANY);
      ClipboardContent cb = new ClipboardContent();
      cb.putImage(imageview01.getImage());
      cb.putString(imageview01_label.getText());
      db.setContent(cb);
      System.out.println("Picture 1 is draged");
}
...
...
//drag and drope for imageview100
@FXML
private void handleDragDetected100(MouseEvent event) {
     ...
     ...
}

是否有任何缩短代码的解决方案?

您可以将
标签
指定为相应
图像视图
用户数据
,这允许您使用事件源检索
标签
,从而允许您对所有
图像视图
使用相同的事件处理程序

以下示例使用
按钮
onMouseClicked
事件以简化操作,但同样的方法也适用于您的问题:

FXML

控制器
(您甚至不需要控制器中的
label1
字段。)

不要通过FXML连接100个事件处理程序。相反,只需在代码中使用一个循环。这个循环是什么样子的?谢谢。如果我希望标签使用setUserdata,FXML和Contoller将如何处理?@MarekKrištof请澄清您的意思。什么是*它*
?为什么要使用标签的
setUserData`以及您想要设置的值是什么?因此,我在拖动事件上有imageview,我在拖动事件上分配userdata(标签),接下来我有drop事件,我在其中也有imageview,我在这个imageview中设置了拖动事件的图像,并且我有标签..以及我需要分配给特定imageview的这个特定标签
@FXML
private void click(MouseEvent event) {
    // retrieve the node the event occured on
    Button btn = (Button) event.getSource();

    // retrieve Label associated with event source
    Label label = (Label) btn.getUserData();

    // now we've got all info we need without using any field of the controller
    System.out.println(label.getText());
}