/* FILE : GraphicsProgram.java */

import java.awt.*;

class Shape {
  protected Color color;
  protected int x;
  protected int y;
  protected Shape(Color c, int x, int y) {
    color = c;
    this.x = x;
    this.y = y;
  }


  public abstract void draw();
}



class Rectangle extends Shape {
  private int width;
  private int height;
  public Rectangle(Color c, int x, int y, int width, int height) {
    super(c, x, y);
    this.width = width;
    this.height = height;
  }
  public void draw() {
     System.out.println("rectangle : " + x    + " , 
                                     " + y + ", " + width + ", "+ Height);
  }
}

class Circle extends Shape {
  private int radius;

  public Circle(Color c, int x, int y, int radius)  {
    super(c, x, y);
    this.radius = radius;  
  }
 
  public void draw()  {
    System.out.println ("Circle: "+ x + ", "+ y + ", " + radius);
  }
}



public class GraphicsProgram  {
  public static void main(String args[])  {
     Shape s1 = new Rectangle(Color.red, 0,5,200,300);
     Shape s2 = new Circle(Color.green, 20, 30, 100);
   
     s1.draw();
     s2.draw();
  }
}

===============================================================


class Body
{
 public long idNum;
 public String name = " ";
 public Body orbits = null;
 private static long nextID = 0;
 Body()
 {
   idNum = nextID++ ;
 }
}

or

class Body 
{
 public long idNum;
 public String name = " ";
 public Body orbits = null;
 private static long nextID = 0;
 Body()
 {
   idNum = nextID++ ;
 }  
 public long id()
 { return idNum; }
 public String planetName()
 { return name; }
}

------------------------------------------------------


//  "toString" Method

class Body
{
 public long idNum;
 public String name = " ";
 public Body orbits = null;
 private static long nextID = 0;
 Body()
 { idNum = nextID++ ; }
 Body(String bodyName, Body orbitsAround)
 { this();
   name = bodyName;
   orbits = orbitsAround;
 }
 public String toString()
 { String desc = idNum + "(" + name + ")" ;
   if (orbits !=null)
        desc += "orbits" + orbits.toString();
   return desc;
 }
}

-------------------------------------------------


parent 1			parent 2


		printable
   		   class


class 1				class2



Need a "print" for class 1 @ class 2. Java only supports single inheritance.


Solution : Use interfaces

class ClassName implements
      interface1, interface2, ...

{ ...;
} 


 [public] interface Printable
 {
   void print();
 }

 class class1 implements Printable
 {
   void print()
     { System.out.println ("one"); }
 }

 class class2 implements Printable
 {
   void print()
     { System.out.println ("two"); }
 }  


 interface Lookup
 { Object find(String name); }

 class SimpleLookup implements Lookup
 {
   private String[] Names;
   private Object[] Values;
   public Object find(String name)
   { 
     for (int i=0; i < Names.length;i++){
     	if(Names[i].equals(name))
		return Values[i];
       }
       return null;
    }
}

------------------------------------------------------

Java Exceptions 

(General error handling method)

Exception mechanism :

  to signal exception :
    
     throw new ExceptionName();
 
  to set up exception handler :

try { . . .
    }
catch [ExceptionType e1)
    { . . .
    }


example :
/* when closing file */

File file;
try {
   file = new File("filename");
   file.write("good");
   file.write("boy");
    }

catch (IOException e)
    { . . .
       return;
    }

finally {
          file.close();
        }



// Java Exceptions

class IllegalAverage extends Exception
{
}

class myclass
{
  public double average(double[] vals, int i, int j)
    throws IllegalAverage
  {
    try
       {
	return (vals[i] + vals[j])/2;
       }
    catch(IndexOutofBoundsException e)
    {  throw new IllegalAverage();  }
  }
}

-------------------------------------------------------------

/* Displaying multiple strings*/

import java.applet.Applet; // import Applet class
import java.awt.Graphivs;  // import Graphics class

public class Welcome extends Applet  {
  public void paint(Graphics g)
  {
    g.drawString("Welcome to", 25, 25);
    g.drawString("Java Programming", 25, 40);
  }
}


-------------------------------------------------------------


// Additional program

import java.awt.*;  // import the java.awt package
import java.applet.Applet;

public class Additional extends Applet {
  Lable prompt;	  // prompt user to input    
  TextField input // input values here
  int number;	  // store input value
  int sum;	  // store sum of integers

// setup the graphical user interface components
// and intialize variables

