我想创建一个网格作为JavaFX应用程序的背景。我当前的解决方案是在画布上绘制一个矩形,从该矩形创建图像图案并将其设置为填充。
问题:是否有更好的方法(最好通过CSS)来解决此问题?
当前版本:
public class BackgroundGrid extends Application {
double gridSize = 20;
@Override
public void start(Stage primaryStage) {
Scene scene = new Scene(new Group(), 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
scene.setFill(createGridPattern());
}
public ImagePattern createGridPattern() {
double w = gridSize;
double h = gridSize;
Canvas canvas = new Canvas(w, h);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setStroke(Color.BLACK);
gc.setFill(Color.LIGHTGRAY.deriveColor(1, 1, 1, 0.2));
gc.fillRect(0, 0, w, h);
gc.strokeRect(0, 0, w, h);
Image image = canvas.snapshot(new SnapshotParameters(), null);
ImagePattern pattern = new ImagePattern(image, 0, 0, …Run Code Online (Sandbox Code Playgroud)