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

Unit 1

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

R C Technical Institute

Computer Engineering Department


Advance Java Programming (3360701)
Unit-1 Java Apple ts
Applet Programming
 Applets are small Java applications that can be accessed on an Internet server, transported over
Internet, and can be automatically installed and run as a part of a web document.
 An Applet is a Java class that extends the java.applet.Applet class.
 An Applet class does not have any main() method.
 It is viewed using JVM. The JVM can use either a plug-in of the Web browser or a separate runtime
environment to run an applet application that is “appletviewer”.
 Applets are designed to be embedded within an HTML page.
 When a user views an HTML page that contains an applet, the code for the applet is downloaded
to the user's machine.

Local Applet and Remote Applet


Local Applet Remote Applet
 It is developed and stored in local system.  It is developed and stored on remote
system.
 The web page will search the local system  The web page will require an internet
directories, find the local applet and execute connection to locate and load the remote
it. applet from the remote computer.
 Execution of local applet does not require  Execution of remote applet must require
internet connection. internet connection.
 Example:  Example:
<applet codebase="path" code="xyz.class" <applet codebase="URL " code="xyz.class"
width=120 height=120 > width=120 height=120 >
</apple> </applet>
path = Path of an applet on local system. URL = Url at which applet is located.

Applet and Application


Applet Application
 It requires some third party tool like a  It called as stand-alone application as
browser to execute. application can be executed from command
prompt.
 In applet main() method is not present.  In application main() method is present.
 It cannot access anything on the system  It can access any data or software available
except browser’s services. on the system.
 It requires highest security for the system as  It does not require any security.
they are untrusted.
 Applet starts execution after init() method.  Applications start execution after main()
method.

1 Dept: CE AJava Programming


ProProgramming(3350703)
Life Cycle of Applet

 In applet life cycle, there are 5 stages which are given in above figure and these stages are
represented by 5 methods.
 These methods called automatically by the browser whenever required for the execution of the
applet.
 No need to call these methods by the user.
 Following are the methods of the life cycle :
1) init() method
2) start() method
3) paint() method
4) stop() method
5) destroy() method
 All above mention methods are defined in java.applet.Applet class except paint() method.
 paint() method is defined in java.awt.Container class.
1) init() :
o It is used to initialize the Applet. It is invoked only once.
o This method is called before all the other methods.

2) Start() :
o This method is automatically called after the browser call the init method. It is also called
whenever the user returns to the page containing the applet after having gone off to other
pages.
3) Stop() :
o An applet comes in idle state when its execution has been stopped either implicitly or
explicitly.
o An applet is implicitly stopped when we leave the page containing the currently running
applet.
o An applet is explicitly stopped when we call stop() method to stop its execution.
o So, this method called repeatedly in the same applet.

2 Dept: CE AJava Programming


ProProgramming(3350703)
4) Destroy():
o This method is only called when the browser shuts down normally. It is called only once.
o It is called just before an applet object is removed from the memory.
5) Paint():
o It is invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser.
o The paint() method is actually inherited from the java.awt.
o It provides Graphics class object that can be used for drawing oval, rectangle etc.
 There are two ways to run an applet :
1) Using HTML file
2) Using AppletViewer tool

 Example using HTML file :


// Demo.java //Applet.html
import java.applet.Applet; <html>
import java.awt.Graphics; <body>
public class Demo extends Applet <applet code="Demo.class"
{ width="300" height="300">
public void paint(Graphics g) </applet>
{ </body>
g.drawString("welcome",200,200); </html>
}
}

 Example using AppletViewer tool :


//Demo.java
/*
<applet code="Demo.class" width="300" height="300">
</applet>
*/

import java.applet.Applet;
import java.awt.*;
public class Demo extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome",200,200);
}
}

 To run these above two code write following code in prompt :


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

3 Dept: CE AJava Programming


ProProgramming(3350703)
Applet Tag
 The HTML <applet> tag specifies an applet.
 It is used for embedding a Java applet within an HTML document.
 Syntax :

< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>
o Attribute written in square brackets are optional.
Attribute Value Description
CODEBASE url URL of the directory or folder that contains the applet code.
CODE .Class file Name of the file that contains the applet's compiled Applet
subclass.
ALT alternateText It specifies any text that should be displayed if the browser
understands the APPLET tag but can't run Java applets.
NAME appletInstanceName It specifies a name for the applet instance, which makes it
possible for applets on the same page to find (and
communicate with) each other.
WIDTH pixels It givea the initial width (in pixels) of the applet display area.
HEIGHT pixels It give a the initial height (in pixels) of the applet display area.
ALIGN alignment It specifies the alignment of the applet.
VSPACE pixels It specifies the number of pixels above and below the applet
HSPACE pixels It specifies the number of pixels on each side of the applet
PARAM Attribute Name and The PARAM tag allows you to specify applet-specific
NAME and Value arguments in an HTML page. Applets access their attributes
VALUE with the getParameter( ) method.

4 Dept: CE AJava Programming


ProProgramming(3350703)
 Example :

//AppletParameter.html //AppletParameter.java
<HTML> import java.applet.*;
<HEAD> import java.awt.*;
<TITLE>Java Applet Example</TITLE>
</HEAD> public class AppletParameter extends Applet
<BODY> {
<APPLET CODE=" AppletParameter.class" public String myString;
WIDTH="400" HEIGHT="50"> public void init()
<PARAM NAME="Hello" {
VALUE="Hello, Welcome to Java myString = getParameter("Hello");
World :)" > }
</APPLET> public void paint(Graphics g)
</BODY> {
</HTML> g.setColor(Color.red);
g.drawString(myString, 20, 20);
}
}

Methods of Applet
Methods Description
void init( ) It Called when an applet begins execution.
void start( ) It Called by the browser when an applet should start
(or resume) execution.
void stop( ) It Called by the browser to suspend execution of the
applet. Once stopped, an applet is restarted when
the browser calls start( ).
void destroy( ) It Called by the browser just before an applet is
terminated. It released all resources allocated to the
applet.
String getAppletInfo( ) Returns a string that describes the applet.
URL getCodeBase( ) Returns the URL associated with the invoking applet.
URL getDocumentBase( ) Returns the URL of the HTML document that invokes
the applet.
String getParameter(String paramName) Returns the parameter associated with paramName.
If not found then return NULL.
String[ ] [ ] getParameterInfo( ) Returns information about the parameters that are
understood by this applet.
boolean isActive( ) Returns true if the applet has been started else
returns False.
void play(URL url) Plays the audio clip at the specified absolute URL.
void play(URL url, String clipName) Plays the audio clip is found at the location specified
by url with the name specified by clipName.

5 Dept: CE AJava Programming


ProProgramming(3350703)
Methods Description
void resize(Dimension dim) Resizes the applet according to the dimensions
specified by dim. Dimension class contains two field
width and height.
void resize(int width, int height) Resizes the applet according to the dimensions
specified by width and height.
void showStatus(String str) Displays str in the status window of the browser or
applet viewer.
AudioClip getAudioClip(URL url) Returns the AudioClip object specified by the url.
AudioClip getAudioClip(URL url, Returns the AudioClip object specified by
String clipName) the url and name specified by clipName.
Image getImage(URL url) Returns the Image object specified by the url.
Image getImage(URL url, Returns the Image object specified by
String imageName) the url and name specified by imageName.
AppletContext getAppletContext( ) Returns the context associated with the applet.

 Example : A simple applet that sets the foreground, background colors, draw rectangle, fill
rectangle, get base code ,get document code and display as a string.

