Java 5 TH
Java 5 TH
Java 5 TH
UNIT-5
APPLETS, AWT & EVENT HANDLING APPLET:
An applet is a special kind of java program that runs in a java enabled browser. This is the first java program
that can run over the internet browser. Applets are typically embedded inside the webpage and runs in browser.
In some other ways the applets are small java application that can be accessed on an internet server.
Advantage of Applet
There are many advantages of applet
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many plateforms, including Linux, Windows, Mac OS
etc.
Drawback of Applet
• Plugin is required at client browser to execute applet.
There are two ways to run an applet (steps for designing an applet)
1. By html file.
2. By appletViewer tool (for testing purpose).
Example for by using HTML file:
//First.java import
java.applet.Applet; import
java.awt.Graphics; public class
First extends Applet{ public void
paint(Graphics g){
g.drawString("welcome",150,150); }
}
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:
//First.java
import java.applet.Applet; import
java.awt.Graphics; public class
2
g.drawString("welcome to applet",150,150);
} }
/* <applet code="First.class" width="300" height="300"> </applet> */ To
execute the applet by appletviewer tool, write in command prompt:
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Methods in applets:
init(): The init() method is the first method to run that initializes the applet. It can be invoked only
once at the time of initialization.
start(): The start() method contains the actual code of the applet and starts the applet. It is invoked
immediately after the init() method is invoked.
stop(): The stop() method stops the execution of the applet. The stop () method is invoked whenever
the applet is stopped, minimized, or moving from one tab to another in the browser, the stop() method
is invoked.
destroy(): The destroy() method destroys the applet after its work is done. It is invoked when the
applet window is closed or when the tab containing the webpage is closed. It removes the applet object
from memory and is executed only once.
paint(): The paint() method belongs to the Graphics class in Java. It is used to draw shapes like circle,
square, trapezium, etc., in the applet. It is executed after the start() method and when the browser or
applet windows are resized.
Method 1: init()
This is the first method to be called. Variables can be initialized here. This method can be called only once
during the run time of the applet. It is invoked at the time of Initialization Syntax:
This method is called after init() method. start() method is used for starting the applet. It is also called to restart
an applet after it has been stopped. i.e. to resume the applet.
Syntax:
public void start()
{ // To start the applet code } Method 3: paint() void paint(Graphics g){ } paint() method is used for painting
any shapes like square, rectangle, trapeziums, etc. paint() method has one parameter of type Graphics Class,
this Graphics class enables the painting features in an applet. This parameter will contain the graphics context,
which is used whenever output for the applet is required.
It is invoked every time the browser is stopped, minimized or when there is an abrupt failure in the application.
After stop()method called, we can also use start() method whenever we want. This method mainly deals with
clean up code. 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.
Syntax:
public void stop()
{ // To stop the applet code }
Method 5: destroy()
Destroy() method is used to destroy the application once we are done with our applet work. It can be invoked
only once. Once applet is destroyed we can’t start() the applet (we cannot restore the applet again). The
destroy() method is called when the environment determines that your applet needs to be removed completely
from memory.
Syntax:
public void destroy()
{ // To destroy the applet }
AWT: (abstract window toolkit)
AWT stands for Abstract window toolkit is an Application programming interface (API) for creating
Graphical User Interface (GUI) in Java. It allows Java programmers to develop window-based applications.
AWT provides various components like button, label, checkbox, etc. used as objects inside a Java Program.
AWT provides various components like button, label, checkbox, etc. used as objects inside a Java Program.
AWT components use the resources of the operating system, i.e., they are platform-dependent, which means,
component's view can be changed according to the view of the operating system. The classes for AWT are
provided by the Java.awt package for various AWT components.
GRAPHICS CLASS METHODS UPDATE() PAINT(), DRAWING LINES, RECTANGLE,
CIRCLES, POLYGONS
4
The graphics class is an abstract class that provides the means to access different graphics devices. The actual
work is done by concrete classes that are closely tied to a particular platform. Once we have a graphics object,
we can call all the methods of the graphics class without caring about platform specific classes. We rarely
need to create a graphics object. A graphics object is always available when you override a components paint()
and update() methods. It is the sole parameter of the component.paint() and component.update(). We can also
get a graphics context of a component by calling component.getGraphics(). The graphics class defines a
number of drawing functions. Each shape can be drawn edge-only (or) filled.
Drawing strings:
These methods let you draw text string on the screen. The coordinates refer to the left end of the text baseline
(a) public abstract void drawstring(String text, int x, int y)
(b) public void drawChars (char text[], int offset, int length, int x,
int y) (c) public void drawBytes (byte text[], int offset, int length, int x, int
y) Drawing lines:
Public abstract void drawLine (int x1, int y1, int x2, int y2) Example:
import java.awt.Graphics; // This applet draws a pair of lines using the Graphics class
import java.applet.Applet; public class DrawLines extends Applet
{
// Draw a line from the upper-left corner to the point at (40, 20) g.drawLine(0,
0, 40, 20);
}
}
/* <applet code=DrawLines width = 150 height = 150> </applet> */
Drawing rectangle: import java.awt.*; import java.applet.*;
{
public void paint(Graphics g)
{
g.drawRect(10,10,60,50);
g.fillRect(100,100,100,0);
g.drawRoundRect(190,10,60,50,15,15);
5
g.fillRoundRect(70,90,140,100,30,40);
} }
Drawing ellipses, circles and ovals:
import java.awt.*; import java.applet.*;
public class DrawEllipses extends Applet
{
g.drawOval(10, 10, 50, 50);
g.setColor(Color.GREEN);
g.fillOval(100, 10, 75, 50);
g.setColor(Color.cyan);
g.drawOval(190, 10, 90,30);
g.fillOval(70, 90, 140, 100);
} }
/* <applet code="DrawEllipses" width=300 height=200></applet> */ Drawing
polygons:
{
g.drawPolygon(xCoords, yCoords, 6);
g.fillPolygon(xFillCoords, yCoords, 6);
}}
/* <applet code=DrawFillPolygon width=300 height=300></applet> */
PROCESS OF WORKING WITH COLOR FONT CLASSES
Process of working with colours:
The AWT colour system allows us to specify any colour we want. Colour is encapsulated by the colour class.
Colour class defines several constrants to specify a number of common colours.
Constructors:
• color(int red, int green, int blue)
• color(int rgb value)
6
}
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.drawString("Applet background example", 0, 50);
} }
Using color for creating buttons
import java.awt.*; public class
ButtonExample { public static void
main (String[] args) {
f.add(b);
f.setSize(400,400);
7
f.setLayout(null);
f.setVisible(true);
} }
Process of working with fonts
The AWT supports multiple type fonts. Years ago, fonts emerged from the domain of traditional type setting
to become an important part of computer-generated documents and displays. The AWT provides flexibility
by abstracting font-manipulation operations and allowing for dynamic selection of fonts. Fonts have a family
name, a logical font name, and a face name. The family name is the general name of the font, such as courier.
The logical name specifies a name, such as monospaced, that is linked to an actual font at runtime. The face
name specifies a specific font, such as courier italic. Fonts are encapsulated by the font class.
Display fonts
/* <applet code=”JavaFontExample” width=550 height=60></applet>*/
import java.applet.Applet; import java.awt.Font; import
java.awt.Graphics; public class JavaFontExample extends Applet
{
public void paint(Graphics gph)
{
Font font= new Font("Courier", Font.PLAIN, 20);
gph.setFont(font); gph.drawString("Javatpoint is the best learning
platform.", 12, 45); } }
BorderLayout : The border layout manager. Border layouts use five componentsNorth, South, East, West, and
Center.
Button : Creates a push button control.
Canvas : A blank, semantics-free window.
Checkbox : Creates a check box control.
CheckboxGroup : Creates a group of check box controls.
CheckboxMenuItem : Creates an on/off menu item.
Choice : Creates a pop-up list.
Color : Manages colors in a portable, platform-independent fashion.
Component : An abstract superclass for various AWT components.
Container : A subclass of Component that can hold other components.
Cursor : Encapsulates a bitmapped cursor.
Dialog : Creates a dialog window.
Dimension : Specifies the dimensions of an object. The width is stored in width, and the height is stored in
height.
EventQueue : Queues events.
Font : Encapsulates a type font.
Frame : Creates a standard window that has a title bar, resize corners, and a menu bar.
Graphics : Encapsulates the graphics context. This context is used by the various output methods to display
output in a window. Featurs of AWT in java
The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. AWT features
include:
A set of native user interface components
A robust event-handling model
Graphics and imaging tools, including shape, color, and font classes
Layout managers, for flexible window layouts that do not depend on a particular window size or screen
resolution
Data transfer classes, for cut-and-paste through the native platform clipboard. Supports wide range
of libraries for creating graphics.
AWT UI Aspects:
UI elements: Thes are the core visual elements the user eventually sees and interacts with. GWT provides a
huge list of widely used and common elements varying from basic to complex which we will cover in this
tutorial.
Layouts: They define how UI elements should be organized on the screen and provide a final look and feel to
the GUI (Graphical User Interface). This part will be covered in Layout chapter.
Behavior: These are events which occur when the user interacts with UI elements. This part will be covered
in Event Handling chapter.
Hierarchy of AWT:
The hierarchy of Java AWT classes are given below.
9
AWT components:
AWT components in java are platform-dependent components that mean a display of components on a
graphical user interface depends on the underlying operating system; AWT components are generally heavy
components that make high use of operating system resources.
Containers: 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. It is basically a screen where the where the components are placed at their specific
locations. Thus it contains and controls the layout of components.
There are four types of containers in Java AWT:
• Window
• Panel
• Frame
• Dialog
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. We need to create an instance of Window class to
create this container.
Panel: The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc. An
instance of Panel class creates a container, in which we can add components.
Frame: The Frame is the container that contain title bar and border and can have menu bars. It can
have other components like button, text field, scrollbar etc. Frame is most widely used container while
developing an AWT application.
By instantiating frame class (association)
By extending frame class (inheritance)
Dialog: dialog class is also a subclass of window and comes with the border as well as the title. Dialog
class instance always needs an associated frame class instance to exist.
Button: The Button class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. In the package
java.awt.button class.
public class Button extends Component implements Accessible
Text field: java.awt.Textfiels class can creates a single line of text box. The object of a TextField class
is a text component that allows a user to enter a single line text and edit it. It inherits TextComponent
class, which further inherits Component class.
public class TextField extends TextComponent
10
Lable: java.awt.lable class can provide descriptive text string that is visible on GUI. The object of the
Label class is a component for placing text in a container. It is used to display a single line of read only
text.
public class Label extends Component implements Accessible
Canvas: The Canvas class controls and represents a blank rectangular area where the application can
draw or trap input events from the user. It inherits the Component class.
Creating frame window by instantiating frame class:
import java.awt.*; public
class Testawt
{
Testawt()
{
Frame fm=new Frame();
Label lb= new Lable(“welcome to java graphics”);
fm.add(lb); frame fm.setSize(300,300);
fm.setVisible(true);
{
Testawt ta=new Tesrawt();
}}
Creating frame window by extending frame class
import java.awt.*; import java.awt.event.*; public
class Textawt extends Frame
{
Public Testawt() {
}
DESIGN FRAME WINDOW
Frame is a top-level container which is used to hold components in it with border and title. Components
such as a button, checkbox, radio, button, menu, list, table… etc. it uses BorderLayout as default layout
manager. We can use frame class to create child windows with in applet.
Constructors:
public Frame()—creates a frame window with no name. public
Frame()—creates a frame window with a name.
Methods:
Public void add(component comp)—used adda the component, comp, to the container frame.
Public void remove(component comp)—used remove a component, comp, from the container, frame.
Creating frame window import java.awt.*; public class AwtProgram1 { public
AwtProgram1()
{
Frame f = new Frame();
Button btn=new Button("Hello World");
btn.setBounds(80, 80, 100, 50);
Background events:
i. Those events that require the interaction of end user are known as background events. ii.
Operating system interrupts, hardware/software failure, timer expires etc.
SOURCES OF EVENTS
Event sources:
• Events are generated by an object called source.
• An event is generated when there is transition in the object.
• Event sources can generate various types of events.
• The event source must register itself to a listener to notify users about occurrence of specific event.
Syntax: public void addTypeListener(TypeListener t1) Event
sources with description:
This model was introduced with JDK 1.0, the starting version of java in 1995. In this model if the event is
not handled, it propagate through the hierarchy of containers like panel, frame, JVM, OS etc. in search of
suitable event handler which will be time consuming. Hierarchical event model is a big overhead to the
operating system and thereby programs execute slow. This model was discarded immediately in JDK 1.1
version and replaced by delegation event model.
2. Delegation event model:
The Delegation Event model is defined to handle events in GUI programming languages. The GUI stands for
Graphical User Interface, where a user graphically/visually interacts with the system. 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.
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.
example: public void addTypeListener (TypeListener e1)
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.
Example:
Event Classes
An event is some of occurrence. An action is usually initiated by the user through an action over a GUI
component. Generally, every GUI component is capable to generate an event with human interaction.
HANDLING MOUSE EVENTS
MOUSE_PRESSED: BUTTON1_MASK BUTTON1
MOUSE_PRESSED: BUTTON2_MASK BUTTON2
MOUSE_RELEASED: BUTTON1_MASK BUTTON1
MOUSE_CLICKED: BUTTON1_MASK BUTTON1
MOUSE_RELEASED: BUTTON2_MASK BUTTON2
MOUSE_CLICKED: BUTTON2_MASK BUTTON2 Example:
import java.awt.*;
import java.applet.*; import java.awt.event.*; public class mou extends Applet
implements MouseListener,MouseMotionListener
15
{ public void
init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent e)
{
showStatus("mouse clicked : "+e.getX()+","+e.getY());
}
public void mouseEntered(MouseEvent e)
{
showStatus("mouse entered : "+e.getX()+","+e.getY());
for(int i=0;i<100000;i++);
}
public void mouseExited(MouseEvent e)
{
showStatus("mouse exited : "+e.getX()+","+e.getY());
}
public void mousePressed(MouseEvent e)
{
showStatus("mouse pressed : "+e.getX()+","+e.getY());
}
public void mouseReleased(MouseEvent e)
{
showStatus("mouse released : "+e.getX()+","+e.getY());
}
public void mouseMoved(MouseEvent e)
{
showStatus("mouse moved : "+e.getX()+","+e.getY());
}
public void mouseDragged(MouseEvent e)
{
16
/*
<applet code="Key" width=300 height=400>
</applet>
*/
public class Key extends Applet implements
KeyListener
{
int X=20,Y=30;
String msg="KeyEvents--->"; public void
init()
{
addKeyListener(this);
requestFocus();
setBackground(Color.green);
setForeground(Color.blue);
}
17
{
case KeyEvent.VK_UP:
showStatus("Move to Up");
break; case
KeyEvent.VK_DOWN:
showStatus("Move to Down");
break; case
KeyEvent.VK_LEFT:
showStatus("Move to Left");
break; case
KeyEvent.VK_RIGHT:
showStatus("Move to Right");
break;
}
repaint();
}
public void keyReleased(KeyEvent k)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent k)
{
msg+=k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
18
g.drawString(msg,X,Y);
}
}
AWT CONTROLS IN APPLET PROGRAMMING
These controls are the components that allows a user to interact with our application in various ways. Layout
manager automatically positions the controls within a container so we can say that the appearance of
window is a combination of awt controls and layout manager.
Label: A Label object is a component for placing text in a container.
Button: This class creates a labeled button.
Check Box: A check box is a graphical component that can be in either an on (true) or off (false) state.
Check Box Group: The CheckboxGroup class is used to group the set of checkbox.
List: The List component presents the user with a scrolling list of text items.
Text Field: A TextField object is a text component that allows for the editing of a single line of text.
Text Area: A TextArea object is a text component that allows for the editing of a multiple lines of text.
Choice: A Choice control is used to show pop up menu of choices. Selected choice is shown on the top of the
menu.
Canvas: A Canvas control represents a rectangular area where application can draw something or can receive
inputs created by user.
Image: An Image control is superclass for all image classes representing graphical images.
Adding and removing control:
To include a control in a window, we must add it to the window. So we must first create an instance of the
desired control and then add it to a window by calling add(), which is defined by container.
Component add(Component compObj)
Sometimes we will want to remove a control from a window when the control is no longer needed. For this
we can call remove(). This method is also defined by container.
void remove(Component obj)
1. Label: The easiest control to use is a label. A label is an object of type label, and it contains a string,
which it display. Is a passive control that do not support interaction with the user. Label(String str)
2. Button: 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 object type buttons. Button(String
str)
3. Check boxes: a checkbox is a control that is used to turn an option on (or) off. It consists of a small box
that can either contain a checkmark or not. Checkbox(String str)
4. Checkbox Group: It is possible to creatr a set of mutually exclusive check boxes in which one and only
one checkbox in the group can be checkd at any one time. Checkbox getSelectedCheckbox()
5. Lists: The list class provides a compact, multiple-choice, scrolling selection list. It can also be created
to allow multiple selections. List provides these constructors. List(int numRows)
Sample java program to handle mouse and keyboard event in AWT import java.awt.*;
import java.awt.event.*; public class EventHandlingExample extends Frame implements
MouseListener, KeyListener { public EventHandlingExample() {
19
}
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked");
}
} }
Q). Is it possible to implement method overriding concept in java without inheritance? If possible, give
reasons, if not, give reasons with suitable example.
A). No, it is not possible to implement method overriding in Java without inheritance. Method overriding is a
concept that allows a subclass to provide a different implementation of a method that is already defined in its
superclass. In Java, method overriding is directly tied to inheritance, where a subclass inherits the methods of
its superclass and can choose to override them. The main reason why method overriding requires inheritance
is that it relies on the "is-a" relationship between classes. By inheriting from a superclass, the subclass can be
considered as an instance of both the subclass and the superclass. This enables the subclass to override the
superclass's methods with its own implementation while still maintaining the ability to be treated as an instance
of the superclass.
Example:
class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
} class Cat extends Animal
{
@Override
public void makeSound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
}}
21
Q). Explain button and text field AWT controls in java with an example program.
A). import java.awt.*; import java.awt.event.*;
// Text field
Label nameLabel = new Label("Name:");
textField = new TextField(20);
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == submitButton) {
} }