JClass Chart

PreviousNextIndex

6

Chart Programming Tutorial

Introduction  A Basic Plot Chart  Loading Data From a File  Adding Header, Footer, and Labels 

Changing to a Bar Chart  Inverting Chart Orientation  Bar3d and 3d Effect

End-User Interaction  Get Started Programming with JClass Chart


6.1 Introduction

This tutorial shows you how to start using JClass Chart by compiling and running an example program. It is different from the SimpleChart Bean tutorial because it focuses on programmatic use of JClass Chart. For a Bean tutorial, see the SimpleChart Bean Tutorial, in Chapter 3. This program, Plot1.java, will graph the 1963 Quarterly Expenses and Revenues for "Michelle's Microchips", a small company a little ahead of its time.

The following table shows the data to be displayed:

 

Q1

Q2

Q3

Q4

Expenses

150.0 175.0 160.0 170.0

Revenue

125.0 100.0 225.0 300.0


6.2 A Basic Plot Chart

When Plot1.java is compiled and run, the window shown below is displayed:

Figure 16 :  The Plot1.java program displayed.

The following listing displays the program Plot1.java. This is a minimal Java program that creates a new chart component and loads data into it from a file. It can be run as an applet or a standalone application.

Line

Source

1

package examples.chart.intro;

2

 

3

import java.awt.GridLayout;

4

import javax.swing.JPanel;

5

import com.klg.jclass.chart.JCChart;

6

import com.klg.jclass.chart.ChartDataView;

7

import com.klg.jclass.chart.data.JCFileDataSource;

8

import com.klg.jclass.util.swing.JCExitFrame;

9

 

10

import demos.common.FileUtil;

11

 

12

/**

13

* Basic example of Chart use. Load data from

14

* a file and displays it as a simple plot chart.

15

*/

16

public class Plot1 extends JPanel {

17

 

18

/**

19

* Default constructor for this class. Loads data and

20

* sets up chart.

21

*/

22

public Plot1() {

23

   setLayout(new GridLayout(1,1));

24

 

25

   // Create new chart instance.

26

   JCChart chart = new JCChart();

27

   // Load data for chart

28

   try {

29

     // Use JCFileDataSource to load data from specified file

30

     String fname = FileUtil.getFullFileName(

31

        "examples.chart.intro","chart1.dat");

32

     chart.getDataView(0).setDataSource(new JCFileDataSource

33

        (fname));

34

   }

35

   catch (Exception e) {

36

     e.printStackTrace(System.out);

37

   }

38

   // Add chart to panel for display.

39

   add(chart);

40

}

41

 

42

public static void main(String args[]) {

43

   JCExitFrame f = new JCExitFrame("Plot1");

44

   Plot1 p = new Plot1();

45

   f.getContentPane().add(p);

46

   f.setSize(200, 200);

47

   f.setVisible(true);

48

}

49

 

50

}

51

 

Most of the code in Plot1.java should be familiar to Java programmers. The first few lines (3-10) import the classes necessary to run Plot1.java. In addition to the standard AWT GridLayout class and Swing JPanel class, three classes in the jclass.chart package are needed: JCChart (the main chart class), ChartDataView (the data view object), and JCFileDataSource (a stock data source). This example also makes use of the JCExitFrame from JClass Elements, which is a part of the JClass DesktopViews suite. Line 16 provides the class definition for this program, a subclass of JPanel.

Lines 22-40 define the constructor. The Layout property on line 23 lays out a simple grid structure to display the components it holds. A new chart is then instantiated on line 26. Lines 30-31 load data from a file named chart1.dat into a new data source object (JCFileDataSource) and tell the chart to display this data.

Lines 42-48 define the main() method needed when the program is run as a standalone Java application.


6.3 Loading Data From a File

A common task in any JClass Chart program is to load the chart data into a format that the chart can use. JClass Chart uses a "model view/control" (MVC) architecture to handle data in a flexible and efficient manner. The data itself is stored in a object that implements the ChartDataModel interface created and controlled by your application. The chart has a ChartDataView object that controls a view on this data source, providing properties that control which data source to use, and how to display the data.

JClass Chart includes several stock (built-in) data sources that you can use (or you can define your own). This program uses the data source that reads data from a file: JCFileDataSource. With this understanding we can look more closely at lines 32-33:

