The method setOnMouseClicked on the scene is used to listen for mouse clicks.
The coordinates of the point clicked is printed on the canvas.
package ex31;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
public class Ex31 extends Application
{
public static void main(String[] args)
{
launch(args);
}
@Override
public void start(Stage primaryStage)
{
primaryStage.setTitle( "Example 31. Mouse Click" );
Group root = new Group();
Scene scene = new Scene(root);
primaryStage.setScene(scene);
Canvas canvas = new Canvas(500, 200);
GraphicsContext gc = canvas.getGraphicsContext2D();
Font font = Font.font( "Georgia", FontWeight.BOLD, 32 );
gc.setFont(font);
gc.setStroke(Color.BLUE);
gc.setFill(Color.GREEN);
gc.fillRect(0,0, 512,512);
gc.strokeText("Please Click!", 100, 100 );
root.getChildren().add( canvas );
scene.setOnMouseClicked ( e -> {
double x = e.getX();
double y = e.getY();
gc.fillRect(0,0, 512,512);
gc.setFill(Color.GREEN);
String pointText = "Point: (" + x + ", " + y + ")";
gc.strokeText( pointText, 100, 100 );
});
primaryStage.show();
}
}
This is the output after clicking at the upper-left corner:
No comments:
Post a Comment