用JAVA编写一个饼图

以下是一个使用Java编写的生成饼图的简单示例:

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

public class PieChart extends JPanel {
    private double[] values;
    private String[] labels;
    private Color[] colors;

    public PieChart(double[] values, String[] labels, Color[] colors) {
        this.values = values;
        this.labels = labels;
        this.colors = colors;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        int width = getWidth();
        int height = getHeight();
        int radius = Math.min(width, height) / 2;
        int centerX = width / 2;
        int centerY = height / 2;

        double total = 0;
        for (double value : values) {
            total += value;
        }

        double startAngle = 0;
        for (int i = 0; i < values.length; i++) {
            double arcAngle = values[i] / total * 360;
            g2d.setColor(colors[i]);
            g2d.fill(new Arc2D.Double(centerX - radius, centerY - radius, 2 * radius, 2 * radius, startAngle, arcAngle, Arc2D.PIE));
            startAngle += arcAngle;
        }

        int legendX = centerX + radius + 10;
        int legendY = centerY - radius;
        for (int i = 0; i < labels.length; i++) {
            g2d.setColor(colors[i]);
            g2d.fillRect(legendX, legendY + i * 20, 10, 10);
            g2d.setColor(Color.BLACK);
            g2d.drawString(labels[i], legendX + 15, legendY + i * 20 + 10);
        }
    }

    public static void main(String[] args) {
        double[] values = {30, 20, 10, 40};
        String[] labels = {"Label 1", "Label 2", "Label 3", "Label 4"};
        Color[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.ORANGE};

        JFrame frame = new JFrame("Pie Chart");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setLocationRelativeTo(null);

        PieChart chart = new PieChart(values, labels, colors);
        frame.add(chart);

        frame.setVisible(true);
    }
}

在示例中,我们创建了一个继承自JPanel的类PieChart,用于绘制饼图。构造函数接受三个参数:饼图的值、标签和颜色。我们重写了paintComponent方法,在该方法中进行绘图操作。

在paintComponent方法中,我们首先获取组件的宽度、高度和半径。然后,计算出总和值total。接下来,使用Arc2D.Double类绘制每个饼块,并根据值的比例计算出饼块的角度。最后,我们绘制图例,显示每个饼块对应的标签和颜色。

在main方法中,我们创建了一个JFrame窗口,并将创建的PieChart实例添加到窗口中显示出来。

你可以根据需要修改值、标签和颜色,以及窗口的大小。运行程序后,将会显示一个饼图。

你可能感兴趣的:(java技术教程,java,开发语言)