• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 935
  • Last Modified:

Implementing getCodeBase() to use Applet as Application

Hi,

I'm wanting to turn an Applet of mine into an application. I know the process of doing this for most applets as shown in Code Snippet 1 which works.

Now, I have a second Applet which uses the getCodeBase() method as seen in Code Snippet 2.
To make that applet into an application I know I need to do something akin to theApplet.getCodeBase(); or something, or that I need to implement it somehow, but I have no idea how to do it or if i'm just being blind and missing something simple!
Code Snippet 1:
public class AppletViewer{
	
	public static void main(String[] args) {
	    //... Create an initialize the applet.
	    JApplet theApplet = new MainJApplet();
	    theApplet.init();         
	    theApplet.start();       
	    
	    //... Create a window (JFrame) and make applet the content pane.
	    JFrame window = new JFrame("Sample Applet and Application");
	    window.setContentPane(theApplet);
	    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    window.pack();              // Arrange the components.
	
	    window.setVisible(true);    // Make the window visible.
	}
 
Code Snippet 2:
c10 = java.applet.Applet.newAudioClip(new java.net.URL(getCodeBase(),
        "3s Sine 1000Hz 3s -60dBFS mono.wav"));

Open in new window

0
Lexx87
Asked:
Lexx87
  • 7
  • 5
3 Solutions
 
CEHJCommented:
You're not being blind. The problem is not obvious. What you need to do is implement AppletStub and call setStub on the Applet

http://java.sun.com/javase/6/docs/api/java/applet/AppletStub.html
0
 
Gibu GeorgeChief Technology OfficerCommented:
getCodeBase gives the base URL of the applet, but why you need that for an application
0
 
Lexx87Author Commented:
I get an exception on the first line that uses getCodeBase() (Code snippet 2) when running the main method, and I read somewhere that you need to do something if the applet uses getCodeBase.

I'm looking into the AppletStub at the moment.
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

 
CEHJCommented:
>>and I read somewhere that you need to do something if the applet uses getCodeBase.

That's correct
0
 
Lexx87Author Commented:
I found an implementation of AppletStub in an old Sun artiicle from 1998.

Now the constructor as you can see sets up arguments to be read in by the command line which isn't what I need to do, and the for statement uses syntax which doesn't exist anymore. Could I do without this constructor as I only need the implementation of getCodeBase()?


package graph;
 
import java.applet.*;
import java.util.*;
import java.net.*;
public class MyAppletStub implements AppletStub {
	  private Hashtable properties;
	  private Applet MyApplet;
 
	/**
	 * Creates a new MyAppletStub instance and initializes 
	 * thei nit parameters from the command line.
	 * Arguments are passed in as name=value pairs.
	 * Reading the command line arguments can be made more
	 * sophisciated depending on your needs, but the basic
	 * idea will likely remain the same.
	 * Also, this particular implementation doesn't deal
	 * very well with invalid name=value pairs.
	 * 
	 * @param argv[] Command line arguments passed to Main
	 * @param an Applet instance.
	 */
	  public MyAppletStub (String argv[ 
	                          ], Applet a) {
	    MyApplet = a;
	    properties = new Hashtable();
	    for ( int i = 0; i *lt; argv.length; i++ ) {
	      try {
	        StringTokenizer parser = 
	         new StringTokenizer (
	          argv[i], "=");
	        String name = parser.nextToken(
	                        ).toString();
	        String value = parser.nextToken(
	           "\"").toString();
	        value = value.substring(1);
	        properties.put (name, value);
	      } catch (NoSuchElementException e) {
	        e.printStackTrace();
	      }
	    }
	  }
 
	  /**
	   * Calls the applet's resize
	   * @param width
	   * @param height
	   * @return void
	   */
	  public void appletResize (
	     int width, int height) {
	    MyApplet.resize (width, height);
	  }
 
	  /**
	   * Returns the applet's context, which is 
	   * null in this case. This is an area where more
	   * creative programming
	   * work can be done to try and provide a context
	   * @return AppletContext Always null
	   */ 
	  public AppletContext getAppletContext () {
	    return null;
	  }
 
	  /**
	   * Returns the CodeBase. If a host parameter
	   * isn't provided
	   * in the command line arguments, the URL is based
	   * on InetAddress.getLocalHost(). 
	   * The protocol is "file:"
	   * @return URL
	   */
	  public java.net.URL getCodeBase() {
	    String host;
	    if ( (host=getParameter (
	      "host")) == null ) {
	      try {
	        host = InetAddress.getLocalHost(
	                        ).getHostName();
	      } catch (UnknownHostException e) {
	        e.printStackTrace();
	      }
	    }
	      
	    java.net.URL u  = null;
	    try {
	      u = new java.net.URL (
	       "file://"+host);
	    } catch (Exception e) { }
	    return u;
	  }
 
	  /**
	   * Returns getCodeBase
	   * @return URL
	   */
	  public java.net.URL getDocumentBase() {
	    return getCodeBase();
	  }
 
	  /**
	   * Returns the corresponding command line value
	   * @return String
	   */
	  public String getParameter (
	                    String p) {
	    return (String)properties.get (p);
	  }
 
