by Bryan Morgan
What separates Visual J++ and the Microsoft Virtual Machine from all other Java tools is the integration between Java and Microsoft's component object model (COM). Previous chapters provide an introduction to those readers new to using COM projects or, in particular, programming with COM objects. This chapter is primarily example oriented, illustrating how Java code can be written to call COM objects using Visual J++ and the Microsoft Virtual Machine.
When you have to use some combination of COM and Java (whether through COM objects, ActiveX controls, or some other means), you have three options:
Examples in this chapter examine the first two of these options. Both specifically deal with calling a COM object from within a Java program. The third option is presented in Chapter 21, "Building COM Objects with Java."
Whenever software components are integrated to form a working application, some setup and system configuration are required to ensure that the various components work together correctly. For instance, when a Visual Basic developer uses an OCX control on a form, this control must be registered with the operating system. When a UNIX programmer distributes a set of shared objects for use by one or more applications, the system path must be set to include the directory containing these libraries. Likewise, Java programmers must go through two primary steps before a COM object can be successfully compiled and used in a Java program. First, the COM object must be registered on the local system. Following this, the contents of the COM object's type library must be extracted using tools provided with Visual J++. Another step is required to actually distribute the completed Java classes to other users. This step requires the classes to be digitally signed for security purposes.
The first step applies to not only Java programmers, but programmers developing in any language: You need to register the COM object in the Windows Registry using the CLSIDs stored in the object. (Recall from Chapter 15, "GUI Development Using the Visual J++ Resource Wizard," that CLSIDs are globally unique identification numbers that are used to identify a COM object.) You can register COM objects several different ways.
At the simplest, you can record and manually add the required
Registry settings using the Registry tool, named REGEDIT.EXE
under Windows 95 and REGEDT32.EXE under Windows NT. You
can also write and run registration script files that will automatically
register the script's settings into the Registry. Perhaps the
simplest way to register many COM objects is by using the REGSVR32.EXE
tool.
| NOTE |
Under Windows 95, REGSVR32.EXE is in your \WINDOWS\SYSTEM directory. Under Windows NT, REGSVR32.EXE is in the \WINDOWS\SYSTEM32 directory. |
REGSVR32 takes advantage of the fact that all COM in-process servers (DLLs and OCXs) are required to be self-registering by definition. REGSVR32 simply calls the necessary commands in the object to register it in the Registry. If an application is run without a corresponding COM object being registered, it is common to see an error message such as "Object Not Found" or something along those lines. When an application using OLE controls is originally run with errors, it is common to find that the set of controls was not registered.
REGSVR32 is a command-line tool that has a simple set
of options (see Table 20.1).
| Description | |
| Unregister the specified COM server | |
| Register the COM server silently (with no visible output) | |
| Register the COM server with output to the console |
The REGSVR32 tool is used with the following command-line syntax:
regsvr32 <options> filename.xxx
The /s option is commonly used during an application's installation process to register a control in the background without alerting the user. Microsoft Internet Explorer uses the silent registration option to register ActiveX components as they are downloaded from remote locations.
After a COM object has been registered with the system, it is still simply a DLL/OCX/EXE binary object residing on the hard drive. To allow the Java programmer to use this object, Microsoft could have simply added a thinly disguised native method interface to COM objects. However, because of the many similarities between Java and COM (see Chapter 16, "Java and the Component Object Model"), Microsoft provides a method to seamlessly combine COM and Java objects in source code. In other words, COM objects can be instantiated and used side by side with other Java objects with no special syntax or keywords required. This magic was accomplished by creating a tool that could examine the contents of a COM type library, extract them, and produce the corresponding Java class files to match the contents of the type libraries. As you know by now, after the class files are created, the import statement can be used to import a package or class into another Java class.
The Java Type Library Wizard is used to build these class files in Visual J++. This wizard can be run from the Visual J++ IDE by selecting the Tools | Java Type Library Wizard main menu option. The application that responds to this menu selection is actually JAVATLB.EXE, located in your installation directory's \bin subdirectory. The Type Library Wizard can also be run from the command line with a set of extended options using the following syntax:
javatlb <options> type_library_filename
Keep in mind that a type library can exist in a standalone .tlb
file. It can also be stored as a resource within a COM object
(.exe, .dll, .ocx, .olb).
When run on a type library, a directory (named with the type library's
filename) will be created in the trusted libraries directory on
the local machine.
| NOTE |
To determine which directory is currently being used to store trusted classes, examine the registry key HKEY_LOCAL_MACHINE\Software\Microsoft\Java VM\TrustedLibsDirectory using the Registry Editor. |
One Java class file is created for each class or interface in
the type library. Options that can be used in combination with
the Java Type Library Wizard are listed in Table 20.2.
| Option | Description |
| @list | Displays @ symbol + filename containing list of type library files |
| /U | Displays signatures for all public methods for each class file |
| /U:T | Displays signatures for all public methods for each class file and writes the information to a text file |
| /p package_name | Specifies which package the output class files will be placed into |
When run from the Developer Studio menu selection, the Java Type Library Wizard always produces a file named SUMMARY.TXT and places that file in the type library's trusted directory. This file contains the signatures for each method in the class file. In effect, the Java Type Library Wizard runs JAVATLB with the following syntax:
javatlb /U:T library.tlb > SUMMARY.TXT
Security options become significantly more complex when Java classes
are combined with COM objects to build applications. First, using
ActiveX controls implies an entirely new set of security precautions
that may be new even to the veteran Java programmer. Second, Java
class files generated from a COM type library must be contained
in a CAB file and digitally signed using Microsoft's Code Signing
standard. Applets or applications that make use of these Java
classes will not run outside the Visual J++ Developer Studio unless
they are contained in a CAB file and have been signed. Security
issues are addressed in detail in Chapter 23, "Security with
ActiveX Authenticode." For now, let's assume that the samples
shown in this chapter (and Chapters 21, "Building COM Objects
with Java," 22, "Using ActiveX Documents to Convey Information,"
and 23) will be run from Developer Studio to avoid this problem.
| NOTE |
When loading ActiveX controls embedded in an HTML page using Internet Explorer 3.0, make sure that IE's security options are set to the Medium level. This is done by selecting the View menu and then the Options item. Select the Security tab and then the Safety button. Finally, select either the None or Medium options to enable the downloading and display of ActiveX components. |
Again, be sure to run all Java/COM examples included with Visual J++ or with this book from the Developer Studio environment. Because none of these classes have been signed and are not contained in a CAB file, a java.lang.VerifyError error may occur.
This section gives an example to illustrate how a COM object can be called from a Java applet or application. It would have been possible to create a COM in-process server DLL that exported a class or interface to be called from Java. However, the topic of creating COM objects using C or C++ is outside the scope of this book. (In addition, creating COM objects in Java is not discussed until Chapter 21.) Therefore, for purposes of illustration, the JavaCallingCOM sample included with Visual J++ is studied.
The JavaCallingCOM sample application consists of a COM automation server DLL, Java applet, and set of HTML files used to display and document the sample application. The server DLL, comserver.dll, contains a set of available system sound IDs (stored as constants) along with the IComBeeper interface, which provides helper functions to select and play the sounds.
Although it might seem a little odd because of the underlying complexity of what is actually happening, when the object's structure has been extracted into Java class files, it is extremely easy to use that object in Java source code. Following the steps outlined in "Registering the Object" before the COM DLL can be accessed from a Java program, the DLL must be registered and class files must be generated using the Java Type Library Wizard. Therefore, take the following steps: First, execute the following statement in the directory containing the COMServer DLL: c:\windows\system\regsvr32 comserver.dll. Following this exercise, use the Java Type Library Wizard to select the COMServer 1.0 Type Library to generate class files (see Figure 20.1).
Figure 20.1 : The Java Type Library Wizard.
When the wizard has successfully generated the class files for the COMServer DLL, you can verify the classes by examining the \WINDOWS\SYSTEM\JAVA\TRUSTLIB\COMSERVER directory (or the trusted classes directory on your machine). In this directory, the following class files should have been created:
BeeperConstants.class
CCOMBeeper.class
ICOMBeeper.class
A file named SUMMARY.TXT also should have been created. This file will contain the signatures for all public methods and variables contained in each class or interface in the DLL of the COM. Listing 20.1 shows the contents of the generated SUMMARY.TXT file.
Listing 20.1. The contents of the COMSERVER.DLL summary file.
public interface comserver/ICOMBeeper extends com.ms.com.IUnknown
{
public abstract void putSound(int);
public abstract int getSound();
public abstract java.lang.String getSoundName();
public abstract void Play();
}
public class comserver/CCOMBeeper extends java.lang.Object
{
}
public interface comserver/BeeperConstants extends com.ms.com.IUnknown
{
public static final int Default;
public static final int Asterisk;
public static final int Exclamation;
public static final int Hand;
public static final int Question;
public static final int StandardBeep;
}
Each constant defined in the BeeperConstants interface represents a system sound that will be played by calling the Play() method found in the IComBeeper interface.
As described in Chapter 16, COM objects are always referenced by one of their exposed interfaces. This particular COM object can be accessed by the ICOMBeeper interface. By examining the usecom applet class in the usecom.java source file, you can see the COM object declared exactly like any other Java object:
ICOMBeeper m_beeper;
Later on, the COM object is instantiated using the standard Java new keyword:
m_beeper = new CCOMBeeper();
From there, the Java list box is simply filled with text, and the sound associated with that list's index is set using the following lines of code:
m_beeper.putSound(BeeperConstants.Asterisk); m_nameList[1].name = m_beeper.getSoundName(); m_nameList[1].value = m_beeper.getSound();
As you can see, the putSound(), getSoundName(), and getSound() methods are all defined in the ICOMBeeper interface in Listing 20.1. Figure 20.2 shows the JavaCallingCOM applet being run in Internet Explorer 3.0.
Figure 20.2 : The JavaCallingCOM applet.
By selecting one of the sounds displayed in the list box and pressing the Play the Sound button, you will play the default sounds currently registered under Windows. This is an example of integrating Java with a COM object to do something that is simply not possible using Java alone. Because of security restrictions the Java security model places on Java applets, system resources such as hard drives, audio, or printers cannot be accessed using Java.
Because ActiveX controls are compliant with the COM, you can also access them from Java code. This functionality gives you a huge existing base of ActiveX controls that can be used to build powerful Web pages. To provide truly active functionality to the user, several approaches can be used.
Perhaps the most obvious starting point for a Java programmer is to build a Web page consisting entirely of Java classes. This allows you to design a page that can be viewed on many operating systems, including Windows, Macintosh, OS/2, and UNIX. This is a huge advantage that does not exist for the ActiveX developer. However, hundreds if not thousands of production-quality ActiveX controls currently exist that you can immediately use. The same cannot be said for third-party Java classes. Therefore, under certain circumstances, it may be necessary to build a Web-based application using existing ActiveX components. When this decision has been reached, you can choose to script the controls on a page using VBScript or some other ActiveX scripting language. For many ActiveX developers, this may be a viable option. However, this will not be a cure-all for many others.
When ActiveX controls must be used in conjunction with some other powerful user-interface capabilities, a combination of Java and ActiveX offers the widest range of opportunities. The example used throughout the remainder of this chapter illustrates the use of Java with an ActiveX control to build an interactive charting application.
The program developed in this chapter makes use of an ActiveX control that can be downloaded from the Microsoft Web site at no cost. This control is combined with Java to build a charting application. Data is plotted in an ActiveX charting control based on a variety of user selections in the Java applet. As is shown in the example, a tiny bit of VBScript is used to "glue" the Java applet and ActiveX control together. A knowledge of VBScript is not necessary to understand the example; when the scripting language is used, it is explained.
To download the ActiveX component and run this application, you must use Microsoft Internet Explorer 3.0 (or higher). If another browser appears on the market with ActiveX support, however, this example still might not work. Remember that the Java/COM integration is made possible with the Microsoft Virtual Machine. Any browser that does not support Microsoft's extensions to the Java Virtual Machine will not be able to run the sample application. (For the foreseeable future, it appears that the Internet Explorer is the only browser with ActiveX and Java support.)
The control used to build this example is available free from Microsoft's ActiveX Web site. To download this control, go to http://www.microsoft.com/activex/gallery/default.htm and select the Chart control listed with the other Microsoft entries. When downloading the control, make sure that your security settings in Microsoft Internet Explorer are set correctly. When loading ActiveX controls embedded in an HTML page or installing these controls over the Internet using Internet Explorer 3.0, make sure that IE's security options are set to the Medium level.
While the control is downloading, a digital certificate displays to verify that the software has been signed (see Figure 20.3).
Figure 20.3 : The Chart control's verification certificate.
When downloaded, the Chart control is automatically registered onto your local system. Whereas Java classes are only temporarily cached to the local drive for a finite period of time by most browsers, ActiveX controls are permanently installed to your hard drive. Because this "feature" is unpopular with many users, Microsoft has stated that the permanent installation of ActiveX controls will be a user-configurable option in the future.
To look at it from another angle, ActiveX controls have a temporary advantage over Java classes in this area for intranet developers: One of the frustrating aspects of Java development is that each time a user loads a page, he or she may have to reload entire Java classes even if the user just visited the site recently. This happens often with intranet applications, where corporate users are visiting a page constantly. ActiveX controls must be downloaded only once and are then installed on the user's system. The next time the user visits the page, the control loads instantly with no download time.
Fortunately for "pure" Java developers, the Java Beans 1.0 specification provides for items known as jars, which store groups of Java classes to the local hard drive. This should greatly improve the startup performance of most Web-based Java applications. While Microsoft's Internet Explorer browser does not allow users to disable persistent caching of ActiveX controls, hopefully Java-enabled browsers will allow users to disable the caching of Java classes if they choose to do so.
Also note that the documentation for this ActiveX control is available at http://www.microsoft.com/activex/gallery/ms/ieprog/chart.htm. This document includes a description of the properties, events, and methods supported by this object.
After retrieving the ActiveX Chart control from the Microsoft Web site, you must retrieve the contents of its type library for a Java class to be able to converse with the control at runtime. To do this, use the Java Type Library Wizard, as described in the section "Calling a COM Object from Java." In Visual J++, select the Tools | Java Type Library Wizard menu option and then select the IE Chart object when prompted by the dialog box shown in Figure 20.1. When completed, the following class files will be located in the \iechart subdirectory in your \windows\java\trustlib directory (or the current trusted libraries directory on your machine):
DiechartEvents.class
enumBackStyle.class
enumChartStyle.class
enumChartType.class
enumColorScheme.class
enumGridPlacement.class
enumGridStyle.class
enumLegendStatus.class
enumLineStyle.class
iechart.class
Iiechart.class
The contents of the SUMMARY.TXT file (see Listing 20.2) show the properties, classes, and interfaces exposed in the Chart control.
Listing 20.2. The SUMMARY.TXT file for the IEChart ActiveX control.
public class iechart/iechart extends java.lang.Object
{
}
public interface iechart/DiechartEvents extends com.ms.com.IUnknown
{
}
public interface iechart/Iiechart extends com.ms.com.IUnknown
{
public abstract float getDataItem();
public abstract void putBackColor(int);
public abstract void putDataItem(float);
public abstract void putChartType(int);
public abstract void putForeColor(int);
public abstract java.lang.String getColumnName();
public abstract int getColumns();
public abstract void putColumns(int);
public abstract void putColorScheme(int);
public abstract int gethgridStyle();
public abstract int getvgridStyle();
public abstract void Reload();
public abstract void putVerticalAxis(short);
public abstract int getColorScheme();
public abstract int getRowIndex();
public abstract void putRowIndex(int);
public abstract void putColumnIndex(int);
public abstract int getRows();
public abstract void putRows(int);
public abstract void putGridPlacement(int);
public abstract void putDisplayLegend(int);
public abstract short getHorizontalAxis();
public abstract int getColumnIndex();
public abstract java.lang.String getRowName();
public abstract void putRowName(java.lang.String);
public abstract void putColumnName(java.lang.String);
public abstract java.lang.String getURL();
public abstract void putURL(java.lang.String);
public abstract void puthgridStyle(int);
public abstract void putvgridStyle(int);
public abstract int getGridPlacement();
public abstract void AboutBox();
public abstract int getDisplayLegend();
public abstract float getChartData();
public abstract void putHorizontalAxis(short);
public abstract int getBackStyle();
public abstract short getVerticalAxis();
public abstract void putChartData(float[]);
public abstract void putBackStyle(int);
public abstract short getScale();
public abstract void putScale(short);
public abstract int getBackColor();
public abstract int getForeColor();
public abstract int getChartType();
}
public interface iechart/enumLineStyle extends com.ms.com.IUnknown
{
public static final int Solid;
public static final int Dash;
public static final int Dot;
public static final int DashDot;
public static final int DashDotDot;
}
public interface iechart/enumGridPlacement extends com.ms.com.IUnknown
{
public static final int Bottom;
public static final int Top;
}
public interface iechart/enumLegendStatus extends com.ms.com.IUnknown
{
public static final int Off;
public static final int On;
}
public interface iechart/enumBackStyle extends com.ms.com.IUnknown
{
public static final int Transparent;
public static final int Opaque;
}
public interface iechart/enumColorScheme extends com.ms.com.IUnknown
{
public static final int ColorScheme1;
public static final int ColorScheme2;
public static final int ColorScheme3;
public static final int ColorScheme4;
public static final int ColorScheme5;
}
public interface iechart/enumGridStyle extends com.ms.com.IUnknown
{
public static final int NoGrid;
public static final int SolidGrid;
public static final int BoldGrid;
public static final int DottedGrid;
public static final int BoldDottedGrid;
}
public interface iechart/enumChartStyle extends com.ms.com.IUnknown
{
public static final int Simple;
public static final int Stacked;
public static final int Full;
}
public interface iechart/enumChartType extends com.ms.com.IUnknown
{
public static final int SimplePieChart;
public static final int SpecialPieChart;
public static final int SimplePointChart;
public static final int StackedPointChart;
public static final int FullPointChart;
public static final int SimpleLineChart;
public static final int StackedLineChart;
public static final int FullLineChart;
public static final int SimpleAreaChart;
public static final int StackedAreaChart;
public static final int FullAreaChart;
public static final int SimpleColumnChart;
public static final int StackedColumnChart;
public static final int FullColumnChart;
public static final int SimpleBarChart;
public static final int StackedBarChart;
public static final int FullBarChart;
public static final int HLCSimpleStockChart;
public static final int HLCWsjStockChart;
public static final int OHLCSimpleStockChart;
public static final int OHLCWsjStockChart;
}
As you can see, the majority of the classes defined in the Chart
control are used to provide constants that the Chart
control uses for display purposes. All the functionality contained
in the control can be accessed through the Iiechart interface.
Note the naming convention used for the methods in the Iiechart
interface. Thanks to the propget and propput
keywords used in the type library definition, the Java Type Library
Wizard can determine whether these methods are get or
put methods.
| NOTE |
For more information on the propget and propput keywords, see the section on ODL syntax titled "An ODL Primer" in Chapter 16. |
In short, methods that begin with get are property-accessor methods. Those that begin with put are property-setting methods.
Chances are very good that by now you have built your own HTML page for viewing in a Web browser. Possibly you have even added Java applets to a page or are at least aware of the <APPLET> HTML tag used to embed Java applets in a page. However, it is far less likely that you have ever actually built Web pages containing ActiveX controls. Although this chapter is not intended to be an HTML tutorial (see Chapter 26, "HTML and Web Page Design," for that), you can use the contents of Listing 20.3 to build a "starter" Web page using the ActiveX Chart control.
Listing 20.3. The contents of Example1.html.
<html>
<Title>Visual J++ Unleashed - Java/COM Integration Example</Title>
<CENTER>
<H1>Integrating Java and COM</H1><br>
<H3>Example One</H3>
</CENTER>
<CENTER>
<table cellpadding=15>
<tr>
<td>
<applet
code=ChartApplet.class
codebase=ChartApplet
id="TheApplet"
width=0
height=0>
</applet>
</td>
<td>
<object
classid="clsid:FC25B780-75BE-11CF-8B01-444553540000"
id="TheChart"
width=400
height=200
align=center
hspace=0
vspace=0
>
<param name="ChartType" value="5">
<param name="hgridStyle" value="0">
<param name="vgridStyle" value="0">
<param name="colorscheme" value="0">
<param name="DisplayLegend" value="1">
<param name="BackColor" value="#ffffff">
<param name="ForeColor" value="#0000ff">
<param name="Rows" value="12">
<param name="Columns" value="3">
<param name="RowNames" value="Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec">
<param name="ColumnNames" value="Sales Overhead Profit">
<param name="data[0]" value="500 100 400">
<param name="data[1]" value="600 100 500">
<param name="data[2]" value="750 100 650">
<param name="data[3]" value="400 100 300">
<param name="data[4]" value="250 100 150">
<param name="data[5]" value="800 100 700">
<param name="data[6]" value="875 100 775">
<param name="data[7]" value="1000 100 900">
<param name="data[8]" value="700 100 600">
<param name="data[9]" value="625 100 525">
<param name="data[10]" value="550 100 450">
<param name="data[11]" value="800 100 700">
</object>
</td>
</tr>
</table>
</CENTER>
<hr>
By the end of the chapter, this example will use the
<a href="http://www.microsoft.com/activex/gallery/ms/ieprog/chart.htm">
Microsoft ActiveX Chart control</a> and a Java applet to demonstrate how a
COM object can be used within a Java program. For now, the chart will be filled
with a set of
values passed to the control as parameters.
</html>
This HTML source code constructs a page using an HTML table to
contain the Java applet (nonexistent at this point) and the ActiveX
Chart control. Note the large number of param
tags passed to the ActiveX object. These parameters directly correspond
to various properties of the control. Passing these parameters
allows you to set some properties at design time so that there
is not a lot of initialization when the Java applet starts up.
Among the properties being set are ChartType, BackColor
and ForeColor, Rows, Columns, and ColorScheme.
| NOTE |
If you are curious about how these properties work, experiment with the Example1.html source file on the CD-ROM with this book. Again, the documentation for this control's properties and methods is available at http://www.microsoft.com/activex/gallery/ms/ieprog/chart.htm. |
Figure 20.4 shows the Example1.html file loaded and running in Internet Explorer 3.0.
Figure 20.4 : Example1.html in Internet Explorer 3.0.
This small amount of HTML coding constitutes virtually all the COM work you have to do to build the remainder of the example. From this point on, except for one line of VBScript code to be added to the Web page, the application is written entirely in Java.
Listing 20.3 is used to demonstrate how ActiveX properties are set at startup through parameter passing. You now have an ActiveX (COM) object sitting all alone on a Web page. Earlier the Java Type Library Wizard was used to build class files corresponding to the contents of the ActiveX Chart control. Before you can simply import these classes and begin writing Java code, one last hurdle must be cleared: Java applets cannot directly trap ActiveX control events; instead, these controls must be "hooked" together using VBScript. When an event is fired by the Chart control, VBScript must trap that event and send it to the applet. Likewise, a Java applet cannot directly access an ActiveX control's properties or methods without a little help from VBScript. For a Java class to access a control (using a COM interface), that control must be passed to the applet using VBScript as an object of type java.lang.Object. The applet can then typecast this Object parameter to the appropriate interface.
Accessing the Chart control from within a Java class is rather straightforward because the Chart control only supports properties and methods, not events. Therefore, you must simply create a Java applet that has a method that accepts an Object as a parameter. Inside this method, the Object parameter is typecast to an object of type Iiechart. The following method demonstrates what your applet's method will look like:
public void setCtrl(Object oc)
{
m_Chart = (Iiechart)oc;
}
When this method is created, a single VBScript function is declared that will pass the control to the Java applet. This function is contained in the HTML source file and looks like this:
<script language=VBScript> <!-- ' Send the controls to the applet Sub window_onLoad document.TheApplet.setCtrl TheChart end sub !--> </script>
The onLoad() VBScript method is called after the page has been loaded in Internet Explorer. The one line of code in this method calls the applet's setCtrl() method and passes it the ActiveX Chart control as a parameter.
All the pieces are now in place. The ActiveX control has been
downloaded and registered. Java class files have been generated
to provide access to the ActiveX object. The HTML file has been
created to contain the Java applet and ActiveX control. All that
is left is to build an applet to control the chart!
| NOTE |
Before you start this process, if you are re-creating the HTML files by hand, make sure you add the VBScript onLoad() method described previously to the HTML form. In addition, be sure to reset the Java applet's width and height parameters. (In Example1.html, they are both set to 0.) |
First, the ChartApplet applet performs two basic operations:
When the user changes either of these specifications, the chart is automatically updated. The three chart color schemes are presented as radio button selections (java.awt.Checkbox components), and the various chart types are displayed in a list box. An Update button is provided; when clicked, it updates the chart with the user's settings. Listing 20.4 shows the source code for the ChartApplet class.
Listing 20.4. The ChartApplet class.
//******************************************************************************
// ChartApplet.java: Applet
//
//******************************************************************************
import java.applet.*;
import java.awt.*;
import iechart.*;
//==============================================================================
// Main Class for applet ChartApplet
//
//==============================================================================
public class ChartApplet extends Applet
{
Iiechart m_Chart;
// The button used to update the chart
Button btnUpdateChart = new java.awt.Button("Update Chart");
//The list used to display the chart types
List lstChartTypes = new java.awt.List();
//The Checkbox Group used to select the color scheme
CheckboxGroup grpScheme = new java.awt.CheckboxGroup();
//The Panel used to contain the checkbox group
Panel m_Group = new Panel();
// ChartApplet Class Constructor
//--------------------------------------------------------------------------
public ChartApplet()
{
}
// APPLET INFO SUPPORT:
// The getAppletInfo() method returns a string describing the applet's
// author, copyright date, or miscellaneous information.
//--------------------------------------------------------------------------
public String getAppletInfo()
{
return "Name: ChartApplet\r\n" +
"Author: Bryan Morgan\r\n" +
"Created with Microsoft Visual J++ Version 1.0";
}
public void init()
{
setLayout(new BorderLayout());
add("North", m_Group);
m_Group.add(new Label("Color Scheme:"));
m_Group.add(new Checkbox("0", grpScheme, true));
m_Group.add(new Checkbox("1", grpScheme, false));
m_Group.add(new Checkbox("2", grpScheme, false));
//Add the list to the BorderLayout
add("Center", lstChartTypes);
//Add the button to the BorderLayout
add("South", btnUpdateChart);
//Now fill the list with Chart Types
lstChartTypes.addItem("Simple Pie");
lstChartTypes.addItem("Pie with wedge out");
lstChartTypes.addItem("Simple Point Chart");
lstChartTypes.addItem("Stacked Point Chart");
lstChartTypes.addItem("Full Point Chart");
lstChartTypes.addItem("Simple Line Chart");
lstChartTypes.addItem("Stacked Line Chart");
lstChartTypes.addItem("Full Line Chart");
lstChartTypes.addItem("Simple Area Chart");
lstChartTypes.addItem("Stacked Area Chart");
lstChartTypes.addItem("Full Area Chart");
lstChartTypes.addItem("Simple Column Chart");
lstChartTypes.addItem("Stacked Column Chart");
lstChartTypes.addItem("Full Column Chart");
lstChartTypes.addItem("Simple Bar Chart");
lstChartTypes.addItem("Stacked Bar Chart");
lstChartTypes.addItem("Full Bar Chart");
lstChartTypes.addItem("HLC Stock Chart");
lstChartTypes.addItem("HLC Stock Chart WSJ");
lstChartTypes.addItem("OHLC Stock Chart");
lstChartTypes.addItem("OHLC Stock Chart WSJ");
}
public void setCtrl(Object oc)
{
m_Chart = (Iiechart)oc;
}
public boolean action(Event evt, Object what)
{
if (evt.target == btnUpdateChart)
{
m_Chart.putChartType(lstChartTypes.getSelectedIndex());
Integer caption = new Integer((grpScheme.getCurrent()).getLabel());
m_Chart.putColorScheme(caption.intValue());
// Event handled
return true;
}
return false;
}
}
The majority of the ChartApplet class is a standard Java program. A Layout Manager is added to handle the layout of components on the applet. Again, the VBScript calls the setCtrl() method so that the applet can access the ActiveX object in the HTML page. The action() method is used to trap the button click, and this is where the Chart's methods are called (putChartType() and putColorScheme()). Using these two methods, the chart's type and color scheme can be set remotely in Java.
Figure 20.5 shows the Example2.html file loaded in Internet Explorer 3.0. Changing any of the options on the left side and then clicking the Update Chart button automatically updates the chart.
Figure 20.5 : A Java applet and an ActiveX control coexisting.
COM objects can be easily integrated into Java applets or applications, thanks to the Java Type Library Wizard included with Visual J++. This tool extracts the type library information stored in a COM object (such as an ActiveX control) and creates the corresponding Java class files for the COM interfaces, classes, and constants contained in the type library. When these class files have been created, they can be imported into a Java class. From that point, these classes appear to the Java programmer to be identical to standard Java classes. Of particular interest to many Java developers is the ability to integrate existing ActiveX/OLE controls and Java applets in Web pages. This integration is made possible with the Microsoft Virtual Machine and the Java Type Library Wizard.