Search code examples
jfreechart

JFreeChart: crosshair label custom position


Is it possible to place crosshair label in the custom position? I have x and y crosshair. I want that y crosshair label was positioned near the data point (change label offset X coordinate).

The problem is that RectangleAnchor has no such option

Crosshair yCrosshair = new Crosshair(Double.NaN, Color.DARK_GRAY, new BasicStroke(0f));
yCrosshair.setLabelAnchor(RectangleAnchor.CENTER);

And it seems that JFreeChart completely ignores label offset settings:

Crosshair yCrosshair = new Crosshair(Double.NaN, Color.DARK_GRAY, new BasicStroke(0f));
yCrosshair.setLabelXOffset(5);

I have the desired plot coordinates for the label in the mouse listener but I can't find how to apply it to the label position.


Solution

  • Ok I've solved my problem by using XYPointerAnnotation.

    XYPointerAnnotation pointer = new XYPointerAnnotation( "", 0, 0, 7.0 * Math.PI / 4.0 ); 
    pointer.setTipRadius(3.0); 
    pointer.setBaseRadius(15.0); 
    pointer.setPaint(Color.blue); 
    pointer.setTextAnchor(TextAnchor.HALF_ASCENT_LEFT); 
    pointer.setBackgroundPaint(new Color(180, 180, 180, 180));
    

    And on mouse move event I've position the annotation to the desired point

    mainPlot.removeAnnotation(pointer);
    if ( !sY.isNaN() ) {
        pointer.setX(x);
        pointer.setY(sY);
        pointer.setText("POWER: "+ sY);
        mainPlot.addAnnotation(pointer);
    }