Java Reference
In-Depth Information
applet method paint . This method takes a Graphics object as its single argument and
is not called directly by the applet, but is executed by the Web browser. In Swing
applets, however, the required components are added to the applet's surface within
method init (also executed implicitly by the browser) and no painting should be
specifi ed (though there is nothing that actually prevents us from doing so).
Taking the simplest possible example, we'll create an applet that displays a greeting
to the user. In order to avoid specifying painting onto the applet's window, we can
use a JLabel and add this to the applet (within method init , of course), just as we
would do for the application JFrame in a GUI application.
Remember that the applet class must extend class JApplet .
import java.awt.*;
import javax.swing.*;
public class AppletGreeting extends JApplet
public void init()
JLabel message =
new JLabel("Greetings!",JLabel.CENTER);
//Default layout manager for JApplet is
// BorderLayout
Just as we would do for a Java application, we save this applet with the name . We then compile it in the usual way:
However, before we can run it, we must place it in an HTML page via the
<APPLET> tag. This tag has three mandatory attributes (as well as a number of
optional ones):6
￿ CODE (specifying the name of the applet's .class fi le);
￿ WIDTH (specifying the width of the applet, in pixels);
￿ HEIGHT (specifying height of the applet, in pixels).
As will be the case for all subsequent applets in this chapter, we shall employ a
minimal HTML page:
<APPLET CODE = "AppletGreeting.class"
WIDTH = 300
HEIGHT = 150>
Search WWH ::

Custom Search