ChartDirector 6.1 (Java Edition)

Track Line with Legend (Windows)




NOTE: This section describes Track Line with Legend for Windows applications only. For web applications, please refer to Track Line with Legend (Web).

This sample program demonstrates a track cursor programmed with the following features:

The code first draws the chart, and sets the track cursor to the right side of the plot area. This ensures the chart initially has a legend that reflects the latest data values. In the TrackCursorListener.mouseMovedPlotArea event handler, the track cursor is updated to reflect the mouse position.

The trackLineLegend method is the routine that draws the track cursor. Its key elements are:

Source Code Listing

[Java Version] javademo/tracklegend.java
import ChartDirector.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;

public class tracklegend implements DemoModule
{
    //
    // The main method to allow this demo to run as a standalone program.
    //
    public static void main(String args[]) 
    {
        tracklegend demo = new tracklegend();
        demo.display();
        System.exit(0);
    }

    //
    // Display the window
    //
    private void display() 
    {   
        // Use a JDialog as the window
           JDialog d = new JDialog((java.awt.Frame)null, toString(), true);
        d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        d.setResizable(false);     
   
        // Create the ChartViewer and add it to the JDialog
        ChartViewer viewer = new ChartViewer();
        d.getContentPane().add(viewer);

        // Add a movedMovedPlotArea event listener to draw the track cursor
        viewer.addTrackCursorListener(new TrackCursorAdapter() {
            public void mouseMovedPlotArea(MouseEvent e) {
                chartViewer1_MouseMovedPlotArea(e);
            }
        });
        
        // Draw the chart
        drawChart(viewer);

        // Layout and display the JDialog
        d.pack();
        d.setVisible(true);
    }
  
    //
    // Main code for creating charts
    //
    public void drawChart(ChartViewer viewer)
    {
        // Data for the chart as 3 random data series
        RanSeries r = new RanSeries(127);
        double[] data0 = r.getSeries(100, 100, -15, 15);
        double[] data1 = r.getSeries(100, 150, -15, 15);
        double[] data2 = r.getSeries(100, 200, -15, 15);
        Date[] timeStamps = r.getDateSeries(100, new GregorianCalendar(2011, 0, 1).getTime(), 86400);

        // Create a XYChart object of size 640 x 400 pixels
        XYChart c = new XYChart(640, 400);

        // Add a title to the chart using 18pt Times New Roman Bold Italic font
        c.addTitle("    Product Line Global Revenue", "Times New Roman Bold Italic", 18);

        // Set the plotarea at (50, 55) with width 70 pixels less than chart width, and height 90 pixels less
        // than chart height. Use a vertical gradient from light blue (f0f6ff) to sky blue (a0c0ff) as
        // background. Set border to transparent and grid lines to white (ffffff).
        c.setPlotArea(50, 55, c.getWidth() - 70, c.getHeight() - 90, c.linearGradientColor(0, 55, 0,
            c.getHeight() - 35, 0xf0f6ff, 0xa0c0ff), -1, Chart.Transparent, 0xffffff, 0xffffff);

        // Set legend icon style to use line style icon, sized for 8pt font
        c.getLegend().setLineStyleKey();
        c.getLegend().setFontSize(8);

        // Set axis label style to 8pt Arial Bold
        c.xAxis().setLabelStyle("Arial Bold", 8);
        c.yAxis().setLabelStyle("Arial Bold", 8);

        // Set the axis stem to transparent
        c.xAxis().setColors(Chart.Transparent);
        c.yAxis().setColors(Chart.Transparent);

        // Configure x-axis label format
        c.xAxis().setMultiFormat(Chart.StartOfYearFilter(), "{value|mm/yyyy} ", Chart.StartOfMonthFilter(),
            "{value|mm}");

        // Add axis title using 10pt Arial Bold Italic font
        c.yAxis().setTitle("USD millions", "Arial Bold Italic", 10);

        // Add a line layer to the chart using a line width of 2 pixels.
        LineLayer layer = c.addLineLayer2();
        layer.setLineWidth(2);

        // Add 3 data series to the line layer
        layer.setXData(timeStamps);
        layer.addDataSet(data0, 0xff3333, "Alpha");
        layer.addDataSet(data1, 0x008800, "Beta");
        layer.addDataSet(data2, 0x3333cc, "Gamma");

        // Include track line with legend for the latest data values
        trackLineLegend(c, c.getPlotArea().getRightX());

        // Assign the chart to the ChartViewer
        viewer.setChart(c);
    }

    //
    // Draw track cursor when mouse is moving over plotarea
    //
    private void chartViewer1_MouseMovedPlotArea(MouseEvent e)
    {
        ChartViewer viewer = (ChartViewer)e.getSource();
        trackLineLegend((XYChart)viewer.getChart(), viewer.getPlotAreaMouseX());
        viewer.updateDisplay();
    }

    //
    // Draw the track line with legend
    //
    private void trackLineLegend(XYChart c, int mouseX)
    {
        // Clear the current dynamic layer and get the DrawArea object to draw on it.
        DrawArea d = c.initDynamicLayer();

        // The plot area object
        PlotArea plotArea = c.getPlotArea();

        // Get the data x-value that is nearest to the mouse, and find its pixel coordinate.
        double xValue = c.getNearestXValue(mouseX);
        int xCoor = c.getXCoor(xValue);

        // Draw a vertical track line at the x-position
        d.vline(plotArea.getTopY(), plotArea.getBottomY(), xCoor, d.dashLineColor(0x000000, 0x0101));

        // Container to hold the legend entries
        ArrayList legendEntries = new ArrayList();

        // Iterate through all layers to build the legend array
        for (int i = 0; i < c.getLayerCount(); ++i) {
            Layer layer = c.getLayerByZ(i);

            // The data array index of the x-value
            int xIndex = layer.getXIndexOf(xValue);

            // Iterate through all the data sets in the layer
            for (int j = 0; j < layer.getDataSetCount(); ++j) {
                ChartDirector.DataSet dataSet = layer.getDataSetByZ(j);

                // We are only interested in visible data sets with names
                String dataName = dataSet.getDataName();
                int color = dataSet.getDataColor();
                if ((!(dataName == null || dataName == "")) && (color != Chart.Transparent)) {
                    // Build the legend entry, consist of the legend icon, name and data value.
                    double dataValue = dataSet.getValue(xIndex);
                    legendEntries.add("<*block*>" + dataSet.getLegendIcon() + " " + dataName + ": " + ((
                        dataValue == Chart.NoValue) ? "N/A" : c.formatValue(dataValue, "{value|P4}")) +
                        "<*/*>");

                    // Draw a track dot for data points within the plot area
                    int yCoor = c.getYCoor(dataSet.getPosition(xIndex), dataSet.getUseYAxis());
                    if ((yCoor >= plotArea.getTopY()) && (yCoor <= plotArea.getBottomY())) {
                        d.circle(xCoor, yCoor, 4, 4, color, color);
                    }
                }
            }
        }

        // Create the legend by joining the legend entries
        Collections.reverse(legendEntries);
        String legendText = "<*block,maxWidth=" + plotArea.getWidth() + "*><*block*><*font=Arial Bold*>[" +
            c.xAxis().getFormattedLabel(xValue, "mmm dd, yyyy") + "]<*/*>        " + Chart.stringJoin(
            legendEntries, "        ") + "<*/*>";

        // Display the legend on the top of the plot area
        TTFText t = d.text(legendText, "Arial", 8);
        t.draw(plotArea.getLeftX() + 5, plotArea.getTopY() - 3, 0x000000, Chart.BottomLeft);
    }
    
    //
    // Implementation of the DemoModule interface to allow this demo to run inside the 
    // ChartDirectorDemo browser
    //
    
    // Name of demo program
    public String toString() 
    { 
        return "Track Line with Legend"; 
    }

    // Number of charts produced in this demo
    public int getNoOfCharts() 
    { 
        // This demo open its own dialog instead of using the right pane of the ChartDirectorDemo 
        // for display. We just display the dialog, then return 0.
        display();
        return 0; 
    }

    // Main code for creating charts
    public void createChart(ChartViewer viewer, int chartIndex)
    {
        // do nothing, as the ChartDirectorDemo browser right pane is not used
    }
}