Bca 2nd Java Notes - Ch4
Bca 2nd Java Notes - Ch4
APPLETS:
An applet is a program that comes from server into a client and gets executed at client side anddisplays the
result.
An applet represents byte code embedded in a html page. (Applet = bytecode + html) and run with the help
of Java enabled browsers such as Internet Explorer.
An applet is a Java program that runs in a browser. Unlike Java applications applets do not havea main ()
method.
To create applet we can use [Link] or [Link] class. All applets inherit the super
class ”Applet‟. An Applet class contains several methods that help to control the execution of an applet.
Advantages:
Applets provide dynamic nature for a webpage.
Applets are used in developing games and animations.
Writing and displaying (browser) graphics and animations is easier thanapplications.
In GUI development, constructor, size of frame, window closing code etc. are notrequired
Security Does not require any security Requires highest security for
the system as they are
untrusted
Programming Larger programs Small programs
Accessibility The java applications are Applets are designed just for
design to work with the client handling the client side
as well as server problems
Client side/ server side The applications don’t have Applets are designed for the
such type of criteria client side programming
purpose
Initialization:
public void init(): This method is used for initializing variables, parameters to create components. This
method is executed only once at the time of applet loaded into memory.
Runnning:
public void start (): After init() method is executed, the start method is executed automatically. Start
method is executed as long as applet gains focus. In this method code related to opening files and
connecting to database and retrieving the data and processing the data is written.
Idle / Runnable:
public void stop (): This method is executed when the applet loses focus. Code related to closing the files
and database, stopping threads and performing clean up operations are written in this stop method.
Dead/Destroyed:
public void destroy (): This method is executed only once when the applet is terminated from the memory.
To execute an applet using web browser, we must write a small HTML file which contains the appropriate
„APPLET‟ tag. <APPLET> tag is useful to embed an applet into an HTML page. It has the following form:
<APPLET CODE=”name of the applet class file” HEIGHT = maximum height of applet in pixels WIDTH
= maximum width of applet in pixels ALIGN = alignment (LEFT, RIGHT,MIDDLE, TOP, BOTTOM)>
The <PARAM> tag useful to define a variable (parameter) and its value inside the HTML page which can
be passed to the applet. The applet can access the parameter value using getParameter () method, as: String
value = getParameter (“pname”);
Example Program
Following is a simple applet named [Link] −
import [Link].*; import
[Link].*;
public class HelloWorldApplet extends Applet { public
void paint (Graphics g) {
[Link] ("Hello World", 25, 50);
}}
Invoking an Applet - [Link]
<html>
<title>The Hello, World Applet</title>
<applet code = "[Link]" width = "320" height = "120">
</applet>
</html>
TYPES OF APPLETS
Applets are of two types:
// Local Applets
// Remote Applets
Local Applets: An applet developed locally and stored in a local system is called local applets. So, local
system does not require internet. We can write our own applets and embed them into the web pages.
Remote Applets: The applet that is downloaded from a remote computer system and embed applet into a
web page. The internet should be present in the system to download the applet and run it. To download
the applet we must know the applet address on web known as Uniform Resource Locator(URL) and must
be specified in the applets HTML document as the value of CODEBASE.
EVENT HANDLING
Event handling is at the core of successful applet programming. Most events to which the applet will
respond are generated by the user. The most commonly handled events are those generated by the mouse,
the keyboard, and various controls, such as a push button.
Its concept is quite simple: a source generates an event and sends it to one or more listeners. In this scheme,
the listener simply waits until it receives an event. Once received, the listener processes the event and then
returns.
The advantage of this design is that the application logic that processes events is cleanly separated from the
user interface logic that generates those events. A user interface element is able to "delegate" the processing
of an event to a separate piece of code.
In the delegation event model, listeners must register with a source in order to receive an event notification.
This provides an important benefit: notifications are sent only to listeners that want to receive them.
EVENTS
In the delegation model, an event is an object that describes a state change in a source. It can be generated as
a consequence of a person interacting with the elements in a graphical user interface. Some of the activities
that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an
item in a list, and clicking the mouse.
Events may also occur that are not directly caused by interactions with a user interface. For example, an
event may be generated when a timer expires, a counter exceeds a value, software or hardware failure
occurs, or an operation is completed.
EVENT SOURCES
A source is an object that generates an event. This occurs when the internal state of that object changes in
some way. Sources may generate more than one type of event. A source must register listeners in order for
the listeners to receive notifications about a specific type of event. Each type of event has its own
registration method.
EVENT LISTENERS
A listener is an object that is notified when an event occurs. It has two major requirements. First, it must
have been registered with one or more sources to receive notifications about specific types of events.
Second, it must implement methods to receive and process these notifications. The methods that receive and
process events are defined in a set of interfaces found in [Link].
For example, the MouseMotionListener interface defines two methods to receive notifications when the
mouse is dragged or moved.
EVENT CLASSES
The classes that represent events are at the core of Java's event handling mechanism. At the root of the Java
event class hierarchy is EventObject, which is in [Link]. It is the superclass for all events.
The getSource( ) method returns the source of the event. Ex: Object getSource( )
The package [Link] defines several types of events that are generated by various user interface
elements.
Event Class Description
ActionEvent Generated when a button is pressed, a list item is double-clicked, or a menu
item is selected.
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponentEvent Generated when a component is hidden, moved, resized or becomes visible.
ContainerEvent Generated when a component is added to or removed from a container.
FocusEvent Generated when a component gains or loses keyboard focus.
InputEvent Abstract super class for all component input event classes.
ItemEvent Generated when a check box or list item is clicked; so occurs when a choice
selection is made or a checkable menu item is selected or deselected.
KeyEvent Generated when input is received from the keyboard.
MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or released;
also generated when the mouse enters or exits a component.
MouseWheelEvent Generated when the mouse wheel is moved. (Added by Java 2, version 1.4)
TextEvent Generated when the value of a text area or text field is changed.
WindowEvent Generated when a window is activated, closed, deactivated, deiconified,
iconified, opened, or quit.
An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu item is
selected. The ActionEvent class defines four integer constants that can be used to identify any modifiers
associated with an action event: ALT_MASK , CTRL_MASK , META_MASK , and SHIFT_MASK .
ActionEvent(Object src , int type, String cmd, long when , int modifiers )
//KeyEvent is generated when keyboard input occurs. There are three types of key events, which are
identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED .
The first two events are generated when any key is pressed or released. The last event occurs only when a
character is generated.
MouseListener Defines five methods to recognize when the mouse is clicked, enters a
component, exits a component, is pressed, or is released.
MouseMotionListener Defines two methods to recognize when the mouse is dragged or
moved.
MouseWheelListener Defines one method to recognize when the mouse wheel is moved.
TextListener Defines one method to recognize when a text value changes.
WindowListener Defines seven methods to recognize when a window is activated,
closed, deactivated, deiconified, iconified, opened, or quit.
The delegation event model has two parts: sources and listeners. Listeners are created by implementing
one or more of the interfaces defined by the [Link] package.
This interface defines the actionPerformed( ) method that is invoked when an action eventoccurs.
This interface defines the itemStateChanged( ) method that is invoked when the state of an itemchanges.
This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked when a key
is pressed and released, respectively. The keyTyped( ) method is invoked when a character has been entered.
For example, if a user presses and releases the key, three events are generated in A sequence: key pressed,
typed, and released.
This interface defines five methods. If the mouse is pressed and released at the same point, mouseClicked( )
is invoked. When the mouse enters a component, the mouseEntered( ) method is called. When it leaves,
mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are invoked when the mouse
is pressed and released, respectively.
This interface defines two methods. The mouseDragged( ) method is called multiple times as the mouse is
dragged. The mouseMoved( ) method is called multiple times as the mouse is moved.
This interface defines the textChanged( ) method that is invoked when a change occurs in a text area or text
field.
When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed( )
event handler. When the key is released, a KEY_RELEASED event is generated and the keyReleased( )
handler is executed. If a character is generated by the keystroke, then a KEY_TYPED event is sent and the
keyTyped( ) handler is invoked.
Thus, each time the user presses a key, at least two and often three events are generated. If all you care
about are actual characters, then you can ignore the information passed by the key press and release events.
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based application in java. Java
AWT components are platform-dependent i.e. components are displayed according to the view of operating
system. AWT is heavyweight i.e. its components uses the resources of system. The Abstract Window
Toolkit(AWT) support for applets. The AWT contains numerous classes and methods that allow you to
create and manage windows.
The [Link] package provides classes for AWT api such as TextField, Label, TextArea, RadioButton,
CheckBox, Choice, List etc.
AWT Classes
The AWT classes are contained in the [Link] package. It is one of Java's largest packages.
Class Description
Control Fundamentals
GUI (Graphical User Interface): In GUI user interacts with the application through graphics. GUI is user
friendly. GUI makes application attractive. It is possible to simulate real object in GUI programs. In java to
write GUI programs we can use awt (Abstract Window Toolkit) package.
Container
The Container is a component in AWT that can contain other components like buttons, textfields, labels
etc. The classes that extend Container class are known as container such as Frame, Dialog and Panel.
Window
The window is the container that has 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.
Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height) sets the size(width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by
default false.
Listeners are available for components. A Listener is an interface that listens to an event from a
component. Listeners are available in [Link] package. The methods in the listener interface are to
be implemented, when using that listener.
Component Listener Listener methods
Button ActionListener public void actionPerformed(ActionEvent e)
Checkbox ItemListener public void itemStateChanged(ItemEvent e)
CheckBoxGroup ItemListener public void itemStateChanged(ItemEvent e)
TextField ActionListener public void actionPerformed(ActionEvent e)
FocusListener public void focusGained(FocusEvent e)
public void focusLost(FocusEvent e)
TextArea ActionListener public void actionPerformed(ActionEvent e)
FocusListener public void focusGained(FocusEvent e)
public void focusLost(FocusEvent e)
Layout Managers
A layout manager arranges the child components of a container. It positions and sets the size of
components within the container's display area according to a particular layout scheme.
The layout manager's job is to fit the components into the available area, while maintaining the proper
spatial relationships between the components. AWT comes with a few standard layout managers that will
collectively handle most situations; you can make your own layout managers if you have special
requirements.
LayoutManager at work
Every container has a default layout manager; therefore, when you make a new container, it comes with a
LayoutManager object of the appropriate type. You can install a new layout manager at any time with the
setLayout() method. Below, we set the layout manager of a container to a BorderLayout:
Every component determines three important pieces of information used by the layout manager in placing
and sizing it: a minimum size, a maximum size, and a preferred size.
When a layout manager is called to arrange its components, it is working within a fixed area. It usually
begins by looking at its container's dimensions, and the preferred or minimum sizes of the child
components.
Flow Layout
FlowLayout is a simple layout manager that tries to arrange components with their preferred sizes, from left
to right and top to bottom in the display. A FlowLayout can have a specified justification of LEFT,
CENTER, or RIGHT, and a fixed horizontal and vertical padding.
By default, a flow layout uses CENTER justification, meaning that all components are centered within the
area allotted to them. FlowLayoutis the default for Panelcomponents like Applet.
Grid Layout
GridLayout arranges components into regularly spaced rows and columns. The components are
arbitrarily resized to fit in the resulting areas; their minimum and preferred sizes are consequently
ignored.
GridLayout is most useful for arranging very regular, identically sized objects and for allocating
space for Panels to hold other layouts in each region of the container.
GridLayout takes the number of rows and columns in its constructor. If you subsequently give it
too many objects to manage, it adds extra columns to make the objects fit. You can also set the
number of rows or columns to zero, which means that you don't care how many elements the layout
manager packs in that dimension.
Border Layout
BorderLayout is a little more interesting. It tries to arrange objects in one of five geographical
locations: "North," "South," "East," "West," and "Center," possibly with some padding between.
BorderLayout is the default layout for Window and Frame objects. Because each component is
associated with a direction, BorderLayout can manage at most five components; it squashes or stretches those
components to fit its constraints.
When we add a component to a border layout, we need to specify both the component and the position at
which to add it. To do so, we use an overloaded version of the add() method that takes an additional
argument as a constraint.
AWT controls
Labels:
The easiest control to use is a label. A label is an object of type Label, and it contains a string, which it
displays. Labels are passive controls that do not support any interaction with the user
Buttons:
The most widely used control is the push button. A push button is a component that contains a label and that
generates an event when it is pressed. Push buttons are objects of type Button.
Button class is useful to create push buttons. A push button triggers a series of events.
To create push button: Button b1 =new Button("label"); To get the label
of the button: String l = [Link](); To set the label of the button:
[Link]("label");
To get the label of the button clicked: String str = [Link]();
Check Boxes:
A check box is a control that is used to turn an option on or off. It consists of a small box that can either
contain a check mark or not. There is a label associated with each check box that describes what option the
box represents. You change the state of a check box by clicking on it. Check boxes can be used individually
or as part of a group.
TextField:
The TextField class implements a single-line text-entry area, usually called an edit control. Text fields
allow the user to enter strings and to edit the text using the arrow keys, cut and paste keys, and mouse
selections.
TextArea:
Sometimes a single line of text input is not enough for a given task. To handle these situations, the AWT
includes a simple multiline editor called TextArea .
CheckboxGroup
It is possible to create a set of mutually exclusive check boxes in which one and only one check
box in the group can be checked at any one time. These check boxes are often called radio buttons.
A Radio button represents a round shaped button such that only one can be selected from a panel.
Radio button can be created using CheckboxGroup class and Checkbox classes.
Choice Controls
The Choice class is used to create a pop-up list of items from which the user may choose. Thus,
a Choice control is a form of menu. Choice menu is a popdown list of items. Only one item can
be selected.
Lists
The List class provides a compact, multiple-choice, scrolling selection list. Unlike the Choice object, which
shows only the single selected item in the menu, a List object can be constructed to show any number of
choices in the visible window. It can also be created to allow multiple selections. List provides these
constructors: List( )
List(int numRows )
List(int numRows , boolean multipleSelect )
A List box is similar to a choice box, it allows the user to select multiple items.
This list box initially displays 3 items. The next parameter true represents that the user can select more than
one item from the available items. If it is false, then the user can select onlyone item.
Scroll Bars
Scroll bars are used to select continuous values between a specified minimum and [Link] bars may
be oriented horizontally or vertically. Scrollbar class is useful to create scrollbars that can be attached to a
frame or text area. Scrollbars can be arranged vertically or horizontally.
Graphics
The AWT supports a rich assortment of graphics methods. All graphics are drawn relative toa window.
Graphics class and is obtained in two ways:
\} It is passed to an applet when one of its various methods, such as paint( ) or update( ), is
called.
\} It is returned by the getGraphics( ) method of Component.
Drawing Lines
Drawing Rectangles
The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle, respectively. They are shown
here:
The upper-left corner of the rectangle is at top,left. The dimensions of the rectangle are specified by width
and height.
To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval( ). These methodsare shown here:
void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)
Drawing Arcs
void drawArc(int top, int left, int width, int height, int startAngle,int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle,int sweepAngle)
The arc is bounded by the rectangle whose upper-left corner is specified by top,left and whose width
and height are specified by width and height. The arc is drawn from startAngle through the angular
distance specified by sweepAngle. Angles are specified in degrees.
Drawing Polygons
It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon(), shown here:
The polygon’s endpoints are specified by the coordinate pairs contained within the x and y arrays. The
number of points defined by x and y is specified by numPoints. There are alternative forms of these methods
in which the polygon is specified by a Polygon object.