Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures


Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips


Submit News
Search the site here...

A Tweak of Lemon...(Applets)

Custom Search
A Tweak of Lemon...(Applets)

[ Return to Shlurrrpp......Java ]

Page: 1/2 

Next Page (2/2) Next Page

A Tweak of Lemon...


Blowing away the clouds in the coffee..Brewing the first Applet

"Ours is the age of substitutes; instead of principles, we have slogans; instead of genuine ideas, bright ideas; instead of languages, jargon. "

When it comes to bright jargon, Sun Microsystems has left no stone unturned. And the creative terminology goes a long way (if not all the way) in making it like the tidal wave it has been. Java programs are called 'Applets'. In the directory in which the whole downloaded software of Java is saved, there is a subdirectory called Bin. This is where we have the Java compiler called 'Javac.exe'. The first thing we do is to create a subdiretory under the root called, say, "xxx". Then set the path to javain. We are going to write our Applets here. Each applet or program has to be written in a file with the extension of .Java. In keeping with the ritual, let us consider this one-liner code first...


class zzz

You'll agree that even an ice-hockey player or a visitor to Disneyland will love this sort of a program because it is looks manageably concise and absolutely simple. Well, we do not expect fireworks with that sort of a code, but let us compile it all the same. Save the file a1.java. It is noteworthy to mention here that like C/C++, Java is case-sensitive too (and preposterously so!). Type the command javac a1.java. The compiler gives no errors. If you key in the DIR command now, you will see that after successful compilation, a file called zzz.class is made automatically. That is because we specified zzz as the name of our class. This makes it adequately clear that the name of the applet file (the .java file) and the class can very well be different.

Now comes the question of viewing how our applet works. If it is a Java applet, you can call it only from an HTML file (An HTML file, in case you don't know, is nothing but a text file with tags that link it to other documents). Since all the documents on the Internet use this format, an applet has to be specified in an HTML file. Consider the following HTML file.


< applet code = "zzz"  width =120 height =120>

As is evident, the .class file (zzz.class in our case) that is formed after successful compilation of the .java file (a1.java) is specified in the HTML. The width and the heigth This is the way in which you can incorporate an applet in the HTML format. The applet could be a program to display animation or perform any other dynamic task and thus, enliven a page on the net.

But it still remains to be seen how the applet works or what the output looks like. Towards this end, we have a program called the appletviewer (in the same directory as javac). This is a program that allows you to view how your applet works. Hence, we key in the command appletviewer aa.html. Sorry folks, but there is no output (if your stars are not happy with you, your machine might even hang!).

There are a hundred and sixty five things to be done in the background before our class begins work (like the initialization routines et al). Our class does not have any property towards that end. As one does not know what routines are to be initialized internally, the safest thing to do is to derive a class from another class provided with the language. Now edit your a1.java file in the following way.


class zzz extends Applet

Applet is a class that has all the required functions necessary for this purpose, so we derive zzz from Applet or extend zzz to Applet. This means, in plain English, that we can now use all the functions and variables of the Applet class and also add our own ones. The only hitch now is that compiler refuses to recognize Applet, unless we mention specifically the name of the class library in which it is contained. So we now have to formally introduce the compiler to the Applet class. We do this by inviting the Applet class into our program (how else?). Only, the invitation here is in the form of importing a file called Applet.class from the classes javaApplet subdirectory.


import java.applet.*
class zzz extends Applet

When we compile this program, however, we get some lines of dreadful errors, with only one making any sort of horse-sense, " ; expected". Guess what, we missed out on the elusive semicolon after the import statement! Remember, this is a sibling of C and C++ and the use of semicolon is inevitable. And hence, our program now looks like this...

import java.applet.*;
class zzz extends Applet

However, having put that necessary punctuation, when we compile and run the program again, it gives the error that the 'class not public'. As a result, the applet is not initialized. That brings us to another important feature of the Java, as it stands today. All the classes that we define have to be public, otherwise the class cannot be initialised by the Appletviewer. Not being the arguing types, we make our class public in the following way...

import java.applet.*;
public class zzz extends Applet

One snag with making a class public is that the name of your file and that of the class have to be the same. So after adding the word public, rename a1.java to zzz.java. Before you begin to swear about this queue of unending snags, let us state that this is it. We finally have what can be safely labeled as the smallest Java program. Now when we key in the command appletviewer aa.html, a small window appears to show the output. This is the first successful applet and all the economists out there would love it. Because it is concise, precise and absolutely useless ( :-) ). As we are not economists and expect our applet to do something, let us make some additions. But to continue further, we have to quit from the appletviewer. For this, click on the Applet menu that you see in the appletviewer window and select Quit.

import java.applet.*;
public class zzz extends Applet
{	public void init()
	{	resize(300, 500);

All the functions in our class have to be public. The function init() gets called initially when you run an applet. Whenever your applet begins and you need to do something put it in the init(). Inside this, we have the resize() which is one of the many functions of the Applet class. It is used to change the size of the area in which our applet can work. By default, a small area is given to the applet but the resize() says "Give me two parameters, the width and the height and I can increase or decrease the scope of your applet". We obediently pass two parameters to this function, the width of the area(300) and the height(500). When we compile and run the above program, we can see a rectangular box as an output. As yet, we have just plain specified the area for the applet, now let us try displaying something inside it...

import java.applet.*;
import java.awt.*  ;
public class zzz extends Applet
{	public void init()
	{	resize(300, 500);
	public void paint(Graphics g)
	{	g.drawString("Hello", 10, 50);

As you must have realized, this program displays "Hello" at the coordinates 10, 50. As mentioned earlier, the init () gets called first. The workarea is resized in the same way as before. Everytime the screen or the window has to be displayed, the paint() gets called. You cannot set your watch by it. An object g that looks like the class Graphics has to be tagged along as a parameter. As Graphics is a predefined class, we require to import the Graphics class, (which is in the javaawtGraphics subdirectory). The Graphics class has many functions including the drawString(). Give this function its due in the form of three parameters, the string to be displayed, and the x and the y coordinates and promises to display the string at that position. So when the paint is called, "Hello" appears on the screen.

[ Return to Shlurrrpp......Java ]

Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color

[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3

[ More in News Section ]

Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy