2012-08-03 39 views
1

我在图表上显示一条线时出现问题。我有一个JFreeChart,如果我使用paintComponent()如下,我看到的行,但没有看到图表。预先感谢您的帮助。用ChartPanel覆盖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); 
    } 
} 

**我想我smthg错的JFrameJPanel但找不出我的错误;完整的代码发布。

+0

为什么要使用g.create(),是类型转换的G2对象无法正常工作。请移除.create()并检查一次 – 2012-08-03 17:12:49

+0

您可以使用g本身绘制相同的字符串。即g.setColor()..... – 2012-08-03 17:14:31

+0

我只是试验,因为它不工作,不管是否使用g或g2.I可以看到该行,但没有图表 – Georg 2012-08-03 17:36:03

回答

1

你的paintComponent()覆盖应该调用

super.paintComponent(g); 

super.paintComponents(g); 
+0

:)垃圾你是对的..现在它工作..thx非常.. – Georg 2012-08-04 11:02:47