Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

JVM Languages

Examining Visual J++


Dr. Dobb's Sourcebook September/October 1997: Examining Visual J++

Al is the author of Developing ActiveX Web Controls and Developing ActiveX Controls with Visual Basic 5 (both from the Coriolis Group). You can reach Al on the Web at http:// www.al-williams.com/awc.


As an old-time C/C++ programmer, Java's similarity to C++ is probably its chief disadvantage to me. When I use Visual Basic or Delphi, it is clear right away that I am not using C++. I type a few too many equal signs once or twice until I shift mental gears. Then I don't have any more problems. With Java, I never shift gears. It is much like C++, so I never get used to the differences (and there are differences).

Of course, if you have no predisposition to C++, Java is just another language to learn, with nice features such as automatic garbage collection and built-in support for multithreading. However, the overriding question is -- why another language?

The answer to this question is portability. Java is typically interpreted by the Java Virtual Machine (JVM). If you can write the relatively simple JVM on your machine, then you can run Java programs. Of course, other systems tried this before (remember UCSD Pascal?). The big difference here is that Sun (the developer of Java) had two realizations:

  • The Web needs a programming language that works on disparate platforms.
  • Programs that run on the Web should have security constraints to prevent them from harming the system or performing malicious activity over the network.

Since any machine that implements the JVM can run a Java program, that takes care of the first requirement. And because Java runs via an interpreter, you can enforce any security restrictions you like. For example, most web browsers don't allow Java programs to access local files. They also prohibit programs from opening a network connection unless that connection is back to the server that provided the program.

If you want to create programs that run on many different platforms, Java gives you the best chance of accomplishing that. If you want the programs to run on the Web, it is your only chance (for now, anyway). ActiveX works very well on the PC, but it lacks Java's broad platform support. Even on platforms that do support ActiveX, you usually need separate object files for each platform. Since Java is interpreted, a Java .class file will run on any machine with a JVM.

Many people think that Java is a major innovation in language design. In reality, however, it is just an object-oriented language that's similar to C++. The power associated with Java is really due to the class library. This is similar to C or C++. C isn't a very sophisticated language. Most of the interesting things you do in C, you do with the Standard Library.

Among the libraries Java includes is the Abstract Window Toolkit (AWT), which lets you create windows, menus, and other user-interface items. If you're used to Windows programming, you'll find the AWT somewhat anemic. For example, it has no concept of a resource in a Java program. Dialogs and menus require code to create and manage them. However, with its Visual J++ development environment, Microsoft has included a clever Wizard. The Wizard is a big help, but isn't perfect, since many Windows controls have no equivalent in Java.

Java also has some things -- layout managers, for instance -- not readily available in Windows. A layout manager controls the size and position of other windows. You might have a layout manager that resizes all the controls in a user interface when the main window resizes, for example.

Java programs come in two flavors -- applications and applets. An application is a stand-alone program. It has its own main window and behaves like any other program on the target system. An applet does not have its own main window. Instead, it relies on another program to contain it. Usually, this program is a web browser, but it can be any Java-aware program.

Using Visual J++

When you create a Java program using VJ++, you'll usually start with Microsoft's Wizard. It will give you the option of creating an applet or a program that could be either an applet or an application. If you select the dual option, the program detects if it is an application at run time. If it is an application, it creates a main window and uses it to host the core applet. If the program runs as an applet, it does not create a main window. You'll find out more about the Microsoft Wizard shortly.

As Figure 1 illustrates, the VJ++ environment is the familiar Developer's Studio tool that is also integral to Visual C++ and Visual InterDev. If you are familiar with these tools, that's a big plus. However, many of the tools you expect from Visual C++ don't exist for Java programs. For example, Class Wizard isn't part of VJ++. You'll have to handle most events manually.

If you use both VJ++ and C++, you might want to consider Microsoft's new Visual Studio 97. This is little more than Visual C++, Visual J++, Visual Basic, FoxPro, and Visual InterDev in one box. You also get a special version of the Microsoft Developer's Network (MSDN) CD. Even if you don't use all the tools, the price is low enough (around $1000) to make it worthwhile if you use even two of the packages.

Wizards

Like other Microsoft tools, VJ++ comes with several Wizards to help you work. There are two Wizards of interest in VJ++. The first one (the Java Applet Wizard) creates a new Java project. You can specify many details including:

  • The project name, directory, and main class name.
  • If the project should create an applet or a dual applet/application.
  • The initial size of the application window.
  • If the applet will utilize multithreading.
  • If the applet is multithreading, the Wizard can create sample animation code.
  • If you'd like to handle mouse events.
  • Any parameters the applet will use to accept data from the outside world.
  • A copyright string.

The Wizard will also generate helpful comments, and a sample HTML file that uses the applet, if you like. Once you are done with this Wizard, you can't run it again (except, of course, to create a new project). Be sure to make the right selections the first time because you don't get a second chance.

