我们如何更改JavaFX画布的背景? 我现在唯一的解决方案是:
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLUE);
gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
除了绘制矩形之外还有其他解决方案吗?我在CSS中搜索但画布没有-fx-background-color
答案 0 :(得分:17)
画布基本上是“空白的”(即透明的),除非你画上它。您可以通过将背景放置到布局窗格并设置布局窗格的背景来创建背景效果:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class CanvasBackground extends Application {
@Override
public void start(Stage primaryStage) {
Pane root = new Pane();
StackPane holder = new StackPane();
Canvas canvas = new Canvas(400, 300);
holder.getChildren().add(canvas);
root.getChildren().add(holder);
holder.setStyle("-fx-background-color: red");
Scene scene = new Scene(root, 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}