You need to enable JavaScript to run this app. JavaFX Line Chart如何实现曲线效果及线条下方区域着色
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX Line Chart如何实现曲线效果及线条下方区域着色

JavaFX LineChart 曲线效果+区域填充实现方案

1. 开启折线平滑效果

直接为数据系列开启平滑属性即可:

// 基础配置,关闭不需要的节点标记和动画避免干扰效果
lineChart.setCreateSymbols(false);
lineChart.setAnimated(false);
// 单个数据系列开启贝塞尔曲线平滑
XYChart.Series<Number, Number> series = new XYChart.Series<>();
series.setSmooth(true);

也可以通过CSS全局配置平滑效果:

.chart-line {
    -fx-smooth: true;
    -fx-stroke-width: 2px;
}

2. 实现线条下方颜色填充

方案一:改用AreaChart(最简实现)

AreaChart是LineChart的子类,原生支持区域填充,只需修改图表声明,再配置填充样式即可:

// 将原LineChart声明替换为AreaChart
AreaChart<Number, Number> areaChart = new AreaChart<>(xAxis, yAxis);
// 为单个系列配置填充色和线条色
series.nodeProperty().addListener((obs, oldNode, newNode) -> {
    if (newNode != null) {
        newNode.setStyle("-fx-fill: rgba(85, 130, 190, 0.3); -fx-stroke: #5582be;");
    }
});

配套CSS样式参考:

/* 填充区域透明度配置 */
.chart-series-area-fill {
    -fx-opacity: 0.3;
}
/* 线条平滑配置 */
.chart-series-area-line {
    -fx-stroke-width: 2px;
    -fx-smooth: true;
}
/* 隐藏节点标记,匹配目标效果 */
.chart-line-symbol {
    -fx-background-color: transparent;
    -fx-padding: 0;
}
/* 坐标轴网格线样式调整 */
.chart-vertical-grid-lines {
    -fx-stroke: transparent;
}
.chart-horizontal-grid-lines {
    -fx-stroke: #f0f0f0;
}
.chart-plot-background {
    -fx-background-color: transparent;
}

方案二:基于现有LineChart自定义填充

如果必须保留LineChart的使用,可通过监听线条节点手动绘制填充路径:

series.nodeProperty().addListener((obs, oldNode, newNode) -> {
    if (newNode instanceof Path linePath) {
        Path fillPath = new Path();
        // 复制线条路径
        fillPath.getElements().addAll(linePath.getElements());
        // 补充底部闭合路径
        fillPath.getElements().addAll(
            new LineTo(lineChart.getWidth(), yAxis.getHeight()),
            new LineTo(0, yAxis.getHeight()),
            new ClosePath()
        );
        fillPath.setFill(Color.rgb(85, 130, 190, 0.3));
        fillPath.setStroke(null);
        // 将填充路径插入到线条下方层级
        Pane plotArea = (Pane) lineChart.getChildrenUnmodifiable().get(1);
        plotArea.getChildren().add(0, fillPath);
        // 监听图表尺寸变化,动态更新填充路径
        ChangeListener<Number> sizeListener = (o, oldVal, newVal) -> {
            fillPath.getElements().setAll(linePath.getElements());
            fillPath.getElements().addAll(
                new LineTo(lineChart.getWidth(), yAxis.getHeight()),
                new LineTo(0, yAxis.getHeight()),
                new ClosePath()
            );
        };
        lineChart.widthProperty().addListener(sizeListener);
        lineChart.heightProperty().addListener(sizeListener);
    }
});

内容的提问来源于stack exchange,提问作者Syed Sulaiman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 05:12:04