我遇到三个问题:
- 我想创建带有框边界的可调整大小的形状...
- 我还想知道如何在 Pane 中选择子项。
- 我正在一个 Pane 上创建多个形状。我想更改该形状的某些属性,例如“填充”。我该怎么做?
谢谢
最佳答案
下一个示例将回答您的问题:
- 对于(1),它使用绑定(bind),将 Pane 大小与矩形大小连接起来
- 对于 (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(); } }
关于javafx - 如何在javafx中创建动态可调整大小的形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9887485/