chart.getDataView(0).setDataSource(new JCFileDataSource
  (fname));

Two things are happening here: a new JCFileDataSource object is instantiated, with the name of the data file passed as a parameter in the constructor, and the DataSource property of the chart's first (default) data view is being set to use this data source.

The following shows the contents of the chart1.dat file:

  ARRAY 2 4
  # X-values
  1.0 2.0 3.0 4.0
  # Y-values
  150.0 175.0 160.0 170.0
  # Y-values set 2
  125.0 100.0 225.0 300.0

This file is in the format understood by JCFileDataSource. Lines beginning with a `#' symbol are treated as comments. The first line tells the FileDataSource object that the data that follows is in Array layout and is made up of two series containing four points each. The X-values are used by all series.

There are two types of data: Array and General. Use Array layout when the series of Y-values share common X-values. Use General when the Y-values do not share common X-values, or when all series do not have the same number of values.

Note that for data arrays in Polar charts, (x, y) coordinates in each data set will be interpreted as (theta, r). For array data, the X-array will represent a fixed theta value for each point.

In Radar and Area Radar charts, only array data can be used. (x, y) points will be interpreted in the same way as for Polar charts (above), except that the theta (that is, x) values will be ignored. The circle will be split into nPoints segments with nSeries points drawn on each radar line.

For complete details on using data with JClass Chart, please see Data Sources, in Chapter 8.


6.4 Adding Header, Footer, and Labels

The plot displayed by Plot1.java is not very useful to an end-user. There is no header, footer, or legend, and the X-axis numbering is not very meaningful.

The chart below displays various changes that can be made to a chart to make it more useful. The changes made to this chart are listed below. Full source code can be found in the plot2.java program, located in the JCLASS_HOME/examples/chart/intro directory.

Figure 17 :  The program created by Plot2.java.

JClass Chart will always try to produce a reasonable chart display, even if very few properties have been specified. JClass Chart will use intelligent defaults for all unspecified properties.

All properties for a particular chart may be specified when the chart is created. Properties may also be changed as the program runs by calling the property's set method. A programmer can also ask for the current value of any property by using the property's get method.

Adding Headers and Footers

To display a header or footer, we need to set properties of the Header and Footer objects contained in the chart. For example, the following code sets the Text and Visible properties for the footer:

// Make footer visible
  chart.getFooter().setVisible(true);
  // By default, footer is a JLabel - set its Text property
  ((JLabel)chart.getFooter()).setText("1963 Quarterly Results");

Visible displays the header/footer. Text specifies the text displayed in the header/footer.

By default, headers and footers are JLabels, although they can be any Swing JComponent. JLabels support the use of HTML tags. The use of HTML tags overrides the default Font and Color properties of the label.

Please note that HTML labels may not work with PDF, PS, or PCL encoding.

Adding a Legend and Labelling Points

A legend clarifies the chart by showing an identifying label for each series in the chart. We would also like to display more meaningful labels for the points along the X-axis. Both types of information can be easily specified in the data file itself. The following lists chart2.dat, a modified version of the previous data file that includes series labels (for the legend), and point labels (for the X-axis):

  ARRAY '' 2 4
  # Point Labels
  'Q1' 'Q2' 'Q3' 'Q4'
  # X-values, with a blank series label ('') -- a blank series
  # label is required if the Y-values have series labels
  '' 1.0 2.0 3.0 4.0
  # Y-values, with Series label (in this case, Expenses)
  'Expenses' 150.0 175.0 160.0 170.0
  # Y-values set 2, with Series label (in this case, Revenue)
  'Revenue' 125.0 100.0 225.0 300.0

Lines beginning with a `#' symbol are treated as comments.

As noted in the comments within the above code, if series labels are being used for the Y-values, then the X-data must be preceded by a blank series label (''). This blank label will not show up on the chart. The third line specifies the point labels (for instance, "Q1"). Subsequent lines of data begin with a Y-data series label ("Expenses" and "Revenue").

This data file now provides the labels that we want to use, but to actually display them in the chart, we need to set the Legend object's Visible property and change the AnnotationMethod property of the X-axis to annotate the axis with the point labels in the data.

These and the previous changes are combined; now the chart is created with code that looks like this:

