运行以下代码时,只生成一个空白窗口,因为没有可见的圆圈被绘制。预计会在窗口上产生随机放置的黑色圆圈。
这是我的代码:
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);
}
}
答案 0 :(得分:1)
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);
}
}