Posted on 2013-01-21 10:38
TWaver 閱讀(1802)
評論(0) 編輯 收藏
TWaver組件中提供了一些通用的Chart,比如Line Chart,Bar Chart,Bubble Chart,Percent Chart等,對于一些復雜的Chart我們也可以通過定制的方式來實現,如前面所給出的用swing制作精美ERP圖表,仔細看來這些Chart都是單個圖,有客戶要實現多個Chart的整合,比如Line Chart和Bar Chart組合顯示,這改如何來實現?通常我們想到的方式是通過疊加來顯示,將TWaver的這兩個組件疊加起來,但這會帶來很多不必要的麻煩,下面我們通過定制Chart的方式來實現,先看看最終的實現效果:
這個圖展示的是2012年下半年的降雨量和溫度走勢,這就是一個很簡單的Line Chart和Bar Chart疊加的圖,這里采取的實現方式是定制Chart,首先創建一個類繼承于Bar Chart,在Bar Chart上draw出Line Chart,主要的實現代碼也就是在PaintChart里,我們來看看具體的代碼實現:
1 public void paintChart(Graphics2D g2d, int width, int height) {
2 super.paintChart(g2d, width, height);
3 Rectangle rect = this.getBackgroundBounds();
4 double xScaleGap = rect.getWidth()/(xScaleCount*2+1);
5 double yPixelGap = this.toValidHeight(rect.getHeight())/ this.lineRange;
6 for(int i = 0; i< lineDatas.size(); i++){
7 Data data = (Data)lineDatas.get(i);
8 paintData(g2d,data,rect,xScaleGap,yPixelGap);
9 }
10 }
11
1 private void paintData(Graphics2D g2d,Data data,Rectangle rect,double xScaleGap, double yPixelGap){
2 List dataValues = data.getValues();
3 Point2D lastPoint = null;
4 Point2D currentPoint = null;
5 g2d.setColor(data.getColor());
6 g2d.setStroke(new BasicStroke(data.getLineWidth()));
7 if(dataValues != null && dataValues.size() >0){
8 for(int i=0 ;i < xScaleCount; i++){
9 double value = ((Double) dataValues.get(i)).doubleValue();
10 double x = rect.getX() - this.shadowOffset + xScaleGap * (2*(i+1)-0.5);
11 double y = rect.getY() + this.toValidHeight(rect.height) - value*yPixelGap;
12 currentPoint = new Point2D.Double(x,y);
13 if(lastPoint != null){
14 Line2D line = new Line2D.Double(lastPoint,currentPoint);
15 g2d.draw(line);
16 }
17 Shape shape = new Rectangle2D.Double(x-2, y-2,4,4);
18 g2d.fill(shape);
19 g2d.drawString(formatLineValue(value), ((Double)x).floatValue(), ((Double)y).floatValue());
20 lastPoint = currentPoint;
21 }
22 }
23 }
paint方法中主要是通過獲取Bar Chart的背景大小,來計算出x軸刻度的間隙和Y軸像素的間隙,這樣在繪制Line Chart上每個值的具體坐標時就比較容易了。其中我們還定義了Data這樣一個實體bean,用于存放line chart上顯示的數值,主要給出了line chart每條線的顏色和粗細以及具體的值這些參數,我們可以根據實際需求加上自己所需的參數,比如是否顯示lineChart上的值,值的顏色,字體,大小,當然還可以實現雙Y坐標軸,在右方draw出lineChart的坐標軸等。
最后給出上圖實現效果的具體代碼:
lineAndBarChart