Mr. Meinzen - Java Handouts (first 9 weeks)

"Success is the ability to go from one failure to another with no loss of enthusiasm." Winston Churchill

Java Handout: Program 1

 

Your teacher will provide a printout for the first assignment.

 

The student learning objectives include:

  • learning basic editing, compiling, and running of two similar programs (an application and an Applet).

  • following clear and explicit step-by-step instructions fully and carefully.

  • correcting any mistakes in the provided step-by-step instructions.

  • communicating with their teacher and/or peers while following the provided step-by-step instructions.

  • debriefing after assignment is turned in for scoring (i.e. analysis of the grading rubric and code conventions as applied to their assignment)

  • Students are NOT expected to understand Java programming.

Java Handout: Program 2 - Sample Code & Assignment


Sample Code for Program 2


/**
* File:  			PetRock.java
* Author:			Mr. Meinzen
* Programming:	  	1st Hour, [Honors] Programming in Java
* Last Modified: 	July 2001
* Description: This application creates, prints, and computes
* the area of a pet rock (a rectangle with a name)
*/

public class PetRock
{
	private int    length;			// length of rectangular rock
	private int    width;			// width of rectangular rock
	private String name;			// name of rock

	/**
	* The PetRock() method constructs the pet rock with a given
	* length and  and name.
	*/
	public PetRock()
	{
		name 	= "Mr. Meinzen's Pet Rock";
		length	= 30;
		  	= 70;
	}	// PetRock constructor

	/**
	* The calculateArea() method calculates and returns
	* the area of the (rectangular) rock.
	*/
	public double calculateArea()
	{
		double area;
		area = length * width;
		return area;
	}	// calculateArea()

	/**
	* The drawRock() method prints out the rock's length &  as well
	* as the name of the rock then computes and prints the area
	* of the rock using the calculateArea() method.
	*/
	public void drawRock ()
	{
		System.out.println("Hello to the Pet Rock Program");
		System.out.println("");
		System.out.println("The name of my rock is "+name);
		System.out.println("The width of my rock is "+width);
		System.out.println("The length of my rock is "+length);
		System.out.println("The area of my rock is "+calculateArea());
	}	// drawRock()

	/**
	* The main() method starts everything
	*/
	public static void main(String argv[])
	{
		PetRock myPetRock;          // declare an empty PetRock variable called "myPetRock"
		myPetRock = new PetRock();  // create (instantiate) the new PetRock.
		myPetRock.drawRock();       // prints out the rock's information on the screen
	}	// main()
}	// PetRock()

          

Program 2 Assignment for Programming in Java & Honors Programming in Java:

 

Modify the PetRock application program to:

  • Make your pet a circle rather than a rectangle

  • Bonus points for making it an oval

  • Make sure it is "your" pet. (i.e. change the name)

  • Make sure you comment and indent properly!!!

Keep a printed copy of your teacher's PetRock program handy it will serve as a good reference while you are typing your programs.

 

Program 2 Optional Challenge (Bonus) Assignment for Honors Programming:

  • You are to complete the above assignment as well as add another method (verb) to your PetRock that will allow you to change the name of your rock.

  • This method will be called setName().

  • Hint: The body of the setName() method will be an assignment (i.e. = ) that is one line long.

  • Replace the main() method with the following code:

public static void main( String a[])
{
	PetRock myPetRock;
	myPetRock = new PetRock();
	myPetRock.drawRock();
	myPetRock.setName("Bob");
	myPetRock.drawRock();
} 
 

Java Handout: Program 3 - Sample Code and Assignment

 

Sample Code for Program 3

 

/**
* File:  			PetRockGUI.java
* Author:			Mr. Meinzen
* Course:   	        1st Hour Programming in Java [HONORS]
* Last Modified: 	October 2020
* Description: This application creates a Graphical User Interface (GUI)
* by drawing, computing the area, and flipping a pet rock (a rectangle with a name)
*/

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

public class PetRockGUI extends JPanel implements ActionListener
{

     private JFrame  frameObject;   // DECLARE a frameObject variable of type JFrame
     private JButton buttonObject;  // DECLARE a buttonObject variable of type JButton
     private JLabel  labelObject;   // DECLARE a labelObject variable of type JLable

