Javafx polyline

2.2k views Asked by At

In my JavaFX project I have to draw basic line with MouseEvent, I chose to do it with Polyline, but it is not working porperly. Can't find the problem, here is the MouseEvent code:

if (event.getButton() == MouseButton.SECONDARY) {
    Polyline line = new Polyline();
    main.getChildren().add(line);
    line.getPoints().add(event.getX());
    line.getPoints().add(event.getY());
    line.setScaleX(0);
    line.setScaleY(0);
    line.setStroke(Color.CORAL);
    line.setStrokeWidth(4);
} else if (event.getEventType() == MouseEvent.MOUSE_DRAGGED) {
    if (event.getButton() == MouseButton.SECONDARY) {
        Polyline line = new Polyline();
        for (Node s: main.getChildren()) {
            if (s instanceof Polyline) {
                line.getPoints().add(event.getX());
                line.getPoints().add(event.getY());
            }
        }
        main.getChildren().add(line);
    }
}
1

There are 1 answers

0
Muten Roshi On

It can't work cause each time the mouse event is called you create a new PolyLine object. You need to create one single PolyLine at the beginning and add all your points to this PolyLine. With your code is each point a new PolyLine. Btw. I'm not sure if adding the x and the y coordinate separate works well, try to use:

line.getPoints().addAll(event.getX(),event.getY());

Hope this helps :)