  public void init()
  {
    prompt = new Label ("Enter integer and press enter: ");
    input = new TextField ( 10 );
    add (prompt);  // put prompt on applet
    add (input);   // put input on applet
    sum = 0;       // set sum to 0
  }


// process user's action on the input text field

  public boolean action (Event e, Object o)
  {
    number = Integer.parseInt(o.toString() ); // get number
    input.setText (""); // clear data entry field
    sum = sum = number; // add  number to sum
    showstatus (Integer.toString (sum) ); // show result
    return true; // indicates user's action was processed
  }
}

-----------------------------------------------------------------

// Using if statements, relational
// operators and equality operators

import java.awt.*;
import java.applet.Applet;

public class Comparison extends Applet {
  Lable prompt1 ; 	// prompt user to input first value  
  TextField input1;	// input first value here Lable prompt1 ;       
  Label prompt2 ;       // prompt user to input second value
  TextField input2;     // input second value here Lable prompt2 ;

// setup the graphical user interface components
// and intialize variables

  public void init()
  {
    prompt1 = new Label (" Enter an integer ");
    input1 = new TextField (10);
    prompt2 = new Label ( " Enter an integer and press Enter ");
    input2 = new TextField (10);
    add (prompt1); 	// put prompt1 on applet
    add (input1);      // put input1 on applet4
    add (prompt2);      // put prompt2 on applet
    add (input2);      // put input2 on applet
  }

// display the results

public void paint ( Graphics g )
{
  g.drawString ("The Comparison results are: ", 70, 75);

  if (num1 == num2)
      g.drawString ( num1 + " == " + num2, 100, 90);

  if (num1 != num2)
      g.drawString ( num1 + " != " + num2, 100, 105);

  if (num1 < num2)
      g.drawString ( num1 + " < " + num2, 100, 120);

  if (num1 > num2)
      g.drawString ( num1 + " > " + num2, 100, 135);

  if (num1 < = num2)
      g.drawString ( num1 + " < = " + num2, 100, 150);

  if (num1 < = num2)
      g.drawString ( num1 + " > = " + num2, 100, 165);
  }


// process user's action on the input2 text field 

public boolean action (Event event, Object o)
{
  if ( event.target == input2) {
     num1 = Integer.parseInt( input1.getText() );
     num2 = Integer.parseInt( input2.getText() );
     repaint();
    }
  return true; // indicates user's action was processed
  }
}

=============================================================

// Fig.  LinearSearch.java
// Linear search for an array

import java.applet.Applet;

public class LinearSearch extends Applet  {
  int a[];
  int element;
  String searchKey;
  Label enterLabel;
  TextField enter;
  Label resultLabel;
  TextField result;

  public void init()
  {
    a = new int[100];
    for (int i=0; i < a.length; i++) // create data
    a[i] = 2 * i;
   
    enterLabel = new Label ("Enter integer search key");
    enter = new TextField(10);
    resultLabel = new Label ("Result");
    result = new TextField(25);
    result.setEditable(False);
    add(enterLabel);
    add (enter);
    add (resultLabel);
    add (result);
  }

  public int linearSearch( int key)
  {
    for (int n=0; n < a.length; n++)
       if (a[n] == key)
          return n;
  return -1;
}


public boolean action(Event, Object o)
{
  if (event.target == enter)  {
     searchKey = event.arg.toString();
     element = linearSearch ( Integer.parseInt (searchKey));

     if (element != -1)
       result.setText ("Found value in element ' + element);
      else
       result.setText ("Value not found");
  }
  return true;
 }
}

===========================================================

// Time class definition

public class Time  {
  private int hour;  	// 0 - 23
  private int minute	// 0 - 59
  private int second	// 0 - 59
	
