Post on 03-Apr-2018
transcript
7/29/2019 Applets and GUI
1/22
CS153 CHAPTER 9: APPLETS
CHAPTER 9: APPLETS
Chapter Objectives:
Upon completion of this chapter, you would have learnt:
The basics of Applet
What is Abstract Windows Toolkit
What is a Component Class and Methods found in this class
What is Graphics Class and Methods found in this class
How to insert Images to an Applet
What is Animation and Sound
What is a Layout Manager
What is a Container Class
What is an Event Driven Program
Different types of Events
9 - 1
7/29/2019 Applets and GUI
2/22
CS153 CHAPTER 9: APPLETS
9.1 Basics of Applets
Besides, using Java to develop stand-alone application, Java can also used to develop
applets. Applets are programs that are called from within another application. It can be
run within a page on the Internet, or within another program called appletviewer, which
comes with the Java Developments Kit. 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 usingjavac 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()
The init() method 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.
Thestart() method executes after the init() method, and it executes again every time the
applet becomes active after it has been inactive.
Thestop() method is invoked when a user moves off the page, perhaps by minimizing a
window or traveling to a different Web page.
9 - 2
7/29/2019 Applets and GUI
3/22
CS153 CHAPTER 9: APPLETS
The destroy() method is called when the user closes the browser or applet viewer, this
releases any resources the applet may have allocated.
In order to run an applet, a HTML document has to be created. Within the HTML
document, we will have to add an and tag pair. There are three
attributes within the 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.
The following is an example showing how a class file can be called within a tag:
The HTML document will be save 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. To run an applet using the appletviewercommand, at DOS prompt,
type the following: appletviewer .htmland then press the key. After
a few minutes, the Applet Viewer window opens and displays the applet.
9.2 Abstract Windows Toolkit
Most applets contain at least two import statements: import java.applet.*; and import
java.awt.*;. The java.appletpackage contains a class name Applet , where it used to
create every applet. The java.awt. package is the Abstract Windows Toolkit, orAWT. It
contains commonly used Windows components such as Labels, Menus and Buttons.
Hence, we do not have to create these components ourselves and this saves time and can
be reused.
The majority of Java programs use a Graphical User Interface to interact with the user.
This is easier and more fun than the conventional console input and output. The typical
Graphical Interface consists of elements like:
standard windows GUI controls like
buttons
9 - 3
7/29/2019 Applets and GUI
4/22
CS153 CHAPTER 9: APPLETS
labels
text boxes
check boxes
radio buttons
menus
pictures
mouse support
animation
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.
9.3 Component Class
The componentclass is one of the AWT components. It represents the GUI components
provided by java.awt and include buttons, text components, checkboxes, lists and
scrollbars.
9.3.1 Labels
A Labelis a component that displays a single line of text. It is often used for putting a
title or message next to another component. Labelobjects do not generate events. The
common format of a Label declaration is:
9 - 4
7/29/2019 Applets and GUI
5/22
7/29/2019 Applets and GUI
6/22
CS153 CHAPTER 9: APPLETS
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.
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
setText method and 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();.
9 - 6
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);
7/29/2019 Applets and GUI
7/22
CS153 CHAPTER 9: APPLETS
The following program shows the use of TextField class in an applet.
The output of this program is shown below:
9.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);
9 - 7
import java.applet.*;import java.awt.*;
public class textfield extends Applet{
public void init(){
TextField field = new TextField();add(field);
}}
7/29/2019 Applets and GUI
8/22
CS153 CHAPTER 9: APPLETS
// 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 Button-source 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.
9 - 8
7/29/2019 Applets and GUI
9/22
CS153 CHAPTER 9: APPLETS
9 - 9
import java.applet.*;
import java.awt.*;
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);
}
7/29/2019 Applets and GUI
10/22
CS153 CHAPTER 9: APPLETS
9 - 10
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);
}
}
7/29/2019 Applets and GUI
11/22
CS153 CHAPTER 9: APPLETS
9.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.
Another way to display label in an applet is to use thepaint() 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 co-ordinate. 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.
9 - 11
7/29/2019 Applets and GUI
12/22
CS153 CHAPTER 9: APPLETS
The output of this program is shown below:
9 - 12
import java.awt.*;
import java.applet.*;
public class DemoPaint extends Applet
{
Font big = new Font(Courier, Font.BOLD, 24);
// 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);
}
}
7/29/2019 Applets and GUI
13/22
CS153 CHAPTER 9: APPLETS
9.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).
9.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.
9 - 13
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
}
}
7/29/2019 Applets and GUI
14/22
CS153 CHAPTER 9: APPLETS
The output of this program is shown below:
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.
9 - 14
import java.awt.*;
import java.applet.*;
public class Rectangle extends Applet
{
public void paint(Graphics g)
{
g.drawRect(10, 10, 100, 50);
}
}
7/29/2019 Applets and GUI
15/22
CS153 CHAPTER 9: APPLETS
The output of this program is shown below:
9.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.
9 - 15
import java.awt.*;
import java.applet.*;
public class Oval extends Applet
{
public void paint(Graphics g)
{
g.drawOval(50, 50, 100, 80);
}
}
7/29/2019 Applets and GUI
16/22
CS153 CHAPTER 9: APPLETS
The output of this program is shown below:
9.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);
The following is an example to show the use of the drawArc() method to draw an arc.
9 - 16
import java.awt.*;
import java.applet.*;
public class Arc extends Applet
{
public void paint(Graphics g)
{
g.drawArc(50, 50 , 150, 150, 90, 90);
}
}
7/29/2019 Applets and GUI
17/22
CS153 CHAPTER 9: APPLETS
The output of this program is shown below:
9.5 Images
Java has very powerful image handling features. We can control the way images are
rendered an 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
Y co-ordinate
The keyword this, which means current object.
9 - 17
7/29/2019 Applets and GUI
18/22
CS153 CHAPTER 9: APPLETS
The following example demonstrates how we could download an image to the applet
using the two methods.
The output of the above program is shown below:
9 - 18
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);
}
}
7/29/2019 Applets and GUI
19/22
CS153 CHAPTER 9: APPLETS
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.
9.6 Animation
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 thestart() method.
To override the appletsstart() 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 thestop() method to set the running thread to null.
9.7 Sound
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
thegetAudioClip() to get the sound file and used theplay() method to attempt to play the
9 - 19
public void update(Graphics scr)
{
paint(scr);
}
7/29/2019 Applets and GUI
20/22
CS153 CHAPTER 9: APPLETS
audio clip. The loop() method allows us to load the sound data and continuously plays the
audio file.
9.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:
Panelobject
ScrollPane object
Window class
Frame object
Dialogclass
FileDialog, subclass ofDialog
9.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
ThePanelclass allows us to increase the number of screen arrangements.
9.10 Event Driven Program
An event occurs when users who used the applet takes action on a component, such as
clicking the mouse on a Button object. In an event driven program, the user might initiate
any number of events in any order. As compared to procedural, we dictate the order in
which events occurred.
9 - 20
7/29/2019 Applets and GUI
21/22
CS153 CHAPTER 9: APPLETS
Within an even driven program, a component on which an event is generated is the
source of the event. An example of a source is the Button that a user can click or a
TextField that the user can enter text. A listener is an object that is interested in an event.
For example, a Java component source object(e.g. Button) maintains a list of registered
listeners and notifies all registered listeners(e.g. applet) when an event occur(e.g a mouse
click). Hence, an event handling method that is part of the listener object responds to the
event.
9.11 Types of Events
There are different types of event classes defined in the java.awt.eventpackage, which
includes the following:
Keyboard events KeyEventobjects are fired when a key is pressed and/or released.
Mouse events MouseEventobjects 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 ActionEventobjects are generated when a button is clicked, a list or
menu item is selected, or the Return key is pressed with a TextField.
9 - 21
7/29/2019 Applets and GUI
22/22
CS153 CHAPTER 9: APPLETS
9.12 Programming Exercises
1. State the four methods commonly found in an applet program.
2. Give the syntax to view an applet program using the appletviewer.
3. Give any 3 examples of window components and explain briefly each component
identified.
4. Explain the difference using a Label and a TextField to display text on an applet.
5. 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.