|
Oracle® Chart Builder Application Developer's Guide
Release 1.0 Part No. A96127-01 |
|
With Chart Builder, you can create interactive and dynamic charts. Interactive charts detect mouse movement over chart elements and associate that movement with particular actions, such as highlighting a bar or drilling down to another chart. Dynamic charts can load data that is not defined when the application is created, and they can update the data as it is refreshed.
This chapter discusses the following topics:
Building Interactive Charts using image maps or the Chart Builder event model
You can build interactive charts using Java applications, Java applets, servlets, and JavaServer Pages. In addition, you can deploy interactive charts in HTML pages:
For HTML pages that do not rely on running Java in the browser, Chart Builder supports interactive charts that use chart image maps that you can automatically generate using Chart Builder. See Section 5.1.1.
For Java applications, Java applets, JavaServer Pages (JSP), and servlets, Chart Builder supports an event model that allows your application to detect mouse movement (events) over chart elements, such as the mouse entry and exit from individual bars. When the event occurs, your application can take an action, such as drilling down to another chart or highlighting the bar. See Section 5.1.2.
For HTML pages that do not rely on running Java in the browser, Chart Builder supports interactive charts by generating image maps.
When you generate image maps with Chart Builder, the hotspot areas are automatically defined. Each pie slice in a pie chart, each bar in a bar chart, each point on a line chart or area chart, or each group of values representing one time period on a stock chart is defined as a hotspot area in the image map.
Chart Builder lets you associate mouse-related events on the hotspot areas of the image with various actions. For example, when the mouse pointer is positioned over a bar in a bar chart, you can drill down to a more detailed chart, by using image replacement or a reference to a URL.
|
Note: Chart Builder supports both client-side and server-side image maps. For the most part, you use the same Chart Builder methods for either type of image map. |
With Chart Builder, you can associate the following events with areas in an image map:
Mouse-over events: The mouse pointer is positioned over a hotspot area.
Mouse-out events: The mouse pointer moves out of a hotspot area.
When an event occurs, Chart Builder supports loading a specific URL in a new browser window or replacing one image with another image in the same HTML page.
The following table shows the events supported by Chart Builder. Each of the methods enables the generation of a different block of HTML code. These HTML block codes define HTML event handlers associated with each hot spot.
Each hotspot area can respond to more than one mouse event. For example, when a mouse-over event occurs, a bar chart can be displayed to the right of the image map. When a mouse-click event occurs, a line chart can be displayed instead.
To create an image map with Chart Builder, you take the following basic steps:
Define the attributes of the image map. First, allocate an ImageMapDesc object. Using the descriptor object, you can define attributes, such as the name of the image map, the mouse-event handlers to be used, the path to be prepended to a file name, and the target browser window.
The following image map descriptor names the image map imports. It also specifies the href event handler, a prefix and extension for the URL, and the target window for the link.
// Create an image map descriptor object.
ImageMapDesc desc = new ImageMapDesc();
// Name the image map.
desc.setMapName("imports");
// Using the href event handler, set the prefix of the hyperlink.
// The directory "bars/" is prepended to the map name.
desc.getHrefDesc().setHyperLinkPrefix("bars/");
// Set the extension of the URL to .gif.
desc.getHrefDesc().setHyperLinkExtension(".gif");
// Specify that the link open in a new unnamed window.
desc.getHrefDesc().setTarget("_blank");
Enable the image map. For client-side image maps, use the setEnableImageMapCS( ) method. For server-side image maps, use the setEnableImageMapSS( ) method. Invoke one or both methods before invoking the drawBuffer( ) method.
The following code enables a client-side image map and creates the chart:
// Enable the generation of the client-side image map, // passing the image map descriptor parameter. MyPieCh.setEnableImageMapCS(desc); // Create the chart. MyPieCh.drawBuffer(g2);
Retrieve the generated image map. For client-side image maps, use the getImageMapCS( ) method. For server-side image maps, use the getImageMapSS( ) method. Invoke either method after the drawBuffer( ) method.
The following code retrieves a client-side image map, returning a character array that defines an image map:
// Retrieve the client-side image map. char imageMap[] = MyPieCh.getImageMapCS();
Insert the generated image map into an HTML document and associate the image map with the appropriate image. For example, to associate the hotspot image with the image map for a client-side image map, use code similar to the following:
<IMG SRC="clickurl.gif" align=center hspace=5 usemap="#imports">
Axis charts and pie charts use most of the same methods and descriptors to generate image maps.
Use the ImageMapDesc descriptor to define the attributes of the image map. Note the following points about specifying the image map attributes:
The setMapName( ) method, part of the ImageMapDesc class, defines the map name.
Chart Builder uses the attributes to construct the URL for the hyperlink for each area, creating hyperlinks that are numerically sequenced. To construct the URL, Chart Builder uses the following format:
<Prefix><HyperlinkName><Sequence_Number><Extension>
Use the methods of the SequencedHyperLinkDesc class to specify parts of the URL:
Prefix: The setHyperLinkPrefix( ) method adds a prefix to the hyperlink. You can use this method to specify the path of a hyperlink. The default is a null string.
HyperlinkName: For pie charts, Chart Builder uses the map name by default to define the HyperlinkName. For axis charts, Chart Builder uses the series name by default as the HyperlinkName.
You can override the default by using the setHyperLinkName( ) method.
Sequence_Number: Chart Builder assigns a sequence number to each area, such as a slice in a pie chart or a bar in a bar chart. By default, the sequence numbers start with 0. You can override the default by using the setHyperLinkStartIndex( ) method.
Extension: The setHyperLinkExtension( ) method specifies a file extension for the hyperlink. The default is .html.
For a pie chart, the image map contains an HTML area specification for each pie slice. For an axis chart, the image map contains an HTML area specification for each bar on a bar chart, each point on a line chart or area chart, or each group of values representing one time period on a stock chart.
Consider an example where the pie chart contains three slices, the image map is named imports, and the href event handler is used. Chart Builder generates an image map similar to the following:
<!-- Client-Side Image Map --> <!-- Generated by Oracle Chart Builder --> < map name="imports"> <area shape=poly coords=100,111,169,111,168,...84,32,99,100,111 href=#myanchor onClick="document.images['barchart'].src='bars/imports0.gif' "> <area shape=poly coords=100,111,32,99,31,...177,98,180,100,111 href=#myanchor onClick="document.images['barchart'].src='bars/imports1.gif' "> <area shape=poly coords=100,111,98,180,111,...169,111,100,111 href=#myanchor onClick="document.images['barchart'].src='bars/imports2.gif' "> </map>
The following example shows a Java application that creates an image map. When a mouse click occurs on a pie slice, the image map replaces an existing chart with one associated with the clicked pie slice:
.
.
.
// Load the data for each pie slice.
MyMapPieCh.setSeries(USExports);
// Create a buffered image.
BufferedImage bi = new BufferedImage(Ch_width,
Ch_height, BufferedImage.TYPE_BYTE_INDEXED);
Graphics2D g2 = bi.createGraphics();
// Enable the generation of a client-side image map.
ImageMapDesc desc = new ImageMapDesc(); [1]
desc.setMapName("imports"); [2]
// Assert a fixed href.
// This prevents the page from being reloaded when the mouse is
// clicked.
desc.setFixedHref("#myanchor"); [3]
// Define the name of the replacement image.
desc.setReplacementImageName("barchart"); [4]
// Enable the onClick event handler.
desc.getOnClickDesc().setEnable(); [5] [6]
// Set the path prefix and extension of the sequenced URL.
desc.getOnClickDesc().setHyperLinkPrefix("bars/"); [7]
desc.getOnClickDesc().setHyperLinkExtension(".gif"); [8]
// Enable a client-side image map.
MyMapPieCh.setEnableImageMapCS(desc); [9]
// For file encoding.
MyMapPieCh.drawBuffer(g2);
// Retrieve the image map and write it to a file.
char imageMap[] = MyMapPieCh.getImageMapCS(); [10]
writeImageMapFile("clickreplacemap.html", imageMap);
EncodeGifFile(bi, "clickreplace.gif");
.
.
.
The numbers in the example correspond to the numbers in the following list, which describes the example in detail:
The setMapName( ) method defines the map name to be imports. This name is used in the generated image map and to define the HyperlinkName portion of the sequenced hyperlink URL.
The setFixedHref( ) method provides an anchor to the current page. Without this method, the image map would link to another page, instead of only replacing an image on the page.
The setReplacementImageName( ) method specifies that the image named barchart be replaced when the mouse is clicked on a pie slice.
The getOnClickDesc( ) method specifies that the onClick event handler will be used.
The setEnable( ) method enables the onClick event handler and generates the specified action in the image map.
The setHyperLinkPrefix( ) method specifies that the prefix bars/ be added to the URL for the hyperlink.
The setHyperLinkExtension( ) method specifies that the file extension .gif be added to the URL for the hyperlink.
The setEnableImageMapCS( ) method enables a client-side image map. You must invoke this method before invoking the drawBuffer( ) method.
The getImageMapCS( ) method retrieves a client-side image map. Then, the image map is written to a file using the writeImageMapFile( ) method.
This example generates the following image map:
<!-- Client-Side Image Map --> <!-- Generated by Oracle Chart Builder --> <map name="imports"> < map name="imports"> <area shape=poly coords=100,111,169,111,168,...84,32,99,100,111 href=#myanchor onClick="document.images['barchart'].src='bars/imports0.gif' "> <area shape=poly coords=100,111,32,99,31,...177,98,180,100,111 href=#myanchor onClick="document.images['barchart'].src='bars/imports1.gif' "> <area shape=poly coords=100,111,98,180,111,...169,111,100,111 href=#myanchor onClick="document.images['barchart'].src='bars/imports2.gif' "> </map>
Subsequently, Web page designers can insert the image map into an HTML page and associate it with the proper image. In addition, they specify the name of the image to be replaced. The following excerpt from an HTML page shows the coding:
<IMG SRC="clickreplace.gif" align=center hspace=5 usemap="#imports"> <IMG NAME="barchart" SRC="bars/imports0.gif" align=top hspace=5>
Note that this example assumes that the replacement charts, such as import0.gif, have been generated in advance.
The following figure shows an HTML page that contains the image map:
When you click on a pie slice in the chart on the left, the associated bar chart is displayed on the right.
Building an interactive axis chart using image maps is similar to creating an interactive pie chart. The primary difference is that Chart Builder uses the series name, rather than the map name, in constructing the sequenced hyperlink.
The following example builds an interactive axis chart that contains two series:
.
.
.
// Create a new AxisChart object.
AxisChart MyAxisCh = new AxisChart();
// Set the size and background of the chart.
MyAxisCh.setSize(Chart_width, Chart_height);
MyAxisCh.setPlotBackground(lightGray);
MyAxisCh.setChartAttributes(yAxisD);
// Load the timestamps.
MyAxisCh.setXSeries(AnnualDates);
// Load data into two Y-axis series.
MyAxisCh.setYSeries("US Unemployment", USAnnualUnemployment); [1]
MyAxisCh.setYSeries("NH Unemployment", NHAnnualUnemployment);
MyAxisCh.setSeriesColor("NH Unemployment", lightGreen);
// Specify a bar chart.
MyAxisCh.setSeriesGraphType("US Unemployment", AxisChart.BAR);
MyAxisCh.setSeriesGraphType("NH Unemployment", AxisChart.BAR);
MyAxisCh.getTitle().setText("Unemployment Rates");
MyAxisCh.getFootnote().setText("Source: U.S. Bureau of Labor Statistics");
MyAxisCh.setLegendInside();
MyAxisCh.setLegendAlignment(Legend.NORTHEAST);
// Note - Use TYPE_BYTE_INDEXED for color .gifs.
BufferedImage bi = new BufferedImage(Chart_width, Chart_height,
BufferedImage.TYPE_BYTE_INDEXED);
Graphics2D g2 = null;
g2 = bi.createGraphics();
// Define attributes of the client-side image map.
ImageMapDesc desc = new ImageMapDesc(); [2]
desc.setMapName("unemployment"); [3]
// Assert a fixed href.
//This prevents the page from being reloaded when the mouse is clicked.
desc.setFixedHref("#myanchor"); [4]
// Define the name of the replacement image.
desc.setReplacementImageName("expanded"); [5]
// Enable the onMouseOver event handler.
desc.getOnMouseOverDesc().setEnable(); [6] [7]
// Set the path prefix and extension of the sequenced URL.
desc.getOnMouseOverDesc().setHyperLinkPrefix("monthly/"); [8]
desc.getOnMouseOverDesc().setHyperLinkExtension(".gif"); [9]
// Enable the generation of a client-side image map.
MyAxisCh.setEnableImageMapCS(desc); [10]
// For file encoding.
MyAxisCh.drawBuffer(g2);
imageMap = MyAxisCh.getImageMapCS(); [11]
writeImageMapFile("imagemapcs.html", imageMap);
EncodeGifFile(bi, "samplecs.gif");
.
.
.
The numbers in the example correspond to the numbers in the following list, which describes the example in detail:
The names of the Y-axis series defined by the setYSeries( ) method are used by Chart Builder as the HyperlinkName portion of the sequenced hyperlink URL.
The setMapName( ) method defines the map name to be unemployment. This name is used in the generated image map.
The setFixedHref( ) method provides an anchor to the current page. Without this method, the image map would link to another page, instead of replacing an image on the page.
The setReplacementImageName( ) method specifies that the image named expanded be replaced when the mouse is clicked on a bar.
The getOnMouseOverDesc( ) method specifies that the onMouseOver event handler will be used.
The setEnable( ) method enables the onClick event handler and generates the specified action in the image map.
The setHyperLinkPrefix( ) method specifies that the prefix monthly/ be added to the URL for the hyperlink.
The setHyperLinkExtension( ) method specifies that the file extension .gif be added to the URL for the hyperlink.
The setEnableImageMapCS( ) method enables a client-side image map. You must invoke this method before invoking the drawBuffer( ) method.
The getImageMapCS( ) method retrieves a client-side image map. Then, the image map is written to a file, using the writeImageMapFile( ) method.
This example generates the following image map:
<!-- Client-Side Image Map --> <!-- Generated by Oracle Chart Builder --> <map name="unemployment"> <area shape=rect coords=35,82,44,157 href=#myanchor onMouseOver="document.images['expanded'].src='monthly/US_Unemployment0.gif' "> <area shape=rect coords=58,66,67,157 href=#myanchor onMouseOver="document.images['expanded'].src='monthly/US_Unemployment1.gif' "> . . . <area shape=rect coords=251,121,260,157 href=#myanchor onMouseOver="document.images['expanded'].src='monthly/NH_Unemployment9.gif' "> <area shape=rect coords=274,121,283,157 href=#myanchor onMouseOver="document.images['expanded'].src='monthly/NH_Unemployment10.gif' "> </map>
The following figure shows an HTML page that uses the image map:
For more examples that build interactive charts using image maps, see the imagemap subdirectory of the Chart Builder demos directory.
Chart Builder supports mouse events on individual chart elements. For example, it can detect entry of the pointer into a bar or a mouse click on a bar. These capabilities are useful in creating interactive charts in the context of Java applications, Java applets, JSP, and servlets.
Because a chart is implemented as a single component (java.awt.component), Chart Builder provides several methods that you can use in the context of the standard Java event model to detect events on series elements or pie chart slices. These events include mouse-related events, such as entering, exiting, dragging, moving, clicking, pressing, and releasing.
Chart Builder provides the AxisChartInteractive class for building interactive axis charts. The AxisChartInteractive class contains the following event methods for determining when the mouse enters or exits series elements:
The getSeriesElementEntered( ) method detects when the pointer enters a series element.
The getSeriesElementExited( ) method detects when the pointer exits the series element.
The getSeriesIndex( ) method determines the element in the series in which the event occurred.
The getSeriesIndexDesc( ) method determines the series and the element in the series in which the event occurred. This method is for use with charts that contain more than one series.
When the series element events occur, your application can take the following actions:
Take any valid Java action for a component.
Display an annotation for an element, such as a bar in a bar chart, using the setSeriesAnnotation( ) method.
Remove an annotation from an element, using the setSeriesAnnotationRemove( ) method.
Highlight an element, using the setSeriesHighlight( ) method. You highlight an element by specifying a color.
Remove the highlighting of an element, using the setSeriesUnHighlight( ) method.
To build an interactive chart, you take the following basic steps:
Implement the java.awt.event.MouseMotionListener or the java.awt.event.MouseListener interface, or both.
Use the AxisChartInteractive class to create the chart object.
Register the chart object using the addMouseListener( ) or addMouseMotionListener( ) methods, or both.
When particular mouse events occur, take an action. To take an action when a mouse event occurs in a series element, take the following steps:
Use the Chart Builder series element event methods, such as getSeriesElementEntered( ) or getSeriesElementExited( ), to detect when an event occurs in an element. The following example uses the getSeriesElementEntered( ) method in an if statement:
if (MyAxisCh.getSeriesElementEntered(x,y)) { ...
Determine the element in which the event occurred by getting the index of the x, y coordinate at the screen location using the getSeriesIndex( ) or getSeriesIndexDesc( ) method. If the coordinate is contained in a series element (for example, in one of the bars in a bar chart), Chart Builder returns the index. The following example returns the index to the variable ind:
int index = MyAxisCh.getSeriesIndex(x,y);
If the chart contains more than one series, use the getSeriesIndexDesc( ) method. This method returns both the index and the series name. The following example shows how to use this method:
// Allocate a SeriesDesc descriptor object. SeriesDesc SD = MYAxisCh.getSeriesIndexDesc(x,y); int index = SD.getSeriesIndex(); String seriesname = SD.getSeriesName();
Use one of the Chart Builder series element action methods, such as the setSeriesHighlight( ) method, to take the action, passing the series name and index to the method. The following example calls the setSeriesHighlight( ) method to change the color of a bar:
MyAxisCh.setSeriesHighlight("uspopulation", index, Color.orange);
The following example shows excerpts of a Java applet that creates an interactive chart. When the pointer enters a bar, the bar is highlighted; when the mouse is pressed over a bar, an annotation pops ups and the color of the bar changes. The applet also removes the highlighting, annotation, and color change when the pointer exits the bar.
import java.applet.*; import java.lang.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; import oracle.charts.*; import oracle.charts.axischart.*; import oracle.charts.types.*; import oracle.charts.io.*; import java.awt.event.MouseMotionListener; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; public class applet1_inter extends JApplet implements MouseListener, [1] MouseMotionListener { . . . // Initialize the applet. // Create an interactive chart. AxisChartInteractive MyAxisCh = new AxisChartInteractive(); [2] public void init() { [3] this.enableEvents(AWTEvent.COMPONENT_EVENT_MASK); addMouseListener(this); addMouseMotionListener(this); . . . bufferSize = this.getSize(); Display_height = bufferSize.height; Display_width = bufferSize.width; MyAxisCh = createAxisChart(Display_width, Display_height); if (MyAxisCh != null) { this.getContentPane().add(MyAxisCh); MyAxisCh.addMouseListener(this); [4] MyAxisCh.addMouseMotionListener(this); } addMouseMotionListener(this); } . . . // Mouse Events. The first four are not used in this applet. [5] public void mouseDragged(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } // Handle events associated with the mouse exiting the chart component. // On chart exit, if the previous mouse location was on a bar, // remove the highlighting and the annotation from the bar. // public void mouseExited(MouseEvent e) { [6] int x = e.getX(); int y = e.getY(); try { if (MyAxisCh.getSeriesElementExited(x,y)) { [7] MyAxisCh.setSeriesUnHighlight(); MyAxisCh.setSeriesAnnotationRemove(); this.paint(this.getGraphics()); } } catch (ChartException e2) { System.out.println(e2.getMessage()); } } // Handle events associated with the mouse pressed within a chart component. // If the mouse is pressed in a bar, change the color of the bar. public void mousePressed(MouseEvent e) { [8] int x = e.getX(); int y = e.getY(); SeriesDesc SD = MyAxisCh.getSeriesIndexDesc(x,y); [9] int index = SD.getSeriesIndex(); String seriesName = SD.getSeriesName(); try { // Set the highlight color; issue a repaint command. [10] MyAxisCh.setSeriesHighlight(seriesName, index, Color.blue); this.paint(this.getGraphics()); } catch (ChartException e2) { System.out.println(e2.getMessage()); } } // Handle events associated with the mouse moving within a chart component. // If mouse enters a bar, highlight the bar and display an annotation. // If mouse exits a bar, remove the highlighting and annotation. public void mouseMoved(MouseEvent e) { [11] int x = e.getX(); int y = e.getY(); try { if (MyAxisCh.getSeriesElementExited(x,y)) { [12] MyAxisCh.setSeriesUnHighlight(); MyAxisCh.setSeriesAnnotationRemove(); this.paint(this.getGraphics()); } if (MyAxisCh.getSeriesElementEntered(x,y)) { [13] SeriesDesc SD = MyAxisCh.getSeriesIndexDesc(x,y); [14] int index = SD.getSeriesIndex(); String seriesName = SD.getSeriesName(); MyAxisCh.setSeriesHighlight(seriesName, index, Color.orange); [15] MyAxisCh.setSeriesAnnotation(seriesName, index); this.paint(this.getGraphics()); } . . .
The numbers in the example correspond to the numbers in the following list, which describes the example in detail:
The applet implements the java.awt.event.MouseMotionListener and the java.awt.event.MouseListener interface.
The AxisChartInteractive( ) constructor creates a new interactive axis chart object.
In the init( ) method, the applet is initialized. The enableEvents( ) method enables Java events.
The chart object is registered with the addMouseListener( ) and addMouseMotionListener( ) methods.
All Java mouse events are handled, even though some of them are not used in this applet.
The mouseExited( ) method detects when the pointer exits the chart.
If the previous location of the pointer was in a series element, such as a bar, the getSeriesElementExited( ) method detects when the pointer exits the element. The setSeriesUnHighlight( ) method removes the highlighting; the setSeriesAnnotationRemove( ) method removes the annotation from the element.
The getSeriesIndexDesc( ) method determines the element in which the pointer is located. The method returns the index and series name.
The setSeriesHighlight( ) method, using the index and series name returned from the getSeriesIndexDesc( ) method, changes the color of the element within the series.
If the previous location of the pointer was in a series element, such as a bar, the getSeriesElementExited( ) method detects when the pointer exits the element. The setSeriesUnHighlight( ) method removes the highlighting; the setSeriesAnnotationRemove( ) method removes the annotation from the element.
The getSeriesElementEntered( ) method detects if the pointer entered a series element.
The getSeriesIndexDesc( ) method determines the element in which the pointer is located. The method returns the index and series name.
The setSeriesHighlight( ) method, using the index and series name returned from the getSeriesIndexDesc( ) method, changes the color of the element within the series. The setSeriesAnnotation( ) method displays an annotation for the element.
The following figure shows the interactive chart when the mouse is pressed over a bar:
For more examples of interactive axis charts, see the following directory:
On UNIX:
drive/chartbuilder/demos/dynamic/interact/axischart
On Windows NT:
drive\chartbuilder\demos\dynamic\interact\axischart
Chart Builder provides the PieChartInteractive class for building interactive pie charts. The PieChartInteractive class contains the following event methods for determining when the mouse pointer enters or exits a pie slice:
The getSliceEntered( ) method detects when the pointer enters a pie slice.
The getSliceExited( ) method detects when the pointer exits a pie slice.
The getSliceIndex( ) method determines the slice in which the event occurred. This method returns the index of the pie slice.
When a pie slice event occurs, your application can take the following actions:
Take any valid Java action for a component.
Highlight an element (a pie slice or slice label) using the setSliceHighlight( ) or setSliceLabelHighlight( ) method. You highlight an element by specifying a color.
Remove the highlighting of an element using the setSliceUnHighlight( ) or setSliceLabelUnHighlight( ) method. This method restores the slice or label to its original color.
To build an interactive pie chart, you take the following basic steps:
Implement the java.awt.event.MouseMotionListener or the java.awt.event.MouseListener interface, or both.
Use the PieChartInteractive class to create the chart object.
Register the chart object using the addMouseListener( ) or addMouseMotionListener( ) methods, or both.
When particular mouse events occur, take an action. To take an action when a mouse event occurs in a pie slice, take the following steps:
Use the Chart Builder pie slice event methods, such as getSliceEntered( ), to detect when an event occurs in a pie slice. The following example uses the getSliceEntered( ) method in an if statement:
if (MyPieCh.getSliceEntered(x,y)) { ...
Determine the pie slice in which the event occurred by getting the index of the x, y coordinate at the screen location using the getSliceIndex( ) method. If the coordinate is contained in a pie slice, Chart Builder returns the index. The following example returns the index to the variable ind:
int index = MyPieCh.getSliceIndex(x,y);
Slice index values are integers starting at 0. For example, if a pie chart has three slices, the slice indexes are 0, 1, 2.
Use one of the Chart Builder pie slice action methods, such as the setSliceHighlight( ) method, to take the action. You pass the index of the slice and a color to the method. The following example calls the setSliceHighlight( ) method to change the color of a pie slice:
MyPieCh.setSliceHighlight(index, Color.orange);
The following example shows excerpts of a Java application that creates an interactive pie chart. When the cursor enters a pie slice, the slice is highlighted; when the cursor exits a pie slice, the slice returns to its original color; when the mouse is pressed in a pie slice, the color of the slice changes.
. . . public class pie_inter extends Frame implements MouseListener, [1] MouseMotionListener { . . . PieChartInteractive MyPieCh; pie_inter() { setSize(ChartWidth, ChartHeight + 30 ); enableEvents(AWTEvent.COMPONENT_EVENT_MASK); [2] addMouseListener(this); [3] addMouseMotionListener(this); MyPieCh = createPieChart(ChartWidth, ChartHeight); this.add(MyPieCh); MyPieCh.addMouseListener(this); MyPieCh.addMouseMotionListener(this); show(); } // Set the original colors for the slices. Color SliceColors[] = new Color[] { [4] new Color(204, 204, 204), new Color(0, 204, 0), new Color(204, 0, 0), new Color(0, 0, 204), }; // Set the highlight colors for the slices. Color HilightColors[] = new Color[] { new Color(255, 255, 255), new Color(0, 255, 0), new Color(255, 0, 0), new Color(0, 0, 255), }; // Create the chart and define the data inline. public PieChartInteractive createPieChart(int chartWidth, int chartHeight) { // Define the color for each slice. for (int i=0; i<USExports.length; i++) USExports[i].setBackground(SliceColors[i]); // Create a new PieChart object. PieChartInteractive MyPieCh = new PieChartInteractive(); [5] . . . return(MyPieCh); } // Mouse Events. // No actions taken for the following events. [6] public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseDragged(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } // Handle events associated with the mouse moving within a chart // component. // Highlight slice on mouse entry. // Remove the highlighting from the slice on mouse exit. public void mouseMoved(MouseEvent e) { [7] int x = e.getX(); int y = e.getY(); if (e.getSource().equals(MyPieCh)) { try { if (MyPieCh.getSliceExited(x,y)) { [8] MyPieCh.setSliceUnHighlight(); this.paint(this.getGraphics()); } if (MyPieCh.getSliceEntered(x,y)) { [9] int index = MyPieCh.getSliceIndex(x,y); [10] MyPieCh.setSliceHighlight(index, HilightColors[index]); [11] this.paint(this.getGraphics()); } } catch (ChartException e2) { System.out.println(e2.getMessage()); } } } // Handle events associated with the mouse exiting the chart component. // Remove highlighting on the slice when the mouse exits from it. public void mouseExited(MouseEvent e) { [12] int x = e.getX(); int y = e.getY(); if (e.getSource().equals(MyPieCh)) { try { if (MyPieCh.getSliceExited(x,y)) { [13] MyPieCh.setSliceUnHighlight(); this.paint(this.getGraphics()); } } catch (ChartException e2) { System.out.println(e2.getMessage()); } } } // Handle events associated with the mouse pressed within a chart // component. public void mousePressed(MouseEvent e) { [14] int x = e.getX(); int y = e.getY(); if (e.getSource().equals(MyPieCh)) { try { // Get the index for the slice. int index = MyPieCh.getSliceIndex(x,y); [15] // Set the highlight color; issue a repaint command. MyPieCh.setSliceHighlight(index, Color.orange); [16] this.paint(this.getGraphics()); . . .
The numbers in the example correspond to the numbers in the following list:
The Frame implements the java.awt.event.MouseMotionListener and the java.awt.event.MouseListener interface.
The chart object is registered with the addMouseListener( ) and addMouseMotionListener( ) methods.
The original colors and the colors to be used as a highlight are defined.
The PieChartInteractive( ) constructor creates a new interactive pie chart object.
All Java mouse events are handled, even though some of them are not used in this applet.
If the previous location of the cursor was in a slice, the getSliceExited( ) method detects when the cursor exits the slice. The setSliceUnHighlight( ) method removes the highlighting.
The getSliceEntered( ) method detects if the cursor entered a pie slice.
The getSliceIndex( ) method determines the pie slice in which the cursor is located. The method returns the index.
The setSliceHighlight( ) method, using the index returned from the getSliceIndex( ) method, changes the color of the pie slice.
The mouseExited( ) method detects when the cursor exits the chart.
If the previous location of the cursor was in a pie slice, the getSliceExited( ) method detects when the cursor exits the slice. The setSliceUnHighlight( ) method removes the highlighting.
The getSliceIndex( ) method determines the pie slice in which the cursor is located. The method returns the index.
The setSliceHighlight( ) method, using the index returned from the getSliceIndex( ) method, changes the color of the slice to orange.
The following figure shows the chart when the mouse has been pressed on the pie slice labeled "Canada":
For more examples of interactive pie charts, see the following directory:
On UNIX:
drive/chartbuilder/demos/dynamic/interact/piechart
On Windows NT:
drive\chartbuilder\demos\dynamic\interact\piechart
Because dynamic charts can update the data whenever it changes, they let you present live data to your users or customers and respond to requests in real time. With Chart Builder, you can create dynamic charts that:
Incrementally add data to one or more series
Dynamically add one or more new series to a chart
Dynamically delete existing series from a chart
You can create dynamic charts using Java applications, Java applets, and JavaServer Pages.
Chart Builder lets you add data incrementally to charts in the following ways:
Incrementally adding values to the Y-axis that correspond to existing values in the X-axis. For example, such a chart can replay the history of daily stock prices for the last 60 trading days, loading data for one or more series at the request of the user.
Incrementally adding the Y-axis values and the timestamps to the chart. For example, such a chart can be used to perform a real-time monitoring task, displaying the CPU usage for a particular application.
Chart Builder provides the following methods to incrementally add data to charts:
setYSeries(seriesName): Initializes the chart, but does not load data into the Y-axis.
setYSeriesAppend(seriesName, values[ ]): Appends an array of values to an existing Y-axis series.
setXseriesReserve(count): Reserves space for a specified number of timestamps in the X-axis.
setXSeriesAppend(timestamps[ ]): Appends an additional array of dates to the X-axis.
You can load all of the timestamps into the X-axis and some or none of the values into the Y-axis when the chart is created. Then, you can incrementally add the Y-axis values to the chart. To do so, take the following steps:
Load the timestamps into the X-axis using the setXSeries( ) method.
Invoke the setYSeries( ) method, using only the series name, only to initialize the chart. This does not load any data into the Y-axis. Alternatively, invoke the setYSeries( ) method, using both the series name and the array name to initialize the chart and load some data into the Y-axis data.
Display the initial chart.
When given a specific input, load the data into the Y-axis by using the setYSeriesAppend( ) method and display the updated chart.
The following example shows excerpts of an application that displays a chart that defines all timestamps and loads some Y-axis data when the chart is created. When a user requests additional data, the data is appended to the Y-axis.
.
.
.
public class dyn_incr_y extends Frame {
JPanel p1 = new JPanel();
AxisChartInteractive MyAxisCh;
// Chart dimensions
int ChartWidth = 300;
int ChartHeight = 200;
// Constructor
dyn_incr_y() {
setSize(ChartWidth, ChartHeight + 70 );
this.enableEvents(AWTEvent.COMPONENT_EVENT_MASK);
p1.setLayout(new BorderLayout(0,0);
p1.setBackground(new Color (150, 150, 240));
p1.setLayout(new BorderLayout());
// Add the command buttons to the panel.
CommandButtons CButtons = new CommandButtons();
p1.add(CButtons,"South");
// Initial chart.
MyAxisCh = createChart(ChartWidth, ChartHeight);
// Add the axis chart to the panel.
if (MyAxisCh != null) {
p1.add(MyAxisCh, "North");
}
// Add the panel to the applet.
this.add(p1,"Center");
show();
}
// Create an axis chart containing standard X-axis and Y-axis series.
public AxisChartInteractive createChart(int chartWidth, int chartHeight) {
AxisChartInteractive MyAxisCh = null;
// Chart data, defined inline.
// Initial values for the Y-axis.
double YSeries[] = {0, 2, 1, 3, 2, 4};
try {
// Create a new AxisChart object.
MyAxisCh = new AxisChartInteractive();
// Set the size of the chart.
MyAxisCh.setSize(chartWidth, chartHeight);
// Load the timestamps for the X-axis.
MyAxisCh.setXSeries(Calendar.YEAR, [1]
java.sql.Date.valueOf("1990-01-01"),
java.sql.Date.valueOf("2010-01-01"),
1);
// Load the data for the Y-axis. [2]
MyAxisCh.setYSeries("series0", YSeries);
MyAxisCh.setSeriesColor("series0", myGreen);
// Set the title.
MyAxisCh.getTitle().setText("Dynamically Append Data");
MyAxisCh.getSubtitle().setText("Timestamps are defined at chart creation.");
} catch (ChartException e)
{
System.out.println(e.getMessage());
}
return(MyAxisCh); [3]
}
.
.
.
// Button Events. When the button is clicked, append data to chart.
void button_actionPerformed(ActionEvent e) { [4]
String cmd = e.getActionCommand();
try {
// Define the additional Y-axis values.
double YSeriesAppend[] = {1, 3};
// Append the additional values to the chart. [5]
MyAxisCh.setYSeriesAppend("series0", YSeriesAppend);
// Repaint the chart.
Graphics g = p1.getGraphics();
MyAxisCh.paint(g);
.
.
.
The numbers in the example correspond to the numbers in the following list, which describes the parts of the example that are specific to dynamic charts:
The setXSeries( ) method loads the timestamps for the X-axis when the chart is created.
The setYSeries( ) method, using the series name and array name, loads some initial data for the Y-axis data. In this example, six values are loaded initially.
The initial chart is returned and subsequently displayed.
The button_actionPerformed( ) method handles the event when the button is clicked.
The setYSeriesAppend( ) method adds new data to the Y-axis of the chart.
The following figure shows the chart when it is created and after the user clicks the Append Data button a couple of times:
To incrementally load the timestamps and incrementally add the Y-axis values to the chart, you take the following steps:
Invoke the setXSeriesReserve( ) method to reserve space for a specified number of timestamps. For example, setXSeriesReserve(30) reserves space for 30 timestamps in an empty chart. Note that this method does not label the X-axis with timestamps.
Invoke the setYSeries( ) method, using only the series name. This only initializes the chart; it does not load any data into the Y-axis. (For stock charts, you use the setCandlestickSeries( ), setHiLoCloseSeries( ), or the setOpenHiLoCloseSeries( ) method.)
Display the initial chart. It contains no data.
For each of the initial timestamps and values, take the following steps:
Invoke the setXSeriesAppend( ) method to populate the X-axis with one timestamp.
Invoke the setYSeriesAppend( ) method to populate the Y-axis with a corresponding data value. For stock charts, you use the setCandlestickSeriesAppend( ), setHiLoCloseSeriesAppend( ), or the setOpenHiLoCloseSeriesAppend( ) method.
When the initial incremental loading is complete, the chart will show data for each reserved space. You can continue to add data to the chart in the following ways:
Shifting the earliest data out of the chart and appending additional timestamps to the chart. Invoke the setXSeriesShift( ) method to shift in new timestamps and the setYSeriesAppend( ) method to add the corresponding data.
Extending the X-axis by appending additional timestamps to the chart. Invoke the setXSeriesAppend( ) method to add new timestamps and the setYSeriesAppend( ) method to add the corresponding data.
Consider the number of timestamps you will be adding and the size of the chart. Adding a great number of timestamps to a small chart could make the chart unreadable.
The following example shows excerpts of a Java application that creates a chart and incrementally adds new data while it shifts the earliest data out of the chart:
.
.
.
int InitialXAxisIntervals = 120;
// Initial Y-axis series is empty.
double YSeries2[] = {};
// Create an axis chart. Initially, the chart has no data;
// new data points are added when the user clicks the button.
public AxisChartInteractive createChart(int chartWidth, int chartHeight) {
AxisChartInteractive AxisCh = null;
try{
// Define a circular line marker. Allocate a LineDesc descriptor.
LineDesc markerDescCircle = new LineDesc();
markerDescCircle.setMarkerType(LineDesc.MARKER_CIRCLE);
// Indicate that seconds should be labeled at all times.
// Otherwise, the chart heuristics may disable seconds labeling.
TimeAxisDesc timeDesc = new TimeAxisDesc();
timeDesc.setMinDimension(TimeAxisDesc.SECOND);
// Use a minimum of 2 lines for labeling the time axis.
timeDesc.setMinLabelingLines(2);
// Define the minimum and maximum values of the Y-axis.
NumAxisDesc yAxisD = new NumAxisDesc();
yAxisD.setExtentMin(-1);
yAxisD.setExtentMax(1);
// Create a new AxisChart object.
AxisCh = new AxisChartInteractive();
// Set the size of the chart.
AxisCh.setSize(chartWidth, chartHeight);
// Reserve space for a specified number of points. [1]
AxisCh.setXSeriesReserve(InitialXAxisIntervals);
// Define the name of the Y-axis series. [2]
AxisCh.setYSeries("series0");
// Set the Y-axis attributes. [3]
AxisCh.setChartAttributes(yAxisD);
// Set the X-axis attributes. [4]
AxisCh.setChartAttributes(timeDesc);
// Use a circular line marker for series0.
AxisCh.setSeriesGraphic("series0", markerDescCircle);
// Set the title.
AxisCh.getTitle().setText("Dynamic Strip Chart");
} catch (ChartException e)
{
System.out.println(e.getMessage());
System.exit(1);
}
return(AxisCh); [5]
}
.
.
.
public void actionPerformed(ActionEvent e) {
adaptee.button_actionPerformed(e);
}
}
int hours = 0;
int minutes =0;
int seconds = 29;
String strHrs;
String strMin;
String strSec;
boolean done = false;
double Yvalue = 0;
int Angle = 0;
void incrementAngle()
{
Angle += 10;
Angle %= 360;
Yvalue = Math.sin(Math.toRadians(Angle));
}
// Construct a timestamp in the form of:
// java.sql.Timestamp.valueOf("2001-01-01 00:00:00.000000000")
void incrementTime()
{
seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
// Arbitrary number of minutes to stop chart loading.
if (minutes == 4) done = true;
if (minutes == 60) {
minutes = 0;
hours++;
}
}
if (hours == 0) strHrs = "00";
else if (hours < 10)
strHrs = "0" + Integer.toString(hours);
else strHrs = Integer.toString(hours);
.
.
.
}
int appendCount = 0;
// Button events
void button_actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals(StartCmd)) {
String date1;
while (!done) {
try {
// Increment the X-axis and the Y-axis data.
incrementTime();
incrementAngle();
date1 ="2001-11-01 " + strHrs + ":" + strMin + ":" + strSec + ".000000000";
// The Y-axis series that is appended on each simulation step.
double YSeriesAppend[] = {Yvalue};
// For the first 120 values, the X-axis has reserved intervals.
// Fill these reserved intervals one point at a time.
if ((YSeries2.length + appendCount) < InitialXAxisIntervals) {
java.sql.Timestamp newdates[] = {java.sql.Timestamp.valueOf(date1)};
AxisCh.setXSeriesAppend(newdates); [6]
AxisCh.setYSeriesAppend("series0", YSeriesAppend);
appendCount++;
}
else {
// When all series values along the X-axis are displayed,
// append new dates by shifting old ones out and adding new ones.
java.sql.Timestamp newdates[] = {java.sql.Timestamp.valueOf(date1)};
AxisCh.setXSeriesShift(newdates); [7]
// Append one additional point to the Y-axis.
AxisCh.setYSeriesAppend("series0", YSeriesAppend); [8]
}
// Repaint the chart.
Graphics g = p1.getGraphics();
AxisCh.paint(g);
.
.
.
The numbers in the example correspond to the numbers in the following list:
The setXSeriesReserve( ) method reserves space for 120 timestamps in an empty chart, but it does not label the X-axis with timestamps.
The setYSeries( ) method, using only the series name, initializes the chart; it does not load any data into the Y-axis.
The setChartAttributes(yAxisD) method sets the attributes for the Y-axis. In this case, minimum and maximum values are set using the NumAxisDesc constructor, which is shown earlier in the example. See Section 3.6.1 for more information about setting minimum and maximum values.
The setChartAttributes(timeDesc) method sets the attributes for the X-axis. In this case, seconds are to be labeled at all times and a minimum of two lines are set using the TimeAxisDesc constructor, which is shown earlier in the example. See Section 3.5.4 for information about setting the minimum number of lines and see Section 3.6.1 for information about setting the increments.
The initial chart, containing no data, is displayed.
For each of the initial timestamps and values, the setXSeriesAppend( ) method populates the X-axis with one timestamp, and the setYSeriesAppend( ) method populates the Y-axis with a corresponding data value.
When the initial incremental loading is complete, the chart will show data for each reserved space.
The setXSeriesShift( ) method adds new timestamps by shifting the earliest timestamps out of the chart and adding the new ones incrementally.
The setYSeriesAppend( ) method adds data to the Y-axis that corresponds to the added timestamps.
The following figure shows the resulting chart after the Start Simulation button is clicked:
For more examples of dynamic charts, see the following directory:
On UNIX:
drive/chartbuilder/demos/dynamic/dynupdate
On Windows NT:
drive\chartbuilder\demos\dynamic\dynupdate
You can dynamically add a Y-axis series to a chart at any point. For example, to add a new Y-axis series to a chart when the user clicks the Add Series button, use the setYSeries( ) method as shown in the following example:
} else if (cmd.equals("Add Series")) {
try {
double YSeries_2[] = {3, 5, 4, 4.5, 3.5, 4.75};
// Add a new series to the chart.
MyAxisCh.setYSeries("Series2", YSeries_2);
MyAxisCh.setSeriesColor("Series2", myGreen);
// Repaint the chart.
Graphics g = p1.getGraphics();
MyAxisCh.paint(g);
The following figure shows the resulting chart after the new series is added:
When you add a Y-axis series, Chart Builder automatically relabels the Y-axis to take into account the range of values in the new series.
You can dynamically delete or replace a series or set of series in a chart. With Chart Builder, you can delete one or all Y-axis series in a chart or the X-axis series and all Y-axis series. Then, you can add a new X-axis series and one or more Y-axis series.
Chart Builder provides the following methods:
setDeleteYSeries( ) deletes the named Y-series.
setDeleteAllYSeries( ) deletes all Y-axis series in the chart.
setDeleteAllXYSeries( ) deletes the X-axis series and all Y-axis series.
For example, assume that you have a chart with two Y-axis series. You want to delete both Y-axis series and the X-axis series and replace them with different data, perhaps in response to input from a user. To do that, you take the following steps:
Delete all the series, including the timestamps from the chart:
AxisCh.setDeleteAllXYSeries();
Load another set of timestamps into the X-axis:
AxisCh.setXSeries(Calendar.MONTH,
java.sql.Date.valueOf("2001-01-01")
java.sql.Date.valueOf("2002-01-01"),
1);
Reload data into the two Y-axis series:
AxisCh.setYSeries("series_1", YSeries_1b);
AxisCh.setYSeries("series_2", YSeries_2b);
For more examples of dynamic charts, see the following directory:
On UNIX:
drive/chartbuilder/demos/dynamic/dynupdate
On Windows NT:
drive\chartbuilder\demos\dynamic\dynupdate
|
![]() Copyright © 2002 Oracle Corporation All rights reserved |
|