JavaFx:从事件处理程序访问对象

t40tm48m  于 2023-01-24  发布在  Java
关注(0)|答案(2)|浏览(152)

我想用JavaFX编写一个程序,其中包含一个按钮,单击该按钮时,会创建一个圆圈并将其添加到形状的ArrayList中。

createCircleBtn.setOnMouseClicked(new EventHandler<MouseEvent>() {
    @Override
        public void handle(MouseEvent event) {
            Circle circle1 = new Circle();
            shapes.add(circle1);
            circle1.setCenterX(event.getX());
            circle1.setCenterY(event.getY());
            circle1.setOnMouseDragged(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
         // doesn't work because "circle1" must be declared final (constant) 
                    circle1.setCenterX(event.getX());
                    // "this" doesn't refer to "circle1"
                    this.setCenterY(event.getY());
                }
            });
            mainPane.getChildren().add(circle1);
        }
    });

我的问题是-如何从句柄方法内部访问“circle 1”?在JavaScript中我们使用e.currentTarget
我不能声明“circle 1”为final,因为我需要在以后更改它。

kjthegm6

kjthegm61#

在代码中,没有任何地方需要重新赋值circle1,因此只需将其声明为final即可:

createCircleBtn.setOnMouseClicked(new EventHandler<MouseEvent>() {
    @Override
        public void handle(MouseEvent event) {
            final Circle circle1 = new Circle();
            shapes.add(circle1);
            circle1.setCenterX(event.getX());
            circle1.setCenterY(event.getY());
            circle1.setOnMouseDragged(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    circle1.setCenterX(event.getX());
                }
            });
            mainPane.getChildren().add(circle1);
        }
    });

注意,在Java8中,您的代码将按原样编译,因为circle1是 * 有效的final*(意味着它只被赋值一次,永远不会被重新赋值)。

q3aa0525

q3aa05252#

使用event.getSource(),这样就可以为多个循环编写一个通用的事件处理程序,而不用担心点击了哪个循环:

EventHandler<MouseEvent> handler = new EventHandler<>()
{
    @Override
    public void handle( MouseEvent event )
    {
        if (event.getSource() instanceof Circle) { // to be on safe side, you may 
                                                   // remove this if-statement 
                                                   // if you are sure
            Circle c = (Circle) event.getSource();
            c.setCenterX( event.getX() );
        }
    }
};

// use it on multiple circles
circle1.setOnMouseDragged(handler);
circle2.setOnMouseDragged(handler);
...
circleN.setOnMouseDragged(handler);

相关问题