I’m currently working with time-series data and I’m using JFreeCharts XYLineChart to display my data. For my user interface I want to create click-able thumbnails of these charts (which then show the real big Chart).
I tried this method to create a thumbnail of the chart, but I don’t know how I can use this BufferedImage to display the thumbnail.
XYSeriesCollection coll = new XYSeriesCollection();
coll.addSeries(rw.getT1().getCurMktCapSeries());
coll.addSeries(rw.getT2().getCurMktCapSeries());
JFreeChart chart = ChartFactory.createXYLineChart(rw.getT1().getName() + " - " + rw.getT2().getName(),
"Position",
"Course",
coll,
PlotOrientation.VERTICAL,
true,
true,
false);
BufferedImage bi = chart.createBufferedImage(1000, 1000, 100, 100, null);
I tried searching online, but the only thing I found was the method above to create a thumbnail, not how to display it.
So my question are:
- Is this the right way to create a thumbnail?
- How can I display this thumbnail on my GUI?
Solution
I just created my own custom JPanel
public class ImagePanel extends JPanel
and then I added the following paintComponent method to draw the thumbnail
protected void paintComponent(Graphics g) {
super.paintComponents(g);
//Create Image
BufferedImage bi = this.createBufferedImage(this.rw);
//Draw Background
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(this.backgroundColor);
g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
//Draw Image
g2d.drawImage(bi.getScaledInstance(this.getWidth()-10, this.getHeight()-10, 0), 5, 5, this.backgroundColor, null);
}
To create the BufferedImage I used the following method
private BufferedImage createBufferedImage(ResultWrapper rw2) {
//Create JFreeChart
XYSeriesCollection coll = new XYSeriesCollection();
coll.addSeries(rw.getT1().getCurMktCapSeries());
coll.addSeries(rw.getT2().getCurMktCapSeries());
JFreeChart chart = ChartFactory.createXYLineChart(null, null, null, coll, PlotOrientation.VERTICAL, false, true, false);
//Hide Axis
XYPlot plot = chart.getXYPlot();
plot.getRangeAxis().setVisible(false);
plot.getDomainAxis().setVisible(false);
return chart.createBufferedImage(500, 500, 100, 100, null);
}
With that I got exactly what I wanted, little thumbnails of a JFreeChart. To make it clickable, just add a MouseListener.
Thanks @MadProgrammer for using a custom component and the paintComponent method
Ontop of AndrewThompon’s suggestions, you could provide a custom Component that has the ability to paint the chart.
Take a look at
This is by far more involved then has already been suggested, but does provide you with the greatest of flexibility