JFreeChart 实现全图tooptip

之前也没有接触过JFreeChart,如有错误或更简单的实现恳请指出, 谢谢。

 

JFreeChart的默认只有鼠标在数据点上的时候才显示tooltip;两点之间的数据就不能显示tooptip,如果数据是滚动变化的就更难使用。 所以决定干脆鼠标放哪,就显示鼠标点的数据。

最终效果如下图:

 

 

查了下Api,JFreeChart好像没有这样的功能,只好自己实现了.

 

JFreeChart中画图的面板是ChartPanel, tooltip的文字内容也是由这个类产生的.只要继承ChartPanel并重载getToolTipText方法就行了。下面是代码实现:

package com.straw;

public class ToolTipChartPanel extends ChartPanel
{

    private ValueAxis xAxis;
    private ValueAxis yAxis;
    private SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");   

    public ToolTipChartPanel(JFreeChart chart, XYPlot xyplot)
    {
        super(chart);
        this.xAxis = xyplot.getDomainAxis();
        this.yAxis = xyplot.getRangeAxis();
    }

    @Override
    public String getToolTipText(MouseEvent e) 
    {
        Rectangle2D dataArea = getScaledDataArea();
        
        // 不在区域内的直接返回
        if (!dataArea.contains(e.getX(), e.getY() ))
        {
            return null;
        }        
        
        long x = getValueX(dataArea, e.getX()); 
        double y = getValueY(dataArea, e.getY());        
            
        return sdf.format(new Date(x)) + ", " + 100*y + "%";
    }
    
    

    private long getValueX(Rectangle2D dataArea, int mouseX)
    {
        // 1 获得像素值
        long x = (long) (mouseX - dataArea.getMinX());        
        
        // 2 转化成时间毫秒
        double lowerBound = xAxis.getLowerBound();
        double upperBound = xAxis.getUpperBound();
        x = (long) (x*(upperBound - lowerBound)/dataArea.getWidth() + lowerBound);   
        
        return x;
    }
    
    private double getValueY(Rectangle2D dataArea, int mouseY)
    {
        // 1 获得像素值
        double y = (dataArea.getHeight() - (mouseY - dataArea.getMinY()));
        
        // 2 转化成数值
        double lowerBound = yAxis.getLowerBound();
        double upperBound = yAxis.getUpperBound();
        y =  (y*(upperBound - lowerBound)/dataArea.getHeight() + lowerBound);
        
        return y;
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值