[an error occurred while processing this directive]

Applet - Passing Parameter in Java Applet

                         

Introduction

Java applet has the feature of retrieving the parameter values passed from the html page. So, you can pass the parameters from your html page to the applet embedded in your page. The param tag(<parma name="" value=""></param>) is used to pass the parameters to an applet. For the illustration about the concept of applet and passing parameter in applet, a example is given below.

In this example, we will see what has to be done in the applet code to retrieve the value from parameters. Value of a parameter passed to an applet can be retrieved using getParameter() function. E.g. code:

String strParameter = this.getParameter("Message");

Printing the value:

Then in the function paint (Graphics g), we prints the parameter value to test the value passed from html page. Applet will display "Hello! Java Applet"  if no parameter is passed to the applet else it will display the value passed as parameter. In our case applet should display "Welcome in Passing parameter in java applet example." message.

Here is the code for the Java Program : 

import java.applet.*; 
import java.awt.*; 
             
public class appletParameter extends Applet {
  
private String strDefault = "Hello! Java Applet.";
  
public void paint(Graphics g) {
    String strParameter = 
this.getParameter("Message");
   
 if (strParameter == null)
    strParameter = strDefault;
    g.drawString(strParameter, 50, 25);
  } 
}

Here is the code for the html program : 

<HTML>
<HEAD>
<TITLE>
Passing Parameter in Java Applet</TITLE>
</HEAD>
<BODY>

This is the applet:<P>
<APPLET code="appletParameter.class" width="800" height="100">
<PARAM name="message" value="Welcome in Passing parameter in java applet example.">
</APPLET>
</BODY>
</HTML>

There is the advantage that if need to change the output then you will have to change only the value of the param tag in html file not in java code.

Compile the program : 
javac appletParameter.java

Output after running the program : 
To run the program using appletviewer, go to command prompt and type appletviewer appletParameter.html Appletviewer will run the applet for you and and it should show output like
Welcome in Passing parameter in java applet example. Alternatively you can also run this example from your favorite java enabled browser.

Try the example online

Download this example.

                         

[an error occurred while processing this directive]