The other Wizard that Microsoft supplies is the Resource Wizard. The Resource Wizard exists because Java doesn't use resource templates the way Windows does. With ordinary Windows programming, you'll often design dialogs and menus visually during development and store them in resources. Then, at run time, your program can retrieve the template and create the object with almost no effort on your part.

Java doesn't use resources, so you have to create any dialogs and menus by using Java programming code. This is tedious at best. The Resource Wizard allows you to visually design resources using any standard tool (including the resource editor built into Developers Studio). The Wizard processes these resources into Java code that you can then use in your application or applet.

Although this beats creating everything from scratch, there are a few problems. First, the resource doesn't become part of your project. If you make changes to the resource later, you have to remember to rerun the Resource Wizard. Worse, if you change your Java code, there is no way to preserve those changes if you rerun the Wizard. Still, using the Wizard is better than nothing; you just need to have a little discipline.

So how is VJ++ visual? I suppose it depends on your definition of visual. Languages like Visual Basic, Delphi, and Optima++ are clearly very visual. Visual C++ is somewhat less visual. Sure, you use Class Wizard to wire up events. You can also draw dialogs and menus. However, there is very little visual integration except for Resource Wizard. VJ++ is even less visual than C++.

Developing the Calendar

To test drive VJ++, I developed a calendar applet that you could place on a web page (see Figure 2). This is a simple application that doesn't require any dialogs, multithreading, or much of anything special. All you need is a simple applet, some code to draw the calendar, and enough smarts to figure out which day of the week corresponds to a given date.

To start this project, I did use the Java Applet Wizard. Since the calendar is simple, I turned off multithreading. I didn't change anything else. For parameters, I added the ones in Table 1. The Wizard does a bit of work for you when you name parameters here, so it is better to specify too many parameters than not enough. You can add them later, of course, but it is easier to remove them later if you create too many.

The Wizard makes a perfectly adequate applet for you. The only code I added was in the paint routine (see Listing One). This code calculates the dimensions for the calendar and draws it. It also computes the date/day relationship. Instead of writing a standard Zeller's congruence function to handle things, I relied on a standard Java class, called Date. The getDay function for this class converts a date to a day of the week. My code uses this to correctly assign the date's position on the calendar.

Using the Calendar

You can use the <APPLET> tag to include the calendar applet in a web page (see Listing Two). The code in the listing is essentially the sample file generated by the Wizard. If you only care about compatibility with Internet Explorer, you could also use the <OBJECT> tag to include the applet.

You'll notice a series of <PARAM> tags in Listing Two. These tags set the initial values for the parameters in the applet. The Wizard writes code so that variable m_month, for example, gets the value for the month parameter. If the HTML doesn't supply a value, the Wizard arranges for the default values you specified at design time.

Notice the code that reads the parameters is in the init routine. That means that once you read the parameters, their values are fixed. This is unlike ActiveX controls, where you can change properties at any time using script.

Conclusion

Although Visual J++ is billed as a visual-development tool, you might wonder what Microsoft was thinking when it decided to call it that. Don't get me wrong -- there's nothing inherently wrong with VJ++. It just isn't very visual. Still, it does a good job as a traditional Java environment, and the Wizards and ActiveX additions are a bonus. All in all, it is a capable (and speedy) Java environment.

DDJ

Listing One

//******************// calendar.java:       Applet
//******************
import java.applet.*;
import java.awt.*;
import java.util.Date;


