Ramp Up to Java |
Revised April 30, 1999 |
Steps in Writing Java:
|
Public class first extends Applet { … blah, blah, blah … } |
|
C:\javac first.java |
|
C:\java first |
|
< html><applet code = "first.class" height = 200 width = 300> </applet> </html> |
|
C:\ appletviewer first.html |
Objects
An object is an "active" container of information. It contains both information and methods for manipulating information.
|
Student Name = "Bill"; Credits = 52; StillToDo() { work = 63 - credits; return work; } |
Creating new objects
|
Student s = new student(); Student t = new student(); |
Referencing objects
|
Who = s.name; Incomplete = s.stillToDo(); |
Constructors
|
Public class student { String name; int age; Public student() { Name=""; Age=0; } Public student(String N; int A) { Name = N; Age = A; } } |
Getters and Setters
getter |
Public class student { Int Credits; Public int getRemaining() { Int Diff; Diff = 63 - Credits; Return diff; } |
Extra = s.getRemaining(); |
setter |
Public setCredit (int I) { Credits = I; } |
s.setCredit(4); |
Class hierarchy and java.applet
Ramp Up to Java
Java is a computer language originally designed for consumer electronics, therefore the language is designed to produced small, distributed and robust programs. Java has been used in developing WWW applications because it will run on a wide variety of computer platforms and can be loaded dynamically across the WWW. Java programs that you can embed in HTML pages are called Java Applets (short for applications).
Java is a completely object-oriented language. Accordingly, Applets are themselves members of a larger class called Panels. Panels are members of a larger class called Containers. Containers are members of a larger class called Components. And Components are members of the class of Objects. Thus Applets can inherit methods from the Panel class, the Container class, the Components class and so on.
As a consequence of its object-oriented design, it is common to see importations such as the following at the top of a Java program:
import java.applet.*; The Applet package contains methods to initialize, start, stop or destroy the applet.
import java.awt.*; The Abstract Window Toolkit (AWT) package contains all the classes for creating user interfaces and for painting graphics and images.
A java program is often a set of class definitions where a class describes the values and actions of an object. Examples of objects might be persons, automobiles, trains, planes, etc. Here is a very primitive declaration of a class:
import java.applet.*;
import java.awt.*;
class trial
{
….blah, blah…
}
Here the class "trial" is defined. More detail is required on the declaration of the trial class, specifically that is a subclass of Applet and that it is a "public" class. Declaring a class to be public means that other programs can call it:
public class trial extends Applet
{
… blah, blah …
}
Java is a typed language meaning that every variable that you use must have a declared type. You can invent your own types as well as use standard types. For example:
Button pressMe; Declares an identifier "pressMe" for a new button. It does not create a button; only an identifier for an as yet undefined button. A button is a standard component in the java.awt class that has it own methods.
Label sign; Declares an identifier "sign" for a new label. It does not create a label. A label is a standard component in the java.awt class that displays a single line of text. It has its own methods.
1 |
import java.applet.*; import java.awt.*; |
2 |
public class trial extends Applet { |
3 |
Button pressMe; Label sign; |
4 |
….blah, blah… } |
When you first load up an applet, it must initialize itself. Later on, you could write methods that would start and stop it, but the first time it must initialize itself. It does this by calling one of the Applet classes standard methods init()
public void init()
{
…blah, blah …
}
This declaration of the init() method indicates that it is a public method that could be called by other programs, and that it is not going to produce any result. That is, it is not doing to do a calculation and return an integer, etc. It has a "void" return.
In the example we are building, we want our applet to appear and show a text string (in the label) and show a button (the button should have a label). Therefore, as the applet loads it should create a label and button and add them to the applet.
1 |
public void init () { |
2 |
sign = new Label("This is my first applet"); |
3 |
add(sign); |
4 |
pressMe = new Button("Click Here"); |
5 |
add(pressMe); } |
Comment: Portions 2 and 4 are creating and giving text labels to "sign" the new label and to "pressMe" the new button. Portions 3 and 5 then add these new elements to the default panel that the Applet is creating.
The applet so far looks like this:
The file trial.java
import java.applet.*;
import java.awt.*;
public class trial extends Applet
{
Button pressMe;
Label sign;
public void init ()
{
sign = new Label("This is my first applet");
add(sign);
pressMe = new Button("Click Here");
add(pressMe);
}
}
After having written an applet, you should save it to a file named trial.java. It very important that the file name "trial.java" and the class name "trial" be identical, where upper case and lower case matter. The first task is to compile the applet to bytecode. Bytecode is a compiled version of your applet that is platform neutral and that will run on any browser that is java enabled.
To compile trial.java to bytecode, call the java compiler:
c:\ javac trial.java
This calls the java compiler with the target trial.java. If you have compile errors, etc., then the compiler will give you error messages, etc. After removing any errors, your program will compile and will produce the file trial.class in the same directory. At this point, you will have two files in your subdirectory:
trial.java
trial.class
The task now is to embed trial.class in an html document. You can do this by creating the following file trial.html.
<HTML>
<HEAD><TITLE>test of trial.java</TITLE></HEAD>
<BODY>
<APPLET CODE=trial.class HEIGHT=100 WIDTH=200>
</APPLET>
</BODY>
</HTML>
At this point you have three files:
trial.java
trial.class
trial.html
The relationship among these files is that trial.class is the compiled byte code of the source file trial.java. The file trial.html is an html file that calls trial.class.
To test your applet, you can either point a WWW browser at trial.html, or use the applet viewer tool that comes with the java developer’s kit.
C:\ appletviewer trial.html
The appletviewer will open an html file and show the applet. Initially the applet will appear with a height of 100 pixels and width of 200 pixels and the label and button will be fitted into this size space. Enlarge the applet and see if these two components are arranged differently.
Step two:
The trial applet presented a label and a button but takes no action.
The file trial.java
import java.applet.*;
import java.awt.*;
public class trial extends Applet
{
Button pressMe;
Label sign;
public void init ()
{
sign = new Label("This is my first applet");
add(sign);
pressMe = new Button("Click Here");
add(pressMe);
}
}
Our task is to capture the event of the button being pressed. In the java.awt class we can use the action() method to capture the button pressing.
action (Event evt, Object arg)
This declares an action method that can either react to the type of event "evt" or the type of object "arg". Since our example is so simple in that we have only one button and its pressing is the only thing that can happen, we can rely on the default event.
Actions are boolean-type events in that the program will test if the button pressed tiggers this event (true or false) or another one. We need also to mark the action as a public method.
public boolean action (Event evt, Object arg)
{
… blah, blah …
return true;
}
Note that capturing an action is a boolean test that will check if a certain button triggers this event. If it does, then the last part of the action is to return a "true" to the program that the button action was satisfied.
In our example, we’re not going to test several buttons, but merely act on the button event. We can, for example, change the string on the label "sign".
sign.setText("Done clicked");
repaint();
Here we are using the setText() method of the Label class to set a new text string to the label "sign". repaint() forces the applet to paint itself on the panel again. This time the text string of sign has changed.
The complete applet looks like this:
import java.applet.*;
import java.awt.*;
public class trial extends Applet
{
Button pressMe;
Label sign;
public void init ()
{
sign = new Label("This is my first applet");
add(sign);
pressMe = new Button("Click Here");
add(pressMe);
}
public boolean action(Event evt, Object arg)
{
sign.setText("Done clicked");
repaint();
return true;
}
}
A second java example
For a second example java applet, let’s suppose that we want to create an applet that presents two buttons, and as the buttons are pressed, a corresponding image changes. Say, if you press a button "East", then an east-pointing arrow appears, but if you press "West" a west-pointing arrow appears, etc.
Almost ritualistically, one would begin with the following format:
1 |
import java.applet.*; import java.awt.*; |
2 |
public class second extends Applet { … blah, blah … |
3 |
public void init() { … blah, blah … } |
4 |
… blah, blah … } |
Comments: Section 1 are some standard importations. Sections 2 and 4 set out the applet "second" and section 3 is the standard initiation method.
We will have to declare identifiers for our buttons and images.
Button b_east, b_west;
Image east, west, currentImage;
Here we declare two buttons "b_east" and "b_west" and three images: "east", "west" and "currentImage". The strategy will be to paint the "currentImage" on the applet panel, and as the user presses a button our program will instantiate the currentImage to be either the image "east" or "west". When the program first comes up, we can present the user with an initial image of, say, a question mark.
One way that an applet can reach out and get an image is using the getImage() method of the java.applet package.
GetImage() Retrieves an image at a URL
The simplest situation is to place the image in the same subdirectory as the applet, which case you can use getDocumentBase() method to automatically get the URL. Suppose that an image is called "east.gif", then you can import it and instantiate the identifier "east" with the following:
east = getImage(getDocumentBase(), "east.gif")
Here is the applet "second" with the various declarations and importations.
1 |
import java.applet.*; import java.awt.*;
public class second extends Applet { |
2 |
Button b_east, b_west; Image east, west, currentImage; |
3 |
public void init() { east = getImage(getDocumentBase(), "east.gif"); west = getImage(getDocumentBase(), "west.gif"); currentImage = getImage(getDocumentBase(), "question.gif"); |
4 |
Button b_east = new Button("East"); Button b_west = new Button("West"); |
5 |
add(b_east); add(b_west); } |
6 |
… blah, blah… } |
Comments: Section 2 gives our declarations of buttons and images. Sections 3, 4, 5 set out the initial conditions. They are getting the three images in section 3, declaring two buttons in section 4, and adding the two buttons in section 5.
The strategy of this applet is to expose the question.gif and then as buttons are pushed to expose either the west.gif or the east.gif, etc. Each one of these gifs will be, in turn, the "currentImage". We will need a separate paint() method to paint these images upon the applet panel. Paint() is a method in the java.awt and we can use drawImage() to actually place the image at a certain location on the panel.
public void paint(Graphics g)
{
g.drawImage(currentImage, 0, 0, this);
}
Here the paint() method is called with the graphics object g. We can then manipulate g. For example, we can subclass the drawImage() method to g. For example:
g.drawImage()
There are four parameters to the drawImage() class in this example: "currentImage" is the image to be drawn, "0,0" are the x-coordinate and the y-coordinates of where to place the image on the panel. And "this" refers to an image update observer that we can ignore at this point by just telling java to regard "this" image (i.e., the image that it is currently working with).
Here is the applet so far:
import java.applet.*;
import java.awt.*;
public class second extends Applet
{
Button b_east, b_west;
Image east, west, currentImage;
public void init()
{
east = getImage(getDocumentBase(), "east.gif");
west = getImage(getDocumentBase(), "west.gif");
currentImage = getImage(getDocumentBase(), "question.gif");
Button b_east = new Button("East");
Button b_west = new Button("West");
add(b_east);
add(b_west);
}
… blah, blah …
public void paint(Graphics g)
{
g.drawImage(currentImage, 0, 0, this);
}
}
The last section of the applet to add is the button events. Here we’ll have to test for each button and if a button has been pressed, then instantiate "currentImage" to the desired image. Then we’ll force the applet to repaint itself with the changed image.
To test if a button has been clicked, we use the equals() method of the java.objects class. One of the standard parameters of the action() class is an object (here the object is "arg"):
public boolean action(Event evt, Object arg)
The challenge is to test the condition if the button’s label is the same as the object "arg" by using the equals() method:
if ("East".equals(arg)) Note how the equals() method is subclassed to the object "East".
if ("West".equals(arg)) Note how the equals() method is subclassed to the object "West".
A whole conditional clause would include the "if" test and then the required actions:
if ("East".equals(arg))
{
currentImage = east; // Instantiates "east" as the currentImage
repaint(); // Forces the applet to paint itself
return true; // Returns the true condition that this was button pressed
}
The complete applet:
import java.applet.*;
import java.awt.*;
public class second extends Applet
{
Button b_east, b_west;
Image east, west, currentImage;
public void init()
{
east = getImage(getDocumentBase(), "east.gif");
west = getImage(getDocumentBase(), "west.gif");
currentImage = getImage(getDocumentBase(), "question.gif");
Button b_east = new Button("East");
Button b_west = new Button("West");
add(b_east);
add(b_west);
}
public boolean action(Event e, Object arg)
{
if ("East".equals(arg))
{
currentImage = east;
repaint();
return true;
}
if ("West".equals(arg))
{
currentImage = west;
repaint();
return true;
}
return false;
}
public void paint(Graphics g)
{
g.drawImage(currentImage, 0, 0, this);
}
}