使用ChartPanel覆盖paintComponent

时间:2012-08-03 17:06:46

标签: java jfreechart paintcomponent

我在图表上显示一条线时遇到问题。我有一个JFreeChart,如果我使用paintComponent(),如下所示,我会看到该行而不是图表。提前感谢您的帮助。

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jfree.chart.*;
import org.jfree.data.general.SeriesException;
import org.jfree.data.time.*;
import org.jfree.data.xy.XYDataset;

public class TestChartPanel extends JPanel {

    private static XYDataset createDataset() {

        final TimeSeries series = new TimeSeries("Random Data");
        Day current = new Day(1, 1, 1990);
        double value = 100.0;
        for (int i = 0; i < 4000; i++) {
            try {
                value = value + Math.random() - 0.5;
                series.add(current, new Double(value));
                current = (Day) current.next();
            } catch (SeriesException e) {
                System.err.println("Error adding to series");
            }
        }
        return new TimeSeriesCollection(series);
    }

    private static JFreeChart createChart(final XYDataset dataset) {
        JFreeChart chart = ChartFactory.createTimeSeriesChart(
            "Test",
            "Day",
            "Value",
            dataset,
            false,
            false,
            false);
        return chart;
    }

    /**
    * @param args
    */
    public static void main(String[] args) {

        JFrame f = new JFrame();
        XYDataset xyd = createDataset();
        JFreeChart jfc = createChart(xyd);
        ChartPanel cPanel = new ChartPanel(jfc) {

            /**
            *
            */
            private static final long serialVersionUID = 1L;

            public void paintComponent(Graphics g) {
                super.paintComponents(g);

                System.out.println("paooooooooooooooooooooooo");
                g.setColor(Color.RED);

                g.drawLine(100, 100, 200, 200);
            }
        };
        JPanel jp = new JPanel();
        jp.add(cPanel);
        f.getContentPane().add(jp);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }
}

**我认为我对JFrameJPanel犯了错误,但无法弄清楚我的错误;完整的代码发布。

1 个答案:

答案 0 :(得分:1)

您的paintComponent()覆盖应该调用

super.paintComponent(g);

不是

super.paintComponents(g);