i want to execute an anonymous function when the mouse interacts with the Line. But the methods “setOnMousePressed”, “setOnMouseClicked”, “setOnMouseEntered”, are not working.
this.line = new Line();
this.line.setStartX(10);
this.line.setStartY(10);
this.line.setEndX(20);
this.line.setEndY(40);
this.line.setStroke(Color.PINK);
this.line.setStrokeWidth(5);
this.line.setOnMouseEntered(event -> {
System.out.println("test");
});
If I understand correctly, this happens because the library does not consider a Shape as an interactive element, not having the necessary attributes for the “OnMouse…” methods to work. In my case I cannot use Canvas, how can I achieve this result?
The example code from your question already works, just run it, put the mouse over the line, and look at the console.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class LineApp extends Application {
@Override
public void start(Stage stage) {
Line line = new Line();
line.setStartX(10);
line.setStartY(10);
line.setEndX(20);
line.setEndY(40);
line.setStroke(Color.PINK);
line.setStrokeWidth(5);
line.setOnMouseEntered(event -> System.out.println("test"));
stage.setScene(new Scene(new Group(line)));
stage.show();
}
}
In what specific way does it not work? There is nothing wrong with the code you posted, so any errors must elsewhere. Create and post a minimal reproducible example. “the library does not consider a Shape as an interactive element”. This is not a true statement; mouse events are triggered by shapes.
exactly, i can’t find the error. The console just doesn’t print anything.
So create and post a minimal reproducible example. You can’t expect anyone to diagnose code that has nothing wrong with it.