Using JFree I would like to make a XY plot, and write some information in the right margin outside the plot... and save all of it (i.e. plot + information) in a png file. I thought I found a way to do that with the following code:
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.EmptyBorder;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.AxisSpace;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;
public class example {
public static void main(String[] args) {
XYSeriesCollection dataset = new XYSeriesCollection();
XYSeries series =new XYSeries("data");
series.add(1, 1);
series.add(2, 2);
series.add(3, 3);
series.add(4, 4);
dataset.addSeries(series);
// create the chart...
final JFreeChart chart = ChartFactory.createXYLineChart(
"Example plot",
"X AXIS",
"Y AXIS",
dataset,
PlotOrientation.VERTICAL,
true,
true,
false
);
int plotWidth = 500;
int leftMargin = 70;
int rightMargin = 400;
final XYPlot plot = chart.getXYPlot();
// change margin size
AxisSpace axisSpace=new AxisSpace();
axisSpace.setRight(rightMargin);
axisSpace.setLeft(leftMargin);
plot.setFixedRangeAxisSpace(axisSpace);
// add text outside the plot area
Box b = new Box(BoxLayout.Y_AXIS);
b.setBorder(new EmptyBorder(50, plotWidth+leftMargin, 100, 210));
JLabel label = new JLabel();
label.setText("I want to add some");
b.add(label);
label = new JLabel();
label.setText("information about the plot");
b.add(label);
label = new JLabel();
label.setText("here outside the graph");
b.add(label);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new java.awt.Dimension(500+400, 500));
chartPanel.add(b);
JFrame container = new ApplicationFrame("");
container.setContentPane(chartPanel);
container.pack();
container.setVisible(true);
}
}
When the plot shows up in its frame I got the following:
However, when I save it (performing a dosave, or a doprint, or a save as, or through a bufferedimage) I get the following:
Is there a way to have all the components of a chartpanel in my png file ? Is there another way to put information in the right margin and save the complete result in a png file ?
Thank you for your attention.