Posted on 2013-01-21 10:38
TWaver 閱讀(1810)
評論(0) 編輯 收藏
TWaver組件中提供了一些通用的Chart,比如Line Chart,Bar Chart,Bubble Chart,Percent Chart等,對于一些復(fù)雜的Chart我們也可以通過定制的方式來實(shí)現(xiàn),如前面所給出的用swing制作精美ERP圖表,仔細(xì)看來這些Chart都是單個圖,有客戶要實(shí)現(xiàn)多個Chart的整合,比如Line Chart和Bar Chart組合顯示,這改如何來實(shí)現(xiàn)?通常我們想到的方式是通過疊加來顯示,將TWaver的這兩個組件疊加起來,但這會帶來很多不必要的麻煩,下面我們通過定制Chart的方式來實(shí)現(xiàn),先看看最終的實(shí)現(xiàn)效果:
這個圖展示的是2012年下半年的降雨量和溫度走勢,這就是一個很簡單的Line Chart和Bar Chart疊加的圖,這里采取的實(shí)現(xiàn)方式是定制Chart,首先創(chuàng)建一個類繼承于Bar Chart,在Bar Chart上draw出Line Chart,主要的實(shí)現(xiàn)代碼也就是在PaintChart里,我們來看看具體的代碼實(shí)現(xiàn):
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上每個值的具體坐標(biāo)時就比較容易了。其中我們還定義了Data這樣一個實(shí)體bean,用于存放line chart上顯示的數(shù)值,主要給出了line chart每條線的顏色和粗細(xì)以及具體的值這些參數(shù),我們可以根據(jù)實(shí)際需求加上自己所需的參數(shù),比如是否顯示lineChart上的值,值的顏色,字體,大小,當(dāng)然還可以實(shí)現(xiàn)雙Y坐標(biāo)軸,在右方draw出lineChart的坐標(biāo)軸等。
最后給出上圖實(shí)現(xiàn)效果的具體代碼:
lineAndBarChart