Java Applet Tutorialshttps://codejava.net/java-se/appletSat, 04 May 2024 12:03:51 -0500Joomla! - Open Source Content Managementen-gbHow to sign a Java applethttps://codejava.net/java-se/applet/how-to-sign-a-java-applethttps://codejava.net/java-se/applet/how-to-sign-a-java-applet

This tutorial explains necessary steps to sign a Java applet, either by using a self-signed certificate (self-signing) or by using a trusted certificate issued by a certificate authority like VeriSign or Thawte. Signing a Java applet is not difficult task, and it should be done correctly. First, let’s take a look why sometimes we need to have a Java applet signed.

 

1. Why need to sign Java applet?

When running inside web browser, Java applets are living in a restricted environment so called “sandbox” – which prevents the applets from accessing system resources and devices such as files, network connections, printers, cameras, microphones, etc – without user-granted permission. This tight security is designed to make users safe from malicious code which always tries to execute automatically without user’s intervention.

The following picture illustrates how such restriction is applied for unsigned applet and signed applet within the sandbox:

java applet sandbox

To access system resources and devices, the applet must be signed with a digital certificate which is issued by a trusted Certificate Authority (CA). Thus the user can trust this applet and grant permission.

For example, you are developing applets that read/write files system, capture video from camera, or record audio from microphone… then you must sign your applets, definitely.

Though there is another way to grant permission for applets through the usage of .java.policy file, but this method is for development only. It’s not suitable for deploying applets on production environment because it requires the user manually put the .java.policy file on their computer. Thus signing the applet is the convenient way.

 

2. A Sample applet for signing

To illustrate the process of signing an applet, this tutorial will work with a sample Java applet that shows an open dialog for browsing files on user’s computer. Here is code of the applet:

package net.codejava.applet;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FileBrowseApplet extends JApplet {

	private JButton button = new JButton("Browse");

	public void init() {
		getContentPane().setLayout(new FlowLayout());
		getContentPane().add(button);

		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				JFileChooser fileChooser = new JFileChooser();
				fileChooser.showOpenDialog(FileBrowseApplet.this);
			}
		});
	}
}

 And here is the HTML page that shows the applet:

<html>
<head><title>File Browse Applet Demo</title></head>
<body>
<center>
	<applet id="FileApplet"
			code = "net.codejava.applet.FileBrowseApplet.class"
			archive="FileApplet.jar"
			width="200"
			height="60">
	</applet>
</center>
</body>
</html>

 Opening the FileApplet.html will show up the applet as following screenshot:

file browse applet in browser

When hitting the Browse button, an exception of type java.security.AccessControlException is thrown:

 java console error

It is because the open dialog needs permission to access file system resources, but an unsigned applet is denied this permission by default. So, to overcome this, the applet must be signed.

 

3. Requirement to sign Java applet

Before signing an applet, it requires packaging all applet classes into a single jar file. This can be done by using jar tool which comes with JDK. For example:

jar cfv FileApplet.jar net

That will add all classes under package net.codejava into FileApplet.jar file.

And two programs are required:

    • keytool.exe: A key and certificate management tool. We use this tool for generating a RSA public/private key pair associates with a certificate - called self-signed certificate, or reading a trusted certificate.
    • jarsigner.exe: A signing tool that creates a digital signature of a jar file using a provided certificate.

These tools come with JDK and are installed under JDK_HOME\bin directory.

The following diagram illustrates the signing process:

signing process

Now, let’s dive into the signing process using two types of certificate: self-signed certificate and trusted certificate.

 

4. Sign a Java applet using self-signed certificate

A certificate which is created and signed by a same entity is called self-signed certificate. This self-signing method is simple and quick because we can use our own certificate which is generated by the keytool program; don’t have to spend time on requesting and obtaining certificate from a certificate authority; and it does not cost any bucks. However, its drawback is that the user may not accept the certificate since it is not trusted by any public authority. So this method is suitable for development and testing purpose only.

Syntax of the command to generate a self-signed certificate is as follows:

keytool -genkey -alias <alias> -keystore <filename> -keypass <keypass> -dname <dname> -storepass <storepass> -validity <days>

Where:

    • <alias>: a unique identifier of the certificate. Note that alias is case-insensitive.
    • <filename>: name of the file which stores the certificate.
    • <keypass>: password to protects the key pair.
    • <dname>: distinguished name of the certificate.
    • <storepass>: password of the certificate store.
    • <days>: number of days after which the certificate will expire.

For example, the following command generates a self-signed certificate called “myAlias” and stores it in a file named as “myCert”:

keytool -genkey -alias myAlias -keystore myCert -keypass myKeyPass -dname "CN=FileApplet" -storepass myStorePass -validity 1825

The –validityparameter specifies that this certificate will expire after 5 years (1825=5x365).

Now we use the jarsigner tool to sign the applet’s jar file. Syntax of this command is as follows:

jarsigner -keystore <keystore_file> -keypass <keypass>-storepass <storepass> <jar_file> <alias>

For example, the following command signs the FileApplet.jar using the self-signed certificate stored in the file myCert:

jarsigner -keystore myCert -keypass myKeyPass -storepass myStorePass FileApplet.jar myAlias

The jarsigner tool signs the applet by creating digital signature for all classes of the applet and put it into META-INF directory inside the jar file.

Run the applet again by refreshing the browser, this time a Security Warning dialog shows up:

run self-signed applet warning

Note that the Publisher field is set to UNKNOWN because this certificate is self-signed.

Click More Information, then Certificate Details… to see information about the certificate, like the following screenshot:

self-signed certificate information

To grant permission for the applet, check the option “I accept the risk and want to run this application” in the Security Warning dialog, then click Run.

Now click the Browse button in the applet again, the Open dialog is now displayed:

open dialog

That’s the process of signing a Java applet using a self-signed certificate. Let’s switch to second approach.

 

5. Sign aJava applet using trusted certificate

A trusted certificate is one which is signed by a public trusted certificate authority, such as Verisign, Thawte, Entrust…This process is similar to self-signing, except that we don’t create our own certificate using the keytool tool. Instead, we have to purchase and obtain a certificate issued by the certificate authority – which takes more time and cost. However, this method increases degree of trust to our application, because no one can fake a trusted certificate.

Suppose we have our trusted certificate stored in a .pfx file format, CompanyCert.pfx and we know the password to access the certificate. Use the following command syntax to obtain alias name of the certificate:

keytool -list -storetype pkcs12 -keystore <filename> -storepass <password>

For example:

keytool -list -storetype pkcs12 -keystore CompanyCert.pfx -storepass myStorePass

We got the output like the following screenshot:

get certificate alias

The alias name is shown in the yellow-marked section (for security purpose, other information is blurred in this screenshot). Copy the alias name, and using the following command to sign the applet’s jar file:

jarsigner -storetype pkcs12 -keystore CompanyCert.pfx -storepass myStorePass FileApplet.jar myAlias

Replace the “myStorePass” and “myAlias” by real value correspond to your certificate.

Now run the applet again, a warning dialog appears as following screenshot:

run trusted certificate warning

We can notice that, this time, the warning dialog is slightly different than the one for a self-signed certificate. Obviously the publisher name has a specific value rather than UNKNOWN. Check “Always trust content from this publisher” then click Run. We have granted permission for an applet signed by a trusted certificate.

NOTES:

    • If the applet requires external libraries, we should sign all the required jar files as well.
    • You can find a list of trusted certificates for all Java applets in the Java Plug-in control panel, under Security tab.
    • You can use the command jarsigner –verify <jar_file> to verify if a jar file is signed or not.

 

Other Java Applet Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)AppletTue, 04 Dec 2012 08:29:16 -0600
LiveConnect - The API for communication between Java applet and Javascripthttps://codejava.net/java-se/applet/liveconnect-the-api-for-communication-between-java-applet-and-javascripthttps://codejava.net/java-se/applet/liveconnect-the-api-for-communication-between-java-applet-and-javascript

Java applet can communicate with Javascript in a same HTML page through a technology called LiveConnect which is supported by all major web browsers. The following figure depicts the communication between Java applet and Javascript within web browser’s environment:

liveconnect

JAR files for Java applet – Javascript communication:

The LiveConnect technology is both implemented in browser side as well as in Java side. For the Java side, it is implemented in the plugin.jar library which can be found under either following locations:

    •           JRE_Home\lib (for example: c:\Program Files\Java\jdk1.7.0_03\jre\lib\plugin.jar)
    •           JDK_Home\jre\lib (for example: c:\Program Files\Java\jre7\lib\plugin.jar)

So when compiling source code which is using LiveConnect, remember to include the plugin.jar file to the classpath. But when running Java program, there is no need to include the plugin.jar file because it is already available as a part of Java runtime environment.

 

LiveConnect API:

LiveConnect API allows developers to:

    •           Access Javascript methods, variables and arrays from Java applet.
    •           Access Java applet’s public methods and variables from Javascript.
    •           Access any Java objects and its members if exposed via the applet.
    •           Passing arrays as arguments when calling Javascript methods from Java applet and vice-versa.
    •           Evaluates Javascript expression from Java applet.

The Java Plug-in is responsible for handling communication of Java - Javascript, as well as handling data type conversion on both ends.

The API is fairly simple, with only one class, JSObject, and only one exception, JSException. Both are declared under package netscape.javascript.

    • Class JSObject: acts as main interface between Java code and Javascript. It defines methods for accessing Javascript objects, methods and array elements from Java code.
    • Exception JSException: all methods of the class JSObject throw this exception if there is any error occurred in the Javascript engine. So remember to catch this exception when calling methods of the JSObject class.

The following list summarizes methods of the JSObject class:

Initialization method:

  • static JSObject getWindow(Applet applet): To start Java-Javascript communication, obtain a JSObject for the window that contains the given applet.

 

Method Invocation:

  • Object call(String methodName, Object[] args): Invokes a Javascript method with an array of arguments.

 

Expression evaluation:

  • Object eval(java.lang.String s): Evaluates a Javascript expression.

 

Member methods:

  • Object getMember(String name): Retrieves a named member of a Javascript object.
  • void setMember(String name, Object value): Sets a named member of a Javascript object.
  • void removeMember(String name): Removes a named member of a Javascript object.

 

Array methods:

  • void setSlot(int index, Object value): Sets an indexed member of a Javascript object.
  • Object getSlot(int index): Retrieves an indexed member of a Javascript object.

 

Data type conversion:

When invoking Javascript methods from Java applet and vice-versa, arguments and return values are automatically converted from Java data type to Javascript data type (and vice-versa) by the Java Plug-in. The following table summarizes how the conversion is applied for a particular data type:

Category

From Java data type

To Javascript data type

Numeric values

byte, character, short, int, long, float and double.

are converted to the closest available Javascript numeric type.

Strings

String

are converted to Javascript strings.

Boolean values

boolean

is converted to Javascript boolean.

Objects

Object

is converted to Javascript wrapper object.

Arrays

Java arrays are converted to Javascript pseudo-Array object

Return values

Return values from call() and eval() are always converted to Object in Java.

  

 

For more details about data type conversion between Java an Javascript, see this documentation.

 

Java Applet - Javascript Examples:

The following example briefly illustrates how to call a method, execute an expression, get value of a named member and get value of an indexed array element of Javascript from Java applet.

Source code of HTML and Javascript:

<html>
    <head>
        <title>LiveConnect - Java-Javascript communnication demo</title>
    </head>
    <body>
        <center>
            <applet id="testApplet"
                code="TestApplet.class"
                width="200" height="80"
                    >
            </applet>
        </center>
    </body>
    <script type="text/javascript">
        var coop = "Ooops!";
        this[1] = "Slot 1";

        function foo() {
            return "This is from foo()";
        }

        function bar(firstName, lastName) {
            return "Greeting " + firstName + " " + lastName + "!";
        }
    </script>
</html>

 Source code of Java applet:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import netscape.javascript.*;

public class TestApplet extends JApplet {

    private JButton button = new JButton("Call Javascript");
    private JLabel label = new JLabel();

    public void init() {
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(button, BorderLayout.NORTH);
        getContentPane().add(label, BorderLayout.SOUTH);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                Thread runner = new Thread(new Runnable() {
                    public void run() {
                        try {
                            testLiveConnect();
                        } catch (JSException jse) {
                            // Error
                            jse.printStackTrace();
                        }
                    }
                });
                runner.start();
            }
        });
    }
    private void testLiveConnect() throws JSException {
        JSObject jso = JSObject.getWindow(this);

        // call Javascript's method foo() with no argument
        String result = (String) jso.call("foo", null);
        label.setText(result);

        // delay 2 seconds to see the result
        try { Thread.sleep(2000); } catch (InterruptedException ie) {};

        // call Javascript's method foo() with two arguments
        result = (String) jso.call("bar", new String[] {"Alice", "Alisa"});
        label.setText(result);
        try { Thread.sleep(2000); } catch (InterruptedException ie) {};

        // execute a Javascript expression
        String expression = "alert('Hi, I am from Javascript.');";
        jso.eval(expression);
        try { Thread.sleep(2000); } catch (InterruptedException ie) {};

        // get value of a named member from Javascript
        result = (String) jso.getMember("coop");
        label.setText(result);
        try { Thread.sleep(2000); } catch (InterruptedException ie) {};

        // get value of an indexed member from Javascript
        result = (String) jso.getSlot(1);
        label.setText(result);
    }
}

 