// Create new chart instance.
chart = new JCChart();
  // Load data for chart
  try {
    // Use JCFileDataSource to load data from specified file
    String fname = FileUtil.getFullFileName("examples.chart.intro",
      "chart2.dat");
    chart.getDataView(0).setDataSource(new   
      JCFileDataSource(fname));

  }
  catch (Exception e) {
    e.printStackTrace(System.out);
  }
  // Make header visible, and add some text
  chart.getHeader().setVisible(true);
  // By default, header is a JLabel šš-- set its Text property
  ((JLabel)chart.getHeader()).setText("Michelle's Microchips");
  // Make footer visible
  chart.getFooter().setVisible(true);
  // By default, footer is a JLabel -- set its Text property
  ((JLabel)chart.getFooter()).setText("1963 Quarterly Results");

  // Make legend visible
  chart.getLegend().setVisible(true);

  // Make X-axis use point labels instead of default value labels.
  chart.getChartArea().getXAxis(0).setAnnotationMethod
    (JCAxis.POINT_LABELS);


  // Add chart to panel for display.
  add(chart);

Because we are accessing a variable defined in JCAxis, we need to add that to the classes imported by the program:

import jclass.chart.JCAxis;

In the line that sets the annotation method, notice that XAxis is a collection of JCAxis objects. A single chart can display several X- and Y-axes.


6.5 Changing to a Bar Chart

Figure 18 :  The bar2.java program displayed.

A powerful feature of JClass Chart is the ability to change the chart type independently of any other property. (Although there are interdependencies between some properties, most properties are completely orthogonal.) For example, to change the Plot2 chart to a bar chart, the following code can be used:

c.getDataView(0).setChartType(JCChart.BAR);

This sets the ChartType property of the data view. Alternately, you can set the chart type when you instantiate a new chart, for example:

JCChart c = new JCChart(JCChart.BAR);

The full code for this program (Bar2.java) can be found in with the other examples.

JClass Chart can display data as one of 13 different chart types. For more information on chart types, see Chart Types and Special Chart Properties, in Chapter 2.


6.6 Inverting Chart Orientation

Most graphs display the X-axis horizontally and the Y-axis vertically. It is often appropriate, however, to invert the sense of the X- and Y-axis. This is easy to do, using the Inverted property of the data view object.

In a plot, inverting causes the Y-values to be plotted against the horizontal axis, and the X-values to be plotted against the vertical. In a bar chart, it causes the bars to be displayed horizontally instead of vertically.

When programming JClass Chart, try not to assume that the X-axis is always the horizontal axis. Determining which axis is vertical and which horizontal depends on the value of the Inverted property.

To invert, set the data view object's Inverted property to true. By default it is false.

c.getDataView(0).setInverted(true);

The following shows the windows created by Plot2.java and Bar2.java when inverted:

Figure 19 :  Plot2 and Bar2 windows with Inverted set to true.

Full code for these examples is in the JCLASS_HOME/examples/chart/intro directory.


6.7 Bar3d and 3d Effect

Chart 3D effects can be added to bar and stacking bar charts. Three properties affect the display of 3D information: Depth, Elevation, and Rotation. Modifying these properties will alter the 3D effects displayed. Depth and at least one of Elevation or Rotation must be non-zero to see any 3D effects. The properties can be set as follows:

chart.getChartArea().setElevation(20);
chart.getChartArea().setRotation(30);
chart.getChartArea().setDepth(10);

Function call

Header for the function

Description

setDepth()

public void setDepth(
   int newDepth)

Controls the apparent depth of the chart; the parameter newDepth represents the depth as a percentage of the width; valid values are 0 to 500.

setElevation()

public void setElevation(
   int newElevation)

Controls the distance above the X-axis for the 3D effect; the parameter newElevation is the number of degrees above the X-axis that the chart is to be positioned; valid values are between -45 and 45.

setRotation()

public void setRotation(
   int newRotation)

Controls the position of the eye relative to the Y-axis for the 3D effect; the parameter newRotation is the number of degrees to the right of the Y-axis the chart is to be positioned; valid values are between
-45 and 45.


6.8 End-User Interaction

More than simply a display tool, JClass Chart is an interactive component. Programmers can explicitly add functions that enable an end-user to directly interact with a chart. The following end-user interactions are possible:


6.9 Get Started Programming with JClass Chart

The following suggestions should help you become productive with JClass Chart as quickly as possible:


PreviousNextIndex