Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java 5 TH

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

1

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

First extends Applet{ public void


paint(Graphics g){

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:

c:\>javac First.java c:\>appletviewer


First.java

LIFE CYCLE OF AN APPLET:


The applet life cycle can be defined as the process of how the object is created, started, stopped, and destroyed
during the entire execution of its application. It basically has five core methods namely init(), start(), stop(),
paint() and destroy().These methods are invoked by the browser to execute.

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:

public void init()


{ // To initialize objects }
Method 2: start()
3

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.

Syntax: public void paint(Graphics


graphics)

{ // Any shape's code } Method


4: stop()

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

{ public void paint(Graphics


g)

{
// Draw a line from the upper-left corner to the point at (40, 20) g.drawLine(0,
0, 40, 20);

// Draw a line from (20, 70) to (100, 150) g.drawLine(20,


70, 100, 150);

}
}
/* <applet code=DrawLines width = 150 height = 150> </applet> */
Drawing rectangle: import java.awt.*; import java.applet.*;

/* <applet code="Rectanlge" width=300 Height=300></applet> */ public


class Rectanlge extends 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

{ public void paint(Graphics g)

{
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:

import java.awt.Graphics; public class DrawFillPolygon


extends java.applet.Applet

{ int xCoords[] = { 50, 200, 300, 150, 50, 50 }; int


yCoords[] = { 100, 0, 50, 300, 200, 100 }; int
xFillCoords[] = { 450, 600, 700, 550, 450, 450 };
public void paint(Graphics g)

{
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

• color(float red, float green, float blue)


Methods:
• int getRed()
• int getGreen()
• int getBlue()
• int getRGB()-to obtain a packed, RGB representation of color:
• void setColor(Color newColor)-it is used to set current with specified color class object.
Example:
1. Color c=new Color(225,100,100): then use object c for setting color
2. setColor(c): it sets color withspecified ratios of red, green and blue.
3. Color getColor():used to obtain current color. It returns color class object which is currently assigned
 Color class defines some constants some of them are;
I. Color.black
II. Color.blue
III. Color.gray
IV. Color.green
Example for using colors
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class Main extends Applet {


public void init() {
setBackground(Color.WHITE);

}
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) {

Frame f = new Frame("Button Example");


Button b = new Button("Click Here");
b.setBounds(50,100,80,30);

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); } }

Creating and selecting a font:


To create a new font, construct a font object that describes that font. Constructor has this general form
 Font(string fontName, int fontStyle, intpointSize).
a) Here, fontName specifies the name of the desired font.
b) The name can be specified using either the logical (or) face name.
c) All java environments will support the following fonts: dialog, dialogInput, SansSERIF, Serif,
and monospaced.
d) Dialog is the font used by your systems dialog boxes, dialog is also the default if you don’t
explicitly set a font
e) The style of the font is specifie by fontStyle
f) It may consist of one(or) more of these three constants:
 Font.PLAIN, Font.BOLD and Font.ITALIC. to combine style or them together.
a) void setFont(Font fontObj)
AWT CLASSES
The AWT classes are contained in the java.awt package. It is one of Java’s largest packages. Fortunately,
because it is logically organized in a top-down, hierarchical fashion, it is easier to understand and use than
you might at first believe.
Class and Description
AWTEvent : Encapsulates AWT events.
AWTEventMulticaster : Dispatches events to multiple listeners.
8

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);

} public static void main(String


args[])

{
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() {

Button btn=new Button(“Hello World”);


add(btn); setSize(400,500);
setTitle(“Frame Window”);
setLayout(new FlowLayout());
setVisible(true);

}public static void main(String[]args)


{
Testawt ta= new Testawt();
11

}
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);

f.add(btn); //adding a new Button.


f.setSize(300, 250); //setting size.
f.setTitle("JavaTPoint"); //setting title.
f.setLayout(null); //set default layout for frame.
f.setVisible(true); //set frame visibility true.
}

public static void main(String[] args) {


AwtProgram1 awt = new AwtProgram1(); //creating a frame.
} }
TYPES OF EVENTS
Event: change in the state of an object is known as event. Event describes the change in state of source.
Events are generated as result of user interaction with the graphical user interface components. For
example clicking on a button. Moving the mouse, entering a character through keyboard.. etc.
Types of events:
 Foreground events:
i. Those events which require the direct interaction of user
ii. They are generated as consequences of a person interacting with the graphics components in
graphical user interface.
iii. Clicking on a button, scrolling the page with mouse etc.
12

 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:

Button: Generates action events when the button is pressed.


Check box: Generates item events when the check box is selected or deselected.
Choice: Generates item events when the choice is changed.
List: Generates action events when an item is double-clicked; generates item events when an item is
selected or deselected.
Menu item: Generates action events when a menu item is selected; generates item events when a checkable
menu item is selected or deselected.
Scroll bar: Generates adjustment events when the scroll bar is manipulated.
Text components: Generates text events when the user enters a character.
Window: Generates window events when a window is activated, closed, deactivated, deiconified, iconified,
opened, or quit.
DIFFERENT EVENT CLASSES
The classes that represent events are at the core of Java’s event handling mechanism. Thus, a discussion of
event handling must begin with the event classes. At the root of the Java event class hierarchy is EventObject,
which is in java.util. It is the superclass for all events.
• EventObject(Object src)--Here, src is the object that generates this event.
EventObject defines two methods: getSource( ) and toString( ). The getSource( ) method returns the source of
the event. Its general form is shown here:
• Object getSource( )
As expected, toString( ) returns the string equivalent of the event.
The class AWTEvent, defined within the java.awt package, is a subclass of EventObject. It is the superclass
(either directly or indirectly) of all AWT-based events used by the delegation event model. Its getID( ) method
can be used to determine the type of the event. The signature of this method is shown here:
• int getID( )
Additional details about AWTEvent are provided at the end of Chapter 26. At this point, it is important to
know only that all of the other classes discussed in this section are subclasses of AWTEvent. EventObject is
a superclass of all events. AWTEvent is a superclass of all AWT events that are handled by the delegation
event model. The package java.awt.event defines many types of events that are generated by various user
interface elements.
13

• Event Class : Description


ActionEvent: Generated when a button is pressed, a list item is double-clicked, or a menu item is selected.
ActionEvent(Objectsrc, int type, String cmd)
AdjustmentEvent: Generated when a scroll bar is manipulated.
AdjustmentEvent(Adjustable src, int id, int type, int data)
ComponentEvent: Generated when a component is hidden, moved, resized, or becomes visible.
ComponentEvent(Component src, int type)
ContainerEvent: Generated when a component is added to or removed from a container.
ContainerEvent(Component ssrc, int type, Component comp)
FocusEvent: Generated when a component gains or loses keyboard focus.
FocusEvent(Component src, int type)
EVENT LISTENER INTERFACES
Listeners are created by implementing one or more of the interfaces defined by the java.awt.event package.
When an event occurs, the event source invokes the appropriate method defined by the listener and provides
an event object as its argument.
 Listemer interface--description
ActionListener Interface: This interface defines the actionPerformed( ) method that is invoked when an action
event occurs. void actionPerformed(ActionEvent ae)
AdjustmentListener Interface: This interface defines the adjustmentValueChanged( ) method that is invoked
when an adjustment event occurs. void adjustmentValueChanged(AdjustmentEvent ae)
ComponentListener Interface: This interface defines four methods that are invoked when a component is
resized, moved, shown, or hidden. void componentResized(ComponentEvent ce)
ContainerListener Interface: This interface contains two methods. When a component is added to a container,
componentAdded( ) is invoked. When a component is removed from a container, componentRemoved( ) is
invoked. void componentAdded(ContainerEvent ce)
FocusListener Interface: This interface defines two methods. When a component obtains keyboard focus,
focusGained() is invoked. When a component loses keyboard focus, focusLost( ) is called.
Void focusGained(FocusEvent fe)
EVENT HANDLING MECHANISMS
Java support GUI environment with rich set of GUI components spread in two packages.
• Java.awt
• Javax.swing
The components include likes TextField, Button and List etc. these components can be interacted by the user
and when interacted raises an event. Handling the event so that some code is executed is called event handling
mechanism. For example when a button is checked by the user, it raises actionevent and can be handled by
the programmer.
We have two types of event-handling models
1. Hierarchical event model 2. Delegation event model
1. Hierarchical event model:
14

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

showStatus("mouse dragged : "+e.getX()+","+e.getY());


}
}
/* <body>
<applet code = "mou.class" height = 200 width=200>
</applet>
</body> */
HANDLING KEYBOARD EVENT
When a key is pressed, the event generated is KEY_PRESSED
When a key is released, the event generated is KEY_RELEASED
When a character is typed on the keyboard, that is a key is pressed and then released, the event generated is
int getKeyCode() It is used for getting the integer code associated with a key. It is used for KEY_PRESSED
and KEY_RELEASED events. The keycodes are defined as constants in KeyEvent class
char getKeyChar() This method is used to get the Unicode character of the key pressed. It works with the
KEY_TYPED events KEY_TYPED Example:

import java.awt.*; import


java.awt.event.*; import
java.applet.*;

/*
<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

public void keyPressed(KeyEvent k)


{
showStatus("KeyDown");
int key=k.getKeyCode();
switch(key)

{
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

// Set up the frame setSize(300,


200); setTitle("Event Handling
Example");

// Add event listeners


addMouseListener(this);
addKeyListener(this); //
Make the frame visible
setVisible(true);

}
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked");
}

public void mouseEntered(MouseEvent e) {


System.out.println("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
System.out.println("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
System.out.println("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
System.out.println("Mouse Released");
}
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed: " + e.getKeyChar());
}
public void keyReleased(KeyEvent e) {
System.out.println("Key Released: " + e.getKeyChar());
}
public void keyTyped(KeyEvent e) {
System.out.println("Key Typed: " + e.getKeyChar());
}
20

public static void main(String[] args) {


new EventHandlingExample();

} }
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();

animal.makeSound(); // Output: "Animal makes a sound"


Cat cat = new Cat();

cat.makeSound(); // Output: "Cat meows"


Animal animal2 = new Cat(); // Using polymorphism
animal2.makeSound(); // Output: "Cat meows"

}}
21

Q). Explain button and text field AWT controls in java with an example program.
A). import java.awt.*; import java.awt.event.*;

public class ButtonTextFieldExample extends Frame implements ActionListener {


private TextField textField; private Button submitButton; public
ButtonTextFieldExample() {

// Frame setup setTitle("Button and


TextField Example"); setSize(300, 200);
setLayout(new FlowLayout());

// Text field
Label nameLabel = new Label("Name:");
textField = new TextField(20);

// Button submitButton = new


Button("Submit");
submitButton.addActionListener(this); // Adding
components to the frame add(nameLabel);
add(textField); add(submitButton); // Closing
the frame addWindowListener(new
WindowAdapter() { public void
windowClosing(WindowEvent we) {

System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == submitButton) {

String name = textField.getText();


System.out.println("Hello, " + name + "!");
}}
public static void main(String[] args) {
ButtonTextFieldExample example = new ButtonTextFieldExample();
example.setVisible(true);
22

} }

You might also like