     private int     length;        // DECLARE a length of rectangular rock of type int
     private int     width;         // DECLARE a width of rectangular rock of type int
     private String  name;          // DECLARE a name of rock of type String

     /**
      * This is the main() method to start the application.
      * All it does is to declare and instantiate an instance (or "this" object) of PetRockGUI
      */
     public static void main(String a[])
     {
    	  // DECLARE and INSTANTIATE a game object/variable of type PetRockGUI
          PetRockGUI game = new PetRockGUI();
     }
     
     /**
     * Constructor method to declare, instantiate, and use the various components in the JFrame
     */
     public PetRockGUI()
     {
          length = 50;   // initialize the original length of rectangular rock to be 50 pixels
          width  = 100;  // initialize the original width of rectangular rock to be 100 pixels
          name   = "Mr. Meinzen's PetRock";

          Font niceFont = new Font("Courier New", Font.PLAIN, 24);  // DECLARE and INSTANTIATE a niceFont

          labelObject = new JLabel("My name is "+name); // INSTANTIATE JLabel object
          labelObject.setFont(niceFont);                // change the font of the JLabel object
          labelObject.setForeground(Color.RED);         // change the color of the JLabel object
          this.add(labelObject);                        // add JLabel object to "this" PetRockGUI JPanel object

          buttonObject = new JButton("Click me to flip");  // INSTANTIATE JButton object
          buttonObject.addActionListener(this);            // listen for clicks on the buttonObject
          this.add(buttonObject);                          // add button to "this" PetRockGUI JPanel object

          frameObject = new JFrame("My First Graphical Application"); // INSTANTIATE the JFrame object
          frameObject.setSize(500, 500);                              // frame is 500 pixels high x 500 pixels wide
          frameObject.setLayout(null);                                // no specific layout for frame
          frameObject.setContentPane(this);                           // put "this" JPanel object into the frame
          frameObject.setVisible(true);                               // display the frame on the screen
     }

     /**
     * The paintComponent() method draws the all Graphics (variable "g" is the screen)
     */
     public void paintComponent(Graphics g) 
     {
          super.paintComponent(g);         // first paint the objectLable & objectButton on the screen's JPanel,
          g.setColor(Color.GREEN);         // then set a green color for anything on the screen after this line
          g.fillRect(50,150,length,width); // then fill a rectangle to be painted green on top of screen.
     }

     /**
     * The flip() method will swap the length and width of rectangle
     */
     public void flip()
     {
          int temp = length;
          length   = width;
          width    = temp;
     }

     /**
     * The actionPerformed() method reacts to the user's clicking of buttons.
     */
     public void actionPerformed(ActionEvent e)
     {
          flip();
          repaint();
     }
}
          

Assignment 3 for both Java Programming & Honors Java Programming

 

Modify the PetRockGUI program to:

  1. Make your pet a circle or oval rather than a rectangle.

    • Hint: Look for g.fillRect(...) statement and modify to use g.fillOval(...);
  2. Make sure it is "your" pet. (i.e. change the name)

  3. Change the color - make sure you understand the g.setColor(...); statement and read "HINT" below

    • Bonus if you have two buttons: one to flip the rock and one to change colors
  4. Make sure you comment and indent properly!!!

  • HINT: To modify your PetRock to change colors, consider the following comments & questions:

    1. You will need to declare two field variables for the colors:

      • private Color color1;

      • private Color color2;

      • Where should you declare the colors?

    2. You will need to define (initialize) the color variables:

      • color1 = Color.red;

      • color2 = Color.blue;

      • In which method should you define the colors?

    3. How should you modify the paintComponent() method to use color1?

    4. How should you write (declare and call) another method like the flip() method that will swap the colors?

Assignment 3 for Honors Java Programming

  • create at least 3 pets, each pet should have:

    • A button that will either flip the pet or change its color

    • bonus if each pet has 2 buttons (one to flip and one to change color) for a total of 6 buttons

  • 2 pets must be different shapes (rectangles, ovals, circles, etc.)

  • at least one pet must change color

  • at least one pet must flip

 

Program 3 Optional Challenge (Bonus) Assignment for Java Programming & Honors Java Programming

  • Use an oval and have 2 buttons (one to flip called buttonObject and one to change color called colorButtonObject)

  • The following sample code will be useful for this optional bonus assignment:

