How to Build Charts in Java
The Java programming language comes with a library for building and creating charts. You define the numeric values, set up the colors and fonts and the Java interpreter does the rest. You must include the char libraries in your code, set up a class for the chart program and display the chart on the form. The Java "Graph" class handles rendering of charts for your desktop projects.
Instructions
-
-
1
Open your preferred Java interpreter software and open the Java project you want to use to add a chart. Double-click the Java source code file to load it in the interpreter editor.
-
2
Add the necessary libraries for Java charting. Copy and paste the following code to the top of the source code file:
import org.jfree.chart.*;
import org.jfree.data.*;
import org.jfree.chart.renderer.category.*;
import org.jfree.chart.plot.*; -
-
3
Create the data set for your chart. A data set holds the values that display in the chart. The Java interpreter reads these values and displays the chart graph. The following code creates a data set for the number of customers obtained for three months:
DefaultCategoryDataset data = new DefaultCategoryDataset();
data.setValue(22, "Customers", "October");
data.setValue(43, "Customers", "November");
data.setValue(10, "Customers", "December"); -
4
Create the chart and bind the data set to the chart control. Setting up colors and fonts is optional, but the properties are available for editing with the charting control. The following code sets up a bar chart with the customers data set:
JFreeChart graph = ChartFactory.createBarChart("Customer Chart","", "Customers", data, PlotOrientation.VERTICAL, false,true, false);
graph.getTitle().setPaint(Color.Purple);
CategoryPlot plot = graph.getCategoryPlot(); -
5
Render the chart on the desktop form. The following code sets the graph to visible and draws it on the form:
plot.setRangeGridlinePaint(Color.red);
ChartFrame form1 =new ChartFrame("Customer Chart",graph);
form1.setVisible(true);
-
1