Explain how to pass parameter to an applet ? Write an applet to accept username in the form of parameter and print “Hello ”.
Passing Parameters to Applet
• User defined parameters can be supplied to an applet
using <PARAM…..> tags.
• PARAM tag names a parameter the Java applet needs to
run, and provides a value for that parameter.
• PARAM tag can be used to allow the page designer to
specify different colors, fonts, URLs or other data to be
used by the applet.
To set up and handle parameters, two things must be done.
1. Include appropriate <PARAM..>tags in the HTML document.
The Applet tag in HTML document allows passing the
arguments using param tag. The syntax of <PARAM…> tag
<Applet code=”AppletDemo” height=300 width=300>
<PARAM NAME = name1 VALUE = value1> </Applet>
NAME:attribute name
VALUE: value of attribute named by
corresponding PARAM NAME.
2. Provide code in the applet to parse these parameters. The
Applet access their attributes using the getParameter method.
The syntax is : String getParameter(String name);
Program
import java.awt.*;
import java.applet.*;
public class hellouser extends Applet
{
String str;
public void init()
{
str = getParameter("username");
str = "Hello "+ str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
<HTML>
<Applet code = hellouser.class width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc> </Applet>
</HTML>
(OR)
import java.awt.*;
import java.applet.*;
/*<Applet code = hellouser.class width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>*/
public class hellouser extends Applet
{
String str;
public void init()
{
str = getParameter("username");
str = "Hello "+ str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}