?
Solved

Implementing getCodeBase() to use Applet as Application

Posted on 2009-04-21
13
Medium Priority
?
889 Views
Last Modified: 2012-05-06
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
Comment
Question by:Lexx87
  • 7
  • 5
13 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 24197116
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
 
LVL 12

Expert Comment

by:Gibu George
ID: 24197129
getCodeBase gives the base URL of the applet, but why you need that for an application
0
 

Author Comment

by:Lexx87
ID: 24197155
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 86

Expert Comment

by:CEHJ
ID: 24197180
>>and I read somewhere that you need to do something if the applet uses getCodeBase.

That's correct
0
 

Author Comment

by:Lexx87
ID: 24198403
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 24198599
>>Could I do without this constructor as I only need the implementation of getCodeBase()?

Yes. Just return a file URL
0
 

Author Comment

by:Lexx87
ID: 24199062
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
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 500 total points
ID: 24199472
>>} 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
 

Author Comment

by:Lexx87
ID: 24199579
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
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 500 total points
ID: 24199656
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 24202401
:-)
0
 

Author Comment

by:Lexx87
ID: 24202417
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 24202431
>>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

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses
Course of the Month9 days, 11 hours left to enroll

609 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question