Chapter 2. The Java Programming Environment

In this chapter, you will learn how to install the Java Development Kit (JDK) and how to compile and run various types of programs: console programs, graphical applications, and applets. You run the JDK tools by typing commands in a shell window. However, many programmers prefer the comfort of an integrated development environment. We show you how to use a freely available development environment to compile and run Java programs. Although easier to learn, integrated development environments can be resource-hungry and tedious to use for small programs. As a middle ground, we show you how to use a text editor that can call the Java compiler and run Java programs. Once you have mastered the techniques in this chapter and picked your development tools, you are ready to move on to Chapter 3, where you will begin exploring the Java programming language.

Installing the Java Development Kit

The most complete and up-to-date versions of the Java 2 Standard Edition (J2SE) are available from Sun Microsystems for Solaris, Linux, and Windows. Versions in various states of development exist for the Macintosh and many other platforms, but those versions are licensed and distributed by the vendors of those platforms.

Downloading the JDK

To download the Java Development Kit, you will need to navigate the Sun web site and decipher an amazing amount of jargon before you can get the software that you need.

You already saw the abbreviation JDK for Java Development Kit. Somewhat confusingly, versions 1.2 through 1.4 of the kit were known as the Java SDK (Software Development Kit). You will still find occasional references to the old term.

Next, you’ll see the term “J2SE” everywhere. That is the “Java 2 Standard Edition,” in contrast to J2EE (Java 2 Enterprise Edition) and J2ME (Java 2 Micro Edition).

The term “Java 2” was coined in 1998 when the marketing folks at Sun felt that a fractional version number increment did not properly communicate the momentous advances of JDK 1.2. However, because they had that insight only after the release, they decided to keep the version number 1.2 for the development kit. Subsequent releases were numbered 1.3, 1.4, and 5.0. The platform, however, was renamed from “Java” to “Java 2.” Thus, we have Java 2 Standard Edition Development Kit version 5.0, or J2SE 5.0.

For engineers, all of this might be a bit confusing, but that’s why we never made it into marketing.

If you use Solaris, Linux, or Windows, point your browser to http://java.sun.com/j2se to download the JDK. Look for version 5.0 or later, and pick your platform.

Sometimes, Sun makes available bundles that contain both the Java Development Kit and an integrated development environment. That integrated environment has, at different times of its life, been named Forte, Sun ONE Studio, Sun Java Studio, and Netbeans. We do not know what the eager beavers in marketing will call it when you approach the Sun web site. We suggest that you install only the Java Development Kit at this time. If you later decide to use Sun’s integrated development environment, simply download it from http://netbeans.org.

After downloading the JDK, follow the platform-dependent installation directions. At the time of this writing, they were available at http://java.sun.com/j2se/5.0/install.html.

Only the installation and compilation instructions for Java are system dependent. Once you get Java up and running, everything else in this book should apply to you. System independence is a major benefit of Java.

Note

Note

The setup procedure offers a default for the installation directory that contains the JDK version number, such as jdk5.0. This sounds like a bother, but we have come to appreciate the version number—it makes it easier to install a new JDK release for testing.

Under WIndows, we strongly recommend that you do not accept a default location with spaces in the path name, such as c:Program Filesjdk5.0. Just take out the Program Files part of the path name.

In this book, we refer to the installation directory as jdk. For example, when we refer to the jdk/bin directory, we mean the directory with a name such as /usr/local/jdk5.0/bin or c:jdk5.0in.

Setting the Execution Path

After you are done installing the JDK, you need to carry out one additional step: add the jdk/bin directory to the execution path, the list of directories that the operating system traverses to locate executable files. Directions for this step also vary among operating systems.

  • In UNIX (including Solaris and Linux), the procedure for editing the execution path depends on the shell that you are using. If you use the C shell (which is the Solaris default), then add a line such as the following to the end of your ~/.cshrc file:

    set path=(/usr/local/jdk/bin $path)

    If you use the Bourne Again shell (which is the Linux default), then add a line such as the following to the end of your ~/.bashrc or ~/.bash_profile file:

    export PATH=/usr/local/jdk/bin:$PATH

    For other UNIX shells, you’ll need to find out how to carry out the analogous procedure.

  • Under Windows 95/98/Me, place a line such as the following at the end of your c:autoexec.bat file:

    SET PATH=c:jdkbin;%PATH%

    Note that there are no spaces around the =. You must reboot your computer for this setting to take effect.

  • Under Windows NT/2000/XP, start the control panel, select System, then Environment. Scroll through the User Variables window until you find a variable named PATH. (If you want to make the Java tools available for all users on your machine, use the System Variables window instead.) Add the jdkin directory to the beginning of the path, using a semicolon to separate the new entry, like this:

    c:jdkin;other stuff

    Save your settings. Any new console windows that you start have the correct path.

