Search code examples
javaswingjfreechart

Translating points from Jfreechart component to screen values


I got a problem trying to translate points from JFreeChart to screen in order for the Robot.mouseMove() method to work properly.

As suggested in this topic JFreeChart: how to get coordinates of an XYItemEntity? I wrote a custom CandlestickRenderer where I store certain drawn points. Then I set this custom render as a renderer for my chart:

chart= ChartFactory.createCandlestickChart("Default Chart", "Time", "Value", ohlcSeriesCollection, true);
chart.getXYPlot().setOrientation(PlotOrientation.VERTICAL);
chart.getXYPlot().setDomainPannable(true);
chart.getXYPlot().setRangePannable(true);
chart.getXYPlot().getRangeAxis().setAutoRange(true);
String emptyTitle= "";
chart.setTitle(emptyTitle);
XYPlot plot = (XYPlot) chart.getPlot();
DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setDateFormatOverride(new SimpleDateFormat(DOMAIN_DATE_FORMAT));
XYItemRenderer renderer=new CandleRenderer(); // my custom CandlestickRenderer 
plot.setRenderer(renderer);

Then, I pass the created chart to my custom ChartPanel and add a ChatMouseListener to the CharPanel:

chartPanel=new CandlestickChartPanel(chart, analysis);
chartPanel.setDisplayToolTips(false);
tooltipPanel=new TooltipPanel();
add(chartPanel, BorderLayout.CENTER);
add(tooltipPanel, BorderLayout.EAST);
chartPanel.addChartMouseListener(new MyChartMouseListener());

Now, in the MyChartMouseListener I want to be able to compare points previously stored by my custom CandlestickRenderer to points to which mouse currently points. In order to achieve that, I am using the screen coordinates of the MouseEvent:

Point point = new Point(chartMouseEvent.getTrigger().getXOnScreen(),chartMouseEvent.getTrigger().getYOnScreen());

But I have a huge problem with the proper translation of the points obtained from the custom CandlestickRenderer. I am using the following code for the translation:

SwingUtilities.convertPointToScreen(point, this.chartPanel);

but the values I'm getting are different from when I click on those points and print the coordinates to the console. To simplify: 1. I draw a single candle using my custom CandlestickRenderer. 2. I translate certain points from that candle to screen using SwingUtilities.convertPointToScreen() method. 3. I then click on those points on the screen and print their screen values but the coordinates are very different from the saved ones.

Any help would be appreciated :)


Solution

  • Ok, so for anyone interested, apparently Point translated=chartPanel.translateJava2DToScreen(point) instead of using SwingUtilities does the job :)