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

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

本文介绍了如何在javafx中动态创建可调整大小的形状?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个问题:


  1. 我想创建带有框边界的可调整大小的形状......

  2. 我也想知道如何让孩子在Pane中选择。

  3. 我正在窗格上创建多个形状。我想改变那种形状的一些属性说填充..我该怎么办?

Thanx

推荐答案

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

Next example will answer your questions:


  • for( 1)它使用绑定,连接窗格大小和矩形大小

  • for(2)它为每个存储单击的矩形添加 setOnMouseClick lastOne 字段中。

  • for(3)参见代码setOnMouseClick() handler

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


这篇关于如何在javafx中动态创建可调整大小的形状?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 12:40