2012-06-25 6 views
0

this thread의 코드를 사용하여 timeseries JFreeChart를 개발했습니다. 네 개의 다른 패널이 포함 된 내 메인 패널에 추가하고 싶습니다. 그래서 나는 방법JFreeChart timeseries가 새로 고침되지 않습니다

package com.garnet.panel; 

    import java.awt.*; 
    import java.awt.event.*; 
    import java.text.*; 
    import java.text.SimpleDateFormat; 
    import java.util.Calendar; 
    import java.util.GregorianCalendar; 
    import javax.swing.JPanel; 
    import javax.swing.Timer; 
    import org.jfree.chart.ChartFactory; 
    import org.jfree.chart.ChartPanel; 
    import org.jfree.chart.JFreeChart; 
    import org.jfree.chart.axis.*; 
    import org.jfree.chart.plot.XYPlot; 
    import org.jfree.chart.renderer.xy.XYItemRenderer; 
    import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; 
    import org.jfree.data.time.DynamicTimeSeriesCollection; 
    import org.jfree.data.time.Second; 
    import org.jfree.data.xy.XYDataset; 
    import org.jfree.ui.RectangleInsets; 
    import org.jfree.ui.RefineryUtilities; 


    public class PrepareChart { 

    private static final String TITLE = "Dynamic Series"; 
    private static final int COUNT = 2 * 60; 
    private Timer timer; 
    private static float lastValue = 49.62f; 
    ValueAxis axis; 
    DateAxis dateAxis; 
    public JFreeChart chart; 
    public PrepareChart() { 
     super(); 

     final DynamicTimeSeriesCollection dataset = new DynamicTimeSeriesCollection(1, COUNT, new Second()); 

     // Get the calender date time which will inserted into time series chart 
     // Based on time we are getting here we disply the chart 
     Calendar calendar = new GregorianCalendar(); 
     int date = calendar.get(Calendar.DAY_OF_MONTH); 
     int month = calendar.get(Calendar.MONTH); 
     int year = calendar.get(Calendar.YEAR); 
     int hours = calendar.get(Calendar.HOUR_OF_DAY); 
     int minutes = calendar.get(Calendar.MINUTE); 
     int seconds = calendar.get(Calendar.SECOND); 
     System.out.println("In caht constructor methoed"); 
     dataset.setTimeBase(new Second(seconds, minutes-2, hours, date, month, year)); 
     dataset.addSeries(gaussianData(), 0, "Currency Rate"); 

     chart= createChart(dataset); 

     timer = new Timer(969, new ActionListener() { 

      float[] newData = new float[1]; 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       newData[0] = randomValue(); 
       System.out.println("In caht timer methoed"); 
       dataset.advanceTime(); 
       dataset.appendData(newData); 
      } 
     }); 


    } 

    private float randomValue() { 

     double factor = 2 * Math.random(); 
     if (lastValue >51){ 
     lastValue=lastValue-(float)factor; 
     }else { 
     lastValue = lastValue + (float) factor; 
     } 
     return lastValue; 
    } 
    // For getting the a random float value which is supplied to dataset of time series chart 
    private float[] gaussianData() { 
     float[] a = new float[COUNT]; 
     for (int i = 0; i < a.length; i++) { 
      a[i] = randomValue(); 
     } 
     return a; 
    } 

    // This methode will create the chart in the required format 
    private JFreeChart createChart(final XYDataset dataset) { 

     final JFreeChart result = ChartFactory.createTimeSeriesChart(TITLE, "hh:mm:ss", "Currency", dataset, true, true, false); 

     final XYPlot plot = result.getXYPlot(); 

     plot.setBackgroundPaint(Color.BLACK); 
     plot.setDomainGridlinePaint(Color.WHITE); 
     plot.setRangeGridlinePaint(Color.WHITE); 
     plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); 
     plot.setDomainCrosshairVisible(true); 
     plot.setRangeCrosshairVisible(true); 

     XYItemRenderer r = plot.getRenderer(); 

     if (r instanceof XYLineAndShapeRenderer) { 

      XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r; 
       renderer.setBaseShapesVisible(true); 

       renderer.setBaseShapesFilled(true); 
       renderer.setBasePaint(Color.white); 
       renderer.setSeriesPaint(0,Color.magenta); 
     } 

     dateAxis= (DateAxis)plot.getDomainAxis(); 

     DateTickUnit unit = null; 
     unit = new DateTickUnit(DateTickUnitType.SECOND,30); 

     DateFormat chartFormatter = new SimpleDateFormat("HH:mm:ss"); 
     dateAxis.setDateFormatOverride(chartFormatter); 
     dateAxis.setTickUnit(unit);  

     NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); 
     rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); 
     rangeAxis.setRange(lastValue-4, lastValue+4); 

     return result; 
    } 

    public void start(){ 
     timer.start(); 
    } 


    public JPanel getChartPanel(){ 

     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       PrepareChart chart = new PrepareChart(); 
       System.out.println("In caht getter methoed"); 
       chart.start(); 
      } 
     }); 
     return new ChartPanel(chart); 
    } 

} 