     // Time constructor intializes each instance variable
     // to zero. Ensures that Time object starts in a consistent state.
     public Time()  { setTime( 0, 0, 0 );  }
  
     // Time constructor: hour supplied, minute, second
     // defaulted to 0.
     public Time(int h)  { setTime( h, 0, 0 );  }

     // Time constructor: hour and minute supplied, second
     // defaulted to 0.
     public Time(int h, int m)  { setTime( h, m, 0 );  }
  
     // Time constructor: hour, minute, second supplied
     // defaulted to 0.
     public Time(int h, int m, int s)  { setTime( h, m, s );  }

     // Set Methods
     // Set a new Time value using military time. Perform
     // validity checks on the data. Set invalid values to zero.
     public void setTime(int h, int m, int s)   }  
     {
    	setHour(h);  	// set the hour
   	setMinute(m)	// set the minute
	setSecond(s)	// set the second
     }

     // set the hour
     public void setHour(int h)
    	{ hour = ((h  > = 0 && h < 24 ) ? h : 0);  }

     // set the minute
     public void setMinute(int m)
        { minute = ((m >= 0 && m < 60 ) ? m : 0);  }
 
     // set the second
     public void setSecond(int s)
        { second = ((s > = 0 && s < 60 ) ? s : 0);  }

     // Get Methods
     // get the hour
     public int getHour() { return hour ;  }

     // get the minute
     public int getMinute() { return minute ;  }

     // get the second
     public int getSecond() { return second ;  }

     // Convert Time to String in military-time format
     public String toMilitaryString()
     {
        return (hour<10 ? "0" : "" ) + hour +
               (minute < 10 ? "0" : "") + minute;
     }

     // Convert Time to String in standard-time format
     public String toString()
     {  
       return ( ( hour == 12 || hour == 0) ? 12 : hour % 12) +
              ":" + (minute < 10 ? "0" : "") + minute +
              ":" + (second < 10 ? "0" : "") + second +
              (hour < 12 ? " AM" : " PM" );
     }
  }
=================================================================

  // Demonstrating the Time class set and get methods

  import java.awt.*;
  import java.applet.Applet;

  public class TimeTest extends Applet  {
  	private Time t;
	private Label hrLabel, minLabel, secLabel;
	private TextField hrField, minField, secField, display;
	private Button tickButton;

	public void init()
	{
	  t = new Time();

	  hrLabel = new Label( "Set Hour") ;
	  hrField = new TextField (10);
	  minLabel = new Label( "Set Minute") ;
          minField = new TextField (10);
 	  secLabel = new Label( "Set Second") ;
          secField = new TextField (10);
	  display = new TextField (30)
          display.setEditable ( false );
	  tickButton = new Button( " Add 1 to Second" );

	  add(hrLabel);
	  add(hrField);
	  add(minLabel);
	  add(minField);
	  add(secLabel);
	  add(secField);
	  add(display);
  	  add(tickButton);
	  updateDisplay();
  }

  public boolean action (Event e, Object o)
  {
    if (e.target == tickbutton)
       tick();
    else if (e.target == hrField)  {
       t.setHour (Integer.parseInt (e.arg.toString() ) );
       hrField.setText( "");
    }
    else if (e.target == minField)  {
       t.setMinute (Integer.parseInt (e.arg.toString() ) );
       minField.setText( "");
    }
    else if (e.target == secField)  {
       t.setSecond (Integer.parseInt (e.arg.toString() ) );
       setField.setText( "");
    }

    updateDisplay();

    return true;
  }
  