References:

LiveConnect specification

LiveConnect Javadoc

 

Other Java Applet Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)AppletSat, 08 Sep 2012 01:49:40 -0500
How to show Java applet in HTML pagehttps://codejava.net/java-se/applet/how-to-show-java-applet-in-html-pagehttps://codejava.net/java-se/applet/how-to-show-java-applet-in-html-page

An applet is a Java program runs inside a web browser. Typically, you write the applet as a normal Java class (extending from JApplet class) and embed it into an HTML page using the <applet> tag so the users can see and interact with your applet. This article describes various examples of how to display a Java applet inside an HTML page:

1. Syntax of <applet> tag

According to Oracle documentation, following is a complete syntax of the <applet> tag:

<APPLET
    CODEBASE = codebaseURL
    ARCHIVE = archiveList
    CODE = appletFile...or...  OBJECT = serializedApplet
    ALT = alternateText
    NAME = appletInstanceName
    WIDTH = pixels  HEIGHT = pixels
    ALIGN = alignment
    VSPACE = pixels  HSPACE = pixels
    >
        <PARAM NAME = appletAttribute1 VALUE = value>
        <PARAM NAME = appletAttribute2 VALUE = value>
        . . .
        alternateHTML
</APPLET>

The elements in bold and red are required. Others are optional. Put the <applet> tag with its attributes inside the <body> element of the HTML page, it can be nested in other container tags like <div> or <table>. All the applet’s files (classes, jars, resources, etc) should be placed in the same folder as the HTML page.

 

2. The simplest way to show a Java applet

Suppose you write an applet in SimpleApplet.java file and compile it to SimpleApplet.class file, the following code quickly shows off your applet:

<applet code="SimpleApplet.class"></applet> 

Or set size for the applet explicitly:

<applet code="SimpleApplet.class" width=”125” height=”125”></applet> 


3. Show a Java applet bundled in a jar file

It’s very common that you package the applet and its related classes as a single jar file. In this case, use the following code:

<applet 
	archive="SimpleApplet.jar" 
	code="net.codejava.applet.SimpleApplet.class">
</applet> 

That displays the applet bundled in a jar file named SimpleApplet.jar and the applet class file is SimpleApplet resides under the package net.codejava.applet.


4. Show a Java applet with parameters

Sometimes you need to send some parameters from the HTML page to the Java applet. In this case, use following code:

<applet
	archive="SimpleApplet.jar"
	code="net.codejava.applet.SimpleApplet.class">
		<param name="user" value="tom">
		<param name="password" value="secret">
</applet>

That sends two parameters called user and password with corresponding values to the applet. And inside the applet, we can access these parameters as follows:

String user = getParameter("user");
String password = getParameter("password"); 


5. Show a Java applet having external jar files

In case your applet comes with external library jar files, specify these jar files as follows:

<applet
	archive="SimpleApplet.jar, mail.jar, video.jar"
	code="net.codejava.applet.SimpleApplet.class">
</applet>

In the above code, we specify two additional jar files mail.jar and video.jar which are required by the applet. The jar files are separated by commas. If the jar files in a directory:

<applet
	archive="SimpleApplet.jar, lib/mail.jar, lib/video.jar"
	code="net.codejava.applet.SimpleApplet.class">
</applet> 

In the above code, the additional jar files are placed under lib directory.

 

6. Be prepared if the user cannot run your applet

In practice, the users may have problems of running your applet, such as the JRE/JDK or Java Plug-in have not installed, or their browser’s setting prevents Java applet from running, or even the browser does not understand the <applet> tag. So you need to anticipate such cases, for example:

<applet
	archive="SimpleApplet.jar"
	code="net.codejava.applet.SimpleApplet.class"

	alt="You need to have compatible browser to run this Java applet">
	
	Your browser does not support running applet. <br>
	Please install Java Plug-in from <a href="http://java.com">java.com</a>

</applet> 

In the above code, we use the altattribute and alternate HTML text between the opening and closing elements of the <applet> tag to tell the browse should display that information if it cannot run the applet.

 

Other Java Applet Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)AppletThu, 10 Jan 2013 08:22:02 -0600
How to call Javascript function from Java applethttps://codejava.net/java-se/applet/call-javascript-function-from-java-applethttps://codejava.net/java-se/applet/call-javascript-function-from-java-applet

Java applet can talk to Javascript through the technology called LiveConnect. In this article, we are going to show you how to write Java code to invoke Javascript function from within Java applet (include passing arguments of various data types and receiving return values).