Here is how you test whether you did it right:

Start a shell window. How you do this depends on your operating system. Type the line

java -version

and press the ENTER key. You should get a display such as this one:

java version "5.0"
Java(TM) 2 Runtime Environment, Standard Edition
Java HotSpot(TM) Client VM

If instead you get a message such as “java: command not found”, “Bad command or file name”, or “The name specified is not recognized as an internal or external command, operable program or batch file”, then you need to go back and double-check your installation.

Installing the Library Source and Documentation

The library source files are delivered in the JDK as a compressed file src.zip, and you must unpack that file to get access to the source code. We highly recommend that you do that. Simply do the following:

  1. Make sure that the JDK is installed and that the jdk/bin directory is on the execution path.

  2. Open a shell window.

  3. Change to the jdk directory (e.g., cd /usr/local/jdk5.0 or cd c:jdk5.0).

  4. Make a subdirectory src

    mkdir src
    cd src
    
  5. Execute the command:

    jar xvf ../src.zip
    

    (or jar xvf ..src.zip on Windows)

Tip

Tip

The src.zip file contains the source code for all public libraries. To obtain even more source (for the compiler, the virtual machine, the native methods, and the private helper classes), go to http://www.sun.com/software/communitysource/j2se/java2/index.html.

The documentation is contained in a compressed file that is separate from the JDK. You can download the documentation from http://java.sun.com/docs. Several formats (.zip, .gz, and .Z) are available. Choose the format that works best for you. If in doubt, use the zip file because you can uncompress it with the jar program that is a part of the JDK. Simply follow these steps:

  1. Make sure that the JDK is installed and that the jdk/bin directory is on the execution path.

  2. Download the documentation zip file and move it into the jdk directory. The file is called j2sdkversion-doc.zip, where version is something like 5_0.

  3. Open a shell window.

  4. Change to the jdk directory.

  5. Execute the command

    jar xvf j2sdkversion-doc.zip

    where version is the appropriate version number.

Installing the Core Java Program Examples

You should also install the Core Java program examples. You can download them from http://www.phptr.com/corejava. The programs are packaged into a zip file corejava.zip. You should unzip them into a separate directory—we recommend you call it CoreJavaBook. You can use any zip file utility such as WinZip (http://www.winzip.com), or you can simply use the jar utility that is part of the JDK. If you use jar, do the following:

  1. Make sure the JDK is installed and the jdk/bin directory is on the execution path.

  2. Make a directory CoreJavaBook.

  3. Download the corejava.zip file to that directory.

  4. Open a shell window.

  5. Change to the CoreJavaBook directory.

  6. Execute the command:

    jar xvf corejava.zip
    

Navigating the Java Directories

In your explorations of Java, you will occasionally want to peek inside the Java source files. And, of course, you will need to work extensively with the library documentation. Table 2–1 shows the JDK directory tree.

Table 2–1. Java Directory Tree

Directory Structure

Description

Java Directory Tree

(The name may be different, for example, jdk5.0)

The compiler and tools

Look here for demos

Library documentation in HTML format (after expansion of j2sdkversion-doc.zip)

Files for compiling native methods (see Volume 2)

Java runtime environment files

Library files

The library source (after expanding src.zip)

The two most useful subdirectories for learning Java are docs and src. The docs directory contains the Java library documentation in HTML format. You can view it with any web browser, such as Netscape.

Tip

Tip

Set a bookmark in your browser to the file docs/api/index.html. You will be referring to this page a lot as you explore the Java platform.

