How to create dynamically Resizable shapes in javafx?

后端 未结 1 1489
逝去的感伤
逝去的感伤 2020-12-30 18:23

I have three problems:

  1. I want to create resizable shapes with box bounding...
  2. I also want to know how to get child seleted in a Pane.
  3. I\'m
相关标签:
1条回答
  • 2020-12-30 18:59

    Next example will answer your questions:

    • for (1) it uses binding, connecting pane size with rectangle size
    • for (2) it adds setOnMouseClick for each rectangle which stores clicked one in the lastOne field.
    • for (3) see code of setOnMouseClick() handler

      public class RectangleGrid extends Application {
      
        private Rectangle lastOne;
      
        public void start(Stage stage) throws Exception {
          Pane root = new Pane();
      
          int grid_x = 7; //number of rows
          int grid_y = 7; //number of columns
      
          // this binding will find out which parameter is smaller: height or width
          NumberBinding rectsAreaSize = Bindings.min(root.heightProperty(), root.widthProperty());
      
          for (int x = 0; x < grid_x; x++) {
              for (int y = 0; y < grid_y; y++) {
                  Rectangle rectangle = new Rectangle();
                  rectangle.setStroke(Color.WHITE);
      
                  rectangle.setOnMouseClicked(new EventHandler<MouseEvent>() {
                      @Override
                      public void handle(MouseEvent t) {
                          if (lastOne != null) {
                              lastOne.setFill(Color.BLACK);
                          }
                          // remembering clicks
                          lastOne = (Rectangle) t.getSource();
                          // updating fill
                          lastOne.setFill(Color.RED);
                      }
                  });
      
                  // here we position rects (this depends on pane size as well)
                  rectangle.xProperty().bind(rectsAreaSize.multiply(x).divide(grid_x));
                  rectangle.yProperty().bind(rectsAreaSize.multiply(y).divide(grid_y));
      
                  // here we bind rectangle size to pane size 
                  rectangle.heightProperty().bind(rectsAreaSize.divide(grid_x));
                  rectangle.widthProperty().bind(rectangle.heightProperty());
      
                  root.getChildren().add(rectangle);
              }
          }
      
          stage.setScene(new Scene(root, 500, 500));
          stage.show();
        }
      
        public static void main(String[] args) { launch(); }
      }
      
    0 讨论(0)
提交回复
热议问题