Table of content:

    1. The steps to invoke Javascript function
    2. A complete example
    3. Passing numeric arguments example
    4. Passing String arguments example
    5. Passing boolean arguments example
    6. Passing array argument example

1. The steps to invoke Javascript function

The typical steps to call a Javascript function from a Java applet are as follows:

  • Import the package netscape.javascript. This package contains only two classes: JSObject and JSException and it is provided by the plugin.jar library which resides in the JRE_HOME\lib directory or in JDK_HOME\jre\lib directory. So we have to add path of the plugin.jar file to the compilation classpath.
  • Obtain an instance of the JSObjectclass for the applet:
    JSObject jsObj = JSObject.getWindow(applet);

     

    Where applet is the instance of the applet class which extends from java.applet.Applet class. The JSObject class defines principal methods which allow Java applet accessing Javascript variables and methods.

  • Assuming we want to invoke a Javascript method add(a, b) which returns sum of two numbers, write the following code:
    Object result = jsObj.call("add", new Integer[] {17, 28});
    The call() method’s first parameter is the name of Javascript method, and the second one is an array of Object for the Javascript method’s parameters. The call() method always returns an Object as return value of the invoked method (null if the Javascript method does not return anything).

NOTES:

    • When passing parameters to Javascript method, the Java data types are converted to Javascript equivalents, and the type of return value from Javascript is converted to Java equivalent.
    • All methods of the JSObject class throw JSExceptionso we have to catch this exception.

       

2. A complete Java applet invoking Javascript method example

The following example creates an applet looks like this:

simple applet call javascript

This applet shows two text fields which allow users entering two numbers. On clicking the Sum button, the applet will call a Javascript function to calculate the sum and show result in a message dialog like this:

sum message dialog

Code of the applet (SimpleApplet.java):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import netscape.javascript.*;

/**
 * A simple Java applet that demonstrates invoking a Javascript method
 */
public class SimpleApplet extends JApplet {
	private JTextField textA = new JTextField(5);
	private JTextField textB = new JTextField(5);
	private JButton button = new JButton("Sum");

	public void init() {
		// constructs the GUI
		getContentPane().setLayout(new FlowLayout());
		getContentPane().add(textA);
		getContentPane().add(textB);
		getContentPane().add(button);

		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				buttonActionPerformed(evt);
			}
		});
	}

	public void buttonActionPerformed(ActionEvent evt) {
		int numberA = Integer.parseInt(textA.getText());
		int numberB = Integer.parseInt(textB.getText());

		try {
			JSObject jsObj = JSObject.getWindow(this);

			// calls Javascript method and gets return  value
			Object result = jsObj.call("add", new Integer[] {numberA, numberB});

			JOptionPane.showMessageDialog(this, "Sum is " + result.toString());
		} catch (JSException ex) {
			ex.printStackTrace();
		}
	}
}

 

Compile the applet as follows:

javac -cp JDK_HOME\jre\lib\plugin.jar SimpleApplet.java

NOTE: Replace JDK_HOMEby the real path on your system.

Code of the HTML page (TestSimpleApplet.html):

<html>
	<head>
		<title>Test applet calling Javascript function</title>
	</head>
	<body>
		<center>
			<applet id="simpleApplet"
				code="SimpleApplet.class"
				width="200" height="50"
					>
			</applet>
		</center>
	</body>
	<script type="text/javascript">

		function add(a, b) {

			return (a + b);
		}
	</script>
</html>

 

3. Passing numeric arguments example

Javascript function:

function multiply(x, y) {
	return x * y;
} 
  • Passing integer numbers:
    Object returnObj = jsObj.call("multiply", new Integer[] {81, 92});
    Double result = (Double) returnObj;
    System.out.println("result is: " + result);

    Output: result is 7452.0

  • Passing float/double numbers:
Object returnObj = jsObj.call("multiply", new Double[] {81.2, 92.3});
Double result = (Double) returnObj;
System.out.println("result is: " + result);

Output: result is 7494.76

 

4. Passing String arguments example

  • Javascript function:
    function getFullname(first_name, last_name) {
    	return "Hello " + first_name + " " + last_name;
    }

     

  • Java code:
    String returnValue = (String) jsObj.call("getFullname", new String[] {"Peter", "Smith"});
    System.out.println(returnValue);

     

  • Output: Hello Peter Smith

