JavaFX MouseEvent which mouse button clicked

Description

JavaFX MouseEvent which mouse button clicked


import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class Main extends Application {
   @Override/*from w w w. j  ava 2  s  . co  m*/
   public void start(Stage primaryStage) {
      // Create a pane
      Pane pane = new Pane();

      // Create and register the handle
      pane.setOnMouseClicked(e -> {
         // Create a circle
         Circle circle = new Circle(e.getX(), e.getY(), 5);
         circle.setFill(Color.WHITE);
         circle.setStroke(Color.BLACK);
         if (e.getButton() == MouseButton.PRIMARY) {
            pane.getChildren().add(circle);
         } else if (e.getButton() == MouseButton.SECONDARY) {
            ObservableList<Node> list = pane.getChildren();
            for (int i = 0; i < list.size(); i++) {
               Circle c = (Circle) list.get(i);
               if (circle.contains(c.getCenterX(), c.getCenterY())) {
                  list.remove(i);
               }
            }
         }
      });

      // Create a scene and place it in the stage
      Scene scene = new Scene(pane);
      primaryStage.setTitle("java2s.com");
      primaryStage.setScene(scene);
      primaryStage.show();
   }
}



PreviousNext

Related