Changing background color in javaFX canvas
Javafx canvas background The only solution I have right now is:
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLUE);
gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
Is there any other solution besides drawing a rectangle? I have searched in CSS but canvas doesn't have-fx-background-color
+4
source to share
1 answer
The canvas is essentially "empty" (ie transparent) unless you draw it. You can create a background effect by placing it in the layout panel and setting the background of the layout area:
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);
}
}
+16
source to share