OOPJ Module 5
OOPJ Module 5
Prepared By :
Prepared By :
[Link], HOD /CSE
[Link] SELVA
[Link], RAJ, AP /CSE
AP/CSE
UNIT 5
APPLETS
Applets are small applications that are accessed on an Internet server, transported overthe Internet,
automatically installed, and run as part of a web document.
Applet is a special type of program that is embedded in the webpage to generate thedynamic content. It runs
inside the browser and works at client side.
Advantage of Applet
Drawback of Applet
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extendsContainer which is the
subclass of Component.
The Applet class is contained in the [Link] package. Applet contains several methods that give you
detailed control over the execution of your applet.
It is important to state at the outset that there are two varieties of Applets. The first are those based directly on
the Applet class, which uses the Abstract Window Toolkit (AWT) to provide the graphic user interface (or use no
GUI at all).The second type of applets are those based on the Swing class JApplet. Swing applets use the Swing
classes to provide the GUI.
All applets are subclasses (either directly or indirectly) of Applet. Applets are not stand- alone programs.
Instead, they run within either a web browser or an applet viewer.
Execution of an applet does not begin at main ( ). (Few applets even have main ( ) methods) Instead, execution
of an applet is started and controlled with an entirely different mechanism. Output to your applet’s window is
not performed by [Link]( ). Rather, in non-Swing applets, output is handled with various AWT
methods, such as drawString( ), which outputs a string to a specified X,Y location. Input is also handled
differently than in a console application.
Simple Example:
import [Link].*;
import [Link].*;
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
[Link]("A Simple Applet", 20, 20);
}
}
This applet begins with two import statements. The first imports the Abstract Window Toolkit (AWT) classes.
Applets interact with the user (either directly or indirectly) through the AWT, not through the console-based I/O
classes. The AWT contains support for a window-based, graphical user interface. The second import statement
imports the applet package, which contains the class Applet. Every applet that you create must be a subclass of
Applet. The next line in the program declares the class SimpleApplet. This class must be declared as public,
because it will be accessed by code that is outside the program. Inside SimpleApplet, paint ( ) is declared. This
method is defined by the AWT and mustbe overridden by the applet. Paint ( ) is called each time that the applet
must redisplay its output. Paint ( ) is also called when the applet begins execution. The paint ( ) method has one
parameter of type Graphics. This parameter contains the graphics context, which describes the graphics
environment in which the applet is running. This context is used whenever output to the applet is required.
Inside paint ( ) is a call to drawString( ), which is a member of the Graphics class. This method outputs a
string beginning at the specified X,Y location. It has the following general form:
void drawString(String message, int x, int y) Here,
message is the string to be output beginning at x,y.
Notice that the applet does not have a main ( ) method. Unlike Java programs, applets do not begin execution at
main ( ). In fact, most applets don’t even have a main ( ) method. Instead, an applet begins execution when the
name of its class is passed to an applet viewer or to a network browser.
There are two ways in which you can run an applet:
Executing the applet within a Java-compatible web browser.
Using an applet viewer, such as the standard tool, appletviewer. An applet viewer executes your applet
in a window. This is generally the fastest and easiest way totest your applet.
To execute an applet in a web browser, you need to write a short HTML text file that contains a tag that loads the
applet. Currently, Sun recommends using the APPLET tag for this purpose. Here is the HTML file that executes
SimpleApplet:
<applet code="SimpleApplet" width=200 height=60>
</applet>
The width and height statements specify the dimensions of the display area used by the applet. After you create
this file, you can execute your browser and then load this file, whichcauses SimpleApplet to be executed.
Key Points:
Applets do not need a main ( ) method.
Applets must be run under an applet viewer or a Java-compatible browser.
User I/O is not accomplished with Java’s stream I/O classes. Instead, applets use the
interface provided by the AWT or Swing.
The Applet class defines the methods. Applet provides all necessary support for applet execution, such as
starting and stopping. It also provides methods that load and display images, and methods that load and play
audio clips.
Method Description
void destroy( ) Called by the browser just before an applet is terminated. Your applet
will override this method if it needs to perform any cleanup prior to
its destruction.
AccessibleContext getAccessibleContext( ) Returns the accessibility context for the invoking object.
AppletContext getAppletContext( ) Returns the context associated with the applet.
String getAppletInfo( ) Returns a string that describes the applet.
AudioClip getAudioClip(URL url) Returns an AudioClip object that encapsulates the audio clip found at
the location specified by url.
AudioClip getAudioClip(URL url, String clipName) Returns an AudioClip object that encapsulates the audio clip found at
the location specified by url and having the name specified by
clipName.
URL getCodeBase( ) Returns the URL associated with the invoking applet.
URL getDocumentBase( ) Returns the URL of the HTML document that invokes
the applet.
Image getImage(URL url) Returns an Image object that encapsulates the image found at the
location specified by url.
Image getImage(URL url, String imageName) Returns an Image object that encapsulates the image found at the
location specified by url and having the name specified by
imageName.
String getParameter(String paramName) Returns the parameter associated with paramName. null is returned
if the specified parameter is not found.
String[ ] [ ] getParameterInfo( ) Returns a String table that describes the parameters recognized by
the applet. Each entry in the table must consist of three strings that
contain the name of the parameter, a description of its type and/or
range, and an explanation of its purpose.
void init() Called when an applet begins execution. It is the first method called
for any applet.
boolean isActive( ) Returns true if the applet has been started. It returns false if the
applet has been stopped.
void play(URL url) If an audio clip is found at the location specified by url, the clip is
played.
void play(URL url, String clipName) If an audio clip is found at the location specified by url with the name
specified by clipName, the clip is played.
void resize(Dimension dim) Resizes the applet according to the dimensions specified by dim.
Dimension is a class stored inside [Link]. It contains two integer
fields: width and height.
void resize(int width, int height) Resizes the applet according to the dimensions specified by width
and height.
void showStatus(String str) Displays str in the status window of the browser or applet viewer. If
the browser does not support a status window, then no action takes
place.
void start( ) Called by the browser when an applet should start (or resume)
execution. It is automatically called after init( ) when an applet first
begins.
void stop( ) Called by the browser to suspend execution of the applet. Once
stopped, an applet is restarted when the browser calls start( ).
The [Link] class 4 life cycle methods and [Link] class provides 1life cycle methods for
an applet.
It is important to understand the order in which the various methods shown in the skeletonare called. When an
applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
init( ) : The init( ) method is the first method to be called. This is where you shouldinitialize variables.
This method is called only once during the run time of your applet.
start( ): The start( ) method is called after init( ). It is also called to restart an appletafter it has been
stopped. Whereas init( ) is called once—the first time an applet isloaded—start( ) is called each time an
applet’s HTML document is displayed onscreen. So,if a user leaves a web page and comes back, the applet
resumes execution at start( ). paint( ): The paint( ) method is called each time your applet’s output must be
[Link] situation can occur for several reasons. For example, the window in which the applet isrunning
may be overwritten by another window and then uncovered. Or the applet windowmay be minimized and
then restored. paint( ) is also called when the applet beginsexecution. Whatever the cause, whenever the
applet must redraw its output, paint( ) iscalled. The paint( ) method has one parameter of type Graphics. This
parameter willcontain the graphics context, which describes the graphics environment in which the appletis
running. This context is used whenever output to the applet is required.
stop( ): The stop( ) method is called when a web browser leaves the HTML document containing the applet—
when it goes to another page, for example. When stop( ) is called, the applet is probably running. You should
use stop( ) to suspend threads that don’t need to run when the applet is not visible. You can restart them when
start( ) is called if the user returns to the page.
destroy( ): The destroy( ) method is called when the environment determines that your applet needs to be
removed completely from memory. At this point, you should free up any resources the applet may be using. The
stop( ) method is always called before destroy( ).
import [Link];
import [Link].*;
[Link]([Link]); [Link](170,200,30,30);
[Link](90,150,30,30,30,270);
[Link](270,150,30,30,0,180);
}
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
To set the background color of an applet’s window, use setBackground( ). To set the foreground color use
setForeground( ). These methods are defined by Component, and they have the following general forms:
void setBackground(Color newColor) void
setForeground(Color newColor)
Ex:
setBackground([Link]);
setForeground([Link]);
The GUI programming is inherently event-driven; whenever a user initiates an activity such as a mouse
activity, clicks, scrolling, etc., each is known as an event that is mapped to a code to respond to functionality
to the user. This is known as event handling.
In this section, we will discuss event processing and how to implement the delegation event model in Java.
We will also discuss the different components of an Event Model.
Java support event processing since Java 1.0. It provides support for AWT ( Abstract Window Toolkit), which
is an API used to develop the Desktop application. In Java 1.0, the AWT was based on inheritance. To catch
and process GUI events for a program, it should hold subclass GUI components and override action() or
handleEvent() methods. The below image demonstrates the event processing.
o Events
o Events Sources
o Events Listeners
Events
The Events are the objects that define state change in a source. An event can be generated as a reaction of a
user while interacting with GUI elements. Some of the event generation activities are moving the mouse
pointer, clicking on a button, pressing the keyboard key, selecting an item from the list, and so on. We can
also consider many other user operations as events.
The Events may also occur that may be not related to user interaction, such as a timer expires, counter
exceeded, system failures, or a task is completed, etc. We can define events for any of the applied actions.
Event Sources
A source is an object that causes and generates an event. It generates an event when the internal state of the
object is changed. The sources are allowed to generate several different types of events.
A source must register a listener to receive notifications for a specific event. Each event contains its
registration method. Below is an example:
From the above syntax, the Type is the name of the event, and e1 is a reference to the event listener. For
example, for a keyboard event listener, the method will be called as addKeyListener(). For the mouse event
listener, the method will be called as addMouseMotionListener(). When an event is triggered using the
respected source, all the events will be notified to registered listeners and receive the event object. This
process is known as event multicasting. In few cases, the event notification will only be sent to listeners that
register to receive them.
From the above syntax, the Type is the name of the event, and e2 is the event listener's reference. When the
specified event occurs, it will be notified to the registered listener. This process is known
as unicasting events.
A source should contain a method that unregisters a specific type of event from the listener if not needed.
Below is an example of the method that will remove the event from the listener.
From the above syntax, the Type is an event name, and e2 is the reference of the listener. For example, to remove the
keyboard listener, the removeKeyListener() method will be called.
The source provides the methods to add or remove listeners that generate the events. For example, the Component class
contains the methods to operate on the different types of events, such as adding or removing them from the listener.
Event Listeners
An event listener is an object that is invoked when an event triggers. The listeners require two things; first, it
must be registered with a source; however, it can be registered with several resources to receive notification
about the events. Second, it must implement the methods to receive and process the received notifications.
The methods that deal with the events are defined in a set of interfaces. These interfaces can be found in the
[Link] package.
For example, the MouseMotionListener interface provides two methods when the mouse is dragged and
moved. Any object can receive and process these events if it implements the MouseMotionListener interface.
Design Goals
The design goals of the event delegation model are as following:
Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The
[Link] package provides many event classes and Listener interfaces for event handling.
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
For registering the component with the Listener, many classes provide the registrationmethods. For
example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
EventHandling Codes:
We can put the event handling code into one of the following places:
1. Same class
2. Other class
3. Annonymous class
//create components
tf=new TextField();
[Link](60,50,170,20);
//register listener
[Link](this);//passing current instance
l=new Label();
[Link](20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
Output:
Interface declaration
Following is the declaration for [Link] interface:
1. public abstract void keyPressed (KeyEvent e); It is invoked when a key has been pressed.
2. public abstract void keyReleased (KeyEvent e); It is invoked when a key has been released.
3. public abstract void keyTyped (KeyEvent e); It is invoked when a key has been typed.
[Link]
Output:
Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels
etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another
window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components like
button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other components
like button, textfield etc.
JAVA SWING
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in
java.
The [Link] package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
3) AWT doesn't support pluggable Swing supports pluggable look and feel.
look and feel.
MVC ARCHITECTURE:
The model is the piece that represents the state and low-level behavior of the component. It
manages the state and conducts all transformations on that state. The model has no specific
knowledge of either its controllers or its views. The system itself maintains links between
model and views and notifies the views when the model changes state.
The view is the piece that manages the visual display of the state represented by the model. A
model can have more than one view, but that is typically not the case in the Swing set.
The controller is the piece that manages user interaction with the model. It provides the
mechanism by which changes are made to the state of the model.
Using the keyboard key example, the model corresponds to the key's mechanism, and the
view and controller correspond to the key's façade.
The following figure illustrates how to break a JFC user interface component into a model,
view, and controller. Note that the view and controller are combined into one piece, a
common adaptation of the basic MVC pattern. They form the user interface for the
component
public void setLayout(LayoutManagerm) sets the layout manager for the component.
CONTAINERS:
Containers are an integral part of SWING GUI components. A container provides a space
where a component can be located. A Container in AWT is a component itself and it
provides the capability to add a component to itself. Following are certain noticable points to
be considered.
Sub classes of Container are called as Container. For example, JPanel, JFrame and
JWindow.
SWING Containers
Following is the list of commonly used containers while designed GUI using SWING.
Panel
1
Frame
2
A JFrame is a top-level window with a title and a border.
Window
3
A JWindow object is a top-level window with no borders and no menubar.
SWING COMPONENTS:
Java JButton
The JButton class is used to create a labeled button that has platform independent implementation. The
application result in some action when the button is pushed. It inherits AbstractButton class.
Constructor Description
Methods Description
Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false).
Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It inherits JToggleButton
class.
Constructor Description
JJCheckBox() Creates an initially unselected check box button with no text, no
icon.
JCheckBox(String text, Creates a check box with text and specifies whether or not it is
boolean selected)
initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from the Action
supplied.
this JCheckBox.
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one optionfrom multiple options.
It is widely used in exam systems or quiz.
Constructor Description
JRadioButton(String s, boolean Creates a radio button with the specified text and selected
selected)
status.
Constructor Description
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image,
horizontalAlignment)
and horizontal alignment.
void setText(String text) It defines the single line of text this component will display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along the X axis.
alignment)
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the X axis.
Java JTextField
The object of a JTextField class is a text component that allows the editing of a singleline text. It inherits
JTextComponent class.
Constructor Description
JTextField() Creates a new TextField
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, Creates a new TextField initialized with the specified text and
int columns)
columns.
JTextField(int columns) Creates a new empty TextField with the specified number of
columns.
Action getAction() It returns the currently set Action for this ActionEvent
Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows theediting of multiple
line text. It inherits JTextComponent class
Constructor Description
JTextArea(int row, Creates a text area with the specified number of rows
int column)
and columns that displays no text initially.
JTextArea(String s,int Creates a text area with the specified number of rows
row, int column)
and columns that displays specified text.
Commonly used Methods:
Methods Description
of rows.
of columns.
JList(ary[] listData) Creates a JList that displays the elements in the specified array.
JList(ListModel<ary> Creates a JList that displays elements from the specified, non-null,
dataModel)
model.
ListModel getModel() It is used to return the data model that holds a list of
array of objects.
Java JList Example
1. import [Link].*;
2. public class ListExample
3. {
4. ListExample(){
5. JFrame f= new JFrame();
6. DefaultListModel<String> l1 = new DefaultListModel<>();
7. [Link]("Item1");
8. [Link]("Item2");
9. [Link]("Item3");
10. [Link]("Item4");
11. JList<String> list = new JList<>(l1);
12. [Link](100,100, 75,75);
13. [Link](list);
14. [Link](400,400);
15. [Link](null);
16. [Link](true);
17. }
18. public static void main(String args[])
19. {
20. new ListExample();
21. }}
Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected byuser is shown on
the top of a menu. It inherits JComponent class.
Constructor Description
Mohan Babu University
Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeAllItems() It is used to remove all the items from the list.
is editable.