Search code examples
javafxlambdaeventhandler

JavaFX remove eventhandler from lambda expression


I'm trying to add an event handler to a canvas which removes itself when a condition is fulfilled.

I tried doing this, but I'm getting an error which says the variable may have not been initialized.

EventHandler<MouseEvent> canvasHandler = e -> {
        double x = e.getX();
        double y = e.getY();

        boolean last = false;

        if (Math.abs(x - lastX) < 20f) x = lastX;
        if (Math.abs(y - lastY) < 20f) y = lastY;

        if (points.size() > 2) {
            if (Math.abs(x - points.get(0).getKey()) < 20f && Math.abs(y - points.get(0).getValue()) < 20f) {
                x = points.get(0).getKey();
                y = points.get(0).getValue();
                last = true;
            }
        }

        points.add(new Pair<Double, Double>(x, y));

        lastX = x;
        lastY = y;

        gc.lineTo(x, y);

        if (!last) 
            gc.strokeOval(x - 5f, y - 5f, 10f, 10f);
        else
            canvas.removeEventHandler(MouseEvent.MOUSE_CLICKED, canvasHandler);


        gc.stroke();
    };

    canvas.addEventHandler(MouseEvent.MOUSE_CLICKED, canvasHandler);

Solution

  • If you use an anonymous class instead of a lambda you can reference the EventHandler with this from inside the handle method:

    EventHandler<MouseEvent> canvasHandler = new EventHandler<>() {
      @Override public void handle(MouseEvent event) {
        // handle event...
        if (/* condition */) {
          canvas.removeEventHandler(MouseEvent.MOUSE_CLICKED, this);
    });
    canvas.addEventHandler(MouseEvent.MOUSE_CLICKED, canvasHandler);