| Home > Core Java FAQ
> Applets FAQ |
| Applets |
| Applets
Vs Applications(04) * Installing
Applets(10) * User Interface(12)
* Program Structure(10) * Applet
Communication(05) * Exceptions(06) * Miscellaneous(08) |
| |
|
Q . How do I determine the width and height of my applet?
|
Ans :
Use the getSize
method (or size in the JDK 1.0.2),
which the Applet class inherits from
the Component class in the java.awt
package.
The
getSize method (in JDK 1.1) returns the size of the
applet as a Dimension object, from which you can
extract separate width and height
fields:
/* Using JDK 1.1: */
Dimension dim = getSize();
int appletWidth = dim.width;
int appletHeight = dim.height;
In the JDK 1.0.2,
use the method name size in place of getSize.
|
|
Q . How do I set the background color within the applet area?
|
Ans :
Use the setBackground
method, which the Applet class
inherits from Component.
Component's
setBackground method specifies the background color
for an AWT component. For applets, this sets the color with which
the entire applet area is covered before anything else is drawn on
top (lines, images, or even other components, such as buttons and
text fields).
Unless you're changing background
colors repeatedly, you should set the background color in your
applet's init method:
public void init() {
// ...
setBackground(Color.green);
// ...
}
You can also set a
background image for the applet, on top of which you place any
user-interface components the applet may require
|
|
Q . How
can I create a transparent background for my applet?
|
Ans :
You can't
create transparent backgrounds for applets in the JDK (1.0.2 and
1.1), but you can fake it in some cases.
Applets
inherit from the Component class. In the JDK 1.0.2, Component
instances are always opaque. (The JDK 1.1 provides the basic
infrastructure for lightweight components that can have
transparency, but instances of the Applet class still
come with an opaque background.) Even if an applet doesn't draw
itself in any interesting way, it still fills its rectangular
space with a solid background color. The only way to achieve the
effect of transparent background is by a chameleon trick: attempt
to make your applet's background indistinguishable from the
underlying html page background. Yes, this is a hack
rather than a solution, but you might find it useful.
If the html background is a solid
color, your work is fairly easy. You can write your applet such
that it takes background color as one of its parameters. Then set
that parameter in the APPLET tag to match to color of the html
page you are putting the applet in.
If the html page background is a GIF
image or pattern, you're basically out of luck. You can still
write your applet to take the relevant information as a parameter
(in this case, the name of the GIF file that is providing the
background image), but your applet's location on the page may
cause noticeable discontinuities in the background image. Some
patterns are easier to blend in with than others.
|
|
Q . Can I put menus and a menu bar on my applet?
|
Ans :
No; you
can't put a menu bar (or menus) directly on the applet itself.
The
JDK (1.0.2 and 1.1) restricts menu bars to occur only on frames
(instances of the Frame class or a Frame
subclass). Frames represent independent top-level windows with a
border. The Applet class inherits from Panel
rather than Frame, though.
To provide a menu bar for your
applet, the current workaround is to create a new Frame
instance from your applet and put a menu bar on that. For example:
import java.awt.*;
public class AppletMenuExample extends java.applet.Applet {
static final String FILE = "File";
static final String FILE_NEW = "New...";
static final String FILE_OPEN = "Open...";
// ...
AppletMenuFrame myFrame;
MenuBar myMenuBar;
Menu fileMenu;
public void init() {
myFrame = new AppletMenuFrame(this,
"Applet frame with a menu");
myMenuBar = new MenuBar();
fileMenu = new Menu(FILE);
myFrame.setMenuBar(myMenuBar);
myMenuBar.add(fileMenu);
fileMenu.add(FILE_NEW);
fileMenu.add(FILE_OPEN);
// ...
myFrame.pack();
myFrame.show();
}
}
|
|
Q . I know that cursors can be changed from within frames, but how do I change the cursor in my applet?
|
Ans :
In the JDK
1.0.2 you must find the Frame
instance that contains the applet and change its cursor, but the
JDK 1.1 allows you to set the cursor for instances of any Component
subclass, including Applet.
The
JDK 1.0.2 lets you control one cursor per Frame
instance. (The Frame class represents top-level,
bordered windows.) Since applets aren't a kind of Frame,
you can't set the cursor for an applet directly. You can, however,
trace up the containment hierarchy until you finally find a Frame
instance:
/* using JDK 1.0.2: */
Frame myFrame;
Container parent = getParent();
while (parent != null && !(parent instanceof Frame)) {
parent = parent.getParent();
}
myFrame = (Frame)parent;
if (myFrame != null) {
myFrame.setCursor(Frame.CROSSHAIR_CURSOR);
}
The
JDK 1.1 fixes this shortcoming by letting you set the cursor on
individual components. You can set your applet's cursor by
invoking Component's setCursor method on
the applet itself. For example:
/* using JDK 1.1: */
public void init() {
setCursor(new Cursor(Cursor.HAND_CURSOR));
// ...
}
An
additional benefit of the cursor-per-component service in the JDK
1.1 is that the AWT automatically switches the cursor as needed to
match the component pointed to by the mouse. In contrast, the JDK
1.0.2 forces you to manage the cursor switching by yourself, which
is doable but tedious.
|
|
Q . How Can I Avoid Flicker in an Applet?
|
Ans :
The key to fixing flicker is realizing that the screen isn't actually painted in the paint() method. The pixels get put on the screen in the update() method which most applets don't override. However by overriding the update() method you can do all your painting in an offscreen Image and then just copy the final Image onto the screen with no visible flicker.
The cookbook approach is simple. Add the following three private fields to your applet and the public update() method. Flicker will magically disappear.
private Image offScreenImage;
private Dimension offScreenSize;
private Graphics offScreenGraphics;
public final synchronized void update (Graphics g) {
Dimension d = size();
if((offScreenImage == null) || (d.width != offScreenSize.width) || (d.height != offScreenSize.height)) {
offScreenImage = createImage(d.width, d.height);
offScreenSize = d;
offScreenGraphics = offScreenImage.getGraphics();
}
offScreenGraphics.clearRect(0, 0, d.width, d.height);
paint(offScreenGraphics);
g.drawImage(offScreenImage, 0, 0, null);
}
|
|
Q . How do I use an image as the background to my applet? How do I set the background color of my applet the same as the browser?
|
Ans :
You can simply do a g.drawImage(yourImage, x, y, this) in the
paint() routine of your applet. If the image isn't big enough to fill
the entire background, tile it or scale it. Here is some code to tile
it
// The background image is named "bg".
int w = 0, h = 0;
while (w < size().width) {
g.drawImage(bg, w, h, this);
while ((h + bg.getHeight(this)) < size().height) {
h += bg.getHeight(this);
g.drawImage(bg, w, h, this);
}
h = 0;
w += bg.getWidth(this);
}
Alternatively, the AWT can scale your background image to the size of the applet. The result quality will depend on the kind of image. Inside
an applet class, you can use:
drawImage(img, 0, 0, size().width, size().height, this);
You can set the background color to match the background color of the browser by passing the value in as a parameter, like this:
In the HTML applet tag:
<param name=BrowserColor value=F1F1F1>
(value should be the same hex as the HTML COLOR value).
In the Applet init() method:
String colparam = getParameter("BrowserColor");
int col = Integer.valueOf(colparam,16).intValue();
setBackground( new Color(col) );
An applet cannot override the size imposed by the HTML. If you make the applet larger, the browser will still clip to the original size. If you
need more room, open up a new Frame, Window or Dialog to show your
output.
|
|
Q .
How do you make the applet's background transparent?
|
Ans
: There is no way to give an applet a transparent background that
lets the web browser background show through. You can simulate it by
giving the applet a background that matches the underlying browser
background. (For a straight color, it will be the value of <BODY BGCOLOR=nnnnnn> in the HTML file). It doesn't produce satisfactory
results with a patterned background because of problems aligning the
edges.
Lightweight components (new in JDK 1.1) have a transparent background, but that merely allows other components to show through. A lightweight
component is always ultimately positioned in a heavyweight component.
|
|
Q . How do you get a Menubar/Menu in an applet?
|
Ans
:
In your applet's init() method, create a Frame instance and then attach the Menus,
Menubar etc to that frame. You cannot attach the Menu
or a Menubar to an applet directly.
Or get the parent Frame like this (doesn't work in all execution
environments):
Container parent = getParent();
while (! (parent instanceof Frame) )
parent = parent.getParent();
Frame theFrame = (Frame) parent;
This second suggestion definitely doesn't work in the appletviewer, and probably won't work on Macs
(where would the Menubar go?) or in some browsers. In JDK 1.1, just use a popup menu, which isn't
attached to a Frame.
|
|
Q . How can I position my dialogs centered (not top left)?
|
Ans
:
Use some code like this:
void center(Component parent) {
pack();
Point p = parent.getLocation();
Dimension d = parent.getSize();
Dimension s = getSize();
p.translate((d.width - s.width) / 2, (d.height - s.height) / 2);
setLocation(p);
}
|
|
Q . How can I resize an applet?
|
Ans
:
If you want resizing behavior from an applet, you should launch an
external Frame that can be resized independently.
One programmer suggests using percentages for the height/width parameters in an applet tag, like this:
<APPLET CODE="lewinsky.class" WIDTH="100%" HEIGHT="100%">
You can't resize the applet directly, but it does get resized when you resize the browser window (tested with Netscape 3.04 and 4.04, but does
not work with appletviewer). If you have nothing else on your HTML page
and use 100% for your width and height, the browser window looks almost
like a real application. For the extremely tricky: have the browser reload the page with the
applet when the browser resizes using new values for width and height
(probably not what you want most of the time). You would need Javascript to generate a page dynamically using
document.write("...") when the browser resizes. Not recommended. Another possibility is to
use the new SplitPane class in JFC.
|
|
Q .
How can I change the colors in an applet?
|
Ans
:
Things like background color (and font size, color, etc.) are either set by parameter variables or hard-coded.
If they are set by the parameters, there will be <PARAM> tags inside the <APPLET></APPLET> tags that look something like:
<APPLET CODE="myApplet.class">
<PARAM fontcolor="FFFFCC">
<PARAM bgcolor="CCCCCC">
</APPLET>
Now the names of the variables are determined by the programmer, and they may be something cryptic, like "fc" and "bgc". Look at the HTML that displays the applet, and look at the readme files or any other documentation, and see if there is any mention of parameter tags that can be used to change the background. If you don't (and most of the time you won't) then the values are hard-coded.
If they are hard-coded, you would need access to the .java files that contain the actual Java code. If you have the file(s), you can probably find where the colors are set. You can then change the numbers and recompile with a Java compiler. You can get a free compiler from java.sun.com
If you don't have access to the source code, however, you're out of luck.
|
|
|