How to create dynamically Resizable shapes in javafx?


Question

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 creating multiple shapes on a pane. I want to change some property of that shape say Fill.. How do i do it??

Thanx

1
3
3/27/2012 8:37:41 PM

Accepted Answer

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(); }
    }
    
9
3/28/2012 8:15:23 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon