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

时间:2015-08-03 13:08:49

标签: java javafx eventhandler

我想在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);
        }
    });

我的问题是 - 如何从内部句柄方法中访问“circle1”? 在JavaScript中,我们使用e.currentTarget

我无法宣布“circle1”决赛,因为我之后需要更改它。

2 个答案:

答案 0 :(得分:2)

您展示的代码中没有任何地方重新分配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);
        }
    });

请注意,在Java 8中,您的代码将按照您的方式进行编译,因为circle1 实际上是最终的(意味着它只分配了一次并且永远不会被重新分配)。

答案 1 :(得分:0)

使用event.getSource(),这可以为多个cicrles编写一个公共事件处理程序,而不必担心单击哪一个确切的事件:

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 = event.getSource();
            c.setCenterX( event.getX() );
        }
    }
};

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