Home > Java > javaTutorial > How to implement data visualization and chart display of form data in Java?

How to implement data visualization and chart display of form data in Java?

WBOY
Release: 2023-08-11 09:39:19
Original
1162 people have browsed it

How to implement data visualization and chart display of form data in Java?

How to implement data visualization and chart display of form data in Java?

Overview:
In modern software development, data visualization and chart display are one of the very important functions. Especially when processing large amounts of data, chart display can present the data more intuitively and clearly, and help users better understand and analyze the data. This article will introduce how to use common open source libraries to realize data visualization and chart display of form data in Java.

1. Choose the appropriate open source library
In Java, there are many excellent open source chart libraries to choose from, such as JFreeChart, Chart.js and Apache POI. When choosing a library, you need to evaluate it based on your own needs, such as whether the types of charts are complete, whether it is easy to integrate and use, etc.

2. Collect and process form data
Before realizing data visualization, you first need to collect and process form data. Form data can be obtained through common methods, including querying from the database, collecting through network interfaces, etc. Once the data is obtained, data visualization can begin.

3. Use JFreeChart to achieve data visualization
JFreeChart is a powerful Java chart library that provides a rich range of chart types and styles. The following is a sample code that uses JFreeChart to implement a histogram:

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

import javax.swing.*;
import java.awt.*;

public class DataVisualizationExample extends JFrame {
    public DataVisualizationExample() {
        setTitle("数据可视化示例");
        setSize(500, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        dataset.setValue(80, "成绩", "语文");
        dataset.setValue(90, "成绩", "数学");
        dataset.setValue(70, "成绩", "英语");

        JFreeChart chart = ChartFactory.createBarChart(
                "学生成绩统计", // 图表标题
                "科目", // 横轴标题
                "成绩", // 纵轴标题
                dataset, // 数据集
                PlotOrientation.VERTICAL, // 图表方向
                true, // 是否显示图例
                true, // 是否生成工具
                false // 是否生成URL链接
        );

        ChartPanel chartPanel = new ChartPanel(chart);
        setContentPane(chartPanel);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            DataVisualizationExample example = new DataVisualizationExample();
            example.setVisible(true);
        });
    }
}
Copy after login

The above code demonstrates how to use JFreeChart to create a simple histogram and display it in a graphical interface.

4. Use Chart.js to realize chart display
Chart.js is a JavaScript chart library based on HTML5 Canvas, which can be used directly in web pages. Unlike JFreeChart, Chart.js is implemented through JavaScript code, so charts can be used directly on the front-end page.

The following is a sample code for using Chart.js to implement a pie chart:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图表展示示例</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <canvas id="myChart" height="400" width="400"></canvas>
    <script>
        var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'pie',
            data: {
                labels: ['语文', '数学', '英语'],
                datasets: [{
                    label: '学生成绩',
                    data: [80, 90, 70],
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.7)',
                        'rgba(54, 162, 235, 0.7)',
                        'rgba(255, 206, 86, 0.7)'
                    ],
                    borderColor: [
                        'rgba(255, 99, 132, 1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(255, 206, 86, 1)'
                    ],
                    borderWidth: 1
                }]
            },
            options: {}
        });
    </script>
</body>
</html>
Copy after login

Open the above HTML page in the browser, and you can see a simple pie chart display.

5. Use Apache POI to visualize tabular data
Apache POI is a Java library used to operate Microsoft Office format files (such as Excel). Using Apache POI, form data can be exported to an Excel file and displayed in the form of a table in the file.

The following is a sample code that uses Apache POI to export form data to an Excel file:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class TableVisualizationExample {
    public static void main(String[] args) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("成绩表");

            String[] headers = {"科目", "成绩"};
            Object[][] data = {{"语文", 80}, {"数学", 90}, {"英语", 70}};

            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            for (int i = 0; i < data.length; i++) {
                Row row = sheet.createRow(i + 1);
                for (int j = 0; j < data[i].length; j++) {
                    Cell cell = row.createCell(j);
                    if (data[i][j] instanceof String) {
                        cell.setCellValue((String) data[i][j]);
                    } else if (data[i][j] instanceof Integer) {
                        cell.setCellValue((Integer) data[i][j]);
                    }
                }
            }

            try (FileOutputStream outputStream = new FileOutputStream("成绩表.xlsx")) {
                workbook.write(outputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Copy after login

The above code writes the form data into an Excel file in the form of a table and saves it as a "score table" .xlsx".

Conclusion:
This article introduces how to implement data visualization and chart display of form data in Java. By choosing appropriate open source libraries, such as JFreeChart, Chart.js and Apache POI, we can display various charts simply and quickly. I hope this article can be helpful to readers in their data visualization work in Java development.

The above is the detailed content of How to implement data visualization and chart display of form data in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template