Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Color of Background in javaFX Canvas

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

like image 596
AndroLife Avatar asked Aug 24 '14 05:08

AndroLife


Video Answer


1 Answers

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);
    }
}
like image 70
James_D Avatar answered Oct 06 '22 12:10

James_D