SE450: Java Applets [30/41] ![]() ![]() ![]() |
Applets are embedded in html pages, and are run by the web browser that is displaying the page.
We won't be spending any time with applets in this class, but here is an example:
import java.awt.*; import java.applet.Applet; public class HelloApplet extends java.applet.Applet { public void paint(Graphics g) { Dimension d = getSize(); g.setColor(Color.black); g.fillRect(0,0,d.width,d.height); g.setFont(new Font("Sans-serif", Font.BOLD, 24)); g.setColor(new Color(255,215,0)); g.drawString("Hello World!", 40, 25); } }
And the corresponding html file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>SE450 Hello World</title> </head> <body> <center> <applet code="HelloApplet.class" width="300" height="100"> </applet> </center> </body> </html>
To run the applet, open the html file with appletviewer or a java enabled web browser.
The superclass of all applets is java.applet.Applet
There is no main() method, it is loaded and run by the browser
paint() method paints the picture, but there are three methods that are called implictly by the browser:
The applet tag in the html file needs to expose the source code, width, and height the applet will use on the page.
Applets use a sandbox security model, they can't open network connections to other hosts, start programs, or issue OS commands, unless the user explicitly grants these privileges.