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?

Joris Schellekens
  • 8,483
  • 2
  • 23
  • 54
nzy
  • 854
  • 2
  • 15
  • 28
  • chartPanel is added twice to graph1 – Aubin Aug 24 '14 at 07:13
  • 2
    Don't call updateComponentTree or. UpdateUI, these are expensive calls and are related to updating the look and feel – MadProgrammer Aug 24 '14 at 07:33
  • Please edit your question to include version numbers, an [mcve](http://stackoverflow.com/help/mcve), and a [screenshot](http://meta.stackoverflow.com/questions/99734/how-do-i-create-a-screenshot-to-illustrate-a-post) that shows the expected result. – trashgod Aug 24 '14 at 15:14

2 Answers2

25

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.

Aubin
  • 14,617
  • 9
  • 61
  • 84
4

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!

Paul Efford
  • 261
  • 4
  • 12