【问题标题】:How to create dynamically Resizable shapes in javafx?如何在 javafx 中创建动态可调整大小的形状?
【发布时间】:2012-03-27 10:11:44
【问题描述】:

我有三个问题:

  1. 我想创建带有框边界的可调整大小的形状...
  2. 我还想知道如何让孩子在窗格中被选中。
  3. 我正在窗格上创建多个形状。我想更改该形状的某些属性,比如 Fill.. 我该怎么做??

谢谢

【问题讨论】:

    标签: javafx javafx-2


    【解决方案1】:

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

    • 对于 (1) 它使用绑定,将窗格大小与矩形大小联系起来
    • 对于 (2),它会为每个矩形添加 setOnMouseClick,在 lastOne 字段中存储点击过的矩形。
    • 对于(3)见setOnMouseClick()处理程序的代码

      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(); }
      }
      

    【讨论】:

      猜你喜欢
      • 2017-03-09
      • 2018-01-11
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      • 2012-08-02
      • 2013-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多