import java.awt.*;
import java.applet.*;
import java.net.*;
/*
<applet code="AppletMethods" width=10000 height=500 name = "HelloApplet">
</applet>
*/
public class AppletMethods extends Applet
{
String msg,displayUrl;
//set the foreground and background colors.
public void init()
{
setBackground(Color.green);
setForeground(Color.black);
msg = "Inside init method ----";
}
//Initialize the string to be displayed.
public void start()
{
msg += " Inside start method ---";
}

6 Dept: CE AJava Programming


ProProgramming(3350703)
//Display msg in applet window.
public void paint(Graphics g)
{
msg += " Inside paint method .";
g.drawString(msg, 20, 10);
URL url = getCodeBase(); // get the path of the folder in which applet placed
displayUrl = "Code Base ---"+url;
g.drawString(displayUrl,20,100);

url = getDocumentBase(); // get the path upto the source file


displayUrl = "Document Base ---"+url;
g.drawString(displayUrl,20,150);
// Draw Rectangle needs (x,y,width,height) four arguments
g.drawRect(200, 100, 100, 100);
showStatus("Welcome...");
}
}

Output :

7 Dept: CE AJava Programming


ProProgramming(3350703)
Component Class
 A component is an object having a graphical representation that can be displayed on the screen
and that can interact with the user.
 Examples of components are the buttons, checkboxes, radio buttons and textbox of a typical
graphical user interface.

Methods Description
void add(Component c) inserts a component on this component.
void setSize(int width,int height) sets the width and height of the component.
void setForeground(Color) Set the foreground or background color for the
void setBackground(Color) component
Color getForeground() Get the foreground or background color for the
Color getBackground() component.
void setName(String) Set or get the name of the component
String getName()
void setEnabled(boolean) Set or get whether the component is enabled.
boolean isEnabled()
void setVisible(boolean) Set or get whether the component is visible.
boolean isVisible()
int getWidth() Get the current width or height of the component
int getHeight() measured in pixels.
int getX() Get the current x or y coordinate of the component
int getY()
void repaint() Request that all or part of the component be
void repaint(int, int, int, int) repainted.
void remove(int) Remove one of or all of the components from this
void remove(Component) container.
void removeAll()
void setLayout(LayoutManager) Set or get the component's layout manager.
LayoutManager getLayout()
Rectangle getBounds() Gets the bounds of this component in the form of
Rectangle getBounds(Rectangle) a Rectangle object.
void setBounds(int, int, int, int) Moves and resizes this component.
void setBounds(Rectangle)
 Example : Write a applet program to create simple GUI consist of Button, Radio Button, TextField, Checkbox
and Label.

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

public class AppletComponent extends Applet


{

8 Dept: CE AJava Programming


ProProgramming(3350703)
// Button to click
Button submit;
// A textField to get text input
TextField text;
// A group of radio buttons necessary to only allow one radio button to be selected at the
//same time.
CheckboxGroup radioGroup;
// The radio buttons to be selected
Checkbox male;
Checkbox female;
// An independant selection box
Checkbox option;
//Label dispaly as text only
Label name;

public void init()


{
// Tell the applet not to use a layout manager.
setLayout(null);
// Initialize the button and give it a text.
submit = new Button("Submit");
// Text and length of the field
text = new TextField("Insert name..",100);
// initialize the radio buttons group
radioGroup = new CheckboxGroup();
// first radio button. Gives the label text, tells to which group it belongs and sets the
//default state selected(true)
male = new Checkbox("Male", radioGroup,true);
// same but not selected
female = new Checkbox("Female", radioGroup,false);
// Label and state of the checkbox
option = new Checkbox("Option",false);
// Label named Name
name = new Label("Name : ");

// now we will specify the positions of the GUI components. This is done by
specifying the x and y coordinate and the width and height.
submit.setBounds(100,200,100,30);
text.setBounds(20,50,150,25);
male.setBounds(20,120,100,30);
female.setBounds(120,120,100,30);
option.setBounds(20,160,100,30);
name.setBounds(20, 15, 50, 50);

// now that all is set we can add these components to the applet.
add(submit);
add(text);

9 Dept: CE AJava Programming


ProProgramming(3350703)
add(male);
add(female);
add(option);
add(name1);
}
}

Output :

10 Dept: CE AJava Programming


ProProgramming(3350703)

You might also like