Changing background colour of jFreeChart
Asked Answered
I

2

17

I am trying to change the background color of jfreechart. It is displaying in grey color and I want a white background. I have tried

chart.setBackgroundPaint(Color.WHITE); 

However it does not show me the white background.
I have the following code that displays the the plot

chart = ChartFactory.createXYLineChart("Line Chart","Year","Temperature", dataset);
ChartPanel chartPanel = new ChartPanel(chart, false);
graph1.setLayout(new BorderLayout());
graph1.add(chartPanel, BorderLayout.EAST);
graph1.add(chartPanel);
SwingUtilities.updateComponentTreeUI(this);
graph1.updateUI();
System.out.println("Database created successfully...");

How should I set a white background?

Iverson answered 24/8, 2014 at 7:10 Comment(3)
chartPanel is added twice to graph1Bankruptcy
Don't call updateComponentTree or. UpdateUI, these are expensive calls and are related to updating the look and feelAndromache
Please edit your question to include version numbers, an mcve, and a screenshot that shows the expected result.Cortney
B
27

ChartPanel inherit method javax.swing.JComponent.setBackground(java.awt.Color)

chartPanel.setBackground( Color.RED );

Or try:

chart.getPlot().setBackgroundPaint( Color.BLUE );

See documentation of JFreeChart.getPlot() and Plot.setBackgroundPaint()

See this post on SO or this one too.

Bankruptcy answered 24/8, 2014 at 7:17 Comment(1)
The first example doesn't work on my side, the second one does.Brachy
N
5

You have to use JFreeChart.getPlot().setBackgroundPaint(Color.WHITE); like this:

public static void main(String[] args) {
    DefaultPieDataset pieDataset = new DefaultPieDataset(); 
    pieDataset.setValue("LoggedIn" +": "+ 5, 10);
    pieDataset.setValue("LoggedOut" +": "+ 8, 17);
    JFreeChart jfc = ChartFactory.createPieChart("title", pieDataset, false, false, false );
    jfc.getPlot().setBackgroundPaint(Color.WHITE);
    ChartPanel chart = new ChartPanel(jfc);
    JFrame frame = new JFrame();
    frame.add(chart);
    frame.pack();
    frame.setVisible(true);
}   

I hope it helps!

Neumeyer answered 6/3, 2018 at 6:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.