1

Within the XYPlot legend of a chart created with JFreeChart, I would like items to be arranged with a FlowLayout arrangement such that excessively long lines are automatically wrapped, however I cannot seem to figure out how to have it so that the items are also center-aligned relative to the entire legend. In other words, I would like line wrapping to remain, but I would like the newly wrapped line to have a HorizontalAlignment.CENTER as opposed to a HorizontalAlignment.LEFT.

None of the methods I have yet found in the API or source will allow me to effectively have a centered FlowArrangement. Is there a convenient way to do this or can I expect to write my own custom Arrangement based on FlowArrangement but centered?

The following code snippet is what I had assumed would work, though does not seem to be having any effect on the legend.

LegendTitle chartLegend = chart.getLegend();
chartLegend.setLegendItemGraphicEdge(RectangleEdge.TOP);
chartLegend.getItemContainer().setArrangement(new FlowArrangement(HorizontalAlignment.CENTER, VerticalAlignment.TOP, 0, 0));

EDIT: Another requirement is that the entire graph (with the legend) has to be easily printable, and thus all should be on the same ChartPanel, and thus I don't see using more than one separate JPanel as an option.

Peter Alsen
  • 320
  • 2
  • 5
  • 15
jstrieb
  • 599
  • 1
  • 7
  • 20

1 Answers1

1

I've seen two general approaches:

  1. Remove the legend created by your chosen ChartFactory and create a new one having the desired parameters, as shown here.

  2. Render the legend items in a separate Container having the desired layout, as shown here.

    JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • I have seen the example linked in the first possibility but it did not work as-expected when I tried it. Each element of the legend ended up aligned to its own arbitrary axis. As for the second option, what I failed to mention is that I need the entire thing (with the legend) to be printable, so every element has to be on the same `ChartPanel`. I have edited my question to reflect this requirement. – jstrieb Aug 06 '16 at 15:50
  • Maybe try `GridArrangement`? – trashgod Aug 06 '16 at 18:40