首页 > 解决方案 > javafx中带有渐变颜色的矩形

问题描述

我在我的 javafx 应用程序中使用锚窗格。我想画一个矩形并用这样的渐变颜色填充它:矩形的左侧是蓝色,右侧是红色,我希望它看起来从左到右,蓝色减少,红色增加。

我知道如何放置一个矩形(如何在 javafx 中使用 Rectangle 类),但我不知道如何以这种方式填充它。有任何想法吗?

标签: javajavafx

解决方案


坡度

请参阅有关线性渐变的文档。

public class Gradient extends Application {

    public static final double S = 100;

    @Override
    public void start(Stage stage) {
        Stop[] stops = new Stop[] {
                new Stop(0, Color.BLUE),
                new Stop(1, Color.RED)
        };
        LinearGradient gradient = new LinearGradient(
                0, 0,
                1, 0,
                true,
                CycleMethod.NO_CYCLE,
                stops
        );

        Rectangle rectangle = new Rectangle(S, S, gradient);

        stage.setScene(new Scene(new Group(rectangle)));
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }

}

推荐阅读