public void actionPerformed(ActionEvent e)
{
     // check if buttonObject was clicked
     if (e.getSource() == buttonObject)
     {
         flip();
     }

     // check if colorButtonObject was clicked
     if (e.getSource() == colorButtonObject)
     {
         changeColor();
     }
     repaint();
}   // end actionPerformed()

          

 

Java Handout: Program 4 - Sample Code and Assignment

 

Sample Code for Program 4

 

/**
 * Name   : @author
 * Course :
 * Date   : 
 * (Write a description of your Pet class here...for example...)
 * Mr. Meinzen's DuckPet has a name and has the ability to quack or waddle.
 * Any other program/class that HAS A DuckPet object can command the
 * pet to quack() or to waddle() or can ask/request if the pet is quacking or waddling.
 * but no one can find out its name is "Bob"...except for the programmer.
 */
public class DuckPet
{
	  // instance variables - replace the example below with your own
	  private boolean isQuacking;
	  private boolean isWaddling;
	  private String  name;

	  /**
	  *
	  */
	  public DuckPet()
	  {
	  	  isQuacking = true;
		  isWaddling = false;
		  name       = "Bob";
	  }

	  public void quack()
	  {
	  	  isQuacking = true;
		  isWaddling = false;
	  }

	  public void waddle()
	  {
	  	  isWaddling = true;
		  isQuacking = false;
	  }

	  public boolean getIsQuacking()
	  {
	  	  return isQuacking;
	  }

	  public boolean getIsWaddling()
	  {
	 	  return isWaddling;
	  }

	  public String toString()
	  {
	  	  String temp = "My name is " + name; 
	  	  temp = temp + " and I am waddling is " + isWaddling;
	  	  temp = temp + " and I am quacking is " + isQuacking;
	  	  return temp;
	  }
}


/**
 * Name   : @author
 * Course :
 * Date   : 
 * (Write a description of class DuckPetOwner here...for example...)
 * Mr. Meinzen's DuckPetOwner has one DuckPet object called "myPet"
 * and the DuckPetOwner declares myPet, instantiates a new DuckPet,
 * and tells myPet to sleep then to eat.
 */
public class DuckPetOwner
{

	/**
	* An example of a method - replace this comment with your own
	*
	* @param  arg[]   a sample parameter for a method.  Not used here.
	* @return void    main() method does not return a value
	*/
	public static void main (String arg[])
	{
		DuckPet myPet;
		myPet = new DuckPet();
		System.out.println(myPet.toString());
		myPet.waddle();
		System.out.println(myPet.toString());
	}
}

Assignment 4 for Java Programming & Honors Java Programming

  1. Use UML diagram and create your own class similar to your teacher's DuckPet. Your UML class diagram should include:

    • the name of your class

    • two mutually exclusive boolean variables [Honors must have four boolean variables ,2 groups of two that are mutually exclusive]

    • two methods to change the boolean variables [Honors must have four methods]

    • a method called toString() that returns a description of your pet's name and what it is doing

  2. Get your teacher's signed approval (initials) on the UML diagram before programming (teacher's initials is part of scoring)

  3. Program your DuckPet class. Make sure it compiles without errors.

    • Note: your program will NOT have main() method.

  4. Program an application similar to your teacher's DuckPetOwner application. Your application should include:

    1. a class that will creates (declare & instantiate) and use (call methods) of an instance (object) your DuckPet

    2. the main() method should include:

      • - an object declaration of your DuckPet

      • - an object instantiation of your DuckPet

      • - a test of each of the methods of your DuckPetby calling each method

      • - use of the toString() method to print out the details about your pet

    3. compile and run your application & show your teacher

    4. make sure comments and indentation are correct.

  5. Copy and paste your application to the bottom of your DuckPet class and turn in.

    • This step is to minimize the waste of paper printed out...try to fit both programs on 1 sheet of paper so you aren't printing multiple pages...DO NOT print several pages in an attempt to fit the printout on one sheet...there are no bonus points gained or lost on this step.

  6. BONUS: declare, instantiate, and test two instances (objects) of your DuckPet in your DuckPetOwner.

Java Handout: JavaBeans Assignment

 

For each numbered problem, students should identify the following:

  1. the class (program name)

  2. the nouns (declare the field variables & types)

  3. for each noun, specify the "get" & "set" methods (accessor & mutator methods)

