Embedding an Applet in HTML
PaintApplet from the previous lesson compiles into a plain .class file - on
its own, nothing about it says "web page." What actually told an old browser to load it, size it, and
drop it into the page was a piece of HTML markup. This lesson shows you that markup so you can
recognize it in old code and textbooks. No new Java code is introduced here.
The Classic <applet> Tag
The original, simplest way to embed PaintApplet looked like this:
<applet code="PaintApplet.class" width="400" height="300">
Your browser cannot run Java applets.
</applet>
| Attribute / content | Meaning |
|---|---|
code | The compiled class to load - here, PaintApplet.class, produced by javac as in the previous lesson. |
width | The width, in pixels, of the rectangular area the browser reserves for the applet - this is exactly what PaintApplet.getWidth() would report at runtime. |
height | The height, in pixels, of that same area - what getHeight() would report. |
| Text between the tags | Fallback content shown only by browsers that don't understand the <applet> tag at all (or have no Java plugin) - conceptually similar to alt text on an <img>. |
This is exactly the markup you already used with appletviewer in
Environment Setup - appletviewer understands
this tag and gives you a working preview window, even though a real browser today would simply render
the fallback text (or nothing at all).
The Later <object> / <embed> Variants
As browsers evolved, the plain <applet> tag was gradually superseded by more
generic <object> and <embed> tags carrying MIME-type parameters
that pointed at the Java plugin, often written together so different browsers could pick whichever
one they supported:
<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
width="400" height="300">
<param name="code" value="PaintApplet.class">
<embed type="application/x-java-applet"
code="PaintApplet.class" width="400" height="300">
</embed>
Your browser cannot run Java applets.
</object>
Functionally this aimed at the same goal as the plain <applet> tag - load
PaintApplet.class into a 400×300 area - but with browser-specific plugin-detection
plumbing bolted on. It is just as dead as the tag it replaced; every browser that could run either one
is long gone from general use.
PaintApplet render, use appletviewer with the plain
<applet> markup and a JDK 8 install, exactly as shown in
Environment Setup - not by opening either snippet above in
an actual browser.
<applet code="..." width="..." height="..."> tag was the classic
way to embed a compiled applet class in a page, later joined by <object>/
<embed> variants with plugin-detection parameters. Both are dead in every current
browser; only appletviewer still understands this markup today.
PaintApplet has used plain AWT. See how Swing's
richer component model changes the picture in JApplet and Swing
Components.