如何在javafx中动态创建可调整大小的形状?

时间:2012-03-27 10:11:44

标签: javafx javafx-2

我有三个问题:

  1. 我想创建带有框边界的可调整大小的形状......
  2. 我也想知道如何让孩子在Pane中选择。
  3. 我在窗格上创建了​​多个形状。我想改变那种形状的一些属性说Fill ..我该怎么办?
  4. Thanx

1 个答案:

答案 0 :(得分:9)

下一个例子将回答你的问题:

  • for(1)它使用绑定,连接窗格大小和矩形大小
  • for(2)它为每个矩形添加setOnMouseClick,在lastOne字段中存储点击的矩形。
  • for(3)参见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(); }
    }