Sample:

  • "I want a program that creates a Cake that has a certain amount of sugar and with a specified size (height) as well as a description for the cake and whether it is a chocolate cake or not."

  • public class Cake

  • // nouns: sugar, milk, height, description, chocolateCake

  • // declare variables & types:

    • private int     sugar;
      private double  height;
      private String  description;
      private boolean chocolateCake;
      
  • //declare "get" and "set" methods (accessor & mutator)

    • public int getSugar()
      {
      	return sugar;
      }
      
      public double getHeight()
      {
      	return height;
      }
      
      public String getDescription()
      {
      	return description;
      }
      
      public boolean getChocolateCake()
      {
      	return chocolateCake;
      }
      
      public void setSugar(int s)
      {
      	sugar = s;
      }
      
      public void setHeight(double h)
      {
      	height = h;
      }
      
      public void setDescription(String d)
      {
      	description = d;
      }
      
      public void setChocolateCake(boolean c)
      {
      	chocolateCake = c;
      } 

Assignment:

  1. I want a program that creates a Tree that has a number of branches, leaves and a height as well as whether it is coniferous or not.
  2. I want a program that creates an Animal that has a size, a number of legs, name and whether it is a mammal or not.
  3. I want a program that creates a SuperHero that has a power level, an IQ, a description of abilities, and whether it wears armor or not.
  4. I want a program that creates a Flower that has a number of petals, a Color, a height and whether it can be grown in a mountain or not.
  5. I want a program that creates a mythological creature that has a size, holds 2 objects described by the above 5 (i.e. holds a flower & cake), a description and a name.
  6. I want a program that creates a Tardis that has two SuperHeroes, an Animal and a Mythological creature as well as another Tardis.

Java Handout: Program 5 - Sample Code and Assignment

 

Sample Code for Program 5

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


/* 0. TRY to use a UserInterface Manager
 * 1. DECLARE a frame, then a panel, then components
 *       a. components are buttons, textfield, labels, menus, etc.
 * 2. CONSTRUCT a frame, then a panel, then components
 *       a. create the components by adding pictures (Icons) if desired
 *       b. have buttons and textfields "listen" for actions
 * 3. CONSTRUCT a layout then ADD to panel
 * 4. ADD components to panel
 * 5. ADD panel to frame
 * 6. Set the Frame to be visible
 */

public class SwingTemplate extends JFrame implements ActionListener
{
	// frame which is the window with borders, title bar, min/max/exit buttons and panel.
	private static JFrame f;

	// panel that will huld the contents (i.e. all the components)
	private JPanel        p;

	/*****************************  These are all components */
	// buttons
	private JButton     fancyButton1;

	// text field
	private JTextField  text1;

	// labels
	private JLabel      fancyLabel1;

	// menus at the top of the frame
	private JMenuBar    menuBar;
	private JMenuItem   item1, item2;
	/*****************************  Ending the components */


