Basics of Applets: An Applet Viewer Is A Program Designed To Run An Applet As A Stand-Alone Program
Basics of Applets: An Applet Viewer Is A Program Designed To Run An Applet As A Stand-Alone Program
Basics of Applets: An Applet Viewer Is A Program Designed To Run An Applet As A Stand-Alone Program
BASICS OF APPLETS
Applets are window-based programs that are called from within another application. It can be run within: a page on the Internet(i.e. browser), or a program called appletviewer, which comes with the Java Developments Kit. An applet viewer is a program designed to run an applet as a stand-alone program An applet must be called from within another document written in HTML, or Hypertext Markup Language, which is used to create Web pages for the Internet. When creating an applet, the following have to be done: Write the applet in the Java programming language, and save it with a .java file extension. The applet program must be complied into bytecode using javac command. Write a HTML document that includes a statement to call your compiled Java class. Load the HTML document into a Web browser or run the Applet Viewer program. In every applet, there are four methods, which includes the following: public void init() public void start() public void stop() public void destroy() paint()method init() method This is the first method called in any applet. This method is used to perform initialization tasks, such as setting variables to initial values or placing applet components on the screen. start() method This method executes after the init() method, and it executes again every time the applet becomes active after it has been inactive. stop() method This method is invoked when a user moves off the page, perhaps by minimizing a window or traveling to a different Web page. destroy() method This is called when the user closes the browser or applet viewer, this releases any resources the applet may have allocated. paint()method This is called by the applet container after methods init and start. Method paint is also called when the applet needs to be repainted. For example, if the user covers the applet with another open window on the screen and later uncovers the applet, the paint method is called. 1.1 CREATING APPLET Create the applet like any other java program but include the above methods and extend Applets.
1
Compiling: javac -classpath ./folder appletname.java Running: java -classpath ./folder appletname In order to run an applet, a HTML document has to be created. Within the HTML document, we will have to add an <applet> and </applet> tag pair. There are three attributes within the <applet> tag: code the name of the compiled applet we are calling. width the width of the applet on the screen. Height the height of the applet on the screen. Example showing how a class file can be called within a <html> tag: <applet code = label.class width=300 height=200> The HTML document will be saved with extension .html. The width and height of an applet are measured in pixels. Pixels are the picture elements that make up the image on your video monitor. 1.2 RUNNING APPLET To run an applet using the appletviewer command, at DOS prompt, type the following: appletviewer <filename>.html and then press the <Enter> key. After a few minutes, the Applet Viewer window opens and displays the applet. To run applet using browser, double click the filename or open with the selected browser.
tables fonts frames, windows and dialog boxes When we create an applet using AWT, we may include a user interface, which may consist of 3 parts: Components anything that can be placed onto a user interface e.g. Button, TextField etc. Containers this is a component that contain other component e.g. dialog boxes, applet window, panel. Layout managers it is an object that defines how the components in a container will be arranged.
3 COMPONENT CLASS
The component class is one of the AWT components. It represents the GUI components provided by java.awt and include buttons, text components, checkboxes, lists and scrollbars. 3.1 Labels A Label is a component that displays a single line of text. It is often used for putting a title or message next to another component. Label objects do not generate events. The common format of a Label declaration is: Label label_name = new Label(text string); The following example demonstrates the display of a message using Label in an applet. import java.applet.*;
public class label extends Applet{ public void init() { Label message = new Label(Hello World); add(message); } } import java.awt.*;
The output of
The label will be align automatically in the center. This can be modified to either align the label to the left or right during declaration by using Label.LEFT or Label.RIGHT constant.
3.2 TextFields
A TextField is a primary method of getting user to input using the keyboard in a Java applet. It is a Windows component into which a user can type a single line of text data. The user will type in a line into a TextField and then inputs the data by pressing the Enter key on the keyboard or clicking a Button with the mouse. The format of textfield declaration is as follows: TextField textfield_name = new TextField(); // it creates a black field of a default size. There may also be other ways of constructing a TextField object, which is as follows: TextField textfield_name = new TextField(numColumns); // where numColumns specifies a width for the field. Or TextField textfield_name = new TextField(initialText); // where initialText provides some initial text within the TextField. Or TextField textfield_name = new TextField(initialText, numColumn); // which specifies both initial text and width. The following demonstrates the different ways of declaring a TextField.
Example 1: TextField answer = new TextField(); Example 2: TextField answer = new TextField(5); Example 3: TextField answer = new TextField(Hello); Example 4: TextField answer = new TextField(Hello,5);
There are several other methods which are available for use with TextFields, which There are several other methods which are available for use with TextFields, which are o setText method and o getText method. The setText() method allows us to change the textField that already has been created, as in answer.setText(Hello);. The getText() method allows us to retrieve the String of text in a TextField, as in String result = answer.getText();. The following program shows the use of TextField class in an applet.
} } 4 import java.applet.*; import java.awt.*; public class textfield extends Applet{ public void init() { TextField field = new TextField(); add(field);
3.3 Buttons The Button press is the most common control used in an applet. When a button is pressed by the user, the computer will generate an event. An event can be anything which interacts with the user or with other programs in the computer, e.g. a mouse click. An event can be captured and then examined for determining the source e.g. keyboard or mouse etc. and the corresponding code can be executed. The format below shows us how to create a Button with a label: Button button_name = new Button(String); // where String is the label given to the Button.
To prepare an applet to accept mouse events, we will have to import the java.awt.event package into the program and add the phrase implements ActionListener to the class header. The java.awt.event package includes one of the event class, which is ActionEvent. ActionListener is an interface, which you can use with Event objects. Implementing ActionListener provides standard event method specifications that allow your applet to work with ActionEvents, which are the types of events that occur when a user clicks a button. The addActionListener() method tells an applet to expect ActionEvents. To prepare an applet for Buttonsource events, the following statement will have to be entered: button_name.addActionListener(this); The ActionListener interface contains one method, actionPeformed() , that is called when an ActionEvent object is executed. The header is declared as public void actionPerformed(ActionEvent e), where e is any name we choose for the Event(e.g. Button click) that initiated the notification of the ActionListener(the applet). The body of the method can contain any statements that we want to execute when an action occurs. We can perform some mathematical calculations, construct new objects, produce output, or execute any other operation. The following applet program demonstrate the use of Label, Button, TextField and the actionPerformed() to create an interactive applet.
import java.awt.event.*; public class DemoApplet extends Applet implements ActionListener{ Label title = new Label(Annual Company Function); Button press = new Button(Calculate); Label message = new Label(Enter the number of people going); TextField number = new TextField(5); Font big = new Font(Helvetica,Font.ITALIC,24); Label result1 = new Label(Come and join in the fun.); Label result2 = new Label(Be in the party. ); public void init() { title.setFont(big); add(title); add(message); add(number); add(press); number.requestFocus(); press.addActionListener(this); number.addActionListener(this); add(result1); add(result2); }
} }
public void start(){ result1.setText(Come and join the fun.); number.setText(0); result2.setText(Be in the party. ); invalidate(); // it alerts the applet when it is out of date, //which marks the window so it knows that it is not up to //date with recent changes. validate(); // this will cause the change to take effect, //which redraws any invalid windows. } public void actionPerformed(ActionEvent e){ int num = Integer.parseInt(number.getText()); int singleFee=0, eventFee=0; if (num>=50){ singleFee=100; eventFee=num * singleFee; }else{ singleFee=88; eventFee=num * singleFee; } result1.setText($+singleFee+per person); result2.setText(Event cost $+eventFee);
3.4 The paint() Method The output of this program is shown below: When the user enters a value in the TextField and clicks the calculate button, it performs a calculation and shows the result in the applet. 7
Another way to display label in an applet is to use the paint() method. To display a text in an applet, we will use the drawString() method, which includes three arguments: string of text, x co-ordinate and y coordinate. The format below shows the use of the drawString() method to display a text: g.drawString(Text, x axis, y axis); // g is the Graphics object. The applet below shows an example of the drawString() method within the paint() method. import java.awt.*; import java.applet.*; public class DemoPaint extends Applet{ Font big = new Font(Courier, Font.BOLD, 24); } } 8 // the three arguments in a Font object includes the typeface, style and // point size. public void paint(Graphics g){ g.setFont(big); // sets the Font to the label. g.setColor(Color.red); // sets the text colour of the label. g.drawString(Hello World,80,40);
4 Graphics Class
The Graphics class in Java has a rich variety of graphics function. All the outputs into the window take place through a graphics context. We can easily draw and colour simple objects like lines, circles, rectangles, polygons etc. very easily. The position of these objects is relative to the top left hand corner of the screen(0,0). 4.1 The drawLine() Method The drawLine() method allows us to draw horizontal, vertical and diagonal lines. It takes in four parameters to draw any of these lines. They are the x and y co-ordinates of the starting and ending points of that line. The format for drawing a line using drawLine() method is as follows: drawLine( x1, y1, x2, y2); The following is an example to show the use of the drawLine() method to draw a straight line. import java.awt.*; import java.applet.*; public class Lines extends Applet{ public void paint(Graphics g){ g.drawLine(10, 10, 100, 10); // horizontal line g.drawLine(10, 10, 10, 100); // vertical line g.drawLine(10, 10, 100, 100); // diagonal line } } 9
4.2 The drawRect() Method The drawRect() method allows us to draw a rectangle or a square. It takes in four parameters to draw any of these shapes. They are the x and y co-ordinates of the starting and the width and length of the rectangle. The format for drawing a rectangle or a square using the drawRect() method is as follows: drawRect( x1, y1, width, length); The following is an example to show the use of the drawRect() method to draw a rectangle. import java.awt.*; import java.applet.*; public class Rectangle extends Applet{ public void paint(Graphics g){ g.drawRect(10, 10, 100, 50); } } The output of this program is shown below:
10
4.3 The drawOval() Method The drawOval() method allows us to draw a circle or ellipse. It takes in four parameters to draw the shape. They are the x and y co-ordinates of the starting and the width and length of the circle. The format for drawing a circle or ellipse using the drawOval() method is as follows: drawOval( x1, y1, width, length); The following is an example to show the use of the drawOval() method to draw a circle. import java.awt.*; import java.applet.*; public class Oval extends Applet{ public void paint(Graphics g) { g.drawOval(50, 50, 100, 80); } } The output of this program is shown below:
4.4 The drawArc() Method The drawArc() method allows us to draw an arc. It takes in six parameters to draw an arc. They are the x and y co-ordinates of the starting, the width and length of the arc, the starting position of the arc and the angle of the arc. The format for drawing an arc using the drawArc() method is as follows: drawArc( x1, y1, width, length, starting angle, degree); 11
The following is an example to show the use of the drawArc() method to draw an arc. import java.awt.*; import java.applet.*; public class Arc extends Applet{ public void paint(Graphics g){ g.drawArc(50, 50 , 150, 150, 90, 90); } }
5 IMAGES
Java has very powerful image handling features. We can control the way images are rendered and also the way they appear after they are rendered. Thus, this provides for powerful transition effects like cropping, blurring and contrast. We can use an instance of the Image class to draw images. Methods like getImage() and drawImage() are used to get images and display them on the screen. The images must be in GIF(Graphics Interchange Format) and JPEG(Joint Photographic Experts Group) format. The getImage() method is used to load an image into an Image object, which takes in two arguments: Where to get the image The image file name The drawImage() method is used to display the image on the screen, which takes in four arguments: The image object to display X co-ordinate 12
Y co-ordinate The keyword this, which means current object. The following example demonstrates how we could download an image to the applet using the two methods. import java.applet.*; import java.awt.*; public class ShowImage extends Applet{ Image img; public void init() { img = getImage(getDocumentBase(), winlogo.gif); } public void paint(Graphics g){ g.drawImage(img, 0, 0, this); } } The output of the above program is shown below:
Sometimes the images flickers and the flickering of images is caused by the repaint() method. The repaint() method calls an update() method to clear the screen, then calls the paint() method. In order to prevent the flickering effect, the following code can be used to override the update() method. 13
6 ANIMATIONS
Animation basically involves showing a series of images in rapid succession at a fixed frame rate. It works best with Threads and Java makes use of threads for multithreading(multitasking). A thread is part of a program that is set to run on its own while the rest of the programs are also running.
The following are ways to create a thread: To change the class declaration by adding implements Runnable. To create a thread object to hold the thread in the start() method. To override the applets start() method to create a thread and start running it. To create a run() method that contains the statements that makes the applet run continuously. To override the stop() method to set the running thread to null.
7 SOUNDS
Audio clip handling is the same as Image handling in Java. Java supports several format of sounds such as MIDI(Musical Instrument Digital Interface) and .wav format. We use the getAudioClip() to get the sound file and used the play() method to attempt to play the audio clip. The loop() method allows us to load the sound data and continuously plays the audio file.
8 CONTAINER CLASS
A Container object is a subclass of Component that provides a rectangular display area on the screen. GUI components and other containers can be placed inside a Container object. The Container class provides common methods used by the other container classes, which includes: Panel object ScrollPane object Window class Frame object Dialog class FileDialog, subclass of Dialog
14
9 LAYOUT MANAGERS
A layout manager is an object that is responsible for the positioning and dimensioning of the components contained inside a Container object. The layout of the components can be affected by the size of the applet window, size of the components and containers and the types of layout managers used. The layout manager provides several types of layout, which includes: FlowLayout GridLayout BorderLayout The Panel class allows us to increase the number of screen arrangements.
11 TYPES OF EVENTS
15
There are different types of event classes defined in the java.awt.event package, which includes the following: Keyboard events KeyEvent objects are fired when a key is pressed and/or released. Mouse events MouseEvent objects are created when the mouse is moved, clicked or dragged. Window events WindowEvent objects are generated when a window is opened, closed, iconified, deiconified, activated or deactivated. Action events ActionEvent objects are generated when a button is clicked, a list or menu item is selected, or the Return key is pressed with a TextField.
12 PROGRAMMING EXERCISES
1. State the four methods commonly found in an applet program.
2. 3. 4. 5. Give the syntax to view an applet program using the appletviewer. Give any 3 examples of window components and explain briefly each component identified. Explain the difference using a Label and a TextField to display text on an applet. Explain the arguments needed in the following methods: a. drawString() method b. drawLine() method c. drawRect() method d. drawOval() method 6. State any 3 examples of container class. 7. Describe the difference between an event-driven program and a procedural-oriented program.
16