Step 2 prints text and draws several graphical shapes on the panel. To do this, we have to know that the java virtual machine calls (once) apaint
method as part of the start-up procedure for an applet. If the message is not handled in a class somewhere lower in the hierarchy, it will be processed in theComponent
class. Consequently, if you want to draw something on your applet's panel, you must override thepaint
method in theComponent
class.Example Applet
import java.applet.Applet; import java.awt.*; public class step2 extends Applet{ // draws public void init ( ){ setBackground (Color.white); setForeground (Color.red); } // end init public void paint (Graphics g ) { g.fillRect (50, 50, 100, 100); g.setColor (Color.blue); g.setFont (new Font ("Helvetica", Font.BOLD, 24) ); g.drawString ("Hello, World!", 200, 200); g.setColor (Color.yellow); g.drawOval (300, 50, 100, 100); g.setColor (Color.green); g.fillArc (50, 300, 200, 200, 180, -90); g.setColor (Color.cyan); g.fill3DRect (300, 300, 100, 100, true ); } // end paint }// end step2Run the applet
Discussion
When the Java virtual machine calls the
paint
method, it passes to it something called a Graphics context. Since hardware and software platforms differ in the ways they support graphics operations, theGraphics
class is an abstract specification for a set of graphics operations that must be implemented in the local environment.Thus, your Java program will receive a graphics object produced by this local class that it can use to perform the various graphics operations. All of this is manifest in prefixing the name for the passed Graphics object to the particular
Graphics
method you wish to use, such assetColor
ordrawOval
. In the example code, above, that name is"g"
.