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
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With