Tuesday, December 8, 2009

Java Swing Applet: HowTo

This post explains how to take an existing Java Swing application and wrap it as an applet which can then be used on any website.


This post assumes the java swing class file (which is run in the original application) to be: FileUploadClientGUIView.

  1. Create the java applet wrapper as follows:

package packageName;

import javax.swing.JApplet;
import javax.swing.SwingUtilities;

public class AppletStarter extends JApplet {
//Called when this applet is loaded into the browser.
public void init() {
//Execute a job on the event-dispatching thread;
//creating this applet's GUI.
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("AppletStarter didn't complete successfully");
}
}

private void createGUI() {
//Create and set up the content pane.
FileUploadClientGUIView newContentPane = new FileUploadClientGUIView(new FileUploadClientGUIApp());
//newContentPane.getRootPane().setOpaque(true);
setContentPane(newContentPane.getRootPane());
}
}


The only line you should change is the line showing the actual GUI and is bolded out.


  1. Jar up the whole application with the wrapper class included inside. Just change the main-class in the META-INF/MANIFEST.MF file as follows (to point to the new wrapper class you have just created):

Main-Class: packageName.AppletStarter

  1. In the HTML / PHP code insert the following lines:




<applet code='packageName.AppletStarter '
archive = 'NameOfJarToRun.jar',
width = 300,
height = 260 />


before the end of the /body tag enter the following line:


<script language="JavaScript" src="/js/omi/jsc/s_code_remote.js"></script>



That's it – your applet now appears on your browser.

No comments: