Search code examples
jfreechart

show label when user mouseOver ValueMarker in jFreeChart


Right now i a JFreeChart line graph. I want to add marker to mark some events. I have added the markers. The problem is that the marker labels have started to overlap. I want to solve this by only showing the marker label if the user mouse over's the marker line. How can i capture the mouseover event?

Marker tempMarker = new ValueMarker(hour.getFirstMillisecond());        
tempMarker.setPaint(Color.BLACK); 
tempMarker.setLabelAnchor(RectangleAnchor.TOP_LEFT);
tempMarker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);

//instead of this i want a mouseoverlistner and then show the label
tempMarker.setLabel("Event Name");

code for mouse over

chartPanel.addChartMouseListener(new ChartMouseListener() {
    @Override
    public void chartMouseClicked(ChartMouseEvent event) {
        //do something on mouse click
    }

    @Override
    public void chartMouseMoved(ChartMouseEvent event) {
        System.out.println("Entity Type: " + event.getEntity());
    }
});

When i mouse over the Marker objects a ChartEntity is sent to the chartMouseMoved. This is the same as when i mouse over other non filled portions of the chart.


Solution

  • It's not really possible to do this. I got help from @paradoxoff in this thread on the jfree forum. Here is how I achieved it.

    1. Download the Annotation files from Click here
    2. You only need the org.jfree.chart.annotations folder. Add it to your project.
    3. Replace the Marker with Annotations with this code below

      XYDomainValueAnnotation tempMarker = new XYDomainValueAnnotation();
      tempMarker.setValue(hour.getFirstMillisecond());
      
      //set the color of the lines
      switch (priority) {
          case Constants.HIGH_IMPORTANCE:
              tempMarker.setPaint(Color.RED);
              break;
          case Constants.LOW_IMPORTANCE:
              tempMarker.setPaint(Color.GREEN);
              break;
          default:
              tempMarker.setPaint(Color.BLACK);
      }
      
      // dont set the label
      //tempMarker.setLabel("Event Name");
      
      //set the Tool Tip which will display when you mouse over.
      tempMarker.setToolTipText("Annotation");
      
      //format everything
      tempMarker.setStroke(new BasicStroke(5.0f));        
      tempMarker.setLabelTextAnchor(TextAnchor.TOP_LEFT);
      tempMarker.setLabelAnchor(RectangleAnchor.TOP_LEFT);
      tempMarker.setRotationAnchor(TextAnchor.TOP_LEFT);
      
      //add the annotation lines
      plot.addAnnotation(tempMarker);
      
    4. When you mouse over the annotation lines the tooltip will appear.