나는이 같은 내 패널 생성자 중 하나 내부에이 코드를 호출하고 생성 :

public class ChartPanel extends JPanel{ 

    private Dimension dim; 
    private PrepareChart chart; 
    public JPanel jChart; 

    public ChartPanel(){ 
     dim = super.getToolkit().getScreenSize(); 
     this.setBounds(2,2,dim.width/4,dim.height/4); 
     chart = new PrepareChart(); 
     jChart =chart.getChartPanel();  

     this.add(jChart); 
    } 

을하지만 프레임에이 패널을 추가 할 때, 그래프는 동적으로 변화되지 않습니다.

+1

코드가 컴파일되지 않습니다. 질문을 수정하고 [SSCCE] (http://sscce.org)를 제공하십시오. –

+0

모든 코드를 추가 했으므로 컴파일 할 때 jfreechart 라이브러리가 필요합니다. – mallikarjun

답변

3

그래, 내가 문제를 발견했다고 생각하지만이 코드를 어떻게 사용하는지 완전히 알 수는 없다.

귀하의 주요 문제는 여기에있다 :

public JPanel getChartPanel(){ 

     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       PrepareChart chart = new PrepareChart(); 
       System.out.println("In caht getter methoed"); 
       chart.start(); 
      } 
     }); 
     return new ChartPanel(chart); 
    } 

당신의 Runnable, 당신은 PrepareChart의 새로운 인스턴스를 다시 당신은 그것을 시작합니다. 이것은 어떤 이해가되지 않습니다 :

  1. 귀하의 둘러싸는 인스턴스가 시작되지 않습니다 PrepareChart 그래서 누구/무엇에 의해 도달 할 수없는
  2. 당신이 당신의 실행 가능한에서 만드는 인스턴스 (따라서 당신은 동적 업데이트를 참조하지 않음) AWT 이벤트 큐에서 영원히 잃어 버리면 인스턴스.

그래서 대신에, 나는 단지 다음 사용하는 것입니다 :

public JPanel getChartPanel() { 

    EventQueue.invokeLater(new Runnable() { 
     @Override 
     public void run() { 
      start(); 
     } 
    }); 
    return new ChartPanel(chart); 
} 

이 트릭을 할 것 같았다 내가 쓴 작은 주요 방법이다.

public static void main(String[] args) { 
    PrepareChart prepareChart = new PrepareChart(); 
    JFrame frame = new JFrame(); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.add(prepareChart.getChartPanel()); 
    frame.pack(); 
    frame.setVisible(true); 
} 

는 혼란 된 JFreeChart의 이름과 충돌하기 때문에 클래스 ChartPanel 이름을 바꾸는 것이 좋습니다. 또한 PrepareChart에서 반환 한 ChartPanel에서 직접 모든 작업을 수행 할 수 있으므로 사용법은 알 수 없습니다.

Btw, getter-method에서 start()을 호출하는 것은 상당히 이상합니다.

+0

감사합니다 그것은 나를 위해 잘 작동하고 그것은 그래프를 보여주는 프레임을 최소화하고 최대화 할 때 차트를 보여주지 않습니다. – mallikarjun

+0

@mallikarjun는 JFrame을'visible() '하기 전에'pack()'을 호출하는 것을 고려합니다 . 표시가 된 후에는 컴포넌트를 추가/제거 할 때마다 컨테이너에서'revalidate()'를 호출하십시오. –

+0

예 컨테이너 (chatpanel 클래스)에서 revalidate를 호출했지만 작동하지 않습니다 – mallikarjun

관련 문제