The src directory contains the source code for the public part of the Java libraries. As you become more comfortable with Java, you may find yourself in situations for which this book and the on-line information do not provide what you need to know. At this point, the source code for Java is a good place to begin digging. It is reassuring to know that you can always dig into the source to find out what a library function really does. For example, if you are curious about the inner workings of the System class, you can look inside src/java/lang/System.java.

Choosing a Development Environment

If your programming experience comes from using Microsoft Visual Studio, you are accustomed to a development environment with a built-in text editor and menus to compile and launch a program along with an integrated debugger. The basic JDK contains nothing even remotely similar. You do everything by typing in commands in a shell window. We tell you how to install and use the basic JDK because we have found that the full-fledged development environments don’t necessarily make it easy to learn Java—they can be complex and they hide some of the interesting and important details from the programmer.

Integrated development environments tend to be more cumbersome to use for a simple program because they are slower, require more powerful computers, and often require a somewhat tedious project setup for each program you write. These environments have the edge if you write large Java programs consisting of many source files, and they integrate tools such as debuggers and version control systems. We show you how to get started with Eclipse, a freely available development environment that is itself written in Java. Of course, if you prefer a different development environment such as NetBeans or JBuilder that supports the current version of Java, then you can certainly use it with this book.

For simple programs, a good middle ground between command-line tools and an integrated development environment is an editor that integrates with the JDK. On Linux, our preferred choice is Emacs. On Windows, we also like TextPad, an excellent shareware programming editor for Windows with good Java integration. Finally, JEdit is an excellent cross-platform alternative. Using a text editor with JDK integration can make developing Java programs easy and fast. We used that approach for developing and testing most of the programs in this book. Because you can compile and execute source code from within the editor, it can become your de facto development environment as you work through this book.

In sum, you have three choices for a Java development environment:

  • Use the JDK and your favorite text editor. Compile and launch programs in a shell window.

  • Use an integrated development environment such as Eclipse, or one of many other freely or commercially available development environments.

  • Use the JDK and a text editor that is integrated with the JDK. Emacs, TextPad, and JEdit are so integrated, as are many others. Compile and launch programs inside the editor.

Using the Command-Line Tools

Let us get started the hard way: compiling and launching a Java program from the command line.

Open a shell window. Go to the CoreJavaBook/v1ch2/Welcome directory. (The CoreJavaBook directory is the directory into which you installed the source code for the book examples, as explained on page 18.)

Then enter the following commands:

javac Welcome.java
java Welcome

You should see the output shown in Figure 2–1 in the shell window.

Compiling and running Welcome.java

Figure 2–1. Compiling and running Welcome.java

Note

Note

In Windows, follow these instructions to open a shell window. Select the “Run” option from the start menu. If you use Windows NT/2000/XP, type cmd; otherwise, type command. Press ENTER, and a shell window appears. If you’ve never seen one of these, we suggest that you work through a tutorial that teaches the basics about the command line. Many computer science departments have tutorials on the Web, such as http://www.cs.sjsu.edu/faculty/horstman/CS46A/windows/tutorial.html.

Congratulations! You have just compiled and run your first Java program.

What happened? The javac program is the Java compiler. It compiles the file Welcome.java into the file Welcome.class. The java program launches the Java virtual machine. It executes the bytecodes that the compiler placed in the class file.

Note

Note

If you got an error message complaining about the line

for (String g : greeting)

then you probably use an older version of the Java compiler. JDK 5.0 introduces a number of very desirable features to the Java programming language, and we take advantage of them in this book.

If you are using an older version of Java, you need to rewrite the loop as follows:

for (int i = 0; i < greeting.length; i++)
   System.out.println(greeting[i]);

In this book, we always use the language features of JDK 5.0. It is a straightforward matter to transform them into their old-fashioned counterparts—see Appendix B for details.

The Welcome program is extremely simple. It merely prints a message to the console. You may enjoy looking inside the program shown in Example 2–1—we explain how it works in the next chapter.

Example 2–1. Welcome.java

 1. public class Welcome
 2. {
 3.    public static void main(String[] args)
 4.    {
 5.       String[] greeting = new String[3];
 6.       greeting[0] = "Welcome to Core Java";
 7.       greeting[1] = "by Cay Horstmann";
 8.       greeting[2] = "and Gary Cornell";
 9.
10.       for (String g : greeting)
11.          System.out.println(g);
12.    }
13. }

