【Java万花筒】从入门到精通:Java实时数据可视化库详解

实时数据可视化:Java开发者必备技能

前言

在当今数据时代,实时数据可视化已成为企业和个人决策的关键环节之一。作为一名 Java 开发者,掌握实时数据可视化库的使用,可以帮助您更好地展示数据,提高工作效率和决策质量。本文将为您介绍目前市面上流行的八个 Java 实时数据可视化库,旨在帮助您快速入门和提高数据可视化能力。

【Java万花筒】数据之翼:Java库助您飞跃科学计算高峰
【Java万花筒】Java图形库探秘:创意编程、数据可视化与用户界面设计
【Java万花筒】数据可视化利器:Java图表和图形库全面对比
【Java万花筒】数据魔术师:探索Java商业智能与数据可视化

欢迎订阅专栏:Java万花筒

文章目录

  • 实时数据可视化:Java开发者必备技能
    • 前言
    • 实时数据可视化库
      • [1. Grafana Java Client](#1. Grafana Java Client)
        • [1.1. Grafana 简介](#1.1. Grafana 简介)
        • [1.2. Grafana Java Client 特点](#1.2. Grafana Java Client 特点)
        • [1.3. 安装和配置](#1.3. 安装和配置)
        • [1.4. 基本使用](#1.4. 基本使用)
          • [1.4.1. 创建 Dashboard](#1.4.1. 创建 Dashboard)
          • [1.4.2. 添加数据源](#1.4.2. 添加数据源)
          • [1.4.3. 添加图表](#1.4.3. 添加图表)
        • [1.5. 高级用法](#1.5. 高级用法)
          • [1.5.1. 模板变量](#1.5.1. 模板变量)
          • [1.5.2. 告警和通知](#1.5.2. 告警和通知)
          • [1.5.3. 权限管理](#1.5.3. 权限管理)
      • [2. ECharts Java](#2. ECharts Java)
        • [2.1. ECharts 简介](#2.1. ECharts 简介)
        • [2.2. ECharts Java 特点](#2.2. ECharts Java 特点)
        • [2.3. 安装和配置](#2.3. 安装和配置)
        • [2.4. 基本使用](#2.4. 基本使用)
          • [2.4.1. 创建图表](#2.4.1. 创建图表)
          • [2.4.2. 添加数据](#2.4.2. 添加数据)
          • [2.4.3. 配置图表选项](#2.4.3. 配置图表选项)
        • [2.5. 高级用法](#2.5. 高级用法)
          • [2.5.1. 自定义图表类型](#2.5.1. 自定义图表类型)
          • [2.5.2. 数据集成](#2.5.2. 数据集成)
          • [2.5.3. 图表交互](#2.5.3. 图表交互)
      • [3. XChart](#3. XChart)
        • [3.1. XChart 简介](#3.1. XChart 简介)
        • [3.2. XChart 特点](#3.2. XChart 特点)
        • [3.3. 安装和配置](#3.3. 安装和配置)
        • [3.4. 基本使用](#3.4. 基本使用)
          • [3.4.1. 创建图表](#3.4.1. 创建图表)
          • [3.4.2. 添加数据](#3.4.2. 添加数据)
          • [3.4.3. 配置图表样式](#3.4.3. 配置图表样式)
        • [3.5. 高级用法](#3.5. 高级用法)
          • [3.5.1. 自定义图表类型](#3.5.1. 自定义图表类型)
          • [3.5.2. 图表动画](#3.5.2. 图表动画)
          • [3.5.3. 图表导出](#3.5.3. 图表导出)
      • [4. JavaFX](#4. JavaFX)
        • [4.1. JavaFX 简介](#4.1. JavaFX 简介)
        • [4.2. JavaFX 特点](#4.2. JavaFX 特点)
        • [4.3. 与实时数据可视化库结合使用](#4.3. 与实时数据可视化库结合使用)
      • [5. Vaadin](#5. Vaadin)
        • [5.1. Vaadin 简介](#5.1. Vaadin 简介)
        • [5.2. Vaadin 特点](#5.2. Vaadin 特点)
        • [5.3. 与实时数据可视化库结合使用](#5.3. 与实时数据可视化库结合使用)
      • [6. Birt](#6. Birt)
        • [6.1. Birt 简介](#6.1. Birt 简介)
        • [6.2. Birt 特点](#6.2. Birt 特点)
        • [6.3. 与实时数据可视化库结合使用](#6.3. 与实时数据可视化库结合使用)
      • [7. JFreeChart](#7. JFreeChart)
        • [7.1. JFreeChart 简介](#7.1. JFreeChart 简介)
        • [7.2. JFreeChart 特点](#7.2. JFreeChart 特点)
        • [7.3. 与实时数据可视化库结合使用](#7.3. 与实时数据可视化库结合使用)
      • [8. JasperReports](#8. JasperReports)
        • [8.1. JasperReports 简介](#8.1. JasperReports 简介)
        • [8.2. JasperReports 特点](#8.2. JasperReports 特点)
        • [8.3. 与实时数据可视化库结合使用](#8.3. 与实时数据可视化库结合使用)
    • 总结

实时数据可视化库

1. Grafana Java Client

1.1. Grafana 简介

Grafana 是一款开源的度量分析和可视化工具,支持多种数据源,如 Graphite、InfluxDB、Prometheus 等。Grafana 可以帮助用户创建、探索和分享各种各样的可视化面板。

1.2. Grafana Java Client 特点

Grafana Java Client 是一个用于操作 Grafana 的 Java 库,它提供了一系列的 API 来管理 Grafana 的 Dashboard、数据源、组织、用户等资源。

1.3. 安装和配置
  1. 添加 Maven 依赖
xml 复制代码
<dependency>
    <groupId>com.github.hipages</groupId>
    <artifactId>grafana-client</artifactId>
    <version>0.3.2</version>
</dependency>
  1. 配置 Grafana 客户端
java 复制代码
import com.github.hipages.grafana.client.GrafanaClient;
import com.github.hipages.grafana.client.GrafanaClientBuilder;

GrafanaClient client = new GrafanaClientBuilder()
        .url("http://localhost:3000")
        .auth("admin", "admin")
        .build();
1.4. 基本使用
1.4.1. 创建 Dashboard
java 复制代码
import com.github.hipages.grafana.client.model.Dashboard;
import com.github.hipages.grafana.client.model.Row;
import com.github.hipages.grafana.client.model.Text;
import com.github.hipages.grafana.client.model.TimeSeries;

Dashboard dashboard = new Dashboard();
dashboard.setTitle("My Dashboard");

Row row = new Row();
row.setTitle("Row 1");

Text text = new Text();
text.setContent("Hello, Grafana!");

TimeSeries timeSeries = new TimeSeries();
timeSeries.setAlias("Series A");
timeSeries.setTarget("metric1");

row.addPanel(text);
row.addPanel(timeSeries);

dashboard.addRow(row);

client.dashboards().create(dashboard);
1.4.2. 添加数据源
java 复制代码
import com.github.hipages.grafana.client.model.DataSource;
import com.github.hipages.grafana.client.model.GraphiteDataSource;

DataSource dataSource = new GraphiteDataSource();
dataSource.setName("Graphite");
dataSource.setUrl("http://graphite:8080");

client.dataSources().create(dataSource);
1.4.3. 添加图表
java 复制代码
import com.github.hipages.grafana.client.model.GraphPanel;
import com.github.hipages.grafana.client.model.Target;

GraphPanel graphPanel = new GraphPanel();
graphPanel.setTitle("Graph Panel");

Target target = new Target();
target.setTarget("metric1");
target.setRefId("A");

graphPanel.addTarget(target);

dashboard.getFirstRow().addPanel(graphPanel);

client.dashboards().update(dashboard);
1.5. 高级用法
1.5.1. 模板变量
java 复制代码
import com.github.hipages.grafana.client.model.TemplateVariable;
import com.github.hipages.grafana.client.model.Query;
import com.github.hipages.grafana.client.model.Datasource;

TemplateVariable templateVariable = new TemplateVariable();
templateVariable.setName("host");
templateVariable.setType("query");
templateVariable.setQuery(new Query("host"));
templateVariable.setDatasource(new Datasource("Graphite"));

dashboard.addTemplateVariable(templateVariable);

client.dashboards().update(dashboard);
1.5.2. 告警和通知
java 复制代码
import com.github.hipages.grafana.client.model.Alert;
import com.github.hipages.grafana.client.model.Condition;
import com.github.hipages.grafana.client.model.Notification;

Alert alert = new Alert();
alert.setName("Metric 1 Alert");
alert.setRuleId(graphPanel.getId());
alert.setMessage("Metric 1 is too high");

Condition condition = new Condition();
condition.setEvalMatches(false);
condition.setOperator("gt");
condition.setQuery("$A");
condition.setThreshold(100);

alert.setConditions(Arrays.asList(condition));

Notification notification = new Notification();
notification.setType("email");
notification.setSettings(Map.of("addresses", Arrays.asList("admin@example.com")));

alert.setNotifications(Arrays.asList(notification));

client.alerts().create(alert);
1.5.3. 权限管理
java 复制代码
import com.github.hipages.grafana.client.model.Role;
import com.github.hipages.grafana.client.model.Permission;

Role role = new Role();
role.setName("Viewer");
role.setPermissions(Arrays.asList(Permission.DASHBOARDS_READ));

client.roles().create(role);

client.dashboards().updatePermissions(dashboard.getId(), Map.of("Viewer", Permission.DASHBOARDS_READ));

2. ECharts Java

2.1. ECharts 简介

ECharts 是一个由百度开发的开源可视化库,基于 HTML5 Canvas 实现,支持多种图表类型,如折线图、柱状图、饼图等。

2.2. ECharts Java 特点

ECharts Java 是一个用于操作 ECharts 的 Java 库,它提供了一系列的 API 来创建和配置各种 ECharts 图表。

2.3. 安装和配置
  1. 添加 Maven 依赖
xml 复制代码
<dependency>
    <groupId>com.github.abel533</groupId>
    <artifactId>echarts</artifactId>
    <version>4.7.0</version>
</dependency>
  1. 创建 ECharts 实例
java 复制代码
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.code.AxisType;
import com.github.abel533.echarts.code.Tool;
import com.github.abel533.echarts.json.GsonOption;
import com.github.abel533.echarts.series.Line;
import com.github.abel533.echarts.series.Pie;

Option option = new Option();
2.4. 基本使用
2.4.1. 创建图表
java 复制代码
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.series.Bar;

CategoryAxis xAxis = new CategoryAxis();
xAxis.data("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");

ValueAxis yAxis = new ValueAxis();
yAxis.setType(AxisType.value);

Bar bar = new Bar();
bar.data(150, 230, 224, 218, 135, 147, 260);

option.setxAxis(xAxis);
option.setyAxis(yAxis);
option.setSeries(bar);
2.4.2. 添加数据
java 复制代码
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.series.Line;

CategoryAxis xAxis = new CategoryAxis();
xAxis.data("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");

ValueAxis yAxis = new ValueAxis();
yAxis.setType(AxisType.value);

Line line = new Line();
line.data(820, 932, 901, 934, 1290, 1330, 1320);

option.setxAxis(xAxis);
option.setyAxis(yAxis);
option.setSeries(line);
2.4.3. 配置图表选项
java 复制代码
import com.github.abel533.echarts.code.Tool;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.feature.MagicType;
import com.github.abel533.echarts.feature.SaveAsImage;

option.setTitle("ECharts Example");
option.setTooltipTrigger(Trigger.axis);
option.setLegendData("Email", "Union Ads", "Video Ads", "Direct", "Search Engine");
option.setToolboxFeature(new MagicType(Tool.line, Tool.bar), new SaveAsImage());
2.5. 高级用法
2.5.1. 自定义图表类型
java 复制代码
import com.github.abel533.echarts.series.Custom;

Custom custom = new Custom();
custom.setRenderItem("myRenderItem");
custom.setData(10, 20, 30, 40, 50);

option.setSeries(custom);
2.5.2. 数据集成
java 复制代码
import com.github.abel533.echarts.series.EffectScatter;
import com.github.abel533.echarts.series.Scatter;

Scatter scatter = new Scatter();
scatter.setSymbolSize(10);
scatter.setData(10, 20, 30, 40, 50);

EffectScatter effectScatter = new EffectScatter();
effectScatter.setSymbolSize(10);
effectScatter.setData(10, 20, 30, 40, 50);

option.setSeries(scatter, effectScatter);
2.5.3. 图表交互
java 复制代码
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.code.AxisType;
import com.github.abel533.echarts.series.Line;

CategoryAxis xAxis = new CategoryAxis();
xAxis.data("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");

ValueAxis yAxis = new ValueAxis();
yAxis.setType(AxisType.value);

Line line1 = new Line();
line1.data(820, 932, 901, 934, 1290, 1330, 1320);

Line line2 = new Line();
line2.data(10, 20, 30, 40, 50, 60, 70);

option.setxAxis(xAxis);
option.setyAxis(yAxis);
option.setSeries(line1, line2);

option.setTooltipAxisPointerType("cross");
option.setTooltipTrigger(Trigger.axis);

3. XChart

3.1. XChart 简介

XChart 是一个用于创建各种图表的 Java 库,支持柱状图、折线图、饼图等多种图表类型。

3.2. XChart 特点

XChart 提供了一系列的 API 来创建和配置各种图表,支持自定义图表样式。

3.3. 安装和配置
  1. 添加 Maven 依赖
xml 复制代码
<dependency>
    <groupId>com.github.knowm</groupId>
    <artifactId>xchart</artifactId>
    <version>3.8.2</version>
</dependency>
  1. 导入包
java 复制代码
import org.knowm.xchart.*;
import org.knowm.xchart.style.Styler.ChartTheme;
import org.knowm.xchart.style.markers.SeriesMarkers;
  1. 配置 XChart
java 复制代码
// 设置图表主题
ChartTheme theme = ChartTheme.Matlab;
XYChart chart = QuickChart.getChart("Sample Chart", "X", "Y", "y = x^2", new double[]{-10, -5, 0, 5, 10}, new double[]{100, 25, 0, 25, 100});
chart.getStyler().setChartTheme(theme);

// 设置图例位置
chart.getStyler().setLegendPosition(LegendPosition.InsideNE);

// 设置标题和子标题
chart.setTitle("XChart Example");
chart.setSubTitle("Subtitle");

// 设置轴标签
chart.getXAxis().setTitle("X Axis");
chart.getYAxis().setTitle("Y Axis");

// 设置网格线
chart.getStyler().setYAxisMinorGridlinesVisible(false);
chart.getStyler().setXAxisMinorGridlinesVisible(false);

// 设置数据点标记
chart.getSeriesMap().get("y = x^2").setMarker(SeriesMarkers.CIRCLE);

// 显示图表
new SwingWrapper<>(chart).displayChart();

注意:在使用 XChart 之前,请确保已经正确安装了 JavaFX。如果您使用的是 IntelliJ IDEA,可以按照以下步骤进行安装:

  1. 打开 File -> Project Structure
  2. 选择 SDKs,点击 "+" 添加新的 SDK
  3. 选择 JavaFX SDK,点击 "Download JDK" 下载 JavaFX SDK
  4. 下载完成后,选择 JavaFX SDK 的安装路径,点击 "OK" 完成安装
  5. 在项目的 Module 设置中,选择 Dependencies 标签页,点击 "+" 添加新的库
  6. 选择 Java,点击 "Next",选择 JavaFX SDK 的安装路径,点击 "OK" 完成添加
  7. 在 Build.gradle 或 pom.xml 文件中添加 XChart 的依赖
  8. 重新构建项目,即可使用 XChart 创建图表了。
3.4. 基本使用
3.4.1. 创建图表
java 复制代码
import org.knowm.xchart.CategoryChart;
import org.knowm.xchart.CategoryChartBuilder;

CategoryChart chart = new CategoryChartBuilder()
        .title("Sample Chart")
        .xAxisTitle("Category")
        .yAxisTitle("Value")
        .build();
3.4.2. 添加数据
java 复制代码
import org.knowm.xchart.CategoryChart;
import org.knowm.xchart.Series;

CategoryChart chart = ... // 创建图表

Series series = chart.addSeries("Series A", 10, 20, 30, 40, 50);
series.setMarkerColor(ChartColor.RED);
3.4.3. 配置图表样式
java 复制代码
import org.knowm.xchart.CategoryChart;
import org.knowm.xchart.SwingWrapper;
import org.knowm.xchart.style.Styler.ChartTheme;

CategoryChart chart = ... // 创建图表

chart.getStyler().setChartTheme(ChartTheme.GGPlot2);
chart.getStyler().setLegendVisible(false);
chart.getStyler().setMarkerSize(10);

new SwingWrapper(chart).displayChart();
3.5. 高级用法
3.5.1. 自定义图表类型
java 复制代码
import org.knowm.xchart.XYChart;
import org.knowm.xchart.XYChartBuilder;
import org.knowm.xchart.XYSeries.XYSeriesRenderStyle;

XYChart chart = new XYChartBuilder()
        .title("Custom Chart")
        .xAxisTitle("X Axis")
        .yAxisTitle("Y Axis")
        .build();

chart.addSeries("Series A", new double[] {1, 2, 3, 4, 5}, new double[] {10, 20, 30, 40, 50})
        .setRenderStyle(XYSeriesRenderStyle.Line);

new SwingWrapper(chart).displayChart();
3.5.2. 图表动画
java 复制代码
import org.knowm.xchart.CategoryChart;
import org.knowm.xchart.SwingWrapper;
import org.knowm.xchart.animation.ChartAnimator;

CategoryChart chart = ... // 创建图表

new SwingWrapper(chart).displayChart();

ChartAnimator animator = new ChartAnimator(chart);
animator.animate(1000); // 持续 1 秒
3.5.3. 图表导出
java 复制代码
import org.knowm.xchart.CategoryChart;
import org.knowm.xchart.BitmapEncoder;

CategoryChart chart = ... // 创建图表

BitmapEncoder.saveBitmap(chart, "./chart.png");

4. JavaFX

4.1. JavaFX 简介

JavaFX 是一个用于创建桌面应用程序和富互联网应用程序的 Java 库,支持各种图形、媒体和控件。

4.2. JavaFX 特点

JavaFX 提供了一系列的 API 来创建和配置各种控件和图形,支持自定义样式和动画。

4.3. 与实时数据可视化库结合使用
  1. 添加 Maven 依赖
xml 复制代码
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-controls</artifactId>
    <version>16</version>
</dependency>
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-fxml</artifactId>
    <version>16</version>
</dependency>
  1. 创建 JavaFX 应用程序
java 复制代码
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("JavaFX Sample");
        primaryStage.setScene(new Scene(root, 800, 600));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
  1. 创建 FXML 文件
xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.chart.LineChart?>
<?import javafx.scene.chart.NumberAxis?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane xmlns="http://javafx.com/javafx/16"
            xmlns:fx="http://javafx.com/fxml/1"
            fx:controller="com.example.Controller">

    <LineChart fx:id="lineChart" title="JavaFX Chart" animated="false" createSymbols="false">
        <xAxis>
            <NumberAxis label="X Axis" autoRanging="false" lowerBound="0" upperBound="10" tickUnit="1"/>
        </xAxis>
        <yAxis>
            <NumberAxis label="Y Axis" autoRanging="false" lowerBound="0" upperBound="100" tickUnit="10"/>
        </yAxis>
    </LineChart>

</AnchorPane>
  1. 创建控制器
java 复制代码
import javafx.fxml.FXML;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;

import java.util.Random;

public class Controller {

    @FXML
    private LineChart<Number, Number> lineChart;

    public void initialize() {
        NumberAxis xAxis = (NumberAxis) lineChart.getXAxis();
        NumberAxis yAxis = (NumberAxis) lineChart.getYAxis();

        XYChart.Series<Number, Number> series = new XYChart.Series<>();
        series.setName("Series A");

        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            series.getData().add(new XYChart.Data<>(i, random.nextInt(100)));
        }

        lineChart.getData().add(series);
    }
}

5. Vaadin

5.1. Vaadin 简介

Vaadin 是一个用于创建 Web 应用程序的 Java 框架,支持各种控件和组件。

5.2. Vaadin 特点

Vaadin 提供了一系列的 API 来创建和配置各种控件和组件,支持自定义样式和事件处理。

5.3. 与实时数据可视化库结合使用
  1. 添加 Maven 依赖
xml 复制代码
<dependency>
    <groupId>com.vaadin</groupId>
    <artifactId>vaadin-charts</artifactId>
    <version>4.4.7</version>
</dependency>
  1. 创建 Vaadin 应用程序
java 复制代码
import com.vaadin.flow.component.page.AppShellConfigurator;
import com.vaadin.flow.server.PWA;
import com.vaadin.flow.theme.Theme;

@Theme("my-theme")
@PWA(name = "My App", shortName = "My App")
public class AppShellConfigurator implements AppShellConfigurator {

    @Override
    public void onInit(AppShellSettings settings) {
    }
}
  1. 创建视图
java 复制代码
import com.vaadin.flow.component.charts.Chart;
import com.vaadin.flow.component.charts.model.ChartType;
import com.vaadin.flow.component.charts.model.Configuration;
import com.vaadin.flow.component.charts.model.Title;
import com.vaadin.flow.component.charts.model.Tooltip;
import com.vaadin.flow.component.charts.model.style.SolidColor;
import com.vaadin.flow.router.Route;

import java.util.Random;

@Route("chart")
public class ChartView extends Div {

    public ChartView() {
        Configuration configuration = getConfiguration();
        Chart chart = new Chart(configuration);
        add(chart);
    }

    private Configuration getConfiguration() {
        Configuration configuration = new Configuration();
        configuration.setChartType(ChartType.LINE);
        configuration.setTitle(new Title("Vaadin Chart"));
        configuration.getTooltip().setValueSuffix(" units");
        configuration.getxAxis().setTitle("X Axis");
        configuration.getyAxis().setTitle("Y Axis");

        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            configuration.addSeries("Series A", new double[] {i}, new double[] {random.nextInt(100)});
        }

        return configuration;
    }
}

6. Birt

6.1. Birt 简介

Birt 是一个用于创建报表的开源 Java 库,支持各种图表、表格和跨表。

6.2. Birt 特点

Birt 提供了一系列的 API 来创建和配置各种报表,支持自定义样式和数据源。

6.3. 与实时数据可视化库结合使用
  1. 添加 Maven 依赖
xml 复制代码
<dependency>
    <groupId>org.eclipse.birt.runtime</groupId>
    <artifactId>org.eclipse.birt.runtime</artifactId>
    <version>4.8.0</version>
</dependency>
  1. 创建 Birt 报表
java 复制代码
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;

public class BirtReport {

    public void generateReport() {
        EngineConfig config = new EngineConfig();
        Platform.startup(config);
        IReportEngineFactory factory = (IReportEngineFactory) Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
        IReportEngine engine = factory.createReportEngine(config);

        IReportRunnable design = engine.openReportDesign("report.rptdesign");
        IRunAndRenderTask task = engine.createRunAndRenderTask(design);

        task.setRenderOption(new RenderOption());
        task.setAppContext(new AppContext());
        task.run();
        task.close();

        engine.destroy();
        Platform.shutdown();
    }
}

7. JFreeChart

7.1. JFreeChart 简介

JFreeChart 是一个用于创建各种图表的 Java 库,支持柱状图、折线图、饼图等多种图表类型。

7.2. JFreeChart 特点

JFreeChart 提供了一系列的 API 来创建和配置各种图表,支持自定义图表样式。

7.3. 与实时数据可视化库结合使用
  1. 添加 Maven 依赖
xml 复制代码
<dependency>
    <groupId>org.jfree</groupId>
    <artifactId>jfreechart</artifactId>
    <version>1.5.3</version>
</dependency>
  1. 创建 JFreeChart 图表
java 复制代码
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame;

import java.awt.EventQueue;

public class JFreeChartExample extends ApplicationFrame {

    public JFreeChartExample(String title) {
        super(title);
        setContentPane(createChartPanel());
    }

    private ChartPanel createChartPanel() {
        JFreeChart chart = ChartFactory.createLineChart(
                "JFreeChart Example",
                "X Axis",
                "Y Axis",
                createDataset(),
                PlotOrientation.VERTICAL,
                true, true, false);

        return new ChartPanel(chart);
    }

    private DefaultCategoryDataset createDataset() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        dataset.addValue(10.0, "Series A", "Category 1");
        dataset.addValue(20.0, "Series A", "Category 2");
        dataset.addValue(30.0, "Series A", "Category 3");
        dataset.addValue(40.0, "Series A", "Category 4");
        dataset.addValue(50.0, "Series A", "Category 5");
        return dataset;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            JFreeChartExample example = new JFreeChartExample("JFreeChart Example");
            example.setVisible(true);
        });
    }
}

8. JasperReports

8.1. JasperReports 简介

JasperReports 是一个用于创建报表的 Java 库,支持各种图表、表格和跨表。

8.2. JasperReports 特点

JasperReports 提供了一系列的 API 来创建和配置各种报表,支持自定义样式和数据源。

8.3. 与实时数据可视化库结合使用
  1. 添加 Maven 依赖
xml 复制代码
<dependency>
    <groupId>net.sf.jasperreports</groupId>
    <artifactId>jasperreports</artifactId>
    <version>6.17.0</version>
</dependency>
  1. 创建 JasperReports 报表
java 复制代码
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JasperReportExample {

    public void generateReport() throws Exception {
        String jrxmlFile = "report.jrxml";
        JasperReport jasperReport = JasperCompileManager.compileReport(jrxmlFile);

        List<ReportBean> reportBeans = new ArrayList<>();
        reportBeans.add(new ReportBean("Category 1", 10.0));
        reportBeans.add(new ReportBean("Category 2", 20.0));
        reportBeans.add(new ReportBean("Category 3", 30.0));
        reportBeans.add(new ReportBean("Category 4", 40.0));
        reportBeans.add(new ReportBean("Category 5", 50.0));

        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(reportBeans);
        Map<String, Object> parameters = new HashMap<>();
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);

        JasperExportManager.exportReportToPdfFile(jasperPrint, new File("report.pdf").getAbsolutePath());
    }

    public static class ReportBean {

        private String category;
        private double value;

        public ReportBean(String category, double value) {
            this.category = category;
            this.value = value;
        }

        public String getCategory() {
            return category;
        }

        public void setCategory(String category) {
            this.category = category;
        }

        public double getValue() {
            return value;
        }

        public void setValue(double value) {
            this.value = value;
        }
    }
}

总结

本文从多个方面对比了八个Java实时数据可视化库,从特点、安装和配置、基本使用、高级用法等方面进行了详细介绍。这些库各有优缺点和适用场景,选择最适合自己的工具需要结合实际情况综合考虑。通过本文的学习,您可以更好地理解这些库,提高数据可视化能力,更好地应对工作中的需求。

相关推荐
晴子呀13 分钟前
Spring底层原理大致脉络
java·后端·spring
只吹45°风19 分钟前
Java-ArrayList和LinkedList区别
java·arraylist·linkedlist·区别
阿华的代码王国27 分钟前
【JavaEE】多线程编程引入——认识Thread类
java·开发语言·数据结构·mysql·java-ee
黑蛋同志27 分钟前
array和linked list的区别
java
andrew_121933 分钟前
腾讯 IEG 游戏前沿技术 一面复盘
java·redis·sql·面试
寻求出路的程序媛41 分钟前
JVM —— 类加载器的分类,双亲委派机制
java·jvm·面试
这孩子叫逆43 分钟前
35. MyBatis中的缓存失效机制是如何工作的?
java·spring·mybatis
骆晨学长43 分钟前
基于SpringBoot的校园失物招领系统
java·spring boot
汇匠源43 分钟前
零工市场小程序:保障灵活就业
java·小程序·零工市场
计算机编程-吉哥1 小时前
计算机毕业设计 二手图书交易系统 Java+SpringBoot+Vue 前后端分离 文档报告 代码讲解 安装调试
java·spring boot·毕业设计·毕业论文·计算机毕业设计选题·计算机毕业设计开题报告·二手图书交易系统