The following section details how to utilize the API. Again, the API examples and code is designed using the above recommendation (template based and no EspressManager).
Note that unless otherwise noted, all examples use the Woodview HSQL database, which is located in the <EspressChartInstall>/help/examples/DataSources/database
directory. In order to run the examples, you will need to add database HSQL JDBC driver (hsqldb.jar
) to your classpath. The driver is located in the <EspressChartInstall>/lib
directory.
Also, all the API examples will show the core code in the manual. To compile the examples, make sure the CLASSPATH includes EspressAPI.jar
and qblicense.jar
.
For more information on the API methods, please refer the API documentation.
Charts can be saved to a file using the PAC, CHT or TPL formats (both proprietary formats). A TPL file stores all of the chart information, except for the actual data; PAC or CHT file stores the actual data as well. These formats can be used to reconstruct a chart object. The data is automatically reloaded from the original data source each time the TPL file is opened. When PAC or CHT file is opened, the data used to create it is shown (although the option to fetch data from the data source also exists).
It is important to note that the TPL file, by default, does NOT contain the data. It contains, along with the chart template information (i.e., the look and feel of the chart), the specified data source. Therefore, when loading a TPL file, the data for the chart is obtained by querying the data source. The CHT file, on the other hand, does NOT query the data source when it is opened. It shows the data used to create the chart to begin with. Both formats can be obtained by using Designer
or the export()
method provided in the QbChart
class.
The following example, which can run as a Java Web Start Application, reads a CHT file and reconstructs a chart:
Component doOpeningTemplate(Applet parent) { // Do not use EspressManager QbChart.setEspressManagerUsed(false); // Open the template QbChart chart = new QbChart (parent, // container "OpeningChartTemplate.cht"); // template // Show chart in Viewer return chart; }
The constructor in this example is:
public QbChart(Applet applet, String file);
where applet is the applet container and file is a CHT/TPL file name.
Tip | |
---|---|
File names may be specified either as URL strings or by using relative/absolute paths. Path names are interpreted as being relative to the current directory of EspressManager or to the current application if EspressManager is not used. |
Charts can also contain parameters to either limit the data in some form. Typically, query (or IN) parameters are used by the data source to limit the data.
Query parameters can be both single-value and multi-value parameter types.
When a parameterized template is opened using following constructor:
QbChart(Applet parent, String templateName);
a dialog box appears, asking for the value(s) of the parameter(s). This dialog box is the same as the one that appears in Designer when the template is opened.
A parameterized chart can also be opened without the dialog box prompting for any value(s). This can be done by passing in an object arrays. Each element in the array represents the value for that particular parameter.
The order of the array must match the order in which the parameters were created in Designer
. For correct results, the data type of the value must also match the data type of the parameter.
Query parameters can also be multi-value parameter types. For multi-value parameters, a vector is passed to the object array. The vector contains all the values for the multi-value parameter.
The following example, which can run as a Java Web Start Application, passes in the parameter values when opening a chart template:
Component doObjectArray(Applet parent) { // Do not use EspressManager QbChart.setEspressManagerUsed(false); // Object array for Query Parameters Vector vec = new Vector(); vec.add("CA"); vec.add("NY"); GregorianCalendar beginDate = new GregorianCalendar(2001, 0, 4); GregorianCalendar endDate = new GregorianCalendar(2003, 1, 12); long beginLong = beginDate.getTimeInMillis(); long endLong = endDate.getTimeInMillis(); Date beginDateTime = new Date(beginLong); Date endDateTime = new Date(endLong); Object queryParams[] = new Object[3]; queryParams[0] = vec; queryParams[1] = beginDateTime; queryParams[2] = endDateTime; // Open the template QbChart chart = new QbChart(parent, // container "ObjectArray.cht", // template queryParams); // Query Parameters // Show chart in Viewer return chart; }
When a QbChart object is created from scratch (see Appendix 10.B - Creating the Chart), the chart is created using default attributes. However, you can use a chart template (.tpl) to specify user defined attributes during chart construction. Almost all the attributes (except for data source and chart type) are extracted from the template and applied to the QbChart
object. The template name usually appears as the last argument in the QbChart
constructors.
You can also specify the template name using the applyTemplateFile(String fileName)
method in the QbChart
class.
The following example, which can be run as a applet(More in: Section 2.6 - Run Applets in WebStart with JNLP file) or application, applies a template onto the QbChart
object:
Component doApplyingTemplate(Applet parent) { // Do not use EspressManager QbChart.setEspressManagerUsed(false); String templateLocation = ".."; // Apply the template QbChart chart = new QbChart (parent, // container QbChart.VIEW2D, // chart dimension QbChart.BAR, // chart type data, // data columnMapping, // column mapping templateLocation); // template // Show chart in Viewer return chart; }
Please note that the above code is not complete and is only there as a guide. However, the link contains a complete application code that can be run.
You can also take the column mapping from the template and have it applied on the QbChart
object being created. This is done by passing in null
instead of a ColInfo
object.
You can create chart templates in Designer and open those templates using the API. The QbChart
object created uses the same data source as the template and attempts to fetch the data. However, it may be that while the template has all the look and feel needed, the data source may be an incorrect one. The following sections show how to switch the data source, without recreating the entire chart.
Please note that for best results, the number of columns and the data type of each column must match between the two data sources (i.e., the one used to create the template in Designer and the new data source).
After switching the data source, the QbChart
object must be forced to fetch the new data. This can be done by calling the refresh method in the QbChart
class.
Switching the data source to point to a database is simple. All you would need to do is provide the database connection information as well as the query to be used and pass that to the QbChart
object. You can provide the database connection information (as well as the query) in a DBInfo
object (for more information on creating a DBInfo
object, please refer to Appendix 10.A.1 - Data from a Database).
The following example, which can be run as a applet(More in: Section 2.6 - Run Applets in WebStart with JNLP file) or application, switches the data source of the QbChart
object to a database:
Component doChartSwitchToDatabase(Applet parent) { // Do not use EspressManager QbChart.setEspressManagerUsed(false); // Open the template QbChart chart = new QbChart (parent, // container "SwitchToDatabase.cht"); // template // New database connection information DBInfo newDatabaseInfo = new DBInfo(.....); try { // Switch data source chart.gethInputData().setDatabaseInfo(newDatabaseInfo); // Refresh the chart chart.refresh(); } catch (Exception ex) { ex.printStackTrace(); } // Show chart in Viewer return chart; }
Please note that the above code is not complete and is only there as a guide. However, the link contains a complete application code that can be run.
You can also change the data source to a JNDI data source. This is done by specifying the JNDI connection information in a DBInfo
object and then passing it to the QbChart
object.
The following example, which can be run as a applet(More in: Section 2.6 - Run Applets in WebStart with JNLP file) or application, switches the data source of the QbChart
object to a JNDI database:
Component doChartSwitchToDatabaseJNDI(Applet parent) { // Do not use EspressManager QbChart.setEspressManagerUsed(false); // Open the template QbChart chart = new QbChart (parent, // container "ChartSwitchToDatabaseJNDI.cht"); // template // New database connection information DBInfo newDatabaseInfo = new DBInfo(.....); try { // Switch data source chart.gethInputData().setDatabaseInfo(newDatabaseInfo); // Refresh the chart chart.refresh(); } catch (Exception ex) { ex.printStackTrace(); } // Show chart in Viewer return chart; }
Please note that the above code is not complete and is there only as a guide. However, the link contains a complete application code that can be run. Note that for the application code to run, the Woodview database needs to be set up as a JNDI data source in the Tomcat environment and the application code changed to match the connection information.
You can switch the data source to a text file as long as the text file follows the Quadbase guidelines (for more details, please refer to Appendix 10.A.2 - Data from a Data file (TXT/DAT/XML)).
The following example, which can be run as a applet(More in: Section 2.6 - Run Applets in WebStart with JNLP file) or application, switches the data source of the QbChart
object to a text file:
Component doChartSwitchToDataFile(Applet parent) { // Do not use EspressManager QbChart.setEspressManagerUsed(false); // Open the template QbChart chart = new QbChart (parent, // container "../templates/ChartSwitchToDataFile.cht"); // template try { // Switch data source chart.gethInputData().setDataFile(....); // Refresh the chart chart.refresh(); } catch (Exception ex) { ex.printStackTrace(); } // Show chart in Viewer return chart; }
Please note that the above code is not complete and is there only as a guide. However, the link contains a complete application code that can be run.
You can switch the data source to your custom XML data as long as there is a .dtd or .xml schema accompanying your data. The XML data information is specified (for more details, please refer to Appendix 10.A.3 - Data from a XML Data Source) and then passed to the QbChart
object.
The following example, which can be run as a applet(More in: Section 2.6 - Run Applets in WebStart with JNLP file) or application, switches the data source of the QbChart
object to XML data:
Component doSwitchToXMLData(Applet parent) { // Do not use EspressManager QbChart.setEspressManagerUsed(false); // Open the template QbChart chart = new QbChart (parent, // container "../templates/ChartSwitchToXMLData.cht"); // template // XML data source information XMLFileQueryInfo newData = new XMLFileQueryInfo(...); try { // Switch data source chart.gethInputData().setXMLFileQueryInfo(newData); // Refresh the chart chart.refresh(); } catch (Exception ex) { ex.printStackTrace(); } // Show Chart in Viewer return chart; }
Please note that the above code is not complete and is there only as a guide. However, the link contains a complete application code that can be run.
In addition to the regular data sources, you can also pass in your own custom data. The custom data is passed to the QbChart
object using the IDataSource
interface (for more details, please refer to Appendix 10.A.5 - Data Passed in your Custom Implementation).
The following example, which can be run as a applet(More in: Section 2.6 - Run Applets in WebStart with JNLP file) or application, switches the data source to a custom implementation:
Component doSwitchToCustomData(Applet parent) { // Do not use EspressManager QbChart.setEspressManagerUsed(false); // Open the template QbChart chart = new QbChart (parent, // container "ChartSwitchToCustomData.cht"); // template try { // Switch data source chart.gethInputData().setClassFile(..); // Refresh the chart chart.refresh(); } catch (Exception ex) { ex.printStackTrace(); } // Show chart in Viewer return chart; }
Please note that the above code is not complete and is there only as a guide. However, the link contains a complete application code that can be run.
You can also pass in data using arrays. The array data is usually stored is memory and passed to the QbChart
object (for more details, please refer to Appendix 10.A.4 - Data Passed in an Array in Memory).
The following example, which can be run as a applet(More in: Section 2.6 - Run Applets in WebStart with JNLP file) or application, switches the data source to an array in memory:
Component doSwitchToArrayData(Applet parent) { // Do not use EspressManager QbChart.setEspressManagerUsed(false); // Open the template QbChart chart = new QbChart (parent, // container "ChartSwitchToArrayData.cht"); // template // Create array data DbData newData = new DbData(...); try { // Switch data source chart.gethInputData().setData(newData); // Refresh the chart chart.refresh(); } catch (Exception ex) { ex.printStackTrace(); } // Show chart in Viewer return chart; }
Please note that the above code is not complete and is there as a guide. However, the link contains a complete application code that can be run.
EspressChart has hundreds of properties, which provide a fine control over various elements of a chart. In order to facilitate ease-of-use, most properties have been categorized into groups and exposed in the form of interfaces. An application first obtains a handle to a group interface using a gethXXX
method and then manipulates the chart's properties directly by calling methods on that interface. Most interfaces are contained in the quadbase.util and quadbase.ChartAPI packages.
A chart is comprised of different elements (for instance, the canvas, the axis, the legend, the chart data, etc). Each element can be modified independently of the other by getting the appropriate interface and changing the properties by calling the methods therein.
For instance, the following code sets the background color of the chart to white:
chart.gethCanvas().setBackgroundColor(Color.white); // chart being an object of type QbChart
while the code given below changes the color of the X axis to black:
chart.gethXAxis().setColor(Color.black); // chart being an object of type QbChart
You can also set the color of the data elements of the chart based on the series or based on the category (if no series is defined). For example, if the chart is a Column chart with 5 elements in the series, the following code sets the columns colors in the series, to be yellow, orange, red, green and blue.
Color dataColors[] = {Color.yellow, Color.orange, Color.red, Color.green, Color.blue}; chart.gethDataPoints().setColors(dataColors); // chart being an object of type QbChart
Note that the number of colors defined must match the number of unique elements in the series (or the category if the series is not defined).
Similarly, the font styles can be set by calling the appropriate interface and using the method. The following code sets the text used in the legend to be of Arial, bold type and size 15.
Font legendFont = new Font("Arial", Font.BOLD, 15); chart.gethLegend().setFont(legendFont); // chart being an object of type QbChart
while the following code sets the font and color of the labels used in the Y Axis:
Font YAxisFont = new Font("Helvetica", Font.ITALIC, 15); chart.gethYAxis().gethLabel().setFont(YAxisFont); // chart being an object of type QbChart chart.gethYAxis().gethLabel().setColor(Color.blue); // chart being an object of type QbChart
Similarly, other properties can be set using the methods in the interfaces.
The class QbPattern
is a subclass of java.awt.Color
, so there is no new method introduced to set patterns explicitly. You create a QbPattern
object first, and then use it as if it is a Color
object. The pattern feature is only applicable to data points. For other chart elements (such as axis, canvas), EspressChart will ignore the QbPattern
properties, and use it just like a Color
.
The following example, which can be run as a applet(More in: Section 2.6 - Run Applets in WebStart with JNLP file) or application, shows how to set a pattern to a data point:
Color[] dataColors = chart.gethDataPoints().getColors(); QbPattern dataPattern = new QbPattern(colors[2], QbChart.PATTERN_THICK_FORWARD_DIAGONAL); dataColors[2] = dataPattern; chart.gethDataPoints().setColors(dataColors);
There are totally 30 predefined patterns available for you to use. The pattern ID range from 0 to 29. If the user passes an integer beyond this range, it will be considered as ID = 0, which is a solid color block. The Pattern ID is defined in quadbase.ChartAPI.IMiscConstants class as well as in quadbase.common.swing.color.PatternImage
class. Since QbChart
implements the IMiscConstants
interface, you can obtain these IDs directly from QbChart
. You can also see what each pattern looks like in the pattern palette Designer
.
You can also set up your own pattern (texture) images. This feature is only available via API and the modification will not be saved to the template. This feature is mainly for those who want to modify the chart during the run time.
The following example, which can be run as a applet(More in: Section 2.6 - Run Applets in WebStart with JNLP file) or application, shows how to set a custom pattern to a data point:
Color[] dataColors = chart.gethDataPoints().getColors(); QbPattern dataPattern = new QbPattern(dataColors[2]); File customImageFile = new File("Quadbase_Logo.png"); BufferedImage customImage = ImageIO.read(customImageFile); dataPattern.setPatternImage(customImage); dataColors[2] = dataPattern; chart.gethDataPoints().setColors(dataColors);
In the above code, a QbPattern
object is created without specifying the pattern ID. The newly created object is equivalent to a java.awt.Color object
. The developer is responsible for providing an image so as to avoid the NullPointerException
prompting in the procedure. An existing image (from a file) is then passed as the pattern for data point 2.
There are two sizes to be considered when creating a chart:
This size is defined relative to the chart canvas. For instance, the chart plot height might be set as .7 and the chart plot width set as .8 . In the case where the canvas is 300 by 300 pixels, the height of the chart plot becomes 210 (.7 x 300) pixels and the width becomes 240 pixels (or .8 x 300). If the canvas size is increased to 500 by 600 pixels, the height of the chart plot becomes 420 pixels (.7 * 600) and the width becomes 400 pixels (.8 * 500). Relative sizes depend on the canvas height and width.
This size denotes an absolute size of the canvas in pixels.
Every element of the chart (where the size parameter is used) is defined relative to the chart canvas. A float is used to represent the relative size of the chart element. For instance, the following code sets the chart plot height to .85 and the chart plot width to .65:
chart.gethChartPlot().setRelativeHeight(.85f); // chart being an object of type QbChart chart.gethChartPlot().setRelativeWidth(.65f); // chart being an object of type QbChart
The code given below sets the canvas size of the chart:
Dimension canvasSize = new Dimension(500, 450); chart.gethCanvas().setSize(canvasSize); // chart being an object of type QbChart
Similarly, the sizes of the other elements can be set using the methods in the interfaces.
You can modify the properties (such as scale and starting/ending time perion) of a Date/Time Zoom template created in the Designer. This is done by getting a handle to the Zoom properties (using the IZoomInfo
interface) and using the various methods there to change the presentation.
The following example, which can be run as a applet(More in: Section 2.6 - Run Applets in WebStart with JNLP file) or application, shows how to modify a Date/Time Zoom chart:
// Modify starting and ending period and scale IZoomInfo zoomInfo = chart.gethZoomInfo(); // Begin Date Calendar beginDate = new GregorianCalendar(2001, 0, 1); // End Date Calendar endDate = new GregorianCalendar(2003, 11, 31); zoomInfo.setLowerBound(beginDate.getTime()); zoomInfo.setUpperBound(endDate.getTime()); zoomInfo.setScale(6, IZoomInfo.MONTH); chart.refresh();
In the above code, chart is an object of type QbChart
. Note that after modifying the chart's zoom properties, the chart must be refreshed for the modified properties to take effect.
Any charts included in the chart can be exported into JPEG, GIF and PNG formats as well; although by default, the charts in the chart are exported as JPEG's. The format for the chart can be changed, when creating the ChartChartObject
object, by specifying the image type use the method setImageType(int)
.
The EspressChart API has the capability to export stand-alone charts in a variety of formats. These include GIF, JPEG, PNG, BMP and PDF formats. In addition, a chart may be exported to the proprietary .cht or .tpl formats. A .cht stores all the chart information and can be considered the EspressChart equivalent of a static image file. A .cht file differs from a static image file in that its data can be refreshed from the data source and it allows additional functionality such as zooming, drill-down etc A .tpl file is identical to a .cht file except it doesn't store actual data. For a .tpl file, the data is automatically reloaded from the original data source at the time of chart reload. Both .cht and .tpl files can be viewed using the EspressChart Viewer or EspressChart API. When using stand-alone charts, you can specify the format by creating a QbChart
object and using the various export methods within the class.
There are different methods available for exporting a stand-alone chart in a variety of formats with different options. The simplest method would be:
public export(int format, String filename)
In the above method, format is one of the format constants and filename is the output filename (with or without an extension).
The following is a list of the constants used for exporting the chart components:
Bitmap | QbChart.BMP |
GIF | QbChart.GIF |
JPEG | QbChart.JPEG |
PNG | QbChart.PNG |
QbChart.PDF | |
Flash | QbChart.FLASH |
Scalable Vector Graphics | QbChart.SVG |
Text Data | QbChart.TXTFORMAT |
XML Data | QbChart.XMLFORMAT |
Windows Meta File | QbChart.WMF |
Depending on the format selected, additional options are also available. For example, exporting a chart object as a jpeg gives you the choice of the image quality (represented as number from 0 - 99) while export a chart object as a PNG gives you the choice of specifying the compression used. The options can be specified using the following method:
public export(int format, String filename, int option)
The following code, which can be run as an applet or application, shows how to construct and export a chart:
// Open the template QbChart chart = new QbChart(parent, "ExportChart.cht"); try { chart.export(QbChart.PNG, "ExportChart"); } catch (Exception ex) { ex.printStackTrace(); }
Please note that when you export the chart to a text file, the default delimiter is a tab space. However, you can set another delimiter (available delimiters are “,”, “;” and “ ”) by using the following method:
chart.exportDataFile("TextData", QbChart.COMMA, QbChart.TXTFORMAT); // where chart is an object of type QbChart
If you plan on exporting the chart object without viewing it, setting the following static method to true would improve performance slightly:
QbChart.setForExportOnly(boolean);
Calling this method before constructing the QbChart
object would result in better performance.
You can also export the QbChart
object to a byte array using the following method:
public byte[] exportChartToByteArray();
This will give the .cht equivalent in the form of a byte array. This is useful if you need to serialize the QbChart
object.
EspressChart also has record file exporting to handle large amounts of data. In record file exporting, you specify the number of records to be held in memory and a temp directory. When the number of records in the data exceeds the number specified to be held in memory, the data is stored on disk in the temp directory specified.
There are certain conditions that have to be met before you can use this feature. You must:
make sure that EspressManager is not used;
make sure that the data is NOT from a XML source;
make sure that the data is sorted;
To use record file export, the following code must be added before calling the QbChart
constructor:
QbChart.setEspressManagerUsed(false); QbChart.setTempDirectory(<specify the temp directory to store data. Default is ./temp>); QbChart.setMaxCharForRecordFile(<specify the maximum character length. Default is 40>); QbChart.setMaxRecordInMemory(<specify the maximum number of rows to be kept in memory. Default is -1 i.e., store all records in memory>); QbChart.setFileRecordBufferSize(<specify the number of rows to be retrieved at one time from disk. Default is 10,000>);
In addition to exporting to local drives, charts can also be exported as a byte stream and streamed directly to a web browser. Note that server side code typically exports the image only in a binary format. You are responsible for creating a wrapper (i.e., DHTML/HTML content) around the exported image.
Given below is an example that exports a chart to PNG and streams it to the browser. In order to run the example, you will need to configure and compile the source code, then deploy the class file in the servlet directory of your servlet runner. Replace the chartTemplate
variable with either an absolute path or a path relative to the working directory of your application server.
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Do not use EspressManager QbChart.setEspressManagerUsed(false); String chartTemplate = "StreamingChart.cht"; // Open template QbChart chart = new QbChart((Applet)null, chartTemplate); // Export the chart to PNG and stream the bytes ByteArrayOutputStream chartBytes = new ByteArrayOutputStream(); try { chart.export(QbChart.PNG, chartBytes); } catch (Exception ex) { ex.printStackTrace(); } resp.setContentType("image/x-png"); resp.setContentLength(chartBytes.size()); OutputStream toClient = resp.getOutputStream(); chartBytes.writeTo(toClient); toClient.flush(); toClient.close(); }
To run the example, make sure to copy the chart template to the location accessed by the code. If using a relative path (as shown in the example), remember that the current directory is the working directory of your application server. For example, since the working directory in Tomcat is <Tomcat>/bin
, you will need to create the directory <Tomcat>/templates/
and copy the chart template there to run the code. The resulting chart is shown below.
Chart Designer can be called from Chart API in either an application or an applet. Depending on the code, you can pass in parameters to open up Chart Designer with a specified template file or a specified data source or other parameters.
To call Chart Designer from Chart API, you must:
make sure that EspressManager is up and running;
add EspressAPI.jar
, EspressManager.jar
and qblicense.jar
to the CLASSPATH;
make sure that the information to connect to EspressManager is specified using the relevant API calls (This is especially important if the EspressManager is on a different machine and/or if it started with a port number other than 22071);
copy the images and backgroundimages directories to the working directory or pass the location (of those directories) in the prper constructor in your code;
Depending on the -RequireLogin
and -QbDesignerPassword
flags for EspressManager, you may need to pass in a userid and/or password to connect to EspressManager. If the -RequireLogin
flag is set for EspressManager, you need to add the following line of code before calling setVisible()
or any getDesigner methods:
public login(String userName, String password); // Method found in QbCharttDesigner class
If the -QbDesignerPassword
is specified for EspressManager, you will need to add the following line of code before calling setVisible()
or any getDesigner methods:
public login(String password); // Method found in QbChartDesigner class
Given below are the different ways Chart Designer can be called via Chart API
You can open Chart Designer with a specified chart template file. This allows the end users to create their own custom charts in Chart Designer GUI and then view the finished chart.
The following constructor is used:
QbChartDesigner(Object parent, String chtFile, String[] imagesPath);
Given below is an example of calling Chart Designer with a specified .cht file:
public void doChartDesignerApplet(Object parent) throws Exception { // Connect to EspressManager QbChartDesigner.setServerAddress("127.0.0.1"); QbChartDesigner.setServerPortNumber(22071); // these folders are located in the <InstallDir> directory. Change the paths to absolute paths, or paths relative to this application. String[] imagesPath = {"images", "backgroundImages"}; // Create a new QbReportDesigner instance designer = new QbChartDesigner(parent, "CDWithTemplateFile.cht", imagesPath); // Start Designer designer.setVisible(true); }
Note that the above code can be used as both an application and an applet.
When the user runs this code, Chart Designer is launched with the chart template you specified.
The user can then customize the chart and save the results.
You can open Chart Designer and have it starting with a Data Source Manager (with a specified .xml file for the Data Registry). This allows the end users to choose the data source and create their own custom charts in Chart Designer GUI and then view the finished chart.
The following constructor is used:
QbChartDesigner(Object parent, String nameOfXMLFile, boolean newChart, String[] imagesPath);
Given below is an example of calling Chart Designer with a specified .xml file:
public void doChartDesignerWithDataRegApplet(Object parent) throws Exception { // Connect to EspressManager QbChartDesigner.setServerAddress("127.0.0.1"); QbChartDesigner.setServerPortNumber(22071); // these folders are located in the <InstallDir> directory. Change the paths to absolute paths, or paths relative to this application. String[] imagesPath = {"images", "backgroundImages"}; // QbChartDesigner (Object, name of XML file, start from Data Registry?, images directory) designer = new QbChartDesigner(parent, "DataRegistry/sample.xml", true, imagesPath); designer.setVisible(true); }
Note that the above code can be used as both an application and an applet.
You can open Chart Designer and have it starting at the Select Chart Type wizard window (with a specified DBInfo
object). This allows the end users to create their own custom charts in Chart Designer GUI and then view the finished chart.
The following constructor is used:
QbChartDesigner(Object parent, DBInfo databaseInformation, QueryInParamSet inset boolean newChart, String[] imagesPath);
Given below is an example of calling Report Designer with a specified DBInfo
object:
public QbChartDesigner designer; String url = "jdbc:hsqldb:help/examples/DataSources/database/woodview"; String driver = "org.hsqldb.jdbcDriver"; String username = "sa"; String password = ""; String query = "SELECT * FROM Products"; public void doChartDesignerWithDBInfoApplet(Object parent) throws Exception { // Connect to EspressManager QbChartDesigner.setServerAddress("127.0.0.1"); QbChartDesigner.setServerPortNumber(22071); // these folders are located in the <InstallDir> directory. Change the paths to absolute paths, or paths relative to this application. String[] imagesPath = {"images", "backgroundImages"}; // QbReportDesigner (component, Database Information, start from Select Chart wizard, Parameter Information, Images Path DBInfo dbInfo = new DBInfo(url, driver, username, password, query); designer = new QbChartDesigner(parent, dbInfo, null, true, imagesPath); designer.setVisible(true); }
Note that the above code can be used as both an application and an applet.
You can open Query Builder with a specified DBInfo
object. This allows the end users to create their own custom SQL queries in Query Builder GUI and save them.
Given below is an example of calling Query Builder with a specified DBInfo
object:
public void doQueryBuilderApplet(Object parent, String sqlName) { // Connect to EspressManager QbChartDesigner.setServerAddress("127.0.0.1"); QbChartDesigner.setServerPortNumber(22071); queryMain = new QbQueryBuilder(parent, this); if (sqlName != null) { // sqlName .qry file name (without extension) // System.out.println("OPEN QUERY - " + sqlName); queryMain.openQuery(sqlName, false, null, null, driver, url, username, password); } else { // System.out.println("NEW QUERY "); queryMain.newQuery("Setup Query", false, null, null, driver, url, username, password); } frame = queryMain.getBuilder(); frame.setVisible(true); try { queryMain.showTablesWindow(); } catch (Exception ex) {}; } public void back() {}; public void cancel() {}; public void next() { queryMain.getBuilder().setVisible(false); DBInfo dbInfo = new DBInfo(url, driver, username, password, queryMain.getSQL()); designer = new QbChartDesigner(applet, dbInfo, queryMain.getInSet(), true, imagesPath); designer.setVisible(true); }
Note that the above code can be used as both an application and an applet.
You can also open Query Builder by passing in the database connection (schema) as a java object, rather than as a DBInfo
object. Given below is an example of calling Query Builder by passing in the schema information:
public QBWithDBInfo2() { // Connect to EspressManager QbChartDesigner.setServerAddress("127.0.0.1"); QbChartDesigner.setServerPortNumber(22071); try { Class.forName(driver); conn = DriverManager.getConnection(url, username, password); metaData = conn.getMetaData(); } catch (Exception ex) { ex.printStackTrace(); } queryMain = new QbQueryBuilder(null, this); queryMain.newQuery("Setup Query", this); queryMain.setVisible(true); try { queryMain.showTablesWindow(); } catch (Exception ex) {}; } public void back() {}; public void cancel() {}; public void next() { queryMain.getBuilder().setVisible(false); DBInfo dbInfo = new DBInfo(url, driver, username, password, queryMain.getSQL()); designer = new QbChartDesigner(applet, dbInfo, queryMain.getInSet(), true, imagesPath); designer.setVisible(true); } public String getDatabaseProductName() throws Exception { return metaData.getDatabaseProductName(); } public ResultSet getTables(String catalog, String schemPattern, String tableNamePattern, String[] types) throws Exception { return metaData.getTables(catalog, schemPattern, tableNamePattern, types); } public String getNumericFunctions() throws Exception { return metaData.getNumericFunctions(); } public String getStringFunctions() throws Exception { return metaData.getStringFunctions(); } public String getTimeDateFunctions() throws Exception { return metaData.getTimeDateFunctions(); } public String getSystemFunctions() throws Exception { return metaData.getSystemFunctions(); } public ResultSet executeQuery(String sql) throws Exception { Statement stmt = conn.createStatement(); return stmt.executeQuery(sql); }
Note that the above code can be used as both an application and an applet.
You can also set the directories that charts load from and save to. This feature will restrict users from navigating to any level above the specified directory, giving you the ability to control which files the user is able to see.
Given below is an example that shows you how to customize Chart Designer by specifying the root directory for browsing:
public void doChartDesignerApplet(Object parent) throws Exception { QbChartDesigner.setServerAddress("127.0.0.1"); QbChartDesigner.setServerPortNumber(22071); // these folders are located in the <InstallDir> directory. Change the paths to absolute paths, or paths relative to this application. String[] imagesPath = {"images", "backgroundImages"}; // IMPORTANT: put the CDWithPreSetDirectories.cht file to the <InstallDir>/ directory (for example: C:/EspressChart/CDWithPreSetDirectories.cht) designer = new QbChartDesigner(parent, "CDWithPreSetDirectories.cht", imagesPath); designer.setRootDirectoryForBrowse("."); designer.setVisible(true); }
Note that the above code can be used as both an application and an applet.
In addition to the above approach, you can also use the following method to get the default directories used by Chart Designer:
public BrowseDirectories getBrowseDirectories();
You can then use the methods in BrowseDirectories to get the default location of the directories for the different browse dialogs.
You can also add items to the menu and remove items from the toolbar. Given below is an example illustrating that:
public void doCustomizeDesignerMenuApplet(Object parent) throws Exception { QbChartDesigner.setServerAddress("127.0.0.1"); QbChartDesigner.setServerPortNumber(22071); // these folders are located in the <InstallDir> directory. Change the paths to absolute paths, or paths relative to this application. String[] imagesPath = {"images", "backgroundImages"}; designer = new QbChartDesigner(parent, "CDWithModifiedBars.cht", imagesPath); // Add a new menu item JMenuBar menuBar = designer.getChartMenuBar(); JMenu fileMenu = menuBar.getMenu(0); newItem = new JMenuItem("Hello World"); newItem.addActionListener(this); fileMenu.insert(newItem, 7); // Remove toolbar buttons JToolBar designBar = designer.getChartToolBar(); designBar.remove(5); // Remove Separator designBar.remove(4); // Remove Export designer.setSaveOnExitEnabled(false); // Do not prompt to save the chart if unsaved on exiting Designer designer.setVisible(true); } public void actionPerformed(ActionEvent e) { /*** save report **********/ designer.save("CDWithModifiedBars_Temp.cht"); /**** create new testing frame *********/ JPanel contentPane = new JPanel(); contentPane.setLayout(new BorderLayout()); contentPane.add(new JLabel("Hello World!"), "Center"); JFrame frame = new JFrame(); frame.setContentPane(contentPane); frame.pack(); frame.setVisible(true); }
Note that the above code can be used as both an application and an applet.