</p>
//=================================
// Main Class for applet calendar
//=================================
public class calendar extends Applet
{
        // PARAMETER SUPPORT: Parameters allow an HTML author to pass
        // information to the applet; HTML author specifies them using the
        // <PARAM> tag within the <APPLET> tag. The following variables are 
        // used to store the values of the parameters.
    //--------------------------------


</p>
    // Members for applet parameters
    // <type>       <MemberVar>    = <Default Value>
    //--------------------------------
        private int m_month = 0;
        private int m_year = 1980;
        private int m_bgcolor = 16777215;  // white
        private int m_fgcolor = 0;


</p>
    // Parameter names.  To change a name of a parameter, you need only make
    // a single change.  Simply modify value of the parameter string below.
    //--------------------------------
        private final String PARAM_month = "month";
        private final String PARAM_year = "year";
        private final String PARAM_bgcolor = "bgcolor";
        private final String PARAM_fgcolor = "fgcolor";


</p>
        // calendar Class Constructor
        //--------------------------------
        public calendar()
        {
                // TODO: Add constructor code here
        }
        // APPLET INFO SUPPORT: The getAppletInfo() method returns a string
        // describing the applet's author, copyright date,
        // or miscellaneous information.
    //--------------------------------
        public String getAppletInfo()
        {
         return "Name: calendar\r\n" +
           "Author: Al Williams [email protected]\r\n" +
           "Created with Microsoft Visual J++ Version 1.1";
        }
        // PARAMETER SUPPORT. The getParameterInfo() method returns an array 
        // of strings describing the parameters understood by this applet.
    // calendar Parameter Information:
    //  { "Name", "Type", "Description" },
    //--------------------------------
        public String[][] getParameterInfo()
        {
                String[][] info =
                {
                 { PARAM_month, "int", "Month" },
                 { PARAM_year, "int", "Year" },
                 { PARAM_bgcolor, "int",
                   "Background color" },
                 { PARAM_fgcolor, "int",
                   "Parameter description" },
                };
                return info;
        }
        // init() method is called by AWT when an applet is first loaded or
        // reloaded. Override this method to perform whatever initialization 
        // your applet needs, such as initializing data structures, loading 
        // images or fonts, creating frame windows, setting layout manager,
        // or adding UI components.
    //--------------------------------
        public void init()
        {
          // PARAMETER SUPPORT. The following code retrieves the
          // value of each parameter specified with the <PARAM> tag
          // and stores it in a member variable.
          //----------------------------
                String param;
                // month: Month
                //----------------------------
                param = getParameter(PARAM_month);
                if (param != null)
                    m_month = Integer.parseInt(param);
                // year: Year
                //----------------------------
                param = getParameter(PARAM_year);
                if (param != null)
                    m_year = Integer.parseInt(param);
                // bgcolor: Background color
                //----------------------------
                param = getParameter(PARAM_bgcolor);
                if (param != null)
                    m_bgcolor = Integer.parseInt(param);


</p>
                // fgcolor: Parameter description
                //----------------------------
                param = getParameter(PARAM_fgcolor);
                if (param != null)
                    m_fgcolor = Integer.parseInt(param);
        }
        // Place additional applet clean up code here. destroy() is called when
        // when you applet is terminating and being unloaded.
        //-------------------------------
        public void destroy()
        {
                // TODO: Place applet cleanup code here
        }
        // calendar Paint Handler
        //--------------------------------
        public void paint(Graphics g)
        {
                FontMetrics fm;
                int margin;
                int i,j;
                // height and width of each cell
                int cellheight,cellwidth;
                String months[]= // names of months
                {
                 "January","February","March", "April",
                 "May", "June", "July", "August",
                 "September", "October", "November",
                 "December"
                 };
                String days[]= // names of days
                {
                        "Sun","Mon","Tue",
                        "Wed","Thu","Fri","Sat"
                };
                int len[]= { // 30 days hath September...
                 31, 28, 31, 30, 31,
                 30, 31, 31, 30, 31, 30, 31 };
                int row=0;  // current drawing row
                String title;  // title at top
                Color fg,bg;  // colors
                Rectangle r;
                r=bounds();
                fm=g.getFontMetrics();
                margin=3*fm.getHeight(); // top portion
                cellwidth=r.width/7;
                cellheight=(r.height-margin)/6;
                fg=new Color(m_fgcolor);
                bg=new Color(m_bgcolor);
                g.setColor(bg);
                // draw header
                g.fillRect(0,0,7*cellwidth,margin);
                Integer yr;
                yr=new Integer(m_year);
                title=months[m_month]+" "+yr.toString();
                g.setColor(fg);
                g.drawString(title,10,fm.getHeight());
                // draw cells
                for (j=0;j<7;j++)
                {
                    g.drawString(days[j],
                      j*cellwidth+cellwidth/2-10,
                      fm.getHeight()*2); // day names
                    for (i=0;i<6;i++)
                    {
                        g.setColor(bg); // draw inside
                        g.fillRect(j*cellwidth,margin+
                           i*cellheight,cellwidth,
                           cellheight);
                        g.setColor(fg); // draw outside
                        g.drawRect(j*cellwidth,
                           margin+i*cellheight,
                           cellwidth,cellheight);
                    }
                }
                j=len[m_month];
                // add one for leap years
                if (m_month==1 && m_year%4 == 0) j++;
                // draw dates
                for (i=0;i<j;i++)
                {
                   Date date = new Date(m_year-1900,
                      m_month,i+1);
                   Integer day= new Integer(date.getDay());
                   Integer I= new Integer(i+1);
                   g.drawString(I.toString(),
                     day.intValue()*cellwidth+cellwidth/2,
                     margin+cellheight*row+cellheight/2);
                   if (day.intValue()==6) row++;
                }
        }
        // The start() method is called when the page containing the applet
        // first appears on the screen. AppletWizard's initial implementation
        // of this method starts execution of the applet's thread.
        //--------------------------------
        public void start()
        {
                // TODO: Place additional applet start code here
        }
        // The stop() method is called when the page containing the applet is
        // no longer on the screen. AppletWizard's initial implementation of
        // this method stops execution of the applet's thread.
        //--------------------------------
        public void stop()
        {
        }
        // TODO: Place additional applet code here
}

Back to Article

Listing Two

<html><head>
<title>calendar</title>
</head>
<body>
<hr>
<applet
    code=calendar.class
    name=calendar
    ID=cal
    width=320
    height=240 >
    <param name=month value="1">
    <param name=year value="1980">
    <param name=events value="">
    <param name=bgcolor value=16777215>
    <param name=fgcolor value=0>
</applet>
<hr>
</body>
</html>

Back to Article


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.