Java Reference
In-Depth Information
button.setFont(fonts[i%2]); // One of our own fonts
button.setBorder(edge); // Set the button border
}
}
}
Of course, to run the applet we will need an .
html
file containing the following:
<APPLET CODE="TryApplet.class" WIDTH=300 HEIGHT=200>
</APPLET>
This specifies the width and height of the applet - you can use your own values here if you wish. You
can save the file as
TryApplet.html
.
Once you have compiled the applet source code using
javac
, you can execute it with the
appletviewer
program by entering the following command from the folder the .
html
file and class are in:
appletviewer TryApplet.html
You should see the
AppletViewer
window displaying our applet.
The arrangement of the buttons is now right justified in the flow layout. We have the button labels
alternating between the two fonts that we created. The buttons also look more like buttons with a
beveled edge.
How It Works
As we saw in Chapter 1, an applet is executed rather differently from a Java program and it is not really
an independent program at all. The browser (or
appletviewer
in this case) initiates and controls the
execution of the applet. An applet does not require a
main()
method. To execute the applet, the
browser first creates an instance of our applet class,
TryApplet
, and then calls the
init()
method for
it. This method is inherited from the
Applet
class (the base for
JApplet)
and you typically override
this method to provide your own initialization.
We need the
import
statement for
java.awt
in addition to that for
javax.swing
because our code
refers to the
Font
,
Container,
and
FlowLayout
classes.
Before creating the buttons, we create a
BevelBorder
object that we will use to specify the border for
each button. In the loop that adds the buttons to the content pane for the applet, we select one or other
of the
Font
objects we have created depending on whether the loop index is even or odd, and then set
edge
as the border by calling the
setBorder()
member. This would be the same for any component.
Note how the size of each button is automatically adjusted to accommodate the button label. Of course,
the font selection depends on the two fonts being available on your system, so if you don't have the ones
that appear in the code, change it to suit what you have.