barplot.java

来自「这是一个十分有用的java图形工具包」· Java 代码 · 共 94 行

JAVA
94
字号
/*
 * Created on 2003-5-13
 *
 * To change this generated comment go to 
 * Window>Preferences>Java>Code Generation>Code Template
 */
package net.turbochen.graph;

import java.awt.*;
import java.util.*;
/**
 * @author Administrator
 */
public class BarPlot extends Plot
{

    private Color barColor;
    private int barSpace;

    public BarPlot(DataSeries ds,XAxis xaxis, YAxis yaxis)
    {
        dataSeries = new ArrayList();
        this.addDataSeries(ds);
        this.xAxis = xaxis;
        this.yAxis = yaxis;
        barColor = Color.GREEN;
        barSpace = 5;
    }


    /* 绘制柱子.
     * @see net.turbochen.graph.Plot#draw(java.awt.Graphics, net.turbochen.graph.DataSeries, int)
     */
    public void draw(Graphics g, DataSeries ds, int index)
    {
        if ( ds == null ) return;
        /*每组柱子的个数*/
        int bars = this.dataSeries.size();
        /*算出每个柱子应有的宽度*/
        int barWidth = (int) ((double)xAxis.width/((double)ds.size()+1)/bars-barSpace);
        if ( barWidth <=0 ) barWidth = 1;
        int barx,bary,barw,barh;
        int barGroupWidth = barWidth*bars;
        double ymin = yAxis.getScale().getMin();
        for ( int i = 0;i<ds.size(); i++ )
        {
            barx = (int)(xAxis.getScale().getScreenCoordinate(i+1) -
                            barGroupWidth/2.0d) + index*barWidth;
            double val = ((Double)ds.getYData(i)).doubleValue();
            bary = yAxis.getScale().getScreenCoordinate(val);
            if ( ymin<0)
                if ( val<0 )
                {   
                    barh =  bary-yAxis.getScale().getScreenCoordinate(0);
                    bary = bary-barh;
                }else
                {
                    barh = yAxis.getScale().getScreenCoordinate(0)-bary;
                }
            else
            {
                barh = yAxis.getScale().getScreenCoordinate(ymin)-bary;
            }
            barw = barWidth;
            
            g.setColor(barColor);
            g.fillRect(barx,bary,barw, barh);
            g.setColor(Color.BLACK);
            g.drawRect(barx,bary, barw, barh);
        }
        
        

    }

    /**
     * @return Color
     */
    public Color getBarColor()
    {
        return barColor;
    }

    /**
     * Sets the barColor.
     * @param barColor The barColor to set
     */
    public void setBarColor(Color barColor)
    {
        this.barColor = barColor;
    }

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?