How to detect MouseClick on the “stroke” part of a

2019-05-26 01:55发布

I want to detect mouse click event on a QuadCurve but only on the "stroke" part. To be clear only the green part of the image.

enter image description here

Here, i use a red fill value but in my application i use a transparent fill value. So detecting click on the visible part of the curve is critical.

The sample code :

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.QuadCurve;
import javafx.stage.Stage;

public class QuadCurveMouseHandling extends Application {
    @Override
    public void start(Stage stage) throws Exception {
        QuadCurve curve = new QuadCurve();
        curve.setStartX(10);
        curve.setStartY(10);
        curve.setControlX(50);
        curve.setControlY(250);
        curve.setEndX(300);
        curve.setEndY(300);
        curve.setStyle("-fx-stroke-width: 7;-fx-stroke: green;-fx-fill: red;");
        curve.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                System.out.println("clicked");
            }
        });
        stage.setScene(new Scene(new Group(curve), 320, 320));
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

2条回答
唯我独甜
2楼-- · 2019-05-26 02:14

Set the fill to null rather than a color.

e.g. -fx-fill: null; => if the fill is not there, you can't click on it.

查看更多
手持菜刀,她持情操
3楼-- · 2019-05-26 02:16

The simplest solution is to put the check inside OnMouseClicked handler and check the color of underlying point. If green - run your logic, if not green don't do anything. The more complicated way is to check if underlying point sits on the 'stroke' of your figure running some calculation.

查看更多
登录 后发表回答