在窗格上着色多个矩形

时间:2018-06-05 20:56:18

标签: java javafx

我希望用户选择一个点击网格的地方。然后他可以选择元素的大小。因此,如果大小为2x2,则必须为4个矩形着色。

我开始做这个 https://image.noelshack.com/fichiers/2018/23/2/1528232091-capture-du-2018-06-05-22-54-26.png

但我不知道如何为邻居矩形着色:/ 这是代码:

public class Main extends Application{
  private ReadOnlyDoubleProperty heightProperty;
    private ReadOnlyDoubleProperty widthProperty;

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Application.launch();

}

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.setFill(Color.GREY);

                rectangle.setOnMouseClicked(new EventHandler<MouseEvent>() {
                    public void handle(MouseEvent t) {
                        if (lastOne != null) {
                            lastOne.setFill(Color.GREY);
                        }
                        // remembering clicks
                         Rectangle rectangle2 = new Rectangle();
                        lastOne = (Rectangle) t.getSource();

                        System.out.println(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();

}

}

0 个答案:

没有答案