Change Color of Background in javaFX Canvas

倖福魔咒の 提交于 2020-01-01 14:53:27

问题


How do we change the background of JavaFX canvas? The only solution I have now is:

GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLUE);
gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());

Is there another solution except drawing a rectangle? I searched in CSS but canvas doesn't have -fx-background-color


回答1:


The canvas is essentially "blank" (i.e. transparent) unless you draw onto it. You can create the effect of a background by placing it into a layout pane and setting the background of the layout pane:

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);
    }
}


来源:https://stackoverflow.com/questions/25468882/change-color-of-background-in-javafx-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!