Troubleshooting Hints

In the age of visual development environments, many programmers are unfamiliar with running programs in a shell window. Any number of things can go wrong, leading to frustrating results.

Pay attention to the following points:

  • If you type in the program by hand, make sure you pay attention to uppercase and lowercase letters. In particular, the class name is Welcome and not welcome or WELCOME.

  • The compiler requires a file name (Welcome.java). When you run the program, you specify a class name (Welcome) without a .java or .class extension.

  • If you get a message such as “Bad command or file name” or “javac: command not found”, then go back and double-check your installation, in particular the execution path setting.

  • If javac reports an error “cannot read: Welcome.java”, then you should check whether that file is present in the directory.

    Under UNIX, check that you used the correct capitalization for Welcome.java.

    Under Windows, use the dir shell command, not the graphical Explorer tool. Some text editors (in particular Notepad) insist on adding an extension .txt after every file. If you use Notepad to edit Welcome.java, then it actually saves it as Welcome.java.txt. Under the default Windows settings, Explorer conspires with Notepad and hides the .txt extension because it belongs to a “known file type.” In that case, you need to rename the file, using the ren shell command, or save it again, placing quotes around the file name: "Welcome.java".

  • If you launch your program and get an error message complaining about a java.lang.NoClassDefFoundError, then carefully check the name of the offending class.

    If you get a complaint about welcome (with a lowercase w), then you should reissue the java Welcome command with an uppercase W. As always, case matters in Java.

    If you get a complaint about Welcome/java, then you accidentally typed java Welcome.java. Reissue the command as java Welcome.

  • If you typed java Welcome and the virtual machine can’t find the Welcome class, then check if someone has set the class path on your system. For simple programs, it is best to unset it. You can unset the class path in the current shell window by typing

    set CLASSPATH=
    

    This command works on Windows and UNIX/Linux with the C shell. On UNIX/Linux with the Bourne/bash shell, use

    export CLASSPATH=
    

    Chapter 4 tells you how you can permanently set or unset your class path.

  • If you get an error message about a new language construct, make sure that your compiler supports JDK 5.0. If you cannot use JDK 5.0 or later, you need to modify the source code, as shown in Appendix B.

  • If you have too many errors in your program, then all the error messages fly by very quickly. The compiler sends the error messages to the standard error stream, so it’s a bit tricky to capture them if they fill more than the window can display.

    On a UNIX system or a Windows NT/2000/XP system, capturing error messages is not a big problem. You can use the 2> shell operator to redirect the errors to a file:

    javac MyProg.java 2> errors.txt

    Under Windows 95/98/Me, you cannot redirect the standard error stream from the shell window. You can download the errout program from http://www.horstmann.com/corejava/faq.html and run

    errout javac MyProg.java > errors.txt

Tip

Tip

The excellent tutorial at http://java.sun.com/docs/books/tutorial/getStarted/cupojava/ goes into much greater detail about the “gotchas” that beginners can run into.

Using an Integrated Development Environment

In this section, we show you how to compile a program with Eclipse, an integrated development environment that is freely available from http://eclipse.org. Eclipse is written in Java, but because it uses a nonstandard windowing library, it is not quite as portable as Java itself. Nevertheless, versions exist for Linux, Mac OS X, Solaris, and Windows.

After starting Eclipse, select File -> New Project from the menu, then select “Java Project” from the wizard dialog (see Figure 2–2). These screen shots were taken with Eclipse 3.0M8. Don’t worry if your version of Eclipse looks slightly different.

New Project dialog in Eclipse

Figure 2–2. New Project dialog in Eclipse

Click the “Next” button. Supply the project name “Welcome” and type in the full path name of the directory that contains Welcome.java; see Figure 2–3. Be sure to uncheck the option labeled “Create project in workspace”. Click the “Finish” button.

Configuring an Eclipse project

Figure 2–3. Configuring an Eclipse project

The project is now created. Click on the triangle in the left pane next to the project window to open it, and then click on the triangle next to “Default package”. Double-click on Welcome.java. You should now see a window with the program code (see Figure 2–4).

Editing a source file with Eclipse

