Chapter 32

Writing Java Applications


CONTENTS

The bulk of this book is dedicated to using Java to create applets for the Internet. However, Java is a full-fledged computer language that enables you to write complete, stand-alone applications. Although most Java users are interested in creating only applets (there are other, more powerful languages for creating applications), no introductory Java book would be complete without at least dabbling a little with Java applications. In this chapter, then, you learn the basics of creating standalone applications with Java.

About Java Applications

If you've run the HotJava browser, you've already had experience with Java applications. The HotJava browser was programmed entirely in Java and, although the browser is way out of date at the time of this writing, it demonstrates how much you can do with Java, even when dealing with sophisticated telecommunications applications.

Much of what you've learned about applets can be applied toward writing applications. After all, the language doesn't change, just the way you use it does. Of course, conversely, some of what you learned about applets doesn't apply to the writing of applications. For example, because Java applications aren't run "on the Web," they don't have to deal with all the security issues that come up when running applets. A Java application can access any files it needs to access, for example.

If you've ever programmed in C or C++, you'll discover that writing applications in Java is similar. If you haven't programmed in those languages, rest assured that, by this point in the book, you already have 95% of the knowledge you need in order to write standalone Java applications.

The Simplest Java Application

You can create a runnable Java application in only a few lines of code. In fact, an application requires only one method called main().C and C++ programmers will recognize main() as being the place where applications begin their execution. The same is true for Java applications. Listing 32.1 shows the simplest Java application.


Listing 32.1  SimpleApp.java: The Simplest Java Application.

class SimpleApp

{

    public static void main(String args[])

    {

        System.out.println("My first Java app!");

    }

}


Declare the SimpleApp class.
Declare the app's main() method.
Print a line of text on the screen.

If you look a the first line of Listing 32.1, you'll see that even a Java standalone application starts off as a class. In this case, the class has no superclass-that is, the SimpleApp class is not derived from another class (although it could have been). The first line of the body of the class begins the main() method, which is where all Java applications begin execution. This method's single parameter is a String array containing the command line sent to the application when it was started.

Finally, the single line in main() prints a message on your computer's screen. Because this is not a Windows application, the class contains no paint() method. Instead, you display text by using the println() method of the System.out package.

To run the Java application, you must first compile it and then run the byte-code file using Java's interpreter. You compile the program exactly as you would an applet, using javac. The following example describes the entire process.

Example: Building an Application

Building a Java application isn't any more difficult that building an applet, although the steps are slightly different. Follow the steps below to compile and run the SimpleApp application.

  1. Type Listing 32.1, and save it in your C:\CLASSES folder, under the file name SimpleApp.java. (If you don't want to type, you can copy the listing from the CHAP32 folder of this book's CD-ROM.)
  2. Select the MS-DOS Prompt command from the Start menu's Program menu. The DOS window appears on your screen (Figure 32.1).
    Figure 32.1 : You must run SimpleApp from a DOS window.

  3. Type cd c:\classes to switch to your CLASSES folder.
  4. Type javac SimpleApp.java to compile the application's source code. After compilation, you'll have the SimpleApp.class file in your CLASSES folder.
  5. Type java SimpleApp to run the application. The message "My first Java app!" appears on the screen (Figure 32.2).

Figure 32.2 : The SimpleApp applications prints a single line of text on the screen.

Example: Getting an Application's Arguments

You know that when you start a DOS program, you can sometimes append parameters to the command line in order to give the program information it needs to start. You can do the same thing with Java applications. For example, here's how you would start SimpleApp with two parameters:


java SimpleApp param1 param2

Of course, because SimpleApp ignores its parameters, the parameters in the command line don't mean anything. Suppose, however, you wanted to print a user-specified message a user-specified number of times. You might, then, write the Java application shown in Listing 32.2. When you run this application, add two parameters to the command line: the message to print (in quotes if the message is more than one word) and the number of times to print the message. You'll get output like that shown in Figure 32.3.

Figure 32.3 : The ArgApp application prints a message the number of times given in the command-line arguments.


Listing 32.2  ArgApp.java: Using Command-Line Arguments.

class ArgApp

{

    String message;

    int count;



    void GetArgs(String args[])

    {

        String s = args[1];

        count = Integer.parseInt(s);

        message = args[0];

    }



    void PrintMessage()

    {

        for (int x=0; x<count; ++x)

            System.out.println(message);

    }



    public static void main(String args[])

    {

        ArgApp app = new ArgApp();

        app.GetArgs(args);

        app.PrintMessage();

    }

}


Declare the ArgApp class.
Declare the class's data fields.
Define the GetArgs() method.
Extract the number of times to print the message.
Convert the count to an integer.
Extract the message to print.
Define the PrintMessage() method.
Loop for the requested number of times.
Display the message each time through the loop.
Define the app's main() method.
Create an ArgApp() object.
Call the method to extract the arguments.
Call the method to print the message.

The ArgApp application not only shows you how to use command-line parameters, but also how to write a Java application that actually does something. The important thing to notice here is that you must first create an object of the ArgApp class before you can call its methods and access its data fields. This is because a class is just a template for an object; it doesn't actually become an object until you create an instance of the class with the new keyword.