  public void updateDisplay()
  {
    display.setText( " Hour: + t.getHour + ";
         Minute: " + t.getMinute() + ";
         Second: " + t.getSecond() );
    showStatus( "Standard time is: " + t.toString() + " ;
	 Military time is: " + t.toMilitaryString() );
  }

  public void tick()
  {
    t.setSecond ( (t.getSecond() + 1) % 60);
    
    if ( t.getSecond() == 0)  {
        t.setMinute( ( t.getMinute() + 1) % 60);
   
        if ( t.getMinute() == 0)  {
        t.setHour( ( t.getHour() + 1) % 24);
    }
    }    }
}


================================================================

// Demonstrates the static character conversion methods
// of class Character from the java.lang package.
import java.awt.*;
import java.applet.Applet;

public class StaticCharMethod2 extends Applet  {
  char c; 
  int digit, radix;
  boolean ChartoDigit;
  Label prompt1, prompt2;
  TextField input, radixField;
  Button toChar, toInt;

  public void init()
  {
    c = 'A';
    radix = 16;
    chartoDigit = true;

    prompt1 = new Label( "Enter a digit or character ");
    input = new TextField ("A", 5);
    prompt2 = new Label ( "Enter a radix");
    radixField = new TextField ("16", 5);
    toChar = new Button ("Convert digit to character");
    toInt = new Button( "Convert character to digit");
    add(prompt1);
    add(input);

    add(prompt2);
    add(radixField);
    add(toChar);
    add(toInt);
  }

  public void paint (Graphics g)
  {
    if (chartoDigit)
       g.drawString(" Convert character to digit: " +
      	 Character.digit (c, radix), 25, 125);
	 
    else
       g.drawString(" Convert digit to character: " +
         Character.digit (c, radix), 25, 125);

  }
 
  public boolean action( Event e, Object o)
  {
    if (e.target == toChar)  {
	chartoDigit = false;
	digit = Integer.parseInt( input.getText() );
       	radix = Integer.parseInt( radixField.getText() );
	repaint();
    }
    else if (e.target ==toInt) {
	chartoDigit = true;
	String s = input.getText();
	c = s.charAt(0);
	radix = Integer.parseInt(RadixField.getText() );
    }
    return true;
  }
}

============================================================

//    MyLabel.java
// Demonstrating the Label class constructors.
import java.applet.Applet;
import java.awt.*;

public class Mylabel extends Applet  {
  private Font f;
  private Label noLabel, textLabel;

  public void init()
  {
    f = new Font( "Courier", Font.BOLD, 14);
    
    // call Label constructor with no text
    noLabel = new Label();

    // call label constructor with a string argument
    textLabel = new Label( "This is read-only text");

    // set font for text displayed in Label
    textLabel.setFont (f);

    // add label components to applet container
    add (noLabel);
    add (textLabel);
  }
}

======================================================

//    MyLabel2
// Demonstrating the Label getText and setText.
import java.applet.Applet;
import java.awt.*;

public class Mylabel2 extends Applet  {
  private Font f;
  private Label noLabel;

  public void init()
  {
    f = new Font( "Courier", Font.BOLD, 14);

    // call Label constructor with no text
    noLabel = new Label();

    // set text in noLabel
    noLabel.setText ("new text!");

    // set font for noLabel
    noLabel.setFont(f);
   
    // add label component
    add( noLabel);
}

public void paint(Graphics g)
 {
  // get noLabel's text
  showStatus( "Label is displaying: " + noLabel.getText() );
 }
}

===============================================================

// MyButtons.java
// Creating push buttons.
import java.applet.Applet;
import java.awt.*;

public class MyButtons extends Applet  {
  private Button pushButton1, pushButton2, pushButton3;

  public void init()
  {
    pushButton1 = new Button( "Click here");
    pushButton1 = new Button( "Sorry I don't do anything"); 
    pushButton1 = new Button();  // no button label

    // add buttons
    add (pushButton1) ;
    add (pushButton2);
    add (pushButton3);

  // handle the button events
  public boolean action(Event e, Object o)

   // check to see if a button triggered the event
   if (e.target instanceofButton )  {
	// check to see if pushButton1 or pushButton3
 	// was pressed. Nothing will be done if 
	// pushButton2 was pressed.
        if ( e.target == pushButton1)
	   showStatus ("You pressed: " + o.toString() );
	elseIf (e.target == pushButton3)
	   showStatus ("You pressed: " + e.arg);

	return true;  // event was handled here
  }

return true;

===============================================================

Class TextField.constructor

public TextField()
  Constructs a TextField object 

public TextField (int columns) // number of columns
  Constructs an empty TextField object with the specified number of columns

public TextField( String s) // text displayed in the text field
  Constructs a TextField object displyaing s.

public TextField (
  String s,		// text displayed in text field
  int columns  )	// number of columns
  Constructs a TextField object displyaing s in the specified no. of columns
  
==============================================================

//   MyTextField.java
// Demonstrating the TextField class constructors.
import java.applet.Applet;
import java.awt.*;

public class MyTextField extends Applet  {
  private TextField text1, text2, text3, text4;

  public void init()
  {
    // construct text field with default sizing
    text1 = new TextField (); 

    // construct text field with default text
    text2 = new TextField ("some text ");
 
    // construct text field with 25 elements visible
    text3 = new TextField (25);
    
    // construct text field with default text and
    // 40 visible elements
    text4 = new TextField ("Yet some more text", 40);

    // add text fields to applet
    add(text1);
    add(text2);
    add(text3);
    add(text4);
  }
}

==============================================================

//   MyTextField2.java
// Demonstrating the TextField events.
import java.applet.Applet;
import java.awt.*;

public class MyTextField extends Applet  {
  private TextField message, passwordField, message2;
  private String password;

  public void init()
  {
    password = "Marak954"; // set password
    message = new TextField( "Enter password: ");
    message.setEditable(false);

    // add text fields to applet
    add (message);
    add (passwordField);
    add(message2);
  }

  public boolean action (Event e, Object o)
  { 
    // check to see if a text field trriggered the event
    if ( e.target instananceof TextField)
 	// check to see if it was the text field passwordField
	if (e.target == passwordField)
	
	   // check for correct password
	   if (e.arg.equals(password))
	      message2.setText("access Granted");
 	   else
	      message2.setText( "Invalid password. " + "Access Denied" );

    return true;  // event was handled here
  }
}

======================================================================

//    MyChoice.java
// Using a choice button to select a font.
import java.applet.Applet;
import java.awt.*;

public class MyChoice extends Applet  {
  private Choice choiceButton;
  private TextField t;
  private Font f;

  public void init()
  {
    choiceButton = new Choice();
    t = new TextField( "Sample Text", 16);
    t.setEditable (false);

    // add items to choiceButton
    choiceButton.addItem( "TimesRoman");
    choiceButton.addItem( "Courier");
    choiceButton.addItem( "Helvetica");

    f = new Font (ChoiceButton.getItem(0),
			Font.Plain, 14);
    t.setFont (f);
    add (choiceButton);
    add(t);
  }

  public boolean action (Event e, Object o)
  {
    String s;
    
    // Check for Choice button event
    if ( e.target instanceof Choice)  {
	f = new Font (ChoiceButton.getSelectedItem(),
		  	Font.PLAIN, 14);

        t.setFont (f);

        s = "Number of items: " + choiceButton.countItems();
  
        s += "   Current index: " + choiceButton.getSelectedIndex();

      	showStatus (s);
    }
    return true;
  }
}

==================================================================

//    MyCheckbox.java
// Creating Checkbox buttons.
import java.applet.Applet;
import java.awt.*;

public class MyCheckbox extends Applet  {
  private TextField t;
  private Font f;
  private Checkbox checkBold, CheckItalic;

  public void init()
  {
    t = new TextField( "Sample Text", 30 );
    
    // instantiate checkbox objects
    checkBold = new Checkbox("Bold");
    checkItalic = new Checkbox();
    checkItalic.setLabel("Italic"); // set checkbox label

    f = new Font("TimesRoman", Font.PLAIN, 14);
    t.setFont (f);

    add(t);
    add(checkBold);   // unchecked (false) by default
    add(checkItalic); // unchecked (false) by default
  }


	public boolean action(Event e, Object o)
	{
	  int b, i;
	  
	  // Check for Checkbox event
 	  if (e.target instanceof Checkbox )  {
	  
	    // test state of bold checkbox
 	    if ( checkBold.getState() == true )
	       b = Font.Plain;   // value of 0
 	    
	    // test state of italic checkbox
            if ( checkitalic.getState() == true )
               b = Font.ITALIC;   // value of 0
	    else
	       i = Font.Plain;    // value of 0

	    f = new Font("TimesRoman", b + i, 14);
  	    t.setFont(f);
	}
        return true;
      }

================================================================

//    RadioButton.Java
// Creating radio buttons using Checkboxgroup and CheckBox.
import java.applet.Applet;
import java.awt.*;

public class RadioButtons extends Applet  {
  private TextField t;
  private Font f;
  private Checkbox radioBold, radioItalic, radioPlain;

  public void init()
  {
     t = new TextField( "Sample Text", 40 );

    // instantiate checkbox group (i.e. radio buttons)
    radio = new checkboxGroup();

    add(t); // add text field

    // instantiate radio button objects
    add (radioPlain  = new Checkbox ("Plain", radio, true));
    add (radioItalic = new Checkbox("Italic", radio, false));
    add (radioBold = new Checkbox ("Bold", radio, false));
  }

  public boolean action (Event e, Object o)
  {
    int style;
    
    // Check for Checkbox event
    if (e.target instanceof Checkbox) {
       // test state of radio buttons
        if (radioPlain.getState() == true)
          style = Font.Plain;
        else if (radioItalic.getState() == true)
	  style = Font.Italic;
	else
	  style = Font.Bold;

 	f=new Font("TimesRoman", style, 14);
	t.setFont (f);
    }

    return true;
  }
}

=========================================================

//    MyList.Java
// Creating a list.
import java.applet.Applet;
import java.awt.*;

public class MyList extends Applet  {
  private List colorList;

  public void init()
  {
    // create a list with five items visible
    // do not allow multiple selections colorList = new List(5,false);
     
    // add four items to the list
    colorList.addItem("White");
    colorList.addItem("Black");
    colorList.addItem("Yellow");
    colorList.addItem("Green");

    // add list to applet
    add (colorList);
  }

  public boolean action (Event e, Object o)
  {
    // test for a list
    if (e.target instanceof List)  {
      if (e.arg.equals("Yellow"))
	setBackground(Color.yellow);
      else if (e.arg.equals("White"))
        setBackground(Color.white);
      else if (e.arg.equals("Black"))
        setBackground(Color.black);
      else (e.arg.equals("Green"))
        setBackground(Color.green);

      repaint();
    }
    return true;
  }
}


=========================================================

//    MyList2.Java
// Copying items from one List to another.
import java.applet.Applet;
import java.awt.*;

public class MyList2 extends Applet  {
  private List stateList, copyList;
  private Button copy;

  public void init()
  {
    // create a list with 5 items visible
    // allow multiple selections stateList = new List(5,true);

    // create a list with 5 items visible
    // do not allow multiple selections copyList = new List(5,false);
    
    // create copy button
    copy = new Button("Copy >>>");

    add some data to stateList
    stateList.addItem("Texas")
    stateList.addItem("Alaska")
    stateList.addItem("Florida")
    stateList.addItem("Montana")
    stateList.addItem("Mississipi")
    stateList.addItem("Delware")
    stateList.addItem("New Mexico")
    stateList.addItem("South Dakota")
    stateList.addItem("Vest Virginia")

    // add list to applet
    add (stateList);
    add (copy);
    add (copyList);
  }

  public boolean action (Event e, Object o)
  {
    String states[];
    
    // test for a button event
    if (e.target == copy)  {

	// get the selected states
	states = stateList.getSelectedItems();
    
      // copy them to copyList

      for ( int i = 0; i < states.length;  i++)
        copyList.addItem( states[i]);
   }
  }

===================================================