go to previous page   go to home page   go to next page

Answer:

Everything following the <head> tag will be counted as part of the heading. You might see nothing in the browser.


getWidth() and getHeight()

Not all browsers can run applets.     Not all browsers can run applets. If you see this, yours can not.     Not all browsers can run applets. If you see this, yours can not.

It is awkward to hard-code the width and height of the applet in the source code. The width and height given in the <applet> tag must agree with the code. A better way to do this is to use these two methods:

int getWidth()
  --- return the width of the applet

int get Height() 
  --- return the height of the applet

The width and height of the applet are coded in the <applet> tag. The code that draws the applet uses the two methods to get these values at run time. So now, different <applet> tags can ask for the same applet to paint different sized rectangles. The source code does not need to be recompiled for different sizes.

The following code shows the circle applet modified to use these methods.

Since the drawing area varies in size, the radius needs to be based on the smallest of height and width.

The three applets at the top of this page are all running the same applet code with different height and width in the tag. (Click on "View" "Page Source" in your browser to see the HTML tags.)


import javax.swing.JApplet;
import java.awt.*;

// Draw a centered circle.
// Get the height and width from the web page.
// Base the radius on the smallest of the two.
public class JustOneCircleRev extends JApplet
{

  public void paint ( Graphics gr )
  { 
    int width  = getWidth();
    int height = getHeight();
    int radius;
    
    if ( width<height )
      radius = 2*width/5;
    else
      radius = 2*height/5;
    
    gr.setColor( Color.white );
    gr.fillRect( 0, 0, width, height );
    gr.setColor( Color.black );

    gr.drawOval( (width/2 - radius), (height/2 - radius), radius*2, radius*2 );
   }
}


QUESTION 16:

Would it be easy to modify this code so that it draws an oval in the rectangle specified in the <applet> tag?