One way to avoid having to create an object of the class is to declare all the class's data fields and methods as static. Such methods and data fields are accessible in memory, which is why the SimpleApp application in Listing 31.1 runs. Its main() method is declared as static. Of course, it's a heck of a lot easier to just go ahead and create an object of the class than it is to go through the source code and add static to everything.

Windowed Applications

You're probably thinking that it's pretty much a waste of time to write Java applications if you have to run them under the DOS or UNIX text-based operating system. All the action these days is in windowed applications. Yes, you can write windowed applications with Java, as the HotJava browser proves. But, if you've written conventional windowed applications, you're probably a little nervous about writing similar Java applications. After all, writing such applications with languages like C and C++ can be a nightmare.

The truth is, however, you already know almost everything you need to know to write your own standalone applications for GUI operating systems. You can take most any applet and convert it to a standalone application just by adding the main() method to the class. In main(), you have to perform some of the tasks that Java handles for you when running an applet. These tasks include creating, sizing, and displaying the application's window. The following example gives you the details.

Example: Changing an Applet to an Application

As I said in the previous paragraph, you can convert almost any applet to an application simply by adding a main() method that performs a few housekeeping tasks. Listing 32.3 is an applet from a previous chapter's exercises. The previous version drew a face image in the applet's display. The new version displays the face in its own standalone, frame window. When you run the application, you see the window shown in Figure 32.4.

Figure 32.4 : The FaceApp application draws a face in a frame window.


Listing 32.3  FaceApp.java: Converting an Applet to an Application.

import java.awt.*;

import java.applet.*;



public class FaceApp extends Applet

{

    public void init()

    {

        Button button = new Button("Close");

        add(button);

    }



    public void paint(Graphics g)

    {

        // Head.

        g.drawOval(40, 40, 120, 150);





        // Eyes.

        g.drawOval(57, 75, 30, 20);

        g.drawOval(110, 75, 30, 20);



        // Pupils.

        g.fillOval(68, 81, 10, 10);

        g.fillOval(121, 81, 10, 10);



        // Nose.

        g.drawOval(85, 100, 30, 30);



        // Mouth.

        g.fillArc(60, 130, 80, 40, 180, 180);



        // Ears.

        g.drawOval(25, 92, 15, 30);

        g.drawOval(160, 92, 15, 30);

    }



    public boolean action(Event evt, Object arg)

    {

        if (arg == "Close")

            System.exit(0);

 

        return true;

    }



    public static void main(String args[])

    {

        FaceApp app = new FaceApp();

        Frame frame = new Frame("Face Window");



        app.init();

        app.start();



        frame.add("Center", app);

        frame.resize(210, 300);

        frame.show();

    }

}


Tell Java that the class uses the awt package.
Tell Java that the class uses the applet package.
Declare the FaceApp class.
Override the init() method.
Create a button object and add it to the window.
Override the paint() method.
Draw the face image using ovals and arcs.
Override the action() method.
If the user clicks the close button...
Shut down the application.
Tell Java the message was handled.
Define the main() method.
Create the FaceApp object and the frame window.
Call the init() and start() methods.
Add the "applet" to the window.
Size and show the window.

Understanding the FaceApp Application

If you examine Listing 32.3, you'll see that most of the FaceApp application is written exactly like any other applet you've written throughout this book. The big difference is the addition of the main() method, where this program's execution starts. Because you're no longer running the program as an applet, you have to perform some of the start-up tasks that Java automatically performs for applets. The first step is to create an object of the class and a frame window to hold the object, like this:


FaceApp app = new FaceApp();

Frame frame = new Frame("Face Window");

Next, you have to call the methods that get the object going. These methods are init() and start(), which are usually called by Java:


app.init();

app.start();

Note that, although the FaceApp class doesn't show a start() method, it does inherit it from the Applet class. It's true that even the inherited start() method doesn't do anything, but you might as well be consistent and call it anyway. That way, you won't forget that some applets do override the start() method, without which they won't run properly.

Now, you can add the FaceApp object to the frame window, like this:


frame.add("Center", app);

Finally, you must be sure to resize and show the window, like this:


frame.resize(210, 300);

frame.show();

If you fail to resize the application's window, all you'll see is the title bar, forcing the user to resize the window by hand. More importantly, if you fail to call show(), the application's window won't even appear on the screen. That's sure to leave your application's user feeling abused.

Summary

Although Java is used almost exclusively for creating applets, it is possible to use Java to create standalone applications. These applications can be DOS-based (or UNIX, etc.) or be written for a windowed operating system such as Windows 95. The easiest way to create a windowed application is to write the program as if it were an applet and then add a main() method that creates the application object and the frame window that'll contain that object.

Review Questions

  1. What method do you find in an application that you don't find in an applet?
  2. How do you run a Java standalone application?
  3. What is the single parameter received by the main() method?
  4. How can you extract parameters from an application's command line?
  5. What do you have to add to an applet to convert it to an application?
  6. Why do you have to instantiate an object from a class before you can call its methods?
  7. What do you have to do to create and display an application's window?

Review Exercises

  1. Write a stand-alone application that accepts two numbers as parameters and prints out the numbers' sum.
  2. Choose any applet from this book and convert it to a stand-alone application.
  3. Convert the ThreadApplet5 applet from Chapter 31's exercises into a stand-alone application. (You can find the solution for this exercise in the CHAP32 folder of this book's CD-ROM.)