Der er noget som ikke helt virker som man forventer.
Her er hvad jeg er kommet frem til:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.LegendItem;
import org.jfree.chart.entity.LegendItemEntity;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;
public class XYPlotColorDemo extends ApplicationFrame {
private static final long serialVersionUID = 1L;
public XYPlotColorDemo() {
super("XYPlot Color Demo");
XYSeries series1 = new XYSeries("Modul 1.2");
series1.add(20.0, 23.0);
series1.add(40.0, 25.0);
series1.add(70.0, 35.0);
XYSeries series2 = new XYSeries("Modul 3.7");
series2.add(30.0, 25.0);
series2.add(50.0, 28.0);
series2.add(60.0, 30.0);
XYSeries series3 = new XYSeries("Modul 4.7");
series3.add(10.0, 21.0);
series3.add(20.0, 22.0);
series3.add(30.0, 33.0);
XYSeriesCollection col = new XYSeriesCollection();
col.addSeries(series1);
col.addSeries(series2);
col.addSeries(series3);
JFreeChart chart = ChartFactory.createScatterPlot("Temperatur", "Dato", "Temperatur (°C)",
col, PlotOrientation.VERTICAL, true, true, false);
XYPlot plot = chart.getXYPlot();
XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
renderer.setSeriesPaint(0, Color.BLACK);
renderer.setSeriesPaint(1, Color.MAGENTA);
renderer.setSeriesPaint(2, Color.ORANGE);
renderer.setSeriesLinesVisible(0, true);
renderer.setSeriesLinesVisible(1, true);
renderer.setSeriesLinesVisible(2, true);
ChartPanel chartpan = new ChartPanel(chart);
chartpan.setPreferredSize(new Dimension(600, 600));
chartpan.addChartMouseListener(new ChartMouseListener() {
@Override
public void chartMouseClicked(ChartMouseEvent evt) {
if(evt.getEntity() instanceof LegendItemEntity) {
LegendItemEntity itm = (LegendItemEntity)evt.getEntity();
for(int i = 0; i < plot.getLegendItems().getItemCount(); i++) {
if(plot.getLegendItems().get(i).getSeriesKey().equals(itm.getSeriesKey())) {
LegendItem itm2 = plot.getLegendItems().get(i);
//Does not work for unknown reasons:
//itm2.setLinePaint(Color.RED);
//Does not work for unknown reasons:
//Font f = itm2.getLabelFont();
//f = f.deriveFont(40);
//itm2.setLabelFont(f);
// Does work:
renderer.setSeriesPaint(itm2.getSeriesIndex(), Color.RED);
//Does not work for unknown reasons:
//Font f = renderer.getBaseItemLabelFont();
//f = f.deriveFont(40);
//renderer.setBaseItemLabelFont(f);
}
}
}
}
@Override
public void chartMouseMoved(ChartMouseEvent evt) {
}
});
setContentPane(chartpan);
pack();
setVisible(true);
}
public static void main(String[] args) {
new XYPlotColorDemo();
}
}