java - 如何将文字放入饼图的标签中

标签 java swing

我需要将标签和颜色放入每个切片中。所以它应该是“Global -- 20%”并带有颜色。 我还是个初学者,请帮助我!!

import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.text.*;
import javax.swing.*;

public class PieChart
{
    public static void main(String[] args)
    {
        JFrame f = new JFrame("CMIS242 PieChart");
        f.getContentPane().add(new PieChartPanel());
        f.setSize(400,400);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}
 class PieChartPanel extends JPanel
{
    BufferedImage image;
    final int PAD = 30;
    Font font;
    NumberFormat numberFormat;

  public PieChartPanel()
    {
        font = new Font("Comic Sans", Font.BOLD, 18);
        numberFormat = NumberFormat.getPercentInstance();
        addMouseListener(new Visibility(this));
        addComponentListener(new ComponentAdapter()
        {});
    }
 protected void paintComponent(Graphics graphics)
    {
        super.paintComponent(graphics);
        Graphics2D graphics2d = (Graphics2D)graphics;
        graphics2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        createChartImage();
        graphics2d.drawImage(image, 0, 0, this);
    }
    private void createChartImage()
    {
        int[] marks = {10, 24, 30, 36};
        int width = getWidth();
        int height = getHeight();
        int cp = width/2;
        int cq = height/2;
        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        g2.setPaint(Color.white);
        g2.fillRect(0, 0, width, height);
        g2.setPaint(Color.black);
        int pie = Math.min(width,height) - 2*PAD;
        g2.draw(new Ellipse2D.Double(cp - pie/2, cq - pie/2, pie, pie));
        double total = 0;
        for(int j = 0; j < marks.length; j++)
            total += marks[j];
        double theta = 0, phi = 0;
        double p, q;
        for(int j = 0; j < marks.length; j++)
        {
            p = cp + (pie/2) * Math.cos(theta);
            q = cq + (pie/2) * Math.sin(theta);
            g2.draw(new Line2D.Double(cp, cq, p, q));
            phi = (marks[j]/total) * 2 * Math.PI;
            p = cp + (9*pie/24) * Math.cos(theta + phi/2);
            q = cq + (9*pie/24) * Math.sin(theta + phi/2);
            g2.setFont(font);
            String st = String.valueOf(marks[j]);
            FontRenderContext frc = g2.getFontRenderContext();
            float textWidth = (float)font.getStringBounds(st, frc).getWidth();
            LineMetrics lm = font.getLineMetrics(st, frc);
            float sp = (float)(p - textWidth/2);
            float sq = (float)(q + lm.getAscent()/2);
            p = cp + (pie/2 + 4*PAD/5) * Math.cos(theta + phi/2);
            q = cq + (pie/2 + 4*PAD/5) * Math.sin(theta+ phi/2);
            st = numberFormat.format(marks[j]/total);
            textWidth = (float)font.getStringBounds(st, frc).getWidth();
            lm = font.getLineMetrics(st, frc);
            sp = (float)(p - textWidth/2);
            sq = (float)(q + lm.getAscent()/2);
            g2.drawString(st, sp, sq);
            theta += phi;
        }
        //g2.dispose();
    }
 public void toggleVisibility()
    {
        repaint();
    }
}
class Visibility extends MouseAdapter
{
    PieChartPanel piechart;
public Visibility(PieChartPanel pc)
    {
        piechart = pc;
    }
 public void mousePressed(MouseEvent event)
    {
        if(event.getClickCount() > 1)
            piechart.toggleVisibility();
    }
}

最佳答案

使用此函数在饼图中显示标签。

 private PieDataset createSampleDataset() 
 {
    final DefaultPieDataset result = new DefaultPieDataset();
    result.setValue("Java", new Double(20));
    result.setValue("Visual Basic", new Double(20));
    result.setValue("C/C++", new Double(20));
    result.setValue("PHP", new Double(20));
    result.setValue("Perl", new Double(20));
    return result;
  }

看这个例子:

package piechart3D;

import java.text.AttributedString;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.PieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
import org.jfree.util.Rotation;


public class Piechart3D extends ApplicationFrame
{
    public Piechart3D(final String title) 
    {
    super(title);
    final PieDataset dataset = createSampleDataset();
    final JFreeChart chart = createChart(dataset);
    final ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
    setContentPane(chartPanel);

}
private PieDataset createSampleDataset() 
{
    final DefaultPieDataset result = new DefaultPieDataset();
    result.setValue("Java", new Double(20));
    result.setValue("Visual Basic", new Double(20));
    result.setValue("C/C++", new Double(20));
    result.setValue("PHP", new Double(20));
    result.setValue("Perl", new Double(20));
    return result;
}

private JFreeChart createChart(final PieDataset dataset) 
{
    final JFreeChart chart = ChartFactory.createPieChart3D(
        "3D Pie Chart",  // chart title
        dataset,                // data
        true,                   // include legend
        true,
        false
    );

    final PiePlot3D plot = (PiePlot3D) chart.getPlot();
    plot.setStartAngle(290);
    plot.setDirection(Rotation.CLOCKWISE);
    plot.setForegroundAlpha(0.5f);
    plot.setNoDataMessage("No data to display");
    plot.setLabelGenerator(new CustomLabelGenerator() {

        @Override
        public AttributedString generateAttributedSectionLabel(PieDataset pd, Comparable cmprbl) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    });
    return chart;

}

/**
 * Starting point for the demonstration application.
 *
 * @param args  ignored.
 */
public static void main(final String[] args) {

    final Piechart3D demo = new Piechart3D("3D Pie Chart");
    demo.pack();
    RefineryUtilities.centerFrameOnScreen(demo);
    demo.setVisible(true);

}

/**
 * A custom label generator (returns null for one item as a test).
 */
static abstract class CustomLabelGenerator implements PieSectionLabelGenerator {
    /**
     * Generates a label for a pie section.
     * 
     * @param dataset  the dataset (<code>null</code> not permitted).
     * @param key  the section key (<code>null</code> not permitted).
     * 
     * @return the label (possibly <code>null</code>).
     */
    @Override
    public String generateSectionLabel(final PieDataset dataset, final Comparable key) {
        String result = null;    
        if (dataset != null) {
            if (!key.equals("I-Phone")) 
            {
                result = key.toString();   
            }
        }
        return result;
    }

}

}

谢谢..

关于java - 如何将文字放入饼图的标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21519774/

相关文章:

Windows 系统上的 java7 : Files. walkFileTree() 和 "System Volume information"

java - Jquery Webcam插件使用java将图像上传到服务器

java - Java中RNA序列转换为蛋白质的高效方法,以及arrayoutofbound错误

java - 我想在文本字段失去焦点后立即获取文本。为此,我尝试使用 "this"运算符,但它不起作用

java - 为 JButton 提供多个鼠标点击选项(二十一点游戏)

java - 如何用其他字符替换字符串中的 1 个或多个字符?

java - 仅针对选定情况对 JDBC 连接进行多线程访问

java - 在 showConfirmDialog 中按 OK 后获取值

java - JTable 单元格中的多个 JCheckBoxes

java - 在 IntelliJ 上访问在 GUI 设计器中创建的组件