| |||||||
![]() |
Writing a Simple VB Application
Since the talk about Java is everywhere, you might be asking yourself whether it is time to abandon or subdue your interest in VB and move all or partway toward Java. The answer to this question, like all simplistic questions is, of course, "it depends." Before we dig into this at all, let's be very clear that Java and JavaScript are totally different languages whose similarities stop at the four letters of their names. Java is an object-oriented, compiled development language, and JavaScript is a series of interpreted source statements you can embed in your web page to make simple controls interact on that page. This article is about the object oriented Java language. See the sidebar on JavaScript.
If your principal focus is in developing stand alone applications for Windows 95 and Windows 3.x, you will probably be able to continue to do this for a long time to come. Visual Basic is a mature platform with easy to use development tools and hundreds of useful addon controls from a plethora of vendors. But, on the other hand, if you believe that Java is only for animating and adding simple functionality to web pages, you are missing many of its major advantages.
Java is still more or less the new kid on the block: the tools are all version 1.0 quality or less and the performance of some parts of Java as well as its tools still needs work. And, of course, there aren't that many 3rd party controls available yet. On the other hand, since Java tools are being developed by a wide spectrum of companies, you can expect that competition will drive very rapid development cycles of improvement in the next few months. By contrast, we VB users have had to wait for a single company to release each new version of Visual Basic.
By contrast with VB, Java is a cross-platform language which runs identically on Windows-95, OS/2, most flavors of Unix and on the Macintosh. As mainframes gain popularity as servers for web documents, we find Java implementations there as well.
After you write a Java program, its source code is compiled into a binary representation called byte codes and a byte-code interpreter called the Java Virtual Machine (JVM) is provided for each supported platform. Thus, the same compiled binary can be shipped electronically to almost anyone and it will run and produce predictable and pretty much identical results regardless of the operating system or hardware configuration.
This concept of interpreting byte codes should sound familiar: it's the way Visual Basic works as well. Thus, you shouldn't be surprised that the graphical performance of VB programs and Java programs are roughly equivalent: both have a thin layer of interpreter calling native window-platform GUI functions directly. They both do a pretty good job, too. A Java program, in fact, has a much smaller startup latency than does an equivalent VB program.
However, the advantages of programming in Java are real and worth considering. In Java, you can write two kinds of programs, termed applets and applications. Applets are programs designed to be embedded in Web pages. They can communicate with files on the web server, but because of Java's stringent security model, cannot access any files on your hard disk or any other part of your network.
Applications are stand alone programs that have complete freedom to access your disk drive and your network. They have nothing to do with your web browser, and can be as complex as any VB program you might write. While the preliminary emphasis in Java articles, books and code so far has been in the writing of applets, the idea of stand alone programs that run identically across various kinds of hardware and operating systems is also clearly very appealing.
Java has a number of very powerful inducements for you to consider it. Briefly, these include
Well, you need to learn the syntax of Java, which is more C and C++-like than it is Visual Basic like. Then you need to absorb the concept of object-oriented programming into your psyche. While these two statements sound very daunting, you'll actually find that you'll be able to write Java code in just a few minutes.
Using objects in programming is more natural than your old ways, because we tend to think of everyday life in terms of objects all the time: send the customer the quote, get the price from the vendor, get the documents from the server, send a letter to your child, etc. Every one of these operations involves getting or sending information between logical entities: customers, vendors, servers, children, etc.
Object oriented programming is just constructing your program so that it mimics these real world situations more closely, where an object is like a VB record or Type, which contains both data and a series of subroutines and functions that operate on that data, called methods.
Suppose that we wanted to write a simple VB program to convert data between yards and meters. We could do this by building a simple user interface with an entry field, an output field, two option buttons and a Compute button.
Option Explicit '------------------------------------ Private Sub Form_Load() result.Caption = "" 'initialize controls entryvalue.Text = "" Meters.Value = True 'default to meters Compute.Default = True 'set default button End Sub '------------------------------------ Private Sub Compute_Click() 'Compute conversion to meters or to yards Dim dist As Single, newdist As Single dist = Val(entryvalue.Text) If Meters.Value Then newdist = dist * 36 / 39.37 'convert to meters Else newdist = dist * 39.37 / 36 'convert to yards End If result.Caption = Str$(newdist) 'display result End Sub '------------------------------------ Private Sub Quit_Click() End 'exit if quit clicked End Sub |
The display of this program is shown above in Figure 1. You type
a value into the text box and select either "to Meters"
or "to Yards" and click on Compute. The entire program's
logic is really in the Compute_click routine above, where it simple
decides which factor to multiply the distance by.
We can write the same program in Java almost as easily. The critical part of the program will be much the same as in Visual Basic:
private void clickedCompute() { Ruler ruler = new Ruler(); //create ruler object String dist, newdist; dist = Entryval.getText(); //get entry value if (Meters.getState()) //if "to Meters" selected { ruler.setYards(dist); //set into ruler object newdist = ruler.getMeters(); //convert to meters } else //otherwise { ruler.setMeters(dist); //set into ruler object newdist = ruler.getYards(); //convert to yards } Results.setText(newdist); //display result } |
From this, we can see that the main difference between Java and Visual Basic is that subroutines and blocks within subroutines are set off with braces rather then Sub and End Sub or If and EndIf, and that comments begin with a double slash instead of an apostrophe.
Now let's consider what we mean by objects. Much like VB, the text entry field is an object and it has methods getText() and setText(). The Option button Meters has the method getState() just like the VB option button has the property value.
In addition, we have defined a Ruler object whose methods are setYards(), setMeters(), getYards(), and getMeters(). The nice thing about Java is that we don't have to know how this object works or how it represents data inside. We don't have to know whether it remembers values in meters or in yards or even in furlongs. Obviously it must convert from strings to floating point numbers and back again, but we don't need to know how or where this is done. This is the tremendous advantage of object-oriented programming: each object contains knowledge of how to handle its data.
Now suppose we need to be able to convert our distances to furlongs. We could rewrite the Ruler class to have a getFurlongs method, but we might not want or be able to modify the original class. We might only have the binary code and not be able to modify the original. Instead, Java allows us to derive a new class which automatically has all the methods of the original and in addition has whatever new methods we need. We need two new methods setFurlongs and getFurlongs. All the rest are available without our doing anything. Of course we do need to know the conversion factor between meters and furlongs. (I looked it up).
The complete class derived from ruler is just:
class fRuler extends Ruler { final double meters_per_furlong = .00497; //----------------------------------------- public void setFurlongs(String input) { //convert string to number double dist = new Double(input).doubleValue(); //convert the number dist = dist * meters_per_furlong; //store as a string setMeters(new Double(dist).toString()); } //----------------------------------------- public String getFurlongs() { double dist = new Double(getMeters()).doubleValue(); dist = dist / meters_per_furlong; return new Double(dist).toString(); } } |
The critical part of this new class is that it extends Ruler. It then automatically contains all of the methods of the Ruler class as well as any new ones we might add. You could also override some of the methods in Ruler with new ones if you want to add more functionality without ever having to change the Ruler class code at all.
Java is designed so that you can write straight Java code to produce the graphical user interface for your programs. You can either write the code directly yourself or use any of a growing number of GUI builder programs to generate the code for you. These include Symantec Café, Roguewave JFactory, Sun's Java Workshop, and Microsoft's J++. Each takes a slightly different approach, but uses a graphical designer much like VB's to put controls on the page and generate the code to arrange these controls and receive their Click events. These are summarized at the end of the article.
It is in this area that Java has the greatest catching up to do: the number of provided controls is very limited, but third parties are already beginning to fill in the gaps. In addition, it is perfectly possible to write your own controls such as picture buttons or tree lists.
Because of Java's ability to derive new classes from existing ones, you can change the behavior of Java controls much more easily than you can VB controls. For example, if you want to take special action when the user right-clicks on a button, you can derive your own rButton class that has this additional behavior, but still has all the properties of an ordinary button.
The other place where Java is much stronger than VB is in its connection to networks. TCP/IP socket classes and Web URL descriptors are built-in classes. Any Java application can open up a socket connection between two machines. This is particularly advantageous when one of the machines is running Unix, where writing servers is non-trivial. You can write a server in Java to run on a Unix machine and another Java application on your client PC to talk to that server. Since you are reading and writing data through sockets, you can probably even use much of the same code in both programs.
Java applets cannot open sockets indiscriminantly, but they can connect to sockets on the web server itself. So it is perfectly possible to have a Java applet running on a web page you designed communicating through sockets back to a server connected to a database. This cross-platform client server approach is one of Java's great strengths and not easily implemented in VB with so little effort.
Finally, Java is a multithreaded languages. Threads are separate parallel tasks that can run concurrently in a program. Since threads are built into the language, you can write them with impunity whenever you have a time consuming tasks such as file handling or communication that can go on in the background. By using threads, you can make sure that your program's interface stays lively and active. You can also run several parallel threads at once to handle several simultaneous users or to simulate multiple processes.
Java is a powerful object-oriented, compiled, cross-platform language with a lot of promise for bringing order to the complexity of writing for Windows, Macintoshes and Unix. But it is still a very young language, with serious bugs in its Windows 95 graphics implementation and some glaring omissions:
Microsoft's Internet Explorer supports Java. It also will soon support Microsoft's ActiveX controls, which are just OLE controls renamed. Microsoft has modified their Visual C++ tool to produce an integrated development environment (see sidebar) that allows you to write and debug code in what promises to be a smooth fashion. As this is being written, the product, named J++, is still too rough for general use.
You can count on Microsoft being an active player in this field, including Java in their next operating system releases as IBM has already announced it is doing. At the moment it appears that Microsoft's strategy is Windows-centric rather than cross-platform, but never count this company out: they are a powerful force and major competitor to Sun's strategy.
Java is a powerful, new object-oriented programming tool that has the support of much of the computer industry. It is perfectly possible to write nearly any kind of program in Java, and with some work write quite a professional looking user interface. If your work requires developing cross-platform tools or client-server applications or intelligent web pages, you should definitely considering user Java. If your work is exclusively for single-user Windows 95 applications, Java may or may not provide you with any significant advantages, depending on your needs for network access, multithreading and object oriented programming style.
You can find the latest information from Sun on Java developments and plans at the Sun web site. You can download versions of the Java Development Kit for most platforms in their Developer's Corner.
In addition, there are a number of discussion sites where Java tools and applications are posted. The most common of these are:
For product information on various development tools, check out
JavaScript is a procedural language developed by Netscape to enhance web page interactivity before Java became popular. It was originally named LiveScript but was renamed to make it seem as if it was more closely aligned with Java than it actually is. JavaScript is interpreted rather than being compiled and the code is not checked for errors until the interpreter begins running.
JavaScript actually is designed primarily to add to interactivity to forms processing on web pages. You put up fields and buttons within an HTML Form as usual, but add additional arguments indicating what functions are to be called when the controls are clicked. This provides a way for you to validate data before sending it off to a CGI server where real processing can take place.
JavaScript has no ability to access the network, your local drive or PC hardware, or create objects in the Java sense. It does provide you with a way to create a limited sort of objects, but they cannot be extended or subclassed and their methods are external functions, not ones embedded in the objects. Further, JavaScript objects have no concept of public methods and private data.
You can learn about the details of JavaScript at
Netscape
and Stefan Koch's description
Let's consider how we would write the distance conversion program in JavaScript. In the following HTML code, we write a short JavaScript function in the header section which converts between yards and meters. We will then call that from the form that follow s. | <html> <head> <title>JavaScript Demo</title> <script language="JavaScript"> //This function is called when the //Compute button is clicked //--------------------------------------- function compute(form) { //read in entered value dist = parseFloat(form.Entryval.value) if (form.Convert[1].status) //check radio buttons newdist = dist * 36/39.37 else newdist = dist * 39.37/36 form.Results.value = newdist //display result } </script> </head> |
Then the main text of the web page is just an ordinary HTML form which puts up a text entry field, two radio buttons, a result text field and a "Compute" button. Note, however, that the Compute button has an additional property onClick="compute(this.form)" This tells the web browser to call the JavaScript function compute when the button is clicked on. You can see the results of this web page script below. |
<body> <FORM> <hr> <h3>Convert between yards and meters</h2> Enter distance below:<br> <INPUT TYPE="text" SIZE=20 NAME="Entryval"><br> <INPUT TYPE="radio" NAME="Convert" VALUE="Meters" CHECKED>to Meters<br> <INPUT TYPE="radio" NAME="Convert" VALUE="Yards">to Yards<br> <INPUT TYPE="text" SIZE=20 VALUE="" NAME="Results"><br> <INPUT TYPE="button" VALUE="Compute" onClick="compute(this.form)"><br> <hr> </FORM> </body> </html> |
|
James W. Cooper is a Research Staff Member at IBM's Thomas J. Watson Research Center and the author of 10 books in the field. He is author of Object Oriented Programming in Visual Basic 4.0 for Pinnacle. His most recent book is The Visual Basic Programmer's Guide to Java published by Ventana books.
Visual Basic is a trademark of Microsoft Corporation
Java Education | Java Home |
![]() ![]() ![]() ![]() ![]() |