	  /**
	   * Applet is always true
	   * @return boolean True
	   */
	  public boolean isActive () {
	    return true;
	  }
	}

Open in new window

0
 
CEHJCommented:
>>Could I do without this constructor as I only need the implementation of getCodeBase()?

Yes. Just return a file URL
0
 
Lexx87Author Commented:
Using the test class and applet stub classes below I get my Application :)

However, running the application does not seem to be working as it is not playing the audio files specified by the code base. Under "file://" so I need to specify the location of those files? I would attempt that myself but i'm not sure of the format it should be.
APPLET STUB
 
import java.applet.*;
import java.util.*;
import java.net.*;
public class MyAppletStub implements AppletStub {
	  private Hashtable properties;
	  private Applet theApplet;
 
	//  public MyAppletStub (Applet a) {
	    //         theApplet = a;
	           
	    //       }
 
 
	  /**
	   * Calls the applet's resize
	   * @param width
	   * @param height
	   * @return void
	   */
	  public void appletResize (
	     int width, int height) {
	    theApplet.resize (width, height);
	  }
 
	  /**
	   * Returns the applet's context, which is 
	   * null in this case. This is an area where more
	   * creative programming
	   * work can be done to try and provide a context
	   * @return AppletContext Always null
	   */ 
	  public AppletContext getAppletContext () {
	    return null;
	  }
 
	  /**
	   * Returns the CodeBase. If a host parameter
	   * isn't provided
	   * in the command line arguments, the URL is based
	   * on InetAddress.getLocalHost(). 
	   * The protocol is "file:"
	   * @return URL
	   */
	  public java.net.URL getCodeBase() {
	   // String host;
	    //if ( (host=getParameter (
	     // "host")) == null ) {
	      //try {
	       // host = InetAddress.getLocalHost(
	         //               ).getHostName();
	      //} catch (UnknownHostException e) {
	       // e.printStackTrace();
	     // }
	   // }
	      
	    java.net.URL u  = null;
	    try {
	      u = new java.net.URL (
	       //"file://"+host);
	       "file://");
	    } catch (Exception e) { }
	    return u;
	  }
 
	  /**
	   * Returns getCodeBase
	   * @return URL
	   */
	  public java.net.URL getDocumentBase() {
	    return getCodeBase();
	  }
 
	  /**
	   * Returns the corresponding command line value
	   * @return String
	   */
	  public String getParameter (
	                    String p) {
	    return (String)properties.get (p);
	  }
 
	  /**
	   * Applet is always true
	   * @return boolean True
	   */
	  public boolean isActive () {
	    return true;
	  }
	}
 
TEST CLASS
 
import java.applet.Applet;
 
import javax.swing.*;
 
 
public class AppletViewerTest {
	
	public static void main(String[] args) {
	    //... Create an initialize the applet.
	    Applet theApplet = new HearingTest();
	  
	    theApplet.setStub(new MyAppletStub());
	  
	    theApplet.init();         
	    theApplet.start();        
	
	   
	    //... Create a window (JFrame) and make applet the content pane.
	    JFrame window = new JFrame("Sample Applet and Application");
	    window.setSize(500, 500);
	    window.setContentPane(theApplet);
	    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    window.pack();              // Arrange the components.
	    //System.out.println(theApplet.getSize());
	    window.setVisible(true);    // Make the window visible.
	}
 
		
}

Open in new window

0
 
CEHJCommented:
>>} catch (Exception e) { }

Don't ignore exceptions - it can lead to unfindable bugs. printStackTrace. In fact, your url is meaningless. Try instead the below

>>as it is not playing the audio files specified by the code base

Where do you attempt to play them - i don't see that?
return this.getClass().getResource(".");

Open in new window

0
 
Lexx87Author Commented:
Did you mean the return of the getCodeBase() method? As below rather than the previous. The applet is a new HearingTest as you can see, which plays audioclips when certain options are chosen

In code 2 you can see where they are refered by getCodeBase() (i've given one as an example). These are stored in an array and the correct one is selected wheneve necessary. They are not playing at the moment but this is because they are not being referenced properly in the Stub class i'm guessing. In getResource should I reference where they are stored? As in getResource("C:\...") or something?

Alex
Code 1:  
public java.net.URL getCodeBase() {
	
		  return this.getClass().getResource(".");
	  }
 
Code 2: 
c10 = java.applet.Applet.newAudioClip(new java.net.URL(getCodeBase(),
        "3s Sine 1000Hz 3s -60dBFS mono.wav"));

Open in new window

0
 
CEHJCommented:
I would make it simple and keep the wav files with your applet class file for the moment. getCodeBase can stay the way it is. Remove the spaces from your file names or you could get problems
0
 
CEHJCommented:
:-)
0
 
Lexx87Author Commented:
Hehe it's all good now, thank you very much for helping me out :)

Why do problems occur if filenames have spaces in them? Does it trip up when parsing the space for some reason?
0
 
CEHJCommented:
>>Why do problems occur if filenames have spaces in them?

Because you're working with URLs. They need to have spaces encodes as %20
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

  • 7
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now