2011-09-14 16 views
3

如何畫不同顏色不同的酒吧,我試圖用渲染器,這裏是我的示例代碼:在XYJfree圖表自定義欄的顏色

public IntervalXYDataset createDataset() throws InterruptedException { 
    parseFile(); 
    final XYSeries series = new XYSeries("Analysis"); 

    int i=0; 
    while(parsedArray[i]!=0) 
     { 

     series.add(xaxisArray[i], yaxisArray[i]); 

     i++; 
    } 

    final XYSeriesCollection dataset = new XYSeriesCollection(series); 

    dataset.setIntervalWidth(0.15);//set width here 

    return dataset; 
} 

,這是怎麼了圖形繪製:

public className (final String title) throws InterruptedException { 
    super(title); 
    IntervalXYDataset dataset = createDataset(); 
    JFreeChart chart = createChart(dataset); 
    final ChartPanel chartPanel = new ChartPanel(chart); 
    XYPlot plot = (XYPlot) chart.getPlot(); 
    plot.getRenderer().setSeriesPaint(0, Color.black);//0 works and paints all 40 bars in black, 1 and above fails. 
      // plot.getRenderer().setSeriesPaint(1, Color.green);// this fails 
    chartPanel.setPreferredSize(new java.awt.Dimension(2000,1000));//(width,height) of display 
    setContentPane(chartPanel); 

} 

我可以設置寬度,因爲我在我的程序有評論,但是我現在要爲不同的酒吧的顏色,例如我想吧握在圖表,繪製紅色陣列[3]爲藍色,c爲橙色埃爾[17],請你指導我這個。非常感謝你。


回答

2

我找到了答案 創建兩個系列,然後添加您想要的有多少條,併爲每個系列設置顏色。使用setSeriesPaint

3

你想要做的是以下幾點:

XYPlot plot = (XYPlot) chart.getPlot(); 
plot.getRenderer().setSeriesPaint(1, Color.yellow); 

更換1,其顏色要改變欄(從零開始)指數。

編輯迴應評論:

List<Color> myBarColors = ..... 

XYPlot plot = (XYPlot) chart.getPlot(); 
XYItemRenderer renderer = plot.getRenderer(); 

for (int i = 0; i < 40; i++) { 
    renderer.setSeriesPaint(i, myBarColors.get(i)); 
} 

編輯2:被誤讀的有機磷農藥的問題,在評論新的解決方案。

+0

這是一個直截了當的方法;但是'Color.yellow'是第四種默認顏色,所以它會失敗超過三個系列。 – trashgod

+0

你好,我試過這樣做,它的值爲'0',如setSeriesPaint(0,Color.yellow);但我有大約40個酒吧 - 這個循環40次:-(series.add(xaxisArray [i],yaxisArray [i]);)你能幫我解決這個錯誤。我想爲每個欄設置顏色。非常感謝。 –

+1

@helloMaga我完全不知道*你正在嘗試做什麼,但我更新了我的答案,以便在循環中顯示設置顏色。 –