How to Do a Bar Chart in Java
The Java programming language includes a charting library that you use to create a bar chart to display in your Java desktop forms. The charting libraries offer several properties such as colors, fonts and styles you can use to set up the chart, but you can leave all of these properties with the default to display a simple chart from a data set. The data set contains the values you want to display, and the Java chart library takes care of the rest.
Instructions
-
-
1
Open the Java editor you want to use to display the bar chart. Open your project and the source code file. At the top of the file, copy and paste the following library import statements to include the necessary classes:
import org.jfree.chart.*;
import org.jfree.data.category.*;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.xy.*;
import org.jfree.data.*;
import org.jfree.chart.renderer.category.*;
import org.jfree.chart.plot.*;
import java.awt.*; -
2
Create an instance of the class to set up the bar chart. Add the following code to initialize the class and the data set that loads the values into the bar chart:
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
JFreeChart chart = ChartFactory.createBarChart -
-
3
Set up the values in the data set class. For instance, the following code sets up to bars for a data set that contains the values for customer orders:
dataset.setValue(13, "Orders", "Customer1");
dataset.setValue(10, "Orders", "Customer2"); -
4
Set up the properties for the chart. You do not need to set up the properties. If you do not, the chart is set up with the default black color. For instance, the following code sets up the background and the title color:
chart.setBackgroundPaint(Color.blue);
chart.getTitle().setPaint(Color.Red); -
5
Display the chart on the form. The following code renders the chart on the form:
ChartFrame form=new ChartFrame("Customer Orders",chart);
form.setVisible(true);
-
1