六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 143|回复: 0

JFreeChart 实现全图tooptip

[复制链接]

升级  68%

8

主题

8

主题

8

主题

童生

Rank: 1

积分
34
 楼主| 发表于 2013-1-24 06:52:31 | 显示全部楼层 |阅读模式
之前也没有接触过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;    }} 
 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表