为了账号安全,请及时绑定邮箱和手机立即绑定

将 EventHandler 添加到包含在标签中的 ImageView

将 EventHandler 添加到包含在标签中的 ImageView

互换的青春 2021-10-20 11:23:02
我最近开始探索 Java FX 并想创建一个自定义标签,其中将包含一个 ImageView。这是我的自定义标签的代码。Image image = new Image(getClass().getResourceAsStream("/img/remove.png"), 20, 20, true, true);ImageView removeImageView = new ImageView(image);Label customLabel = new Label(labelText, removeImageView);customLabel.setFont(Font.font("Arial", FontWeight.BOLD, 20));这就是我的自定义标签的外观。现在我想在 ImageView 中添加一个鼠标点击 EventHandler。这是我处理鼠标点击的代码。removeImageView.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {      @Override      public void handle(MouseEvent event) {        System.out.println("Imageview Clicked");      }    });但是当我点击cross图像时,事件没有被捕获。我进行了一些试验并尝试将 EventHandler 添加到customLabel. 标签能够捕获鼠标点击。在我看来,我面临这个问题是因为 ImageView 包含在标签中。我想知道的是,这是对 JFX 的限制,还是有其他方法可以实现此功能。谢谢。
查看完整描述

3 回答

?
牛魔王的故事

TA贡献1830条经验 获得超3个赞

这似乎是修复JDK-8117199 的结果。该修复程序将以下内容添加到LabeledSkinBase#updateChildren():


// RT-19851 Only setMouseTransparent(true) for an ImageView.  This allows the button

// to be picked regardless of the changing images on top of it.

if (graphic instanceof ImageView) {

    graphic.setMouseTransparent(true);

}

如您所见,当Labeled控件的图形为 an 时,ImageView它被设置为鼠标透明。一种解决方法是将ImageView背面的鼠标透明度设置为 false。


ImageView view = new ImageView();

view.mouseTransparentProperty().addListener((observable, oldVal, newVal) -> {

    if (newVal) {

        view.setMouseTransparent(false);

    }

});

由于您没有使用 CSS 根据悬停/武装状态更改图像,因此不应导致与错误相关的问题。不过,我会很谨慎;以防万一。


@fabian 提到的更好的解决方法是将 包装ImageView在其他一些Node(例如 a Pane)中。


Label customLabel = new Label(labelText, new Pane(removeImageView));

这使得图形 aPane这意味着不会发生特殊ImageView处理updateChildren()。


查看完整回答
反对 回复 2021-10-20
?
阿晨1998

TA贡献2037条经验 获得超6个赞

处理这种情况的一种方法是使用HBox. 而不是传递ImageView到Label的构造函数集ImageView和Label作为子节点HBox


ImageView removeImageView = new ImageView(image); 

Label customLabel = new Label("rito");

customLabel.setFont(Font.font("Arial", FontWeight.BOLD, 20));



HBox hbox = new HBox(removeImageView,customLabel);

root.getChildren().add(hbox);


removeImageView.setOnMouseClicked(e->{

            System.out.println("ImageView clicked");

        });



customLabel.setOnMouseClicked(e->{

            System.out.println("Lable clicked");

        });


查看完整回答
反对 回复 2021-10-20
  • 3 回答
  • 0 关注
  • 128 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信