Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform mouse listener coordinates into chart coordinates

I want to set dots in my app with mouse click. I use JFreeChart and use in ChartPanel mouse listener. This is look like this:

panel.addChartMouseListener(new ThisMouseListener());

and my mouse listener ThisMouseListener() (it is not finished):

class ThisMouseListener implements ChartMouseListener{

    @Override
    public void chartMouseClicked(ChartMouseEvent event) {
        int x = event.getTrigger().getX();
        int y = event.getTrigger().getY();

        System.out.println("X :" + x + " Y : " + y);

        ChartEntity entity = event.getEntity();
        if(entity != null && (entity instanceof XYItemEntity)){
            XYItemEntity item = (XYItemEntity)entity;
        }
        new JOptionPane().showMessageDialog(null, "Hello", "Mouse Clicked event", JOptionPane.OK_OPTION);
    }

    @Override
    public void chartMouseMoved(ChartMouseEvent arg0) {
        // TODO Auto-generated method stub

    }

} 

but this mouse listener returns me my panel coordinates and I want to get coordinates from my chart. May be I must use listener with other object? or I can transform coordinates with some method?

like image 643
Aleksei Bulgak Avatar asked Sep 27 '12 16:09

Aleksei Bulgak


1 Answers

You added the listener to the panel. Therefore when you click the mouse you receive coordinates relative to the panel - which is the source of the event. You need to add this listener to the chart instead.

Other possibility is to get coordinates of the chart in respect to panel and subtract them from x and y.

Point p = chart.getLocation();     
int px = p.getX();
int py = p.getY();

x = x-px; // x from event
y = y-py; // y from event
// x and y are now coordinates in respect to the chart

if(x<0 || y<0 || x>chart.getWidth() || y>chart.getHeight()) // the click was outside of the chart
else // the click happened within boundaries of the chart and 

If the panel is the container of the chart component your solution might look something like the above one. Note that these coordinates will be coordinates in respect to left top corner of the chart.

like image 52
user1581900 Avatar answered Oct 19 '22 16:10

user1581900