Feb 17

For any serious charting we use JFreeChart but for simple cases such as when we are mentoring Java students who need charting for their assignments we use Swing directly to paint the chart.

Here is a simple example of how a bar chart can be implemented using Swing.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class BarChart extends JPanel
	private Map<Color, Integer> bars =
            new LinkedHashMap<Color, Integer>();
	 * Add new bar to chart
	 * @param color color to display bar
	 * @param value size of bar
	public void addBar(Color color, int value)
		bars.put(color, value);
	protected void paintComponent(Graphics g)
		// determine longest bar
		int max = Integer.MIN_VALUE;
		for (Integer value : bars.values())
			max = Math.max(max, value);
		// paint bars
		int width = (getWidth() / bars.size()) - 2;
		int x = 1;
		for (Color color : bars.keySet())
			int value = bars.get(color);
			int height = (int) 
                            ((getHeight()-5) * ((double)value / max));
			g.fillRect(x, getHeight() - height, width, height);
			g.drawRect(x, getHeight() - height, width, height);
			x += (width + 2);

	public Dimension getPreferredSize() {
		return new Dimension(bars.size() * 10 + 2, 50);

	public static void main(String[] args)
		JFrame frame = new JFrame("Bar Chart");
		BarChart chart = new BarChart();
		chart.addBar(Color.red, 100);
		chart.addBar(Color.green, 8);
		chart.addBar(Color.blue, 54);
		chart.addBar(Color.black, 23);		

written by objects \\ tags: , , ,

One Response to “How to display bar chart using Swing?”

  1. Abdul Says:


    Thanks for the code it was helpful. But i was wondering, if there is anyway to make the graph read the data from a CSV file?

Leave a Reply

You must be logged in to post a comment.