5. Passing boolean arguments example

  • Javascript function (set visibility of a div element):
    function setTableVisible(visible) {
    	var tableDiv = document.getElementById("tableDiv");
    	tableDiv.style.visibility = visible ? "visible" : "hidden";
    }

     

  • Java code:
jsObj.call("setTableVisible", new Boolean[] {false});

 

6. Passing array argument example

  • Javascript function:
    function sumArray(array_numbers) {
    	var total = 0;
    	var i = 0;
    	for (i = 0; i < array_numbers.length; i++) {
    		total += array_numbers[i];
    	}
    
    	return total;
    }
  • Java code:
    int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    Object returnObj = jsObj.call("sumArray", new Object[] {numbers});
    Double result = (Double) returnObj;
    System.out.println("result is: " + result);
  • Output: result is 55.0

     

Other Java Applet Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)AppletThu, 29 Mar 2012 09:56:37 -0500
How to call Java applet's methods and variables from Javascripthttps://codejava.net/java-se/applet/accessing-java-applets-methods-and-variables-from-javascripthttps://codejava.net/java-se/applet/accessing-java-applets-methods-and-variables-from-javascript

Javascript can talk to Java applet in the same HTML page through LiveConnect technology. We can write Javascript code to invoke methods (including arguments) and access objects which are exposed by the applet. Here are the rules:

    • Invoking a public method defined in the applet:

returnValue = AppletID.appletMethod(arg1, arg2, …)

    • Accessing a public variable defined in the applet:

returnValue = AppletID.publicVar

    • Setting value for the variable:

AppletID.publicVar = <value>

    • Invoking a public method of the variable of type Object:

returnValue = AppletID.publicVar.publicMethod(arg1, arg2, …)

Where AppletIDis the id attribute of the <applet> tag:

<applet id="sampleApplet" code="..." />

NOTES:

    • Javascript code can access only public methods and variables.
    • Both static or instance methods/variables can be accessed.

 

1. Javascript call Java Applet Quick Example

Following is a pretty simple example that demonstrates invoking a Java applet’s method from Javascript code. Here is code of the applet (QuickApplet.java):

import java.awt.*;
import javax.swing.*;

public class QuickApplet extends JApplet {

	private JLabel label = new JLabel("This is a Java applet");

	public void init() {
		setLayout(new FlowLayout());
		label.setFont(new Font("Arial", Font.BOLD, 18));
		label.setForeground(Color.RED);
		add(label);
	}

	public void drawText(String text) {
		label.setText(text);
	}
}

This applet shows only label and declare a public method drawText(String) which updates the label’s text.

Here is code of the HTML page (QuickAppletTest.html):

<html>
	<head>
		<title>Javascript call Applet example</title>
	</head>
	<body>
		<center>
			<input type="button" value="Call Applet" onclick="callApplet();"/>
			<br/><br/>

			<applet id="QuickApplet"
				code="QuickApplet.class"
				width="300" height="50"
					>
			</applet>
		</center>
	</body>
	<script type="text/javascript">

		function callApplet() {
			var currentTime = new Date();
			var time = currentTime.toISOString();

			// invoke drawText() method of the applet and pass time string
			// as argument:

			QuickApplet.drawText(time);

		}
	</script>
</html>

This HTML page embeds the above applet and displays a button which will invoke the applet’s method when clicked. The Javascript method callApplet() invokes the drawText() method of the applet and passes a time string as an argument. The applet, in turn, updates the label’s text by the string passed from Javascript code. Here is a screenshot of the page:

Javascript to Applet page

 

2. Invoking Java applet’s methods

Here are some examples of passing arguments to Java applet’s methods from Javascript code.

NOTES:

    • Because variables in Javascript are untyped, so they will be converted to Java equivalents based on signature of Java methods.
    • Return values from Java methods are converted to closest Javascript equivalents (for primitive types) or Javascript wrapper object (for Object types).
  • Passing numeric arguments:

    Code in Java applet:

    public int sum(int x, int y) {
    	return (x + y);
    }

    Code in Javascript:
    var sum = sampleApplet.sum(10, 20);

     

  • Passing String arguments:

    Code in Java applet:

    public String changeCase(String text) {
    	return text.toUpperCase();
    }

    Code in Javascript:
    var returnText = sampleApplet.changeCase("code java");

    Numbers are automatically converted to String:
    var returnText = sampleApplet.changeCase(123456);
     
  • Passing boolean arguments:

    Code in Java applet:

    public boolean toggleVisible(boolean visible) {
    	return !visible;
    }

    Code in Javascript:
    var booleanReturn = sampleApplet.toggleVisible(true);

    Empty string is converted to false, non-empty is converted to true:
    var booleanReturn = sampleApplet.toggleVisible(""); // return true
    var booleanReturn = sampleApplet.toggleVisible("visible"); // return false
     
  • Passing array arguments:

