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

Answer:

A subclass inherits the methods and instance variables of its superclass and can add its own methods and override methods of the super class.


JPanel

Clear White Screen

The SnowFlakePanel extends the class JPanel. It overrides the constructor and by overriding the paintComponent() method. Other methods of JPanel are inherited unchanged.

import javax.swing.*;
import java.awt.* ;
import java.lang.Math ;

class SnowFlakePanel extends JPanel
{

  public SnowFlakePanel()
  {
    setPreferredSize( new Dimension(400, 400) );
    setBackground( Color.WHITE );    
  }  
 
  public void paintComponent ( Graphics gr )
  { 
    int width  = getWidth();
    int height = getHeight();
    
    super.paintComponent( gr );
    gr.setColor( Color.BLUE );
    gr.drawLine( 0, 0, width-1, height-1 );
  }
}

More Details: (Skip if you don't need a review.)

setPreferredSize( new Dimension(400, 400) );

This sets the initial size of the panel. When the pack() method of the frame is invoked, the frame will become this size.

setBackground( Color.WHITE );

This makes the background of the new panel white.

public void paintComponent ( Graphics gr )

This overrides the method that is inherited from the superclass JPanel. It is called by the Java system whenever the panel needs to be drawn. If you don't override it with your custom code, the superclass's method will be called, and it does little.

getWidth()

This is an inherited method of JPanel. It gets the width in pixels of the panel (of course). getHeight() gets the height.

super.paintComponent( gr );

Call the super class's method first before doing the particular things needed in the subclass.

gr.setColor( Color.BLUE );

The Graphics object (which has the methods for drawing on the panel) will use the color blue to draw.

gr.drawLine( 0, 0, width-1, height-1 );

Draw a diagonal line (in blue) from the top left corner at (0,0) to the bottom right corner at ( width-1, height-1 ) .

QUESTION 5:

What is the basic form of our snow flake?