Figure 2–4. Editing a source file with Eclipse

With the right mouse button, click on the project name (Welcome) in the leftmost pane. Select Build Project from the menu that pops up. Your program is compiled. If it compiles successfully, select Run -> Run As -> Java Application. An output window appears at the bottom of the window. The program output is displayed in the output window (see Figure 2–5).

Running a program in Eclipse

Figure 2–5. Running a program in Eclipse

Locating Compilation Errors

Presumably, this program did not have typos or bugs. (It was only a few lines of code, after all.) Let us suppose, for the sake of argument, that your code occasionally contains a typo (perhaps even a syntax error). Try it out—ruin our file, for example, by changing the capitalization of String as follows:

public static void main(string[] args)

Now, run the compiler again. You will get an error message that complains about an unknown string type (see Figure 2–6). Simply click on the error message. The cursor moves to the matching line in the edit window, where you can correct your error. This behavior allows you to fix your errors quickly.

Error messages in Eclipse

Figure 2–6. Error messages in Eclipse

These instructions should give you a taste of working in an integrated environment. We discuss the Eclipse debugger in Chapter 11.

Compiling and Running Programs from a Text Editor

An integrated development environment accords many comforts but also insinuates some drawbacks. In particular, for simple programs that are not distributed over multiple source files, an environment with its long startup time and many bells and whistles can seem like overkill. Fortunately, many text editors can launch the Java compiler, launch Java programs, and capture error messages and program output. In this section, we look at Emacs as a typical example.

Note

Note

GNU Emacs is available from http://www.gnu.org/software/emacs/. For the Windows port of GNU Emacs, see http://www.gnu.org/software/emacs/windows/ntemacs.html. Be sure to install the JDEE (Java Development Environnment for Emacs) when using Emacs for Java programming. You can download it from http://jdee.sunsite.dk. You need JDEE 2.4.3beta1 or later with JDK 5.0.

Emacs is a splendid text editor that is freely available for UNIX, Linux, Windows, and Mac OS X. However, many Windows programmers find the learning curve rather steep. For those programmers, we can recommend TextPad. Unlike Emacs, TextPad conforms to standard Windows conventions. TextPad is available at http://www.textpad.com. Note that TextPad is shareware. You are expected to pay for it if you use it beyond a trial period. (We have no relationship with the vendor, except as satisfied users of the program.)

Another popular choice is JEdit, a very nice editor written in Java, freely available from http://jedit.org. Whether you use Emacs, TextPad, JEdit, or another editor, the concepts are the same. When you are done editing the source code, you invoke a command to compile the code. The editor launches the compiler and captures the error messages. You fix the errors, compile again, and invoke another command to run your program.

Figure 2–7 shows the Emacs editor compiling a Java program. (Choose JDE -> Compile from the menu to run the compiler.)

Compiling a program with Emacs

Figure 2–7. Compiling a program with Emacs

The error messages show up in the lower half of the window. When you move the cursor on an error message and press the ENTER key, the cursor moves to the corresponding source line.

Once all errors are fixed, you can run the program by choosing JDE -> Run App from the menu. The output shows up inside an editor window (see Figure 2–8).

Running a program from within Emacs

Figure 2–8. Running a program from within Emacs

Running a Graphical Application

The Welcome program was not terribly exciting. Next, we will demonstrate a graphical application. This program is a simple image file viewer that just loads and displays an image. Again, let us first compile and run it from the command line.

  1. Open a shell window.

  2. Change to the directory CoreJavaBook/v1ch2/ImageViewer.

  3. Enter:

    javac ImageViewer.java
    java ImageViewer
    

A new program window pops up with our ImageViewer application (see Figure 2–9).

Running the ImageViewer application

Figure 2–9. Running the ImageViewer application

Now select File -> Open and look for a GIF file to open. (We supplied a couple of sample files in the same directory.)

To close the program, click on the Close box in the title bar or pull down the system menu and close the program. (To compile and run this program inside a text editor or an integrated development environment, do the same as before. For example, for Emacs, choose JDE -> Compile, then choose JDE -> Run App.)