	/** this is where we all start
	*/
	public static void main(String arg[])
	{
		try
		{
			UIManager.setLookAndFeel(
		                UIManager.getCrossPlatformLookAndFeelClassName());
		    //could try ...
		    //UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
		    //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		}
		catch (Exception e)
		{
			// do nothing if a problem...just quit
		}

		// this will really do all the work!
		// it declares and creates a new application
		SwingTemplate app = new SwingTemplate();

		// needed at bottom to of main() to be able to close the application
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// automatically resize window (use instead of setSize)
		f.pack();
		f.setVisible(true);
	} // main()

	/** constructor that creates or instatiates the frame, panel, layout, etc.
	*/
	public SwingTemplate()
	{
		// Create the overall window for the application
		f = new JFrame("Swing Template");

		// create the content panel to be put in the frame
		p = new JPanel();

		// set the layout which will be in a grid measuring 3 rows x 2 culumns
		GridLayout layout = new GridLayout(3,2);

		// set whichever layout is chosen above
		p.setLayout( layout);

		// call the following methods so that they will
		// create & add each of the labels, buttons, & textfields
		// to the content panel
		addLabelsToContentPanel();
		addButtonsToContentPanel();
		addFieldToContentPanel();
		addMenuToFrame();

		// finally add the content to the window
		f.setContentPane(p);
	}

	/**
	* create and add for the labels to the content panel
	*/
	public void addLabelsToContentPanel()
	{
		ImageIcon myPicture = new ImageIcon("butterfly.gif");
		fancyLabel1         = new JLabel("Fancy Label", myPicture, SwingConstants.LEFT);
		fancyLabel1.setToolTipText("tooltip for fancy label");
		p.add(fancyLabel1);
	}

	/**
	*  create, add, and attach events for the buttons to the content panel
	*/
	public void addButtonsToContentPanel()
	{
		// create a fancy button with pictures and a rollover
		ImageIcon frog    = new ImageIcon("frog.gif");
		ImageIcon buffalo = new ImageIcon("buffalo.gif");

		fancyButton1      = new JButton("Fancy Button", frog);
		fancyButton1.setRolloverIcon(buffalo);

		// add the button to the content pane then listen for clicks
		p.add(fancyButton1);
		fancyButton1.addActionListener(this);
	}

	/** create,add, and attach events for the text fields to the content panel
	*/
	public void addFieldToContentPanel()
	{
		text1 = new JTextField(10);     // create the textfield & set size to 10
		text1.setEditable(true)        // the user can change it
		p.add(text1);                   // add it to the content
		text1.addActionListener(this);  // listen for an mouse click
	}

	/** this will add menu items and a menu to the menuBar then add
	*   to the frame (not the panel)
	*/
	public void addMenuToFrame()
	{
		menuBar = new JMenuBar();

		JMenu menu = new JMenu("first menu");

		// create first menu item then listen for clicks and add to menu
		item1 = new JMenuItem("remove textfield");
		item1.addActionListener(this);
		menu.add(item1);

		// do the same for 2nd menu item
		item2 = new JMenuItem("Quit");
		item2.addActionListener(this);
		menu.add(item2);

		//add menu to the menuBar
		menuBar.add(menu);

		//finally add to frame
		f.setJMenuBar(menuBar);
	}

	/** handle the actions were taken in the application window
	*/
	public void actionPerformed(ActionEvent e)
	{
		// if button was pressed change the text field
		if (e.getSource() == fancyButton1)
		{
			// swap the text from fancy to plain and back again
			if (text1.getText().equals("fancy"))
			{
				text1.setText("plain");
			}
			else
			{
				text1.setText("fancy");
			}
		}

		// if the textfield was typed in then change the label
		if (e.getSource() == text1)
		{
			fancyLabel1.setText(text1.getText());
		}

		if (e.getSource() == item1)
		{
			// note:  won't remove from screen until resize/update called
			p.remove(text1);
		}

		if (e.getSource() == item2)
		{
			System.exit(0);
		}

		repaint();
	}

} // SwingTemplate
 

Assignment 5 for Java Programming & Honors Java Programming

 

Based upon the above sample GUI application class SwingTemplate, you will write a GUI application that displays your CyberPet from Program 4. The program will have the following specifications:

  • Familiarize yourself with the layout manager

  • Have at least 3 pets

  • Have at least 3 buttons

  • Have at least 3 textfields

  • Use of Icons, rollovers, or tooltips.

  • Your pet should have some graphical representation (i.e. an image that changes, text that changes the name of your pet, etc.)

 

Java Handout: Assignment for Terminology & Logic

 

Define the following and give an example of each.

 

primitive data types (at least 5)

object

class

identifier

instance or field variable

declaration

instantiation

assignment

method

condition

statement

interface

qualified name

 

Determine the final value of the variable.

 

A) B) C)
int x = 1;
x++;
x += 3;
int x = 4;
if (x == 6)
    x = 3;
int x = 3;
while (x < 7)
{
    x ++;
}
x =
x =
x =
 
D) E) F)
int x = 14;
x = x % 3;
x--;
int x = 4;
if ((x > 2) && (x < 7))
{
    x *= 5;
}
int x = 13;
for (int j=1; j < 4; j++)
{
    x = x + j;
}
x =
x =
x =

 

 

 

Reference Answers

 

primitive data types (at least 5) - pre-defined java information ( int, boolean, double, char, float, long, byte, etc.)

object - The "thing" created in the computer's memory that is described by a class. Objects contain field (or instance) variables and methods.

class - The program that is written in Java that describes objects by declaring and instantiating variables and using (or calling) methods.

identifier - The name a programmer chooses to give to a class, variable, or method. Examples: PetRock, side, main()

instance or field variable - An identifier in a class that refers to a memory location that holds data/information (i.e. a noun or ingredient). Usually declared above (not inside) all methods in a class.

declaration - When a programmer gives a variable a name and its type (ex. String name). Also, a method is declared when it is given a method header (name) and its body. Example: public void eat() {...}

instantiation - A programmer uses the reserved word "new" with a constructor to create an object in the computers memory. Example: new CyberPet();

assignment -A programmer uses the "=" to give a variable a value (ex. x = 5;)

method - A function, action, verb, or set of instructions that use and manipulates variables. Method names always end in parenthesis (ex. eat() )

condition - A test that returns either true or false, usually inside an "if" or "for" statement and in parenthesis. Ex. if (score > 90)...

statement - A single java command that ends in a semicolon Ex. System.out.println("hello");

interface - Anything that is public in a class. Usually the methods of a class. Can be accessed outside the class. As opposed to private which cannot be accessed outside the class. Use of private variables is called "information hiding."

qualified name - Using the dot-notation to go inside an object to access the public features (methods). Ex: pet1.eat()

A) B) C)
int x = 1;
x++;
x += 3;
int x = 4;
if (x == 6)
    x = 3;
int x = 3;
while (x < 7)
{
    x++;
}
x = 5
x = 4
x = 7
 
D) E) F)
int x = 14;
x = x % 3;
x--;
int x = 4;
if ((x > 2) && (x < 7))
{
    x *= 5;
}
int x = 13;
for (int j=1; j < 4; j++)
{
    x = x + j;
}
x = 1
x = 20
x = 19

Save this image in the same folder as CalculatorFX.java code shown below.

/**
 * @author (your name & Course Name)
 * @version (a date)
 * Mr. Meinzen's CalculatorFX introduces a more advanced graphical
 * application using the JavaFX framework...it is the basics of a calculator app.
 */
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.image.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.effect.*;           // for shadow and reflection effects
import javafx.scene.paint.*;            // for Colors

public class CalculatorFX extends Application
{
   private Scene     scene;             // The scene is basically a window that will contain the panel.

   private GridPane  rootPanel;         // The "window" pane will display (i.e. contain) all the components.

   // These are the components to add to the panel and to listen for clicks or user input
   private TextField textNumber1, textNumber2;
   private Button    buttonAdd,   buttonSubtract, buttonDivide, buttonMultiply, buttonClear;
   private Label     labelAnswer;

   /**
   *  The main() method just launches the application
   */
   public static void main(String[] args)
   {
       // Call the launch() method which is defined in the Application class.
       // The launch() method will then call the start() method below.
       launch(args);
   }

