如何将JFreeChart图表插入到单独GUI上的面板中?

时间:2017-03-25 11:14:51

标签: java swing jpanel jfreechart

我需要使用JFreeChart将图表放入GUI类文件中的新面板。我有3个Java文件:一个带有调用饼图生成器的按钮,一个用于创建饼图,另一个用于需要显示饼图。我有一个创建图表的按钮:

PieChartGenerator tweetSource = new PieChartGenerator(
    "Comparison", "What device are people using to Tweet?");
tweetSource.pack();
tweetSource.setVisible(true);

特定的GUI类文件被称为" Graphs",并且Panel被称为" sourcePieChartPanel"。创建图表的代码如下:

public class PieChartGenerator extends JFrame {

public PieChartGenerator(String applicationTitle, String chartTitle) throws IOException {
    super(applicationTitle);

    PieDataset dataset = createDataset();
    JFreeChart chart = createChart(dataset, chartTitle);

    ChartPanel pieChartPanel = new ChartPanel(chart);
    pieChartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
    setContentPane(pieChartPanel);
}

/**
 * Creates a sample dataset
 */
private PieDataset createDataset() throws IOException {
    DefaultPieDataset result = new DefaultPieDataset();
    File file = new File("C:\\Users\\markc\\OneDrive\\Documents\\NetBeansProjects\\TwitterProject\\src\\text\\pieChartSource.txt");
    Scanner s = new Scanner(file);
    int twitterWebClient = 0;
    int tweetDeck = 0;
    int android = 0;
    int iphone = 0;
    int hootsuite = 0;
    int other = 0;

    while (s.hasNext()) {
        String Scan = s.nextLine();
        if (Scan.contains("Twitter Web Client")) {
            twitterWebClient++;
        } else if (Scan.contains("TweetDeck")) {
            tweetDeck++;
        } else if (Scan.contains("Twitter for Android")) {
            android++;
        } else if (Scan.contains("Twitter for iPhone")) {
            iphone++;
        } else if (Scan.contains("Hootsuite")) {
            iphone++;
        } else {
            other++;
        }
    }
    s.close();

    result.setValue("Twitter Web Client " + twitterWebClient, twitterWebClient);
    result.setValue("TweetDeck " + tweetDeck, tweetDeck);
    result.setValue("Android " + android, android);
    result.setValue("IPhone " + iphone, iphone);
    result.setValue("Hootsuite " + hootsuite, hootsuite);
    result.setValue("Other " + other, other);
    return result;

}

/**
 * Creates a chart
 */
private JFreeChart createChart(PieDataset dataset, String title) {

    JFreeChart chart = ChartFactory.createPieChart3D(title, dataset, true, true, false);

    PiePlot3D plot = (PiePlot3D) chart.getPlot();
    plot.setStartAngle(290);
    plot.setDirection(Rotation.CLOCKWISE);
    plot.setForegroundAlpha(0.5f);
    return chart;

}

这将创建饼图并将其放入名为pieChartPanel的新内容面板中。我如何实现这一点,以便新图表显示在名为Graphs的类文件的面板中?

0 个答案:

没有答案