Convert mouse listener coordinates to chart coordinates

I want to set points in my application with the mouse. I use JFreeChart and use the ChartPanel mouse listener. It looks like this:

panel.addChartMouseListener(new ThisMouseListener());

and my mouse listener ThisMouseListener () (it's not finished yet):

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 the coordinates from my chart. Maybe I should use a listener with another object? Or can I convert the coordinates using some method?

+5
source share
3 answers

You have added a listener to the panel. Therefore, when you click the mouse, you get the coordinates relative to the panel, which is the source of the event. You need to add this listener to the chart.

- x 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 

, , . , .

+3

x, y

double x = event.getChart().getXYPlot().getDomainCrosshairValue();
double y = event.getChart().getXYPlot().getRangeCrosshairValue();

: , JFreeChart , ChartMouseEvent; , . XYPlot.handleClick(x, y, info), .

+2

ChartPanel, rredraw X, Y . awt . , ( X-)

@Override
public void chartMouseClicked(ChartMouseEvent cme) {
    final ChartMouseEvent cmeLocal = cme;
    ChartPanel hostChartPanel = (ChartPanel) cme.getTrigger().getComponent();
    if (null != hostChartPanel) {

        //Crosshair values are not valid until after the chart has been updated
        //that is why call repaint() now and post Crosshair value retrieval on the
        //awt thread queue to get them when repaint() is finished
        hostChartPanel.repaint();

        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFreeChart chart = cmeLocal.getChart();
                XYPlot plot = chart.getXYPlot();
                double crossHairX = plot.getDomainCrosshairValue();
                JOptionPane.showMessageDialog(null, Double.toString(crossHairX), "X-Value", JOptionPane.OK_OPTION);
            }
        });
    }
}
+1

All Articles