How to send message from Java applet to web page via jQuery

In an attempt to save development time on reworking the RIAs from a old system, a business decision was made to reuse the Java applets on a newer system.

The newer system utilizes jQuery at the front end to fulfill modern user interactivity requirements.

This post documents a proof of concept that I did for the powerful Java applets to communicate with the front-end of the newer system.

The host, the middle man and the Java applet

I divided this proof of concept into three main parts:

  1. The host which is the web page that contains the middle man and the Java applet.
  2. The middle man which is a Javascript function that the Java applet will call to pass the message to other components on the web page.
  3. The Java applet which will harvest the message and send it to the host.

The host and the middle man

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Sending message from Java applet to web page via jQuery - Proof Of Concepts</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
    <h4>Message from applet:</h4>
	<div id="containerToWriteTo">
		
	</div>
	
	<h4>The applet</h4>
	<applet name="MessageSendingApplet" 
			code="com/techcoil/applet/send/message/to/webpage/MessageSendingApplet.class" 
			archive="http://www.techcoil.com/resource/java/applet/MessageSendingApplet.jar" 
			height="45"
			width="350">
	<p>You have to activate Java in order to view this proof of concept</p>
	</applet>
	
	<script type="text/javascript">
		function writeToContainer(msg) {
			$('#containerToWriteTo').html(msg);
		}
	</script>
</body>
</html>

In the body tag, I define a div section to hold the message from the applet and identified it as containerToWriteTo.

I then use the applet tag to hold the applet that I am going to create.

Lastly, near the closing body tag, I define the writeToContainer Javascript function with an input parameter msg. In the function, I use jQuery to look for the containerToWriteTo div and set its content with whatever that is passed into the function via the msg parameter.

The Java applet

Pre compilation work

The netscape.javascript.JSObject class is needed for my Java applet to call some Javascript functions that is contained in the same webpage where it is embedded at.

And for my Java applet to be compiled successfully while it uses JSObject, I will need to specify the plugin.jar library found in the /lib folder in the build path.

The Java codes to realise the applet

package com.techcoil.applet.send.message.to.webpage;

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

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import netscape.javascript.JSException;
import netscape.javascript.JSObject;

public class MessageSendingApplet extends JApplet {

	private static final long serialVersionUID = 1L;
	
	private JButton sendMessageButton;
	private JTextField messageTf;
	private JSObject browserWindow;
	
	public void init() {
		SwingUtilities.invokeLater(new Runnable() {
		    public void run() {
		    	initApplet();
		    }
		});
	}
	
	private void initApplet() {
		
		this.setSize(new Dimension(350, 45));
			
		JPanel mainPane = new JPanel();
		
		ActionListener submitMessageActionListener = new ActionListener() {
			
			public void actionPerformed (ActionEvent e) {
				sendMessageToWebpage();
			}
			
		};
		
		this.messageTf = new JTextField();
		this.messageTf.setPreferredSize(new Dimension(200, 30));
		this.messageTf.setMinimumSize(new Dimension(80, 30));
		this.messageTf.addActionListener(submitMessageActionListener);
		
		this.sendMessageButton = new JButton("Send message");
		this.sendMessageButton.setToolTipText("Send the message in the text field to the web page.");
		this.sendMessageButton.setPreferredSize(new Dimension(120, 29));
		this.sendMessageButton.addActionListener(submitMessageActionListener);
		
		messageTf.requestFocus();
		
		mainPane.add(messageTf);
		mainPane.add(sendMessageButton);
		
		setContentPane(mainPane);
		
		try {
			browserWindow = JSObject.getWindow(this);
		} catch(JSException jse) {
			this.displayErrorMessage("Unable to get a reference to the browser window.");
		}
	}
	
	private void sendMessageToWebpage() {
		if (this.browserWindow != null) {
			try {
				browserWindow.eval("writeToContainer('" + this.messageTf.getText() + "')");
			}
			catch (JSException jse) {
				this.displayErrorMessage(jse.getMessage());
			} // end try-catch
		}
		else {
			this.displayErrorMessage("Unable to get a reference to browser window.");
		}
	}
	
	private void displayErrorMessage(String msg) {
		JOptionPane.showMessageDialog(this, 
				msg, 
				"Message Sending Applet",
				JOptionPane.ERROR_MESSAGE);
	}
	
}

Building the applet user interface

I started building the code by extending a subclass from the javax.swing.JApplet class. I gave life to the applet by overriding the init() function. I then use the SwingUtilities.invokeLater function to ensure that the applet was created by the AWT event dispatch thread.

Within the initApplet method, I create the user interface components for the applet to interact with the user:

  • A text field to collect messages from the user
  • A button for the user to submit the messages
  • A action handler that sends messages from the text field to the web page

Lastly, I get a reference to the Javascript window object for the HTML document via the JSObject.getObject function and remembers it with the browserWindow variable.

Sending the message to the web page

When the user press enter or click on the "Send message" button, the sendMessageToWebpage method will be called. In the sendMessageToWebpage method, I use the JSObject.eval method to invoke the middle man function, passing it the text value that I get from the text field.

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.