运行以下代码时,由于没有绘制可见的圆圈,因此仅生成一个空白窗口。预期会在窗口上产生随机放置的黑色圆圈。

这是我的代码:

package circles;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.stage.Stage;
import java.util.Random;
import javafx.scene.paint.Color;

public class Circles extends Application {

    private Canvas canvas = new Canvas(400, 400);

    @Override
    public void start(Stage primaryStage) {

        VBox root = new VBox();
        root.getChildren().add(canvas);

        Scene scene = new Scene(root);

        primaryStage.setTitle("Draw Circles");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void drawCircles() {
        // radius of the circles
        final int RADIUS = 20;
        Random rand = new Random();
        GraphicsContext gc = canvas.getGraphicsContext2D();
        gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
        gc.setFill(Color.WHITESMOKE);
        for (int i =0; i <50;i++) {
            int x = rand.nextInt(400);
            int y = rand.nextInt(400);
            gc.fillOval(x,  y, RADIUS, RADIUS);
        }
    }

    public static void main(String[] args) {
     Circles x = new Circles();
     x.drawCircles();
     launch(args);
  }
}

最佳答案

Application.launch(...)方法创建应用程序类的实例,并(在进行其他一些工作之后)在其上调用start()

在代码中,首先创建应用程序类Circles的实例,在其上调用drawCircles(),然后调用Application.launch(...)。这将导致创建Circles的第二个实例,并在该第二个实例上调用start()

因此,不会在与drawCircles()相同的对象上调用start(),因此,圆会绘制在从不显示的画布上。

只需将对drawCircles()的调用移动到start()方法:

package circles;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.stage.Stage;
import java.util.Random;
import javafx.scene.paint.Color;

public class Circles extends Application {

    private Canvas canvas = new Canvas(400, 400);

    @Override
    public void start(Stage primaryStage) {

        VBox root = new VBox();
        root.getChildren().add(canvas);

        drawCircles();

        Scene scene = new Scene(root);

        primaryStage.setTitle("Draw Circles");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void drawCircles() {
        // radius of the circles
        final int RADIUS = 20;
        Random rand = new Random();
        GraphicsContext gc = canvas.getGraphicsContext2D();
        gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
        gc.setFill(Color.WHITESMOKE);
        for (int i =0; i <50;i++) {
            int x = rand.nextInt(400);
            int y = rand.nextInt(400);
            gc.fillOval(x,  y, RADIUS, RADIUS);
        }
    }

    public static void main(String[] args) {
        launch(args);
  }
}

关于java - 图形上下文未绘制形状/不可见,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49983863/

10-15 00:52