Exercise 1: Drawing Lines

Home/Java - Tutorial/Java - Applet/Exercise 1: Drawing Lines
Exercise 1: Drawing Lines 2015-12-04T17:33:00+00:00

[ Home | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 ]
Here’s the source code for a first applet:

Start up a plain text editor and type in the source code. It’s important that you use a plain ASCII text editor, such as “Notepad” or Notepad++ on Microsoft Windows, “TextEdit” on Mac OS X, or “vi” or vimor “emacs” on linux/UNIX, or the source code editor in your favorite IDE such as Netbeans or Eclipse. Don’t enter the source code with a word processing application such as “Microsoft Word”, since word processors use a different format for files. If you don’t want to do any typing, you can download the source file. Save the file as DrawingLines.java. It’s important that the filename match the class name in the source code.

Now, you have to compile the source code to generate a bytecode file called DrawingLines.class. If you’re using the Java Software Development Kit, you can compile by typing
javac DrawingLines.java
at a command prompt (on Microsoft Windows, this is done within an MS-DOS shell). Check that the .class file was indeed generated.

Then, create a .html file containing the following line:

<applet width=300 height=300 code="DrawingLines.class"> </applet>
(If the .html file is not in the same directory as the .class file, you’ll have to add a codebase="..." attribute specifying the path to the class file. More information on the <applet> tag can be found here.) When you view the .html file in a web browser, or with the appletviewer command-line utility included with the JDK, you should see something like this:

Here’s a second version of the same source code, this time with comments:

(Download the below file: DrawingLines.java)