Code in Java applet:

public int sum(int[] numbers) {
	int sum = 0;

	for (int i = 0 ; i < numbers.length; i++) {
		sum += numbers[i];
	}

	return sum;
}


Code in Javascript:

var numbers = new Array();
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;

var sum = sampleApplet.sum(numbers);

 

3. Accessing Java applet’s variables

Javascript code can access only public variables (both instance and static) declared in the applet. If the variable is of type Object, we can invoke methods on the returned object (and pass arguments) like the above section.

  • Access primitive variables:

    Code in Java applet:

    public int number;

    Code in Javascript:
    sampleApplet.number = 10;

     

  • Access Object variables:

Code in Java applet:

public String email;


Code in Javascript:

var email = sampleApplet.email;
email = email.substring(5, 18);
email = "info@codejava.net";
email = email.toUpperCase();

In this example, we obtain a String object from the applet and call String’s substring(int, int) and toUpperCase() methods. The similar can be applied for other Object types.

 

Other Java Applet Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)AppletFri, 22 Feb 2013 06:12:08 -0600
How to submit HTML form in Java applethttps://codejava.net/java-se/applet/submitting-html-form-in-java-applethttps://codejava.net/java-se/applet/submitting-html-form-in-java-applet

There would be some cases in which we need to submit an HTML form from within a Java applet. The applet does some tasks and then needs to submit the form in the enclosing HTML page. To do so, we would utilize the capability of communication between Java applet and Javascript through the LiveConnect technology as follows:

  • In the HTML page, write a Javascript function that contains code to submit the form. For example:
    function submitForm() {
    	// do some processing submit the form...
    
    	document.forms[0].submit();
    } 

    That will submit the first form in the HTML document.

  • In the applet, invoke the Javascript’s submitForm() function like this:
try {
	JSObject jsObj = JSObject.getWindow(this);

	jsObj.call("submitForm", null);

} catch (JSException ex) {
	ex.printStackTrace();
}

 

We may want to pass something from the Java applet to Javascript: the Javascript method takes some parameters as follows:

function submitForm(param1, param2) {
	// do something with the params and submit the form...

	document.forms[0].submit();
} 

Then modify the call in Java side as follows:

try {
	JSObject jsObj = JSObject.getWindow(this);

	jsObj.call("submitForm", new String[] {"param1", "param2"});

} catch (JSException ex) {
	ex.printStackTrace();
} 

That passes two String arguments “param1” and “param2” to the Javascript method. 

Following is complete code of the sample HTML page:

<html>
	<head>
		<title>Submitting HTML form in Java applet</title>
	</head>
	<body>
		<center>
			<!-- show the applet -->
			<applet id="SampleApplet"
				code="SampleApplet.class"
				width="200" height="50"
					>
			</applet>

			<!-- show HTML form -->
			<form method="POST" action="http://localhost:8080/SampleApp/process">
				Enter Full Name: <input type="text" name="fullname" size="30"/>
				<br/>
				Enter E-mail: <input type="text" name="email" size="30"/>
			</form>
		</center>
	</body>
	<script type="text/javascript">

		function submitForm() {
			// do some processing submit the form...

			document.forms[0].submit();
		}
	</script>
</html>

This HTML page displays a Java applet with only a button, along with an HTML form with two text fields.

 

And here is complete code of the sample applet:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import netscape.javascript.*;

/**
 * A sample Java applet that demonstrates how to call Javascript in order to
 * submit the form in the enclosing HTML page.
 */
public class SampleApplet extends JApplet {

	private JButton button = new JButton("Submit");

	public void init() {
		getContentPane().setLayout(new FlowLayout());
		getContentPane().add(button);

		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				buttonActionPerformed(evt);
			}
		});
	}

	public void buttonActionPerformed(ActionEvent evt) {
		try {
			JSObject jsObj = JSObject.getWindow(this);

			jsObj.call("submitForm", null);

		} catch (JSException ex) {
			ex.printStackTrace();
		}
	}
}

This applet simply displays a button which will invoke the Javascript function when clicked.

Opening the page SampleAppletTest.html in browser:

applet html form submit

Click the Submit button, values of the two text fields in the form will be submitted to the URL specified by the action attribute of <form> element.

 

Other Java Applet Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)AppletTue, 19 Feb 2013 09:59:04 -0600
How to resize Java applet to fit browser's windowhttps://codejava.net/java-se/applet/resizing-java-applet-to-fit-browsers-windowhttps://codejava.net/java-se/applet/resizing-java-applet-to-fit-browsers-window

Generally, when embedding a Java applet into an HTML page, the size of the applet is determined by two attributes width and height of the <applet> tag. For example:

<applet

	id="myApplet"

	code="MyApplet.class"

	width="640" height="480"
	>
</applet>

That code will set the applet’s size to 640 by 480 pixels. However that size is fixed, so when users resize their browser’s window, the applet’s size does not get updated accordingly.

To get the applet resized automatically when the users resize browser’s window, we can use relative value (percentage) for the width and height attributes. For example:

<applet

	id="myApplet"

	code="MyApplet.class"

	width="80%" height="80%"
	>
</applet>

That will set the applet’s size about 80 percent of the browser’s size. So when the browser’s window is being resized, the applet’s size gets updated accordingly (so the specified percentage is always kept). If we want the applet fits the display area in browser’s window, use the maximum percentage value:

width="100%" height="100%"

Following is code of the sample HTML page:

<html>
	<head>
		<title>Resizable Java applet</title>
	</head>
	<body top="0" left="0">
		<center>
			<applet id="ResizableApplet"
				code="ResizableApplet.class"

				width="100%" height="100%"
					>
			</applet>
		</center>
	</body>
</html>

And code of the sample applet:

import java.awt.*;
import javax.swing.*;

public class ResizableApplet extends JApplet {
	public void init() {
		getContentPane().setBackground(Color.GREEN);
	}
}

This applet simply shows a green background like this:

resizable applet

Try to resize the browser’s window and we’ll see the applet get resized accordingly.

 

Other Java Applet Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)AppletWed, 20 Feb 2013 06:50:43 -0600
Java applet tutorial for beginnershttps://codejava.net/java-se/applet/quick-start-with-java-applethttps://codejava.net/java-se/applet/quick-start-with-java-applet

If you are new to Java applet, this tutorial let you quickly get started with a simple applet from writing code and packaging jar file to embedding in HTML page and running in a browser.

 

1. Code a Java applet

A Java applet class must extends from java.applet.Appletclass or javax.swing.JApplet class and overrides applet’s life cycle methods: init(),start(), stop() and destroy(). Following is code of a simple Java applet that displays only a button “Click me!”. On clicking the button, a message dialog says “Hello! I am an applet!” appears.

package net.codejava.applet;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JOptionPane;

public class QuickApplet extends JApplet {

	private JButton  button;

	public void init() {
		button = new JButton("Click me!");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				JOptionPane.showMessageDialog(QuickApplet.this,
					"Hello! I am an applet!");
			}
		});

		System.out.println("APPLET IS INITIALIZED");
	}

	public void start() {
		getContentPane().add(button);
		System.out.println("APPLET IS STARTED");
	}

	public void stop() {
		System.out.println("APPLET IS STOPPED");
	}

	public void destroy() {
		System.out.println("APPLET IS DESTROYED");
	}
}

Place the QuickApplet.java file under the directory structure: src\net\codejava\applet

 

2. Compile and package Java applet

Create a directory called build in the same directory as the src directory. Suppose the current working directory is the parent of the directories build and src, type the following command to compile the applet:

javac -d build src\net\codejava\applet\QuickApplet.java

The compiled .class files will be placed under the build directory. Type the following command to package the applet (not that there is a period at the end):

jar cvf QuickApplet.jar -C build .

That will add all classes in the build directory to a single jar file named QuickApplet.jar.

 

3. Embed Java applet in HTML page

Now create an HTML file called QuickApplet.html with the following code:

<html>
<head>
	<title>Quick Start Java Applet</title>
</head>
<body>
	<center>
		<applet
			code="net.codejava.applet.QuickApplet.class"
			archive="QuickApplet.jar"
			width="125" height="125"
			>
		</applet>
	</center>
</body>
</html>

We use to embed the applet in the HTML page. See the article How to show Java applet in HTML page for more details about using the <applet> tag.

 

4. Run Java applet in browser

Open the QuickApplet.html file in a Java Plug-in enabled browser:

QuickApplet

Click on the button, a message dialog appears:

Applet message dialog

Note that a dialog message created by Java applet has an exclamation mark in the upper right corner.

And following is logging information from Java applet console:

Java applet console

Download the quick applet project in the attachment section.

 

Other Java Applet Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)AppletSat, 12 Jan 2013 10:21:41 -0600