|
Oracle® Chart Builder Application Developer's Guide
Release 1.0 Part No. A96127-01 |
|
Chart Builder is a Java application programming interface (API) packaged as a JavaBean class library. This chapter describes the following:
Building Basic Axis Charts, such as line, bar, area, and stock charts
The Chart Builder class library contains several packages, each of which contain one or more classes:
The oracle.charts package contains the Chart class, which is the top-level Chart Builder class. This class provides methods for defining titles, subtitles, footnotes, and legends, as well as defining the background areas of the chart.
The oracle.charts.legend package contains the Legend class, which provides methods to display legends and set their attributes, such as positioning and color.
The oracle.charts.axischart package contains the AxisChart class, which provides methods to create axis charts.
It also contains the AxisChartInteractive class, which provides methods to create interactive axis charts.
The oracle.charts.piechart package contains the PieChart class, which provides methods to create pie charts.
It also contains the PieChartInteractive class, which provides methods to create interactive pie charts.
The oracle.charts.types package contains descriptor classes, which provide descriptors to customize charts.
For information about the hierarchy of these and other classes, see Appendix A. For reference information about each class, see the API documentation.
An axis chart is a chart in which the data is plotted according to where it lies along the edges (axes) of the chart. An axis chart contains a horizontal axis, called the X-axis, and a vertical axis, called the Y-axis. An axis chart can have one X-axis and one or two Y-axes.
Bar, line, area, and stock charts are types of axis charts. Axis charts can be oriented vertically or horizontally. Chart Builder supports many types of vertical axis charts, but it supports only bar charts as horizontal axis charts.
The following figure shows the major elements in an axis chart:
Description of the illustration chart_annot.gif
To build an axis chart, you use the Chart Builder AxisChart class. To build any axis chart, whether it is a line, area, bar, or stock chart, you must take the following basic steps:
Create an axis chart object using the AxisChart( ) constructor function:
AxisChart MyAxisCh = new AxisChart();
The name of axis chart object, MyAxisCh in this example, is used in subsequent calls to methods that define the characteristic of the axis chart, such as its size and data.
Define the size of the axis chart using the setSize( ) method. The following line sets the size of the chart area to 240 pixels wide by 180 pixels high:
MyAxisCh.setSize(240,180);
Load data into the axis chart. Use the setXSeries( ) method to load the data for the horizontal axis. Use the setYSeries( ) method to load the data for the vertical axis.
MyAxisCh.setXSeries(MonthlyTimestamps);
MyAxisCh.setYSeries("Canada", ExportsCA);;
In this example, the X-axis is loaded with an array of timestamps named MonthlyTimestamps. The Y-axis is loaded with an array of values named ExportsCA. (Canada is the name of the Y-axis series.)
You can use the frequency-based method to load timestamps instead of specifying the array of timestamps. For example, to load timestamps for each month of the year 2001, use the following code:
MyAxisCh.setXSeries(Calendar.MONTH,
java.sql.Date.valueOf("2001-01-01"),
java.sql.Date.valueOf("2001-12-01")
1);
Because Chart Builder automatically labels the axes, you can avoid tedious editing and positioning of the labels.
These steps, which are universal for all types of axis charts, create a simple axis chart. In addition to these steps, you can use Chart Builder methods and descriptors to add information, such as a title and subtitle, to your chart or to customize your chart. For information about customizing charts, see Chapter 3.
Note the following points about loading data into axis charts:
You can load data by specifying the data directly in the application. However, in most cases, you load data from a database, a text file, or an input stream.
You must call the setXSeries( ) method before you call the setYSeries( ) method.
The setXSeries( ) method takes an array of the following types: String or Date (java.util.Date, including the subclasses java.sql.Date and java.sql.Timestamp).
Chart Builder labels the X-axis with the data provided in the array passed to the setXSeries( ) method. If the array is of type String, Chart Builder labels the X-axis with those strings. If the array is of type Date, Chart Builder labels the X-axis automatically, using the full date or abbreviations depending on the size of the chart.
Section 2.2.3 and Section 2.2.5 show examples of using arrays of type String. The other sections in this chapter show examples of using arrays of type Date or Timestamp.
The setXSeries( ) method expects arrays of dates to be ascending in value and not null.
The setYSeries( ) method takes an array of type double, but you can pass data of any Java Number type.
Chart Builder supports locale-specific formats for dates and numbers.
For more information about loading data into charts, see Section 2.4.
By default, the AxisChart class creates vertical line charts. You can easily change the type of a vertical axis chart by using the setSeriesGraphType( ) method. This method, which sets the type of graph used for each Y-axis series, uses the following format:
axischart_name.setSeriesGraphType(series_name, AxisChart.type)
The following sections describe how to use the Chart Builder API to build different types of vertical axis charts and horizontal bar charts.
For information about customizing charts, see Chapter 3.
Line charts are one of the most commonly used types of charts. This section describes a Java application that creates the following line chart:
The following example shows the code that creates this chart:
//Import the Java AWT package. import java.awt.*; //Import Oracle Chart Builder packages. [1] import oracle.charts.*; import oracle.charts.axischart.*; import oracle.charts.types.*; public class linechart1 extends Frame { // Chart data, defined inline. // Monthly timestamps for 2000. [2] public final static java.sql.Date MonthlyTimestamps[] = { java.sql.Date.valueOf("2000-01-01"), java.sql.Date.valueOf("2000-02-01"), java.sql.Date.valueOf("2000-03-01"), java.sql.Date.valueOf("2000-04-01"), java.sql.Date.valueOf("2000-05-01"), java.sql.Date.valueOf("2000-06-01"), java.sql.Date.valueOf("2000-07-01"), java.sql.Date.valueOf("2000-08-01"), java.sql.Date.valueOf("2000-09-01"), java.sql.Date.valueOf("2000-10-01"), java.sql.Date.valueOf("2000-11-01"), java.sql.Date.valueOf("2000-12-01") }; // Define the values for the Y-axis--Exports to Canada. [3] public final static double ExportsCA[] = { 13604.5, 14968.7, 17085.7, 14794.0, 15834.0, 16054.0, 12153.0, 15325.0, 14847.4, 15725.1, 15159.3, 13390.4 }; public static void main(String[] argv) { // Dimensions of chart. int Chart_width = 400, Chart_height = 200; // Create a new frame and set its size. [4] Frame f = new Frame(); f.setSize(Chart_width + 10, Chart_height + 40); try { // Create a new AxisChart object. [5] AxisChart MyAxisCh = new AxisChart(); // Set the size of the chart. MyAxisCh.setSize(Chart_width, Chart_height); [6] // Load the timestamps from the MonthlyTimestamps array. [7] MyAxisCh.setXSeries(MonthlyTimestamps); // Load the values for the Y-axis from the ExportsCA array. [8] MyAxisCh.setYSeries("Canada", ExportsCA); // Set the chart title. [9] MyAxisCh.getTitle().setText("Exports to Canada"); // Add the chart to the frame. [10] f.add(MyAxisCh); } catch (ChartException e) { System.out.println(e.getMessage()); } f.show(); } }
The numbers in the example correspond to the numbers in the following list, which describes the example in detail:
The application imports the Chart Builder packages that you need for your chart. This example uses three packages.
To make it easier to follow the example, the values for the X-axis are defined directly in the code, in the MonthlyTimestamp array. In most cases, you would load data from a database, a text file, an input stream, or using the frequency-based setXSeries( ) method. The frequency-based setXSeries( ) method uses start and end timestamps with an interval.
To make it easier to follow the example, the Y-axis values are defined directly in the code. In most cases, you would load the values from a database, a text file, or an input stream.
Because this is a Java application, you must create a container, such as a frame to display the chart.
The AxisChart( ) constructor creates a new axis chart object. In this example, the object is named MyAxisCh.
The setSize( ) method specifies the width and height of the chart by referring to variables that are initialized earlier in the code.
The setXSeries( ) method loads the data for the X-axis. In this example, it loads the timestamps from the MonthlyTimestamp array, which was previously initialized with data. The setXSeries( ) method accepts an array of type Date or String as input. If the array is of type Date, Chart Builder labels the X-axis automatically, using the full date or abbreviations depending on the size of the chart and the amount of data. Because of the size of the chart specified for this example, Chart Builder uses the initial letters of each month.
The setYSeries( ) method loads the data for the Y-axis. In this example, it loads the values from the ExportsCA array, which was initialized earlier in the code. The Y-axis series is named Canada. The setYSeries( ) method accepts an array of type double as input.
The java.awt.frame.add( ) method adds the chart to the frame.
When you run the Java application, Chart Builder creates the chart and displays it in a frame.
Building an area chart is similar to building a line chart or any vertical axis chart. To specify an area chart, you use the setSeriesGraphType( ) method to set the type of graph to AREA for each Y-axis series.
For example, to change the line chart example in Section 2.2.1 to an area chart, use the following code:
MyAxisCh.setSeriesGraphType("Canada", AxisChart.AREA);
The following figure shows the chart in Section 2.2.1 after it is modified to be an area chart:
Building a bar chart is similar to building a line chart or any vertical axis chart. To specify a bar chart, you use the setSeriesGraphType( ) method to set the type of graph to BAR for each Y-axis series.
For example, to change the line chart example in Section 2.2.1 to a bar chart, use the following code:
MyAxisCh.setSeriesGraphType("Canada", AxisChart.BAR);
The following figure shows the chart after it is modified to be a vertical bar chart:
The previous examples loaded an array of type Dates into the X-axis. You can create axis charts that load an array of type String into the X-axis. You can use any type of axis chart, although bar charts are often best in conveying the meaning of this type of data.
To create a chart that loads an array of type String into the X-axis, you must define the array of strings, as shown in the following example:
// Define the array of strings.
public final static String AirportsLabels[] =
{"ATL","ORD", "LAX", "LHR","DFW",
"HND", "FRA", "CDG", "SFO", "AMS" };
Then, you pass the array to the setXSeries( ) method, as shown in the following example:
MyAxisCh.setXSeries(AirportsLabels);
The following figure shows the resulting bar chart:
Chart Builder supports three types of stock charts:
High-Low-Close: The high, low, and close values are displayed for each timestamp. A vertical line segment indicates the low and high price; a marker connected to the vertical line segment indicates the closing price.
Open-High-Low-Close: The open, high, low, and close values are displayed for each timestamp. A vertical line segment indicates the low and high price. A marker connected to the left side of the vertical line segment indicates the opening price; a marker connected to the right side of the vertical line segment indicates the closing price.
Candlestick: The open, high, low, and close values are displayed for each timestamp. The opening and closing prices are represented by a color-coded rectangle, known as the body. A white rectangle indicates that the closing price was higher than the opening price. A black rectangle indicates that the closing price was lower than the opening price. The low and high prices are represented by a vertical line segment, known as the shadow.
Building a stock chart is similar to building any vertical axis chart. The primary difference is that you must use one of the following methods to load the data into a stock chart:
For High-Low-Close charts, use the setHiLoCloseSeries( ) method and pass three arrays of values to it.
For Open-High-Low-Close charts, use the setOpenHiLoCloseSeries( ) method and pass four arrays of values to it.
For Candlestick charts, use the setCandlestickSeries( ) method and pass four arrays of values to it.
The following example shows the code that is specific to a stock chart (in this case, an Open-High-Low-Close chart):
// Load the OpenHiLoClose series.
MyAxisCh.setOpenHiLoCloseSeries("ACME", Open, High, Low, Close);
The following figure shows the resulting Open-High-Low-Close chart:
You can use Chart Builder to build horizontal bar charts or to easily change vertical charts to horizontal bar charts.
|
Note: Chart Builder supports only horizontal bar charts. It does not support other types of horizontal charts. |
Building a horizontal bar chart is similar to building a vertical axis chart. Note the following differences:
The setXSeries( ) method, which populates the vertical axis in a horizontal chart, accepts only an array of strings as input. Chart Builder uses the strings in the array for the labels for the X-axis. The following example shows the array declaration and the call to the setXSeries( ) method:
public final static String USExportsLabels[] =
{"Canada", "Mexico", "Japan"};
MyAxisCh.setXSeries(USExportsLabels);
In horizontal charts, the setYSeries( ) method defines the horizontal axis and the setXSeries( ) method defines the vertical axis. This allows you to easily change a vertical chart to a horizontal chart.
The setYSeries( ) method, which populates the horizontal axis in a horizontal chart, accepts an array of type double as input.
You call the setChartOrientation( ) method, specifying HORIZONTAL, as shown in the following example:
MyAxisCh.setChartOrientation(AxisChart.HORIZONTAL);
You set the graph type to BAR, using the setSeriesGraphType( ) method, as shown in the following example:
MyAxisCh.setSeriesGraphType("Canada", AxisChart.BAR);
The following example shows an excerpt from a Java application that creates a horizontal bar chart:
.
.
.
public final static String USExportsLabels[] =
{"Canada", "Mexico", "Japan"};
public final static double USExports[] = {13390.0, 8136.0, 5824.0};
.
.
.
// Create a new AxisChart object.
AxisChart MyAxisCh = new AxisChart();
// Set the orientation of the chart to be horizontal.
MyAxisCh.setChartOrientation(AxisChart.HORIZONTAL);
// Set the size of the chart.
MyAxisCh.setSize(Chart_width, Chart_height);
// Set the title text.
MyAxisCh.getTitle().setText("U.S. Exports");
// Load the data.
MyAxisCh.setXSeries(USExportsLabels);
MyAxisCh.setYSeries("USexports", USExports);
//Set the graph type.
MyAxisCh.setSeriesGraphType("USExports", AxisChart.BAR);
.
.
.
The following figure shows the resulting horizontal bar chart:
For complete examples of creating axis charts, see the axischart subdirectory of the Chart Builder demos directory.
A pie chart is a circular graph in which the relative percentages of the values are represented by wedges or slices of the pie. For example, you can use a pie chart to compare the volume of exports to various countries.
The following figure shows the major components of a pie chart:
To build a pie chart, you use the Chart Builder PieChart class. To create a basic pie chart, you can accept the Chart Builder defaults to define many characteristics of the chart. You must take the following basic steps:
Create a pie chart object using the PieChart( ) constructor. The following example creates the object MyPieCh:
PieChart MyPieCh = new PieChart();
The name of the pie chart object, MyPieCh, is used in subsequent calls to methods that define the characteristics of the pie chart, such as its size and data.
Define the size of the pie chart using the setSize( ) method. The following line sets the size of the chart area to 200 pixels wide by 180 pixels high:
MyPieCh.setSize(200, 180);
Define the attributes of the pie slices and load the data into the pie chart by using the setSeries( ) method:
MyPieCh.setSeries(USExports)
The setSeries( ) method accepts an array of pie slice descriptors (PieSliceDesc). Each descriptor includes a label and a numeric value that represents the size of the pie slice. The following example shows the array USExports with three pie slice descriptors:
static PieSliceDesc USExports[] = {
new PieSliceDesc("Mexico", 8136.6),
new PieSliceDesc("Japan", 5824.0),
new PieSliceDesc("France", 2110.0)
};
By default, Chart Builder places the label inside the pie slice. If a label does not fit inside the pie slice, Chart Builder places the label outside the pie slice. If no labels fit in the pie slices, Chart Builder displays the labels in a legend. See Section 4.2 for more information about labels and legends.
For more information about loading data into charts, see Section 2.4.
In addition to these steps, you can use Chart Builder methods and descriptors to add information, such as a title and subtitle, to your chart or to customize your chart. For information about customizing charts, see Chapter 3.
The following example shows a Java application that creates a simple pie chart:
/* * Create a pie chart displaying U.S. exports to Canada, Mexico, * Japan, and France. */ import java.awt.*; import oracle.charts.piechart.*; [1] import oracle.charts.types.*; public class pie_example extends Frame { // Data for each slice. USExports[] is an array of PieSliceDesc. [2] static PieSliceDesc USExports[] = { new PieSliceDesc("Canada $13390", 13390), new PieSliceDesc("Mexico $8136", 8136), new PieSliceDesc("Japan $5824", 5824), new PieSliceDesc("France $2110", 2110) }; public static void main(String argv[]) { // Dimensions of chart int Chart_width = 300, Chart_height = 240; // Create a new frame; set its size. [3] Frame f = new Frame(); f.setSize(Chart_width + 10, Chart_height + 20); // Define the color for each pie slice. [4] USExports[0].setBackground(Color.green); USExports[1].setBackground(Color.red); USExports[2].setBackground(Color.yellow); USExports[3].setBackground(Color.blue); try { // Create a new PieChart object. [5] PieChart MyPieCh = new PieChart(); // Set the size of the pie chart. [6] MyPieCh.setSize(Chart_width, Chart_height); // Set the title text and font. [7] MyPieCh.getTitle().setText("U.S. Exports"); // Load the data for each pie slice. MyPieCh.setSeries(USExports); // Add the pie chart component to the frame. f.add(MyPieCh); } catch (ChartException e) { System.out.println(e.getMessage()); } f.show(); } }
The numbers in the example correspond to the numbers in the following list, which describes the example in detail:
The example imports the Chart Builder packages that you need for your chart. This example uses two packages.
An array of pie slice descriptors named USExports is declared. Each descriptor (PieSliceDesc) contains a label and a numeric value that represents the size of the pie slice. The label, which lists the country name and the value, will be displayed in the pie slice. (See Section 4.3.2 for information about a Chart Builder method that automatically includes the value in the label.)
Because this is a Java application, you must create a container, such as frame to display the chart.
Define the colors for each slice of the pie using the setBackground( ) method.
The PieChart( ) constructor creates a new pie chart object. In this example, the object is named MyPieCh.
The setSize( ) method specifies the width and height of the chart by referring to variables that are initialized earlier in the code.
The setSeries( ) method loads the data for the chart. In this example, it loads the data in the array USExports. The setSeries( ) method accepts an array of pie slice descriptors (PieSliceDesc) as input.
The java.awt.frame.add( ) method adds the chart to the frame.
The following figure shows the pie chart created by this example:
For complete examples of creating pie charts, see the piechart subdirectory of the Chart Builder demos directory.
With Chart Builder, you can load data from a variety of sources into the charts you create:
Directly in the application. That is, the data is defined directly in the application code. This method provides the least flexibility, but is useful in testing an application.
The example in Section 2.2.1 demonstrates entering the data directly into the application.
From a text file. This method is available only for axis charts and accepts only arrays of Date and double. See Section 2.4.1.
From an input stream. This method is available only for axis charts and accepts only arrays of Date and double. See Section 2.4.2.
From a database using JDBC. See Section 2.4.3.
Regardless of the source of the data, you use Chart Builder methods to load the data into the charts. The methods you use depend on whether the chart is a vertical axis chart, a horizontal axis chart, or a pie chart.
For vertical axis charts, note the following points about loading data:
Use the setXSeries( ) method to load the data for the X-axis and the setYSeries( ) method to load the data for the Y-axis.
The setXSeries( ) method expects an array of the following types: String or subclasses of java.util.Date (java.sql.date and java.sql.Timestamp). The subclass java.sql.date represents the year, month, and date; the subclass java.sql.Timestamp represents the year, month, date, hour, minute, second, and nanosecond.)
Chart Builder labels the X-axis with the data provided in the array passed to the setXSeries( ) method. If the array is of type String, Chart Builder labels the X-axis with those strings. If the array is of type Date, Chart Builder labels the X-axis automatically, using the full date or abbreviations depending on the size of the chart.
The setXSeries( ) method expects an array of dates to be ascending and not null.
The setYSeries( ) method accepts an array of type double, but you can pass data of any Java Number type. Chart Builder converts it to the type double. See Section 3.6.3 for information about formatting the number.
You must call the setXSeries( ) method before you call the setYSeries( ) method.
For horizontal axis charts, note the following points:
In horizontal charts, the setYSeries( ) method defines the horizontal axis, and the setXSeries( ) method defines the vertical axis. This allows you to easily change a vertical chart to a horizontal chart.
The setYSeries( ) method accepts an array of type double as input.
The setXSeries( ) method accepts only an array of strings as input.
For pie charts, note the following points:
Use the setSeries( ) method to load data into the pie chart.
The setSeries( ) method accepts an array of pie slice descriptors (PieSliceDesc). Each descriptor includes a label and a numeric value that represents the size of the pie slice.
Using the Chart Builder class TimeSeriesFileReader, you can load data from a text file into an axis chart. This class, part of the oracle.charts.io package, reads data from files and converts the data into arrays suitable for populating charts.
This class supports only vertical, not horizontal, axis charts. It accepts only Date (java.util.Date) and Number data types, including locale-specific formats of dates and numbers. It ignores any other data, such as text data, in the file.
Chart Builder is flexible in its support of the format of the data. It supports comma-separated values, space-separated values, and tab-separated values. For example, the following formats are valid:
DATE, NUMBER[, NUMBER][, NUMBER] ...[, NUMBER] DATE NUMBER [NUMBER] [NUMBER] ... [NUMBER] DATE <tab> NUMBER [<tab>NUMBER] [<tab>NUMBER] ... [<tab>NUMBER]
Chart Builder accepts any Java Number type and converts it to the type double. Each data value of type double that is associated with a date value is referred to as an observation. You can have an unlimited number of observations associated with a date value, but all date values must have the same number of observations.
To load data from a text file into a vertical axis chart, take the following basic steps:
Create a new TimeSeriesFileReader object and read the contents of the file into the object using the readFile( ) method. Chart Builder converts the data to arrays of dates and observations.
TimeSeriesFileReader tsReader = new TimeSeriesFileReader();
tsReader.readFile("myfile.txt");
Retrieve the array of dates using the getDates( ) method:
java.util.Date FileDates[] = tsReader.getDates();
Retrieve the array of observations using the getObservations( ) method:
double FileObs[] = tsReader.getObservations();
If each date value is associated with more than one observation, resulting in more than one array of observations, you use the getObservations( ) method for each array. For example, if the file contains two arrays of observations, you could use the following code to retrieve the arrays:
double FileObs[] = tsReader.getObservations(0) double FileObs2[] = tsReader.getObservations(1)
To determine the number of arrays of observations, you can use the getObservationCount( ) method, as shown in the following example:
double FileObs[] = tsReader.getObservations(0)
ObsCount = tsReader.getObservationCount();
if (ObsCount == 2)
FileObs2 tsReader.getObservations(1);
Assume that you have a text file that contains loan rates for 30-year fixed mortgages and for bank prime rates. This file, called loanrate.txt, contains the following data:
Date Mortgage Prime 01/01/2000 8.2100 8.50 02/01/2000 8.3250 8.73 . . . 12/01/2000 7.3820 9.50
You can embed other characters besides dates and numbers in the text file. Chart Builder ignores these characters.
The following example shows excerpts from a Java application that are pertinent to reading data from a file:
import java.awt.*;
import oracle.charts.*;
import oracle.charts.Chart;
import oracle.charts.axischart.*;
import oracle.charts.types.*;
import oracle.charts.legend.*;
import oracle.charts.io.*;
public class readloanrate extends Frame {
//Arrays read in from the file.
static java.util.Date FileDates[];
static double FileObs[];
static double FileObs2[];
static int ObsCount;
public static void main(String[] argv)
{
String fileName = "loanrate.txt";
if (argv.length > 0) fileName = argv[0];
try {
TimeSeriesFileReader tsReader = new TimeSeriesFileReader(); [1]
tsReader.readFile(fileName);
FileDates = tsReader.getDates(); [2]
ObsCount = tsReader.getObservationCount(); [3]
FileObs = tsReader.getObservations(); [4]
if (ObsCount == 2) [5]
FileObs2 = tsReader.getObservations(1);
.
.
.
// Load the timestamps.
MyAxisCh.setXSeries(FileDates); [5]
// Load two data series associated with the timestamps. [6]
MyAxisCh.setYSeries("Mortgage", FileObs);
MyAxisCh.setYSeries("Prime", FileObs2);
.
.
.
}
The numbers in the example correspond to the numbers in the following list, which describes the example in detail:
The TimeSeriesFileReader( ) constructor creates a new object. Using the readFile( ) method, it reads the contents of the data file, loanrate.txt, into the object. The constructor converts the data to arrays of dates and observations.
The getDates( ) method retrieves the array of dates and places it in the array named FileDates.
The getObservationCount( ) method returns the number of arrays of observations in the file.
The getObservations( ) method retrieves the array of observations and places it in the array named FileObs.
The setXSeries( ) method loads the array of dates (FileDates) for the X-axis.
The first setYSeries( ) method loads the first array of observations (FileObs) into the Y-axis. The second setYSeries( ) method loads the second array of observations (FileObs2) into the Y-axis.
The following figure shows the resulting line chart:
For complete examples of reading data from a file, see the readfile subdirectory of the Chart Builder demos directory.
Using the Chart Builder class TimeSeriesFileReader, you can load data from an input stream into an axis chart. The data can originate anywhere, such as in memory, in a file, or generated by another program. As with loading data from a text file, this class accepts only Date (java.util.Date) and Number data types, including locale-specific formats of dates and numbers. The TimeSeriesFileReader class reads the data and converts it into arrays suitable for populating charts.
Loading data from an input stream is similar to loading data from a file. Instead of the readFile( ) method, you use the read( ) method.
The following describes the steps pertinent to reading an input stream:
Create the input stream using a Java input stream method. The following example uses the FileInputStream( ) method.
FileInputStream myInputStream = null;
Open the input stream using the openInputStream( ) method:
myInputStream = openInputStream(fileName);
Create a new TimeSeriesFileReader object and read the contents of the input stream into the object using the read( ) method. Chart Builder converts the data to arrays of dates and observations.
TimeSeriesFileReader tsReader = new TimeSeriesFileReader(); tsReader.read(myInputStream); FileObs = tsReader.getObservations(); FileDates = tsReader.getDates();
For a complete example of reading data from an input stream, see the readfile subdirectory of the Chart Builder demos directory.
Using Java Database Connectivity (JDBC), you can retrieve data from a database and then use Chart Builder to load the data into a chart.
JDBC is a standard Java interface for connecting from Java to relational databases. You can use JDBC to query tables and return data where, for example, the number and types of the columns are not known until runtime. This capability is called dynamic SQL. Therefore, JDBC is a way to use dynamic SQL statements in Java programs. With Chart Builder, you can load the data from the database into any chart.
When you use JDBC to load data into charts, you take the following steps:
Take the typical JDBC steps, such as loading the JDBC driver, connecting to the database, and creating a statement object. See the JDBC documentation for more information.
Create the SQL statement that queries the database to get the data. Then, execute a SQL statement that counts the number of rows that will be returned by the statement. Use the number of rows to allocate arrays for the data.
Execute the SQL statement and store the returned values into the arrays.
Use the setXSeries( ) and setYSeries( ) methods to load the data into the charts from the arrays.
Assume that a database table, ECONOMIC_TAB, contains data about the amount of imports and exports each month from a number of countries. This table contains the following data:
SYMBOL TSTAMP OBS1 ---------- --------- ---------- EXPCA 01-JAN-90 6377.5 IMPFR 01-JAN-90 1078.3 EXPJP 01-JAN-90 4028 IMPJP 01-JAN-90 6878.2 . . . EXPCA 01-JAN-00 13570 IMPJP 01-JAN-00 10302 IMPMX 01-JAN-00 9567
The following example shows excerpts from a Java application that gets the amount of imports from Japan, by month, from the database and loads the data into an axis chart:
// Import the Java classes.
import java.awt.*;
// Import the JDBC classes.
import java.sql.*;
// Import the Chart Builder classes.
import oracle.charts.*;
import oracle.charts.axischart.*;
import oracle.charts.types.*;
public class jdbc_imp extends Frame {
// Declare the driver to be loaded.
static final String driver_class = "oracle.jdbc.driver.OracleDriver";
// Declare the connect string.
static final String connect_string =
"jdbc:oracle:thin:scott/tiger@host:1521:orcl2";
// Declare the connection to the database.
static Connection conn;
// Declare the arrays to hold the data.
static java.sql.Timestamp TimeStamps[];
static double Observation[];
static int Display_height;
static int Display_width;
public static void main(String[] argv)
{
.
.
.
getData();
try {
// Create a new AxisChart object.
AxisChart MyAxisCh = new AxisChart();
.
.
.
// Load the timestamps. [9]
MyAxisCh.setXSeries(TimeStamps);
// Load the data series, JapanImp, associated with the timestamps. [9]
MyAxisCh.setYSeries("JapanImp", Observation);
// Add the chart to the frame.
f.add(MyAxisCh);
} catch (ChartException e)
{
System.out.println(e.getMessage());
}
f.show();
}
public static void getData() {
// Open a connection to the database if one is not open.
if (conn == null) {
// Load the JDBC driver. [1]
try {
Class.forName (driver_class);
}
catch (ClassNotFoundException ex ) {
System.out.println ("Could not load class: " +
driver_class + "\n");
}
// Connect to the database and create a connection object. [2]
try {
conn = DriverManager.getConnection (connect_string);
} catch (SQLException e)
{ System.out.println(e.getMessage()); };
}
// When the connection has been established, query the database.
try {
// Create a statement object. [3]
Statement stmt = conn.createStatement ();
ResultSet rset;
// Describe the source of data.
// Define table and column names.
String tableName = "economic_tab";
String dateColumnName = "TSTAMP";
String obsColumnName = "OBS1";
String symbolColumnName = "SYMBOL";
// Define the data we wish to query.
String obs = "IMPJP";
String startDate = "01-JAN-1991";
String endDate = "01-JAN-2000";
// Define strings to be used to construct the query. The query will
// return timestamps and numeric values from two columns in the
// ECONOMIC_TAB table where the date is between a given start
// and end date.
String selectClauseCount = "SELECT count(*) "; [4]
String selectClause = "SELECT " + dateColumnName + ", " +
obsColumnName + " ";
String fromClause = "FROM " + tableName + " ";
String whereA = "WHERE tstamp >= to_date(" + "'" + startDate
+ "', 'DD-MON-YYYY') ";
String whereB = "AND tstamp <= to_date(" + "'" + endDate +
"', 'DD-MON-YYYY') ";
String whereC = "AND " + obsColumnName + " is not null ";
String whereD = "AND " + symbolColumnName + " = '" + obs + "'";
String fromWhere = fromClause + whereA + whereB + whereC + whereD;
// Execute a SELECT statement to get the number of rows that will
// be returned by the query and save the result in numRows.
rset = stmt.executeQuery (selectClauseCount + fromWhere); [5]
rset.next();
int numRows = rset.getInt(1);
// Allocate arrays for the timestamps and the data, using
// the value of numRows to size the arrays.
TimeStamps = new java.sql.Timestamp[numRows]; [6]
Observation = new double[numRows];
// Execute the SELECT statement and store the results
// in the result set object.
rset = stmt.executeQuery (selectClause + fromWhere); [7]
// Iterate through the results and store the values in the arrays.
int k = 0; [8]
while (rset.next ()) {
TimeStamps[k] = rset.getTimestamp(1);
Observation[k] = rset.getDouble(2);
if (rset.wasNull())
System.out.println("Was null (1) " + k);
k++;
}
.
.
.
The following list describes the parts of the example that pertain to using JDBC to load data into a chart:
The JDBC Class.forName( ) method loads the JDBC driver.
The DriverManager.getConnection( ) method connects to the database and creates the Connection object conn. The connect string you use depends on what JDBC driver you are using.
The JDBC createStatement( ) method creates the Statement object, stmt.
The SQL statements are constructed using variables for the database object names and strings for the clauses.
The executeQuery( ) method executes a SQL statement that counts the number of rows that will be returned.
The count returned in step 5 is used to allocate the arrays for the timestamps and the data associated with them.
The executeQuery( ) method executes the SQL statement and returns the data to the result set object, rset.
The next( ) method iterates through the result set object row by row and stores the values in the arrays.
The setXSeries( ) method loads the array of dates (Timestamps) into the X-axis. The setYSeries( ) method loads the array of imports (Observation) into the Y-axis.
The following figure shows the chart that is generated:
For complete examples of loading data from a database, see the jdbc subdirectory of the Chart Builder demos directory.
Chart Builder makes it easy to generate image files of the charts you create. Chart Builder provides encoders for GIF, JPG, or wireless bitmap (WBMP) files. After you encode the charts, you can embed the resulting files in HTML pages or other documents.
|
Note: The Java Developer's Kit (JDK) provides a JPG encoder. However, JPG is not an ideal image format for creating charts. |
Chart Builder exposes the buffered image that holds the chart, using the BufferedImage constructor of the java.awt.image package. This exposure provides the following advantages:
You can control the attributes of the buffered image. For example, you can specify grayscale or index color image types to encode the resulting file.
You can use one of the encoders provided by Chart Builder or use another encoder of your choice.
The following Java application builds an axis chart and generates a GIF file of the chart:
/*
* Creates GIF chart images.
*/
import java.awt.*;
import java.awt.image.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Calendar;
import oracle.charts.*;
import oracle.charts.axischart.*;
import oracle.charts.types.*;
import oracle.charts.codec.*;
public class generate_img {
// Chart data, defined inline.
// Dates defined with start and end dates in setXSeries.
// Population (in thousands) associated with timestamps.
public final static double Population[] =
{
246224, 248659, 251373, 254025, 256830,
259413, 264291, 266768, 269328, 271883
};
public static void main(String[] argv)
{
// Width and height of the chart.
int Chart_height = 200;
int Chart_width = 400;
try {
// Create a new AxisChart object.
AxisChart MyAxisCh = new AxisChart();
// Set the size of the chart.
MyAxisCh.setSize(Chart_width, Chart_height);
// Load the timestamps, using start and end dates.
MyAxisCh.setXSeries(Calendar.YEAR,
java.sql.Date.valueOf("1990-01-01"),
java.sql.Date.valueOf("1999-01-01"),
1);
// Load the population series associated with the timestamps.
// The series is named uspopulation.
MyAxisCh.setYSeries("uspopulation", Population);
// Specify a bar chart.
// Note that the series is referred to by the name uspopulation.
MyAxisCh.setSeriesGraphType("uspopulation", AxisChart.BAR);
// Set title, subtitle, and footnote.
MyAxisCh.getTitle().setText("U.S. Population");
MyAxisCh.getSubtitle().setText("Reported in Thousands");
MyAxisCh.getFootnote().setText(
"Source: U.S. Department of Commerce, Census Bureau");
//Define a buffered image. Use TYPE_BYTE_INDEXED for color GIFs.[1]
BufferedImage bufimg = new BufferedImage(Chart_width, Chart_height,
BufferedImage.TYPE_BYTE_INDEXED);
// Get the graphics context of the buffered image. [2]
Graphics2D g2 = null;
g2 = bufimg.createGraphics();
// For file encoding. [3]
MyAxisCh.drawBuffer(g2);
// Create the GIF file. [4]
EncodeGifFile(bufimg, "gifsample.gif");
} catch (ChartException e)
{
System.out.println(e.getMessage());
}
System.exit(1);
}
// Encode a GIF file.
public static void EncodeGifFile(BufferedImage bufimg, String filename)
{
FileOutputStream out = null;
try {
File file = new File(".", filename);
out = new FileOutputStream(file);
} catch (java.io.IOException e) {
System.err.println("Cannot create ./" + filename);
System.exit(1);
}
try {
GIFEncoder encoder = new GIFEncoder(out); [5]
encoder.encode(bufimg);
} catch (java.io.IOException e) {
System.err.println("I/O exception");
System.exit(1);
}
}
}
The following list describes the parts of the example that relate to generating an image file:
Define a buffered image using the BufferedImage constructor. This example defines a buffered image called bufimg.
Note that the image type you specify depends on the type of file you are encoding. Because this example creates a color GIF image, it uses the TYPE_BYTE_INDEXED data type.
Get the graphics context of the buffered image using the BufferedImage createGraphics( ) method. This example instantiates it in the graphics object named g2.
Call the drawBuffer( ) method to render the chart into the buffered image associated with g2.
This example calls a routine named EncodeGifFile( ) to encode the file as a GIF file. It names the file gifsample.gif.
Encode the file as a GIF file using the GIFEncoder( ) constructor and write it out to the output file.
The following figure shows the GIF file created by the example:
When you use the BufferedImage constructor, the data type you specify for the image_type argument depends on the type of image file you want to generate:
For color GIF files, use TYPE_BYTE_INDEXED, which generates 8-bit images.
For grayscale GIF files, use TYPE_BYTE_GRAY.
For color JPG files, use TYPE_INT_RGB, which generates 24-bit images.
For grayscale JPG files, use TYPE_USHORT_GRAY.
For WBMP files, use TYPE_BYTE_BINARY.
Note that GIF files provide clearer images than JPG files. Because of compression, JPG files may display banding across the images.
For information about other image types, see the Java documentation for the BufferedImage constructor.
For complete examples of generating GIF files, see the piechart subdirectory of the Chart Builder demos directory.
Generally, when you use the encoders to generate image files of the charts, Chart Builder generates image files with good image quality. However, charts that contain many colors or contain transparencies may benefit from additional processing. To create a higher-quality GIF image, Chart Builder provides the Quantizer class. This class provides the rgb24to8( ) method, which converts (quantizes) a 24-bit image to an 8-bit image.
The following example shows the code used to quantize a pie chart:
// Define a buffer for a 24-bit image. Use TYPE_INT_RGB. [1] BufferedImage bufimg24 = new BufferedImage(Chart_width, Chart_height, BufferedImage.TYPE_INT_RGB); // Define a buffer for an 8-bit image. Use TYPE_BYTE_INDEXED. [2] BufferedImage bi = new BufferedImage(Chart_width, Chart_height, BufferedImage.TYPE_BYTE_INDEXED); // Get the graphics context of the 24-bit buffered image. [3] Graphics2D g2 = null; g2 = bufimg24.createGraphics(); // For file encoding. MyPieCh.drawBuffer(g2); [4] // Use the rgb24to8() method to convert the 24-bit image to 8-bit. [5] bi = Quantizer.rgb24to8(bufimg24); // Create the GIF file. [6] EncodeGifFile(bi, "pie_example_quant.gif");
Define a buffered image for a 24-bit image using the BufferedImage constructor. This example defines a buffered image called bufimg24.
Note that the image type you specify depends on the type of file you are encoding. Because this example creates a 24-bit image, it uses TYPE_INT_RGB.
Define a buffered image for an 8-bit image using the BufferedImage constructor. This example defines a buffered image called bi.
Note that the image type you specify depends on the type of file you are encoding. Because this example creates an 8-bit GIF image, it uses TYPE_BYTE_INDEXED.
Get the graphics context of the 24-bit buffered image using the BufferedImage createGraphics( ) method. This example instantiates it in the graphics object named g2.
Call the drawBuffer( ) method to render the chart into the buffered image associated with g2.
Use the rgb24to8( ) method to convert (quantize) the 24-bit image to an 8-bit image.
Encode the file as a GIF file using the GIFEncoder( ) constructor and write it out to the output file.
The following figure shows the resulting GIF file:
|
![]() Copyright © 2002 Oracle Corporation All rights reserved |
|