Can someone comment what each line of code is doing in this program? I know it p
ID: 669352 • Letter: C
Question
Can someone comment what each line of code is doing in this program? I know it prints out a ruler but I dont understand what each line of code does?
import java.awt.Frame;
import java.awt.Graphics;
public class Ruler extends Frame
{
private static final int theSize = 511;
public void paint( Graphics g )
{
drawRuler( g, 10, theSize - 1 + 10, 8 );
}
private void drawRuler( Graphics g, int left, int right, int level)
{
if( level < 1 )
return;
int mid = ( left + right ) / 2;
//*************
//**** drawing in slow motion
try { Thread.sleep( 300 ); }// try with 1000
catch( InterruptedException e ) { }
//*************/
g.drawLine( mid, 80, mid, 80 - level * 5 );
drawRuler( g, left, mid - 1, level- 1 );
drawRuler( g, mid + 1, right, level - 1 );
}
// Simple test program
// For simplicity, must terminate from console
public static void main( String [ ] args )
{
Frame f = new Ruler( );
f.setSize( theSize + 20, 110 );
f.setVisible( true );
}
}
Explanation / Answer
1. import java.awt.frame
awt(Abstract windowing toolkit) is a java package and imports java.awt.frame through import keyword. Frame is a container class.
2.import java.awt.Graphics
imports class Graphics of awt library
3.public class Ruler extends Frame
class ruler extends class Frame. Public means the clas is accessible everywhere.
4.private static final int theSize = 511
private is access modifier. It means the variable theSize is accessible in its own class only. Static means all objects have common property.
5. public void paint( Graphics g )
It is definition of function paint that works on parameter g of graphics type.
6. drawRuler( g, 10, theSize - 1 + 10, 8 )
It is a function declaration with 4 variables
7. Thread.sleep( 300 )
stops the execution of a thread for 300 sec
8. try-catch block is used in exeption handling. try has the code that may throw exception whereas catch has the code that handles the exception.