I have a problem displaying a line on a chart. I have a JFreeChart
and if I use paintComponent()
as below, I see the line but not the chart. Thanks in advance for any help.
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);
}
}
**I think I do smthg wrong with the JFrame
and JPanel
but can't figure my mistake; full code posted.
Your override of paintComponent()
should invoke
super.paintComponent(g);
not
super.paintComponents(g);