   /**
   * The start() method initializes the primaryStage which is often the same as the computer screen
   */
   public void start(Stage primaryStage)
   {
        //make container for application
        rootPanel = new GridPane();

        setComponents(); // call the setComponents() method below to instantiate all the components and preferences
        attachCode();    // call the attachCode()  method below to trigger the "buttonCode()" method when clicked on

        //center text in label
        labelAnswer.setAlignment(Pos.CENTER);

        //apply ccs-like style to label (yes, you can)
        labelAnswer.setStyle("-fx-border-color: #0000ff; -fx-padding: 5px;");

        //put container in middle of scene and set spacing between controls in grid
        rootPanel.setAlignment(Pos.CENTER);
        rootPanel.setHgap(10);
        rootPanel.setVgap(10);

        //add buttons and textfields to panel in a grid, cell by cell
        rootPanel.add(buttonAdd,0,0);       // column 0, row 0 is the add button
        rootPanel.add(buttonSubtract,1,0);  // column 1, row 0 is the subtract button
        rootPanel.add(buttonMultiply,0,1);  // column 0, row 1 is the multiply button
        rootPanel.add(buttonDivide,1,1);    // column 1, row 1 is the divide button
        rootPanel.add(textNumber1, 0,2);    // column 0, row 2 is the 1st number textfield
        rootPanel.add(textNumber2,1,2);     // column 1, row 2 is the 2nd number textfield

        //last 2 rows span across 2 columns
        //col, rol, colspan, rowspan
        rootPanel.add(labelAnswer,0,3,2,1); // column 0, row 3, spanning 2 columns, 1 row
        rootPanel.add(buttonClear,0,4,2,1); // column 0, row 4, spanning 2 colunns, 1 row

        // instantiate the scene and attach to the rootPanel panel.
        scene = new Scene(rootPanel, 300, 250);  // 300 pixels wide, 250 pixels high

        // set the scene to the primaryStage then display it on the screen
        primaryStage.setTitle("Calculator 0.1");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

	/**
	*   instantiate and set the properties of all controls/components
	*/
    public void setComponents()
    {
        //make the controls/components
        textNumber1    = new TextField();
        textNumber2    = new TextField();

        buttonAdd      = new Button("+");
        buttonSubtract = new Button("-");
        buttonMultiply = new Button("x");
        buttonDivide   = new Button("/");
        buttonClear    = new Button("Clear");

        ImageView image1 = new ImageView(new Image("spinnerCircle.gif"));
        labelAnswer    = new Label("?", image1);

        // create some local CSS and other styling
        DropShadow shadow = new DropShadow();
        shadow.setOffsetY(10.0);      // shadow should be 10 pixels down from Control
        shadow.setOffsetX(10.0);      // shadow should be 10 pixels right from Control
        shadow.setColor(Color.GREEN); // shadow should be green

        // add the CSS and styling to any Control (button, label, etc.)
        buttonClear.setEffect(new Reflection());
        buttonClear.setStyle("-fx-font: 12 arial; -fx-base: #008800;"); // 008800 is 0% red, 50% green, 0% blue
        buttonSubtract.setEffect(shadow);
        buttonMultiply.setEffect(shadow );
        buttonDivide.setEffect(shadow);
        buttonAdd.setEffect(shadow);
        labelAnswer.setStyle("-fx-font: 24 arial; -fx-base: #cc00cc;"); // cc00cc is 70% red, 0% green, 70% blue (i.e. purple)

        // set the preferences for each text component...basically 70 pixels wide x 40 pixels tall.
        textNumber1.setPrefWidth(70);
        textNumber2.setPrefWidth(70);
        textNumber1.setPrefHeight(40);
        textNumber2.setPrefHeight(40);

        buttonAdd.setPrefWidth(70);
        buttonSubtract.setPrefWidth(70);
        buttonMultiply.setPrefWidth(70);
        buttonDivide.setPrefWidth(70);
        buttonClear.setPrefWidth(150);    // 150=double the width of a button plus 10 pixel spacing in between buttons

        labelAnswer.setPrefWidth(150);
    }

    /**
    * Have each button execute the buttonCode() method when clicked
    */
    public void attachCode()
    {
        // the (e -> buttonCode(e)) is a Java8 lambda function feature
        buttonAdd.setOnAction(e -> buttonCode(e));
        buttonSubtract.setOnAction(e -> buttonCode(e));
        buttonMultiply.setOnAction(e -> buttonCode(e));
        buttonDivide.setOnAction(e -> buttonCode(e));
        buttonClear.setOnAction(e -> buttonCode(e));
    }

    /**
    *  The buttonCode() method determines the action to be taken as each button is pressed.
    */
    public void buttonCode(ActionEvent e) //e tells us which button was clicked
    {
       int num1, num2, answer;
       char symbol;

       //read Strings from textfields then convert to Integer objects then store as int primitives
       num1=Integer.parseInt(textNumber1.getText());
       num2=Integer.parseInt(textNumber2.getText());

       if(e.getSource()==buttonAdd)
       {
            symbol='+';
            answer=num1+num2;
       }
       else if(e.getSource()==buttonSubtract)
       {
            symbol='-';
            answer=num1-num2;
       }
       else if(e.getSource()==buttonMultiply)
       {
            symbol='x';
            answer=num1*num2;
       }
       else
       {
            symbol='/';
            answer=num1/num2;
       }

       //display answer & set the style to clear image and highlight the new information
       labelAnswer.setText("" + num1 + symbol + num2 + "=" + answer);
       labelAnswer.setGraphic(null);
       labelAnswer.setStyle("-fx-font: 24 arial; -fx-border-color: red; -fx-border-width: 2;");

       // Clear the textfields when the "Clear" button was pressed
       if(e.getSource()==buttonClear)
       {
            textNumber1.setText("");
            textNumber2.setText("");
            labelAnswer.setText("?");
            textNumber1.requestFocus();
            return;
       }
    }
}