在javaFX Canvas中更改背景颜色 [英] Change Color of Background in javaFX Canvas

查看:406
本文介绍了在javaFX Canvas中更改背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何更改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());

除了绘制矩形外,还有其他解决方案吗?我在CSS中搜索,但是canvas没有 -fx-background-color

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

这篇关于在javaFX Canvas中更改背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