之前也没有接触过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;
}
}