FAQ 3g
Updated: 1/7/00
>>>>>> Can I put my Applet in a Window?
=======================================
Yes you can! And putting your applet into a window makes it loads easier to debug.
Here are the key concepts: The window is called a Frame. Frames are Containers.
You can create a Frame that contains your Applet. You won't need to change much of your
applet code at all.
Here is the basic code for making an Applet containing Frame:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class MyFrame extends Frame implements WindowListener {
final static int DEFAULT_WIDTH = 400;
final static int DEFAULT_HEIGHT = 300;
//--- constructor ---
MyFrame(String title){
super(title);
addWindowListener(this);
}
//--- window environment launch ---
public static void main(String args[]) {
MyFrame win;
MyApplet app;
Insets edge;
win = new MyFrame("My Window Title");
win.show();
app = new MyApplet();
app.inBrowser = false;
edge = win.getInsets();
win.setSize( edge.left+edge.right+MyFrame.DEFAULT_WIDTH,
edge.top+edge.bottom+MyFrame.DEFAULT_HEIGHT);
win.add("Center",app); // for microsoft
app.init();
//app.start(); // for launching game loop
}
//--- Window Events ---
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowClosing(WindowEvent e){
dispose();
System.exit(0);
}
}
Here is what changes in your applet. First you need a new value:
boolean inBrowser;
Your applets constructor will set this value to true:
MyApplet(){inBrowser=true;}
The window launcher will set the value to false. This way, your applet
can know if it is in a browser or in a window.
The only time it makes a difference (window vs browser) is when your applet
tries to load a file. When (inBrowser==TRUE) you can load using URLs.
When (inBrowser==FALSE) you need to load using local file tools.
Here is an example of my loadImage function, and how it changes depending
on the inBrowser value:
class MyApplet extends Applet {
String artpath;
publiv void init(){
if (inBrowser) artpath = "http:/www.mySite.com/images/";
else artpath = "c:\\website\\images\\";
}
Image loadImage(String path){
Image temp;
if (path==null) return null;
if (inBrowser) {
try {temp = getToolkit().getImage(new URL(artpath+path));}
catch (MalformedURLException e){return null;}
}
else temp = getToolkit().getImage(artpath+path);
return temp;
}
}
:::::: final static values
==========================
final static values are constants. This value is the same every time you use
it in your code. It will cause an error if you try to change it.