We hope that you find this program interesting and useful. Have a quick look at the source code. The program is substantially longer than the first program, but it is not terribly complex if you consider how much code it would take in C or C++ to write a similar application. In Visual Basic, of course, it is easy to write or, rather, drag and drop, such a program. The JDK does not have a visual interface builder, so you need to write code for everything, as shown in Example 2–2. You learn how to write graphical programs like this in Chapters 7 through 9.

Example 2–2. ImageViewer.java

 1. import java.awt.*;
 2. import java.awt.event.*;
 3. import java.io.*;
 4. import javax.swing.*;
 5.
 6. /**
 7.    A program for viewing images.
 8. */
 9. public class ImageViewer
10. {
11.    public static void main(String[] args)
12.    {
13.       JFrame frame = new ImageViewerFrame();
14.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15.       frame.setVisible(true);
16.    }
17. }
18.
19. /**
20.    A frame with a label to show an image.
21. */
22. class ImageViewerFrame extends JFrame
23. {
24.    public ImageViewerFrame()
25.    {
26.       setTitle("ImageViewer");
27.       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
28.
29.       // use a label to display the images
30.       label = new JLabel();
31.       add(label);
32.
33.       // set up the file chooser
34.       chooser = new JFileChooser();
35.       chooser.setCurrentDirectory(new File("."));
36.
37.       // set up the menu bar
38.       JMenuBar menuBar = new JMenuBar();
39.       setJMenuBar(menuBar);
40.
41.       JMenu menu = new JMenu("File");
42.       menuBar.add(menu);
43.
44.       JMenuItem openItem = new JMenuItem("Open");
45.       menu.add(openItem);
46.       openItem.addActionListener(new
47.          ActionListener()
48.          {
49.             public void actionPerformed(ActionEvent event)
50.             {
51.                // show file chooser dialog
52.                int result = chooser.showOpenDialog(null);
53.
54.                // if file selected, set it as icon of the label
55.                if (result == JFileChooser.APPROVE_OPTION)
56.                {
57.                   String name = chooser.getSelectedFile().getPath();
58.                   label.setIcon(new ImageIcon(name));
59.                }
60.             }
61.          });
62.
63.       JMenuItem exitItem = new JMenuItem("Exit");
64.       menu.add(exitItem);
65.       exitItem.addActionListener(new
66.          ActionListener()
67.          {
68.             public void actionPerformed(ActionEvent event)
69.             {
70.                System.exit(0);
71.             }
72.          });
73.    }
74.
75.    private JLabel label;
76.    private JFileChooser chooser;
77.    private static final int DEFAULT_WIDTH = 300;
78.    private static final int DEFAULT_HEIGHT = 400;
79. }

Building and Running Applets

The first two programs presented in this book are Java applications, stand-alone programs like any native programs. On the other hand, as we mentioned in the last chapter, most of the hype about Java comes from its ability to run applets inside a web browser. We want to show you how to build and run an applet from the command line. Then we will load the applet into the applet viewer that comes with the JDK. Finally, we will display it in a web browser.

First, open a shell window and go to the directory CoreJavaBook/v1ch2/WelcomeApplet, then enter the following commands:

javac WelcomeApplet.java
appletviewer WelcomeApplet.html

Figure 2–10 shows what you see in the applet viewer window.

WelcomeApplet applet as viewed by the applet viewer

Figure 2–10. WelcomeApplet applet as viewed by the applet viewer

The first command is the now-familiar command to invoke the Java compiler. This compiles the WelcomeApplet.java source into the bytecode file WelcomeApplet.class.

This time, however, you do not run the java program. You invoke the appletviewer program instead. This program is a special tool included with the JDK that lets you quickly test an applet. You need to give this program an HTML file, rather than the name of a Java class file. The contents of the WelcomeApplet.html file are shown below in Example 2–3.

Example 2–3. WelcomeApplet.html

 1. <html>
 2.    <head>
 3.       <title>WelcomeApplet</title>
 4.    </head>
 5.    <body>
 6.       <hr/>
 7.       <p>
 8.          This applet is from the book
 9.          <a href="http://www.horstmann.com/corejava.html">Core Java</a>
10.          by <em>Cay Horstmann</em> and <em>Gary Cornell</em>,
11.          published by Sun Microsystems Press.
12.       </p>
13.       <applet code="WelcomeApplet.class" width="400" height="200">
14.          <param name="greeting" value ="Welcome to Core Java!"/>
15.       </applet>
16.       <hr/>
17.       <p><a href="WelcomeApplet.java">The source.</a></p>
18.    </body>
19. </html>

If you are familiar with HTML, you will notice some standard HTML instructions and the applet tag, telling the applet viewer to load the applet whose code is stored in WelcomeApplet.class. The applet viewer ignores all HTML tags except for the applet tag.

The other HTML tags show up if you view the HTML file in a Java 2-enabled browser. Unfortunately, the browser situation is a bit messy.

  • Mozilla (and Netscape 6 and above) support Java 2 on Windows, Linux, and Mac OS X. To experiment with applets, just download the latest version and make sure Java is enabled.

  • Some versions of Internet Explorer have no support for Java at all. Others only support the very outdated Microsoft Java Virtual Machine. If you run Internet Explorer on Windows, go to http://java.com and install the Java Plug-in.

  • If you have a Macintosh running OS X, then Safari and Internet Explorer are integrated with the Macintosh Java implementation, which supports JDK 1.4 at the time of this writing. OS 9 supports only the outdated version 1.1.

Provided you have a browser that supports the Java 2 platform, you can try loading the applet inside the browser.

  1. Start your browser.

  2. Select File -> Open File (or the equivalent).

  3. Go to the CoreJavaBook/v1ch2/WelcomeApplet directory.

You should see the WelcomeApplet.html file in the file dialog. Load the file. Your browser now loads the applet, including the surrounding text. It will look something like Figure 2–11.

Running the WelcomeApplet applet in a browser

Figure 2–11. Running the WelcomeApplet applet in a browser

You can see that this application is actually alive and willing to interact with the Internet. Click on the Cay Horstmann button. The applet directs the browser to display Cay’s web page. Click on the Gary Cornell button. The applet directs the browser to pop up a mail window, with Gary’s e-mail address already filled in.

Notice that neither of these two buttons works in the applet viewer. The applet viewer has no capabilities to send mail or display a web page, so it ignores your requests. The applet viewer is good for testing applets in isolation, but you need to put applets inside a browser to see how they interact with the browser and the Internet.

Tip

Tip

You can also run applets from inside your editor or integrated development environment. In Emacs, select JDE -> Run Applet from the menu. In Eclipse, use the Run -> Run as -> Java Applet menu option.

Finally, the code for the applet is shown in Example 2–4. At this point, do not give it more than a glance. We come back to writing applets in Chapter 10.

In this chapter, you learned about the mechanics of compiling and running Java programs. You are now ready to move on to Chapter 3, where you will start learning the Java language.

Example 2–4. WelcomeApplet.java

 1. import javax.swing.*;
 2. import java.awt.*;
 3. import java.awt.event.*;
 4. import java.net.*;
 5.
 6. public class WelcomeApplet extends JApplet
 7. {
 8.    public void init()
 9.    {
10.       setLayout(new BorderLayout());
11.
12.       JLabel label = new JLabel(getParameter("greeting"), SwingConstants.CENTER);
13.       label.setFont(new Font("Serif", Font.BOLD, 18));
14.       add(label, BorderLayout.CENTER);
15.
16.       JPanel panel = new JPanel();
17.
18.       JButton cayButton = new JButton("Cay Horstmann");
19.       cayButton.addActionListener(makeURLActionListener(
20.          "http://www.horstmann.com"));
21.       panel.add(cayButton);
22.
23.       JButton garyButton = new JButton("Gary Cornell");
24.       garyButton.addActionListener(makeURLActionListener(
25.          "mailto:[email protected]"));
26.       panel.add(garyButton);
27.
28.       add(panel, BorderLayout.SOUTH);
29.    }
30.
31.    private ActionListener makeURLActionListener(final String u)
32.    {
33.       return new
34.          ActionListener()
35.          {
36.             public void actionPerformed(ActionEvent event)
37.             {

38.                try
39.                {
40.                   getAppletContext().showDocument(new URL(u));
41.                }
42.                catch(MalformedURLException e)
43.                {
44.                   e.printStackTrace();
45.                }
46.             }
47.          };
48.    }
49. }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset