Applet New
Applet New
Basics of Applet
Remote Applets:- A remote applet is developed by someone else and stored on a remote
computer connected to the Internet. If our system is connected to the internet, we can
download the remote applet onto our system via at the Internet and run it. To locate and
load a remote applet, we must know the applet’s address on the Web. This address is
known as Uniform Resource Locator (URL) and must be specified in the applet’s HTML
document as the value of the CODEBASE attribute.
Specifying a Remote Applet:
<applet
codebase=http://www.myconnectdemo.com/applets/code="NewApplet.class"
width=120 height=120> </applet>
Attributes of <applet>
tags
ATTRIBUTE NAME VALUES REMARKS
left
right
top
align Specifies the alignment of an applet.
bottom
middle
baseline
alt text Specifies an alternate text for an applet
archive URL Specifies the location of an archive file
Specifies the border around the applet
border pixels
panel
Specifies a relative base URL for applets
codebase URL
specified in the code attribute
height pixels Specifies the height of an applet
Defines the horizontal spacing around an
hspace pixels
applet
Defines the name for an applet (to use in
name name
scripts)
Defines the vertical spacing around an
vspace pixels
applet
Parameter in Applet
We can get any information from the HTML file as a parameter. For this
purpose, Applet class provides a method named getParameter(). Syntax:
public String getParameter(String parameterName)
Example of using parameter in Applet:
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet{
public void paint(Graphics g){
String str=getParameter("msg");
g.drawString(str,50, 50);
}
} //UseParam.java file
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Display numerical value in applet
import java.awt.*;
import java.applet.*;
public class DisplayNumericalValues extends Applet
{
public void paint(Graphics g)
{
int val1 = 10;
int val2 = 20;
int sum = val1 + val2;
String str_sum = "Sum="+String.valueOf(sum);
g.drawString(str_sum,100,200);
}
} // DisplayNumericalValues.java file
Html file
<HTML>
<HEAD>
<TITLE>Display Numerical Values</TITLE>
</HEAD>
<BODY>
<APPLET Code="DisplayNumericalValues.class“
Width=400 Height=300>
</APPLET>
<BODY>
</HTML>
Getting Input from User
import java.awt.*;
import java.applet.*;
public class textFieldDemo extends Applet
{ String str;
int a,b,result;
TextField t1,t2; //Creating Object of TextField Class
public void init()
{ t1=new TextField(10);
t2=new TextField(10);
add(t1);
add(t2);
t1.setText("0");
t2.setText("0"); }
public void paint(Graphics g)
{ str=t1.getText();
a=Integer.parseInt(str);
str=t2.getText();
b=Integer.parseInt(str);
result=a+b;
str=String.valueOf(result);
Html File
<html>
<body>
<applet code="textFieldDemo.class" width="300"
height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Commonly used methods of Graphics class:
public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
public abstract void fillRect(int x, int y, int width, int height): is used to fill
rectangle with the default color and specified width and height.
public abstract void drawOval(int x, int y, int width, int height): is used to draw
oval with the specified width and height.
public abstract void fillOval(int x, int y, int width, int height): is used to fill oval
with the default color and specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
Commonly used methods of Graphics class:
public abstract void drawArc(int x, int y, int width, int height, int startAngle,
int arcAngle): is used draw a circular or elliptical arc.
public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
public abstract void setColor(Color c): is used to set the graphics current color to
the specified color.
public abstract void setFont(Font font): is used to set the graphics current font to
the specified font.
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
} } //GraphicsDemo.java file
Html file
<html>
<body>
<applet code="GraphicsDemo.class" width="300"
height="300">
</applet>
</body>
</html>
Example of displaying image in
applet:
import java.awt.*;
import java.applet.*;
/* <html>
<applet code="DisplayImage.class" width="300" height="300">
</html>*/
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"sonoo.jpg"); }
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this); } }
Animation in Applet
import java.awt.*;
import java.applet.*;
/* <html> <body>
<applet code=“AnimationExample.class" width="300" height="300">
</applet> </body> </html> */
public class AnimationExample extends Applet {
Image picture;
public void init() {
picture =getImage(getDocumentBase(),"bike_1.gif"); }
public void paint(Graphics g) {
for(int i=0;i<500;i++){
g.drawImage(picture, i,30, this);
try{Thread.sleep(100);}
catch(Exception e){} } } }
Event
Change in the state of an object is known as event i.e. event describes the change in
state of source. Events are generated as result of user interaction with the graphical user
interface components.
Types of Event: The events can be broadly classified into two categories:
1. Foreground Events - Those events which require the direct interaction of user. They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering a
character through keyboard,selecting an item from list, scrolling the page etc.
2. Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer expires,
an operation completion are the example of background events.
Event handling
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs.
Java Uses the Delegation Event Model to handle the events. This model defines the standard
mechanism to generate and handle the events. Let's have a brief introduction to this model.
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 Delegation Event Model has the following key participants namely:
Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source object.
Listener - It is also known as event handler. Listener is responsible for generating response to
an event. From java implementation point of view the listener is also an object. Listener waits
until it receives an event. Once the event is received , the listener process the event an then
returns.
The benefit of this approach is that the user interface logic is completely separated
The Delegation Event Model
Contd….
Inthe 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.
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.
public void addTypeListener(TypeListener el)
Here,Type is the name of the event and el is a
reference to the event listener. For example,
The method that registers a keyboard event listener
is called addKeyListener( ).
The method that registers a mouse motion listener
is called addMouseMotionListener( ).
A source must also provide a method that allows a listener to
unregister an interest in a specific type of event. The general
form of such a method is this:
public void removeTypeListener(TypeListener el)
Event Listeners
Methods in Interfaces:
ActionListener
void actionPerformed (ActionEvent ae)
AdjustmentListener
void adjustmentValueChanged (AdjustmentEvent ae)
ComponentListener
void componentResized (ComponentEvent ce)
void componentMoved (ComponentEvent ce)
void componentShown (ComponentEvent ce)
void componentHidden (ComponentEvent ce)
ContainerListener
void componentAdded (ContainerEvent ce)
void componentRemoved (ContainerEvent ce)
FocusListener
void focusGained (FocusEvent fe)
void focusLost (FocusEvent fe)
ItemListener: void itemStateChanged (ItemEvent ie)
KeyListener: void keyPressed (KeyEvent ke)
void keyReleased (KeyEvent ke)
void keyTyped (KeyEvent ke)
MouseListener: void mouseClicked (MouseEvent me)
void mouseEntered (MouseEvent me)
void mouseExited (MouseEvent me)
void mousePressed (MouseEvent me)
void mouseReleased (MouseEvent me)
MouseMotionListener: void mouseDragged (MouseEvent me)
void mouseMoved (MouseEvent me)
TextListener: void textChanged (TextEvent te)
WindowListener: void windowActivated (WindowEvent we)
void windowClosed (WindowEvent we)
void windowClosing (WindowEvent we)
void windowDeactivated (WindowEvent we)
void windowDeiconified (WindowEvent we)
void windowIconified (WindowEvent we)
Handling Keyboard Events
To handle keyboard events, you use the same general
architecture as that shown in the mouse event example in the
preceding section. The difference, of course, is that you will be
implementing the KeyListener interface.
Before looking at an example, it is useful to review how key
events are generated.
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.
Introduction to AWT Package
AWT stands for Abstract Window Toolkit. It is a platform
dependent API for creating Graphical User Interface (GUI) for java
programs.
Component
At the top of the AWT hierarchy is the Component
class. Component is an abstract class that
encapsulates all of the attributes of a visual
component. All user interface elements that are
displayed on the screen and that interact with the
user are subclasses of Component.
It defines over a hundred public methods that are
responsible for managing events, such as mouse and
keyboard input, positioning and sizing the window,
and repainting
Component object is responsible for
remembering the current foreground and
background colors and the currently selected text
font.
Container
The Container class is a subclass of Component. It has
additional methods that allow other Component objects to
be nested within it.
Other Container objects can be stored inside of a
Container (since they are themselves instances of
Component).
Panel
The Panel class is a concrete subclass of Container.
It doesn’t add any new methods; it simply
implements Container. A Panel may be thought of as
a recursively nestable, concrete screen component.
Panel is the superclass for Applet. When screen
output is directed to an applet, it is drawn on the surface
of a Panel object. In essence, a Panel is a window that
does not contain a title bar, menu bar, or border.
Window
The Window class creates a top-level window. A top-level
window is not contained within any other object; it sits directly
on the desktop.
Frame
Frame encapsulates what is commonly thought of as a
“window.” It is a subclass of Window and has a title bar, menu
bar, borders, and resizing corners.
Canvas
Although it is not part of the hierarchy for applet or frame
windows, there is one other type of window that you will find
valuable: Canvas.
Canvas encapsulates a blank window upon which you can
draw.
Useful Methods of Component class
Method Description
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.
BoxLayout
CardLayout
FlowLayout
GridBagLayout
GridLayout
GroupLayout
SpringLayout
ActionListener Interface
The Java ActionListener is notified whenever you click on the button or menu item. It is
notified against ActionEvent. The ActionListener interface is found in java.awt.event
package. It has only one method: actionPerformed().