简体   繁体   中英

Javafx Canvas rect does not draw

i do something very basical and i just can't figure out what went wrong.

i try to draw a grid on a canvas, which seems straight forward, but i have problems with the outline of my rectangles. They simply are not drawn!!

    canvas.getGraphicsContext2D().setFill(Color.YELLOW);
    canvas.getGraphicsContext2D().setStroke(Color.BLACK);
    canvas.getGraphicsContext2D().setLineWidth(2d);

    for (int dy = 0; dy < height; dy ++){
        for (int dx = 0; dx < width; dx ++){
            canvas.getGraphicsContext2D().setFill(new Color( random.nextDouble(), random.nextDouble(), random.nextDouble() ,1));
            canvas.getGraphicsContext2D().fillRect(dx*32,dy*32,32,32);
            canvas.getGraphicsContext2D().rect(dx*32,dy*32,32,32);
        }
    }

the result is quite funny since it DOES draw, but not the outline...

在此处输入图像描述

can't be that hard, can it? what am i missing?

You just append elements to the path, but you never do anything with it. You need to invoke some method using the path. In your case you need to call stroke :

@Override
public void start(Stage stage) throws IOException {
    Canvas canvas = new Canvas(512, 512);
    Scene scene = new Scene(new Pane(canvas));

    Random random = new Random();
    final int height = 16;
    final int width = 16;

    GraphicsContext gc = canvas.getGraphicsContext2D();
    gc.setStroke(Color.BLACK);
    gc.setLineWidth(2d);

    for (int dy = 0; dy < height; dy++) {
        for (int dx = 0; dx < width; dx++) {
            gc.setFill(new Color(random.nextDouble(), random.nextDouble(), random.nextDouble(), 1));
            gc.fillRect(dx * 32, dy * 32, 32, 32);
            gc.rect(dx * 32, dy * 32, 32, 32);
        }
    }

    // draw the path we've constructed during the loop
    gc.stroke();

    stage.setScene(scene);
    stage.show();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM