Category Archives: Lesson

Chapter 2: Objects and Primitives

Objects and Primitive Data

  1. The information we manage in a Java program is either primitive data or objects.
  2. An abstraction hides details. A good abstraction hides the right details at the right time.
  3. A variable is a name for a memory location used hold a value of a particular data type.
  4. A variable can store only one value of its declared type.
  5. Java is a strongly typed language. Each variable has a specific type, and we cannot assign a value of one type to a variable of another type.
  6. Constants are like variables, but they hold one particular value.
  7. Java has two kinds of numeric values: integers and floating point. The primitive type int is an integer data type and double is a floating point data type.
  8. Many programming statements involve expressions. Expressions are combinations of one or more operands and the operators used to per­ form a calculation.
  9. Java has rules that govern the order in which operators will be evaluated in an expression.
  10. Avoid narrowing conversions because they can lose information.
  11. The new operator returns a reference to a newly created object.
  12. The Java standard class library is a useful set of classes that anyone can use when writing Java programs.

First Days – Introductions and policies

September 7th, 2016

How to turn in assignments:
1. Program name: initials followed by an underscore and assignment name. Example: GE_Snowman.java
2. Header information: Description of assignment, author and date
3. If the program generates output from test run, the output should be included in the program as comments
4. Upload the files with extension “.java”
5. Copy and paste your code onto the reply.

Classwork:
1. If you have not done so, visit edmodo.com
Create and account or join with the code given in the home page.
Note: Please use your full name as your screen name.

2. Read thoroughly the assignment below. Find a partner and discuss it.

3. Use paper and pencil/pen to “show” the IntegerSet and its functionality.

Homework due tomorrow:
1. Send me an email(graciela_elia@princetonk12.org) with your parents email address: the email subject should have student name and class period and class name:
Ex:
Subject: 3rd period – Intro to Comp -Your name 

2. Discuss the class policy with your parents.

3. Visit edmodo.com and reply to the “Introduce yourself” post.

Java Language and OOD Review Assignment
Due date: September 14th, 2016

  1. It will be graded based on design and correct implementation of the specifications.
  2. It is due on September 14th, 2016.
  3. Attach pseudocode for the union and intersection methods
  4. Attach a flowchart for the union and intersection methods. Here are some basic flowhcart symbols you need to know:
  5. Screen Shot 2013-09-01 at 8.24.32 PM

  6. Implement the driver/test class.

Create class IntegerSet. Each object of the class can hold integers in the range 0 through 100. A set is represented internally as an array of booleans. Array element a[i] is true if integer i is in the set. Array element a[j] is false if integer j is not in the set. The no-argument constructor initializes a set to the so-called “empty set” (i.e., a set whose array representation contains all false values).

Provide the following methods:

1. Method unionOfIntegerSets creates a third IntegerSet which is the set-theoretic union of two existing sets (i.e., an element of the third set’s array is set to true if that element is true in either or both of the existing sets; otherwise, the element of the third set is set to false).

2. Method intersectionOfIntegerSets creates a third IntegerSet which is the set-theoretic intersection of two existing sets i.e., an element of the third set’s array is set to false if that element is false in either or both of the existing sets; otherwise, the element of the thirds set is set to true).

3. Method insertElement inserts a new integer k into a set (by setting a[k] to true).

4. Method deleteElement deletes integer m (by setting a[m] to false).

5. Method setPrint prints a set as a list of numbers separated by spaces. Print only those elements that are present in the set. Print “- – -” (3 dashes) for an empty set.

6. Method isEqualTo determines if two sets are equal.

Write a program to test your IntegerSet class. Instantiate several IntegerSet objects. Include proof that all your methods work properly.

NOTE: Use your IntegerSet drawing and flowchart to work on the implementation.

I WILL COLLECT ALL YOUR PAPERS. MAKE SURE YOUR NAME AND PERIOD ARE ON IT.

GUI: ButtonViewer

November 4th, 2013

import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
   This program demonstrates how to install an action listener.
*/
public class ButtonViewer
{  
   private static final int FRAME_WIDTH = 100;
   private static final int FRAME_HEIGHT = 60;

   public static void main(String[] args)
   {  
      JFrame frame = new JFrame();
      JButton button = new JButton("Click me!");
      frame.add(button);
     
      ActionListener listener = new ClickListener();
      button.addActionListener(listener);

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
   An action listener that prints a message.
*/
public class ClickListener implements ActionListener
{
   public void actionPerformed(ActionEvent event)
   {
      System.out.println("I was clicked.");
   }            
}

/**
   A bank account has a balance that can be changed by 
   deposits and withdrawals.
*/
public class BankAccount
{  
   private double balance;

   /**
      Constructs a bank account with a zero balance.
   */
   public BankAccount()
   {   
      balance = 0;
   }

   /**
      Constructs a bank account with a given balance.
      @param initialBalance the initial balance
   */
   public BankAccount(double initialBalance)
   {   
      balance = initialBalance;
   }

   /**
      Deposits money into the bank account.
      @param amount the amount to deposit
   */
   public void deposit(double amount)
   {  
      double newBalance = balance + amount;
      balance = newBalance;
   }

   /**
      Withdraws money from the bank account.
      @param amount the amount to withdraw
   */
   public void withdraw(double amount)
   {   
      double newBalance = balance - amount;
      balance = newBalance;
   }

   /**
      Gets the current balance of the bank account.
      @return the current balance
   */
   public double getBalance()
   {   
      return balance;
   }
}

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
   This program demonstrates how an action listener can access 
   a variable from a surrounding block.
*/
public class InvestmentViewer1
{  
   private static final int FRAME_WIDTH = 120;
   private static final int FRAME_HEIGHT = 60;

   private static final double INTEREST_RATE = 10;
   private static final double INITIAL_BALANCE = 1000;

   public static void main(String[] args)
   {  
      JFrame frame = new JFrame();

      // The button to trigger the calculation
      JButton button = new JButton("Add Interest");
      frame.add(button);

      // The application adds interest to this bank account
      final BankAccount account = new BankAccount(INITIAL_BALANCE);
      
      class AddInterestListener implements ActionListener
      {
         public void actionPerformed(ActionEvent event)
         {
            // The listener method accesses the account variable
            // from the surrounding block
            double interest = account.getBalance() * INTEREST_RATE / 100;
            account.deposit(interest);
            System.out.println("balance: " + account.getBalance());
         }            
      }
     
      ActionListener listener = new AddInterestListener();
      button.addActionListener(listener);

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
   This program displays the growth of an investment. 
*/
public class InvestmentViewer2
{  
   private static final int FRAME_WIDTH = 400;
   private static final int FRAME_HEIGHT = 100;

   private static final double INTEREST_RATE = 10;
   private static final double INITIAL_BALANCE = 1000;

   public static void main(String[] args)
   {  
      JFrame frame = new JFrame();

      // The button to trigger the calculation
      JButton button = new JButton("Add Interest");

      // The application adds interest to this bank account
      final BankAccount account = new BankAccount(INITIAL_BALANCE);

      // The label for displaying the results
      final JLabel label = new JLabel("balance: " + account.getBalance());

      // The panel that holds the user interface components
      JPanel panel = new JPanel();
      panel.add(button);
      panel.add(label);      
      frame.add(panel);
  
      class AddInterestListener implements ActionListener
      {
         public void actionPerformed(ActionEvent event)
         {
            double interest = account.getBalance() * INTEREST_RATE / 100;
            account.deposit(interest);
            label.setText("balance: " + account.getBalance());
         }            
      }

      ActionListener listener = new AddInterestListener();
      button.addActionListener(listener);

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;

/**
   This component displays a rectangle that can be moved. 
*/
public class RectangleComponent extends JComponent
{  
   private static final int BOX_X = 100;
   private static final int BOX_Y = 100;
   private static final int BOX_WIDTH = 20;
   private static final int BOX_HEIGHT = 30;

   private Rectangle box;

   public RectangleComponent()
   {  
      // The rectangle that the paintComponent method draws
      box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT);         
   }

   public void paintComponent(Graphics g)
   {  
      Graphics2D g2 = (Graphics2D) g;

      g2.draw(box);
   }

   /**
      Moves the rectangle to the given location.
      @param x the x-position of the new location
      @param y the y-position of the new location
   */
   public void moveTo(int x, int y)
   {
      box.setLocation(x, y);
      repaint();      
   }
} 

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;

/**
   This program displays a RectangleComponent.
*/
public class RectangleComponentViewer
{  
   private static final int FRAME_WIDTH = 300;
   private static final int FRAME_HEIGHT = 400;

   public static void main(String[] args)
   {        
      final RectangleComponent component = new RectangleComponent();

      // Add mouse press listener         

      class MousePressListener implements MouseListener
      {  
         public void mousePressed(MouseEvent event)
         {  
            int x = event.getX();
            int y = event.getY();
            component.moveTo(x, y);
         }

         // Do-nothing methods
         public void mouseReleased(MouseEvent event) {}
         public void mouseClicked(MouseEvent event) {}
         public void mouseEntered(MouseEvent event) {}
         public void mouseExited(MouseEvent event) {}
      }
         
      MouseListener listener = new MousePressListener();
      component.addMouseListener(listener);

      JFrame frame = new JFrame();
      frame.add(component);

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
} 

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;

/**
   This component displays a rectangle that can be moved. 
*/
public class RectangleComponent extends JComponent
{  
   private static final int BOX_X = 100;
   private static final int BOX_Y = 100;
   private static final int BOX_WIDTH = 20;
   private static final int BOX_HEIGHT = 30;

   private Rectangle box;

   public RectangleComponent()
   {  
      // The rectangle that the paintComponent method draws 
      box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT);         
   }

   public void paintComponent(Graphics g)
   {  
      Graphics2D g2 = (Graphics2D) g;

      g2.draw(box);
   }

   /**
      Moves the rectangle by a given amount. 
      @param x the amount to move in the x-direction 
      @param y the amount to move in the y-direction 
   */
   public void moveBy(int dx, int dy)
   {
      box.translate(dx, dy);
      repaint();      
   }
}


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;

/** 	 	 	 	 	 	
   This program moves the rectangle.
*/
public class RectangleMover
{
   private static final int FRAME_WIDTH = 300;
   private static final int FRAME_HEIGHT = 400;

   public static void main(String[] args)
   {
      JFrame frame = new JFrame();

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setTitle("An animated rectangle");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      final RectangleComponent component = new RectangleComponent();
      frame.add(component);

      frame.setVisible(true);
      
      class TimerListener implements ActionListener
      {
         public void actionPerformed(ActionEvent event)
         {
            component.moveBy(1, 1);
         }
      }

      ActionListener listener = new TimerListener();

      final int DELAY = 100; // Milliseconds between timer ticks
      Timer t = new Timer(DELAY, listener);
      t.start();      
   }
}

Homework: Exercise 4: Enhance the ButtonViewer program so that it prints a message “I was clicked n times!” whenever the button is clicked. The value n should be incremented with each click.

GUI: JTextField, JButton and JLabel

November 11th, 2014

Veterans-Day-2014-Images

How to put some components together:
This application uses JTextField, JButton and JLabel

/**
   A bank account has a balance that can be changed by 
   deposits and withdrawals.
*/
public class BankAccount
{  
   private double balance;

   /**
      Constructs a bank account with a zero balance.
   */
   public BankAccount()
   {   
      balance = 0;
   }

   /**
      Constructs a bank account with a given balance.
      @param initialBalance the initial balance
   */
   public BankAccount(double initialBalance)
   {   
      balance = initialBalance;
   }

   /**
      Deposits money into the bank account.
      @param amount the amount to deposit
   */
   public void deposit(double amount)
   {  
      double newBalance = balance + amount;
      balance = newBalance;
   }

   /**
      Withdraws money from the bank account.
      @param amount the amount to withdraw
   */
   public void withdraw(double amount)
   {   
      double newBalance = balance - amount;
      balance = newBalance;
   }

   /**
      Gets the current balance of the bank account.
      @return the current balance
   */
   public double getBalance()
   {   
      return balance;
   }
}

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
   A frame that shows the growth of an investment with variable interest.
*/
public class InvestmentFrame extends JFrame
{    
   private static final int FRAME_WIDTH = 450;
   private static final int FRAME_HEIGHT = 100;

   private static final double DEFAULT_RATE = 5;
   private static final double INITIAL_BALANCE = 1000;   

   private JLabel rateLabel;
   private JTextField rateField;
   private JButton button;
   private JLabel resultLabel;
   private JPanel panel;
   private BankAccount account;
 
   public InvestmentFrame()
   {  
      account = new BankAccount(INITIAL_BALANCE);

      // Use instance variables for components 
      resultLabel = new JLabel("balance: " + account.getBalance());

      // Use helper methods 
      createTextField();
      createButton();
      createPanel();

      setSize(FRAME_WIDTH, FRAME_HEIGHT);
   }

   private void createTextField()
   {
      rateLabel = new JLabel("Interest Rate: ");

      final int FIELD_WIDTH = 10;
      rateField = new JTextField(FIELD_WIDTH);
      rateField.setText("" + DEFAULT_RATE);
   }
   
   private void createButton()
   {
      button = new JButton("Add Interest");
      
      class AddInterestListener implements ActionListener
      {
         public void actionPerformed(ActionEvent event)
         {
            double rate = Double.parseDouble(rateField.getText());
            double interest = account.getBalance() * rate / 100;
            account.deposit(interest);
            resultLabel.setText("balance: " + account.getBalance());
         }            
      }
      
      ActionListener listener = new AddInterestListener();
      button.addActionListener(listener);
   }

   private void createPanel()
   {
      panel = new JPanel();
      panel.add(rateLabel);
      panel.add(rateField);
      panel.add(button);
      panel.add(resultLabel);      
      add(panel);
   } 
}

import javax.swing.JFrame;

/**
   This program displays the growth of an investment. 
*/
public class InvestmentViewer3
{  
   public static void main(String[] args)
   {  
      JFrame frame = new InvestmentFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

Many shapes GUI

October 27th, 2014

Classwork:
Use a JFrame to create an application, YI_ManyShapes.java and YI_ManyShapesJFrame.java that draws rectangles, ellipses and lines. Use different colors and fill.
Here is a good source for your application:
Screen Shot 2014-10-27 at 1.36.15 PM

Here is a simple example:

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
/**
 * Write a description of class RectangleObject here.
 
 */
public class RectangleObject extends JComponent
{
    public void paintComponent(Graphics g)
    {
      Graphics2D g2 = (Graphics2D) g;

      // Construct a rectangle object
      Rectangle box = new Rectangle(5, 10, 20, 30);
      // draw the rectangle
      g2.draw(box);  
    }
   
}

The JFrame class:

import javax.swing.JFrame;
/**
 * Draw an empty frame using JFrame.
 * 
 */

public class RectangleJFrame
{
       public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setSize(300,400);
        frame.setTitle("A Rectanlge Object in a JFrame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        RectangleObject aRectangle = new RectangleObject();
        
        frame.add(aRectangle);
        frame.setVisible(true);
    }
}

Homework:
Write an application, YI_HappyFace.java using what you learned from Manyshapes to draw a happy face. Make sure to include the JFrame class also.

happyfaces8

JFrame Intro – Rectangle – GUI

October 30th, 2013

Graphical Applications and Frame Windows


A graphical application shows information inside a frame: a window with a title bar.
To show a frame, construct a JFrame object, set its size, and make it visible

import javax.swing.JFrame;

public class EmptyFrameViewer
{
   public static void main(String[] args)
   {
      JFrame frame = new JFrame();

      frame.setSize(300, 400);
      frame.setTitle("An Empty Frame");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      frame.setVisible(true);
   }
}

The JFrame class is a part of the javax.swing package. Swing is the nickname for the graphical user interface library in Java. The “x” in javax denotes the fact that Swing started out as a Java extension before it was added to the standard library.
In order to display a drawing in a frame, declare a class that extends the JComponent class.
Place drawing instructions inside the paintComponent method. That method is called whenever the component needs to be repainted.

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;

/*
   A component that draws two rectangles.
*/
public class RectangleComponent extends JComponent
{  
   public void paintComponent(Graphics g)
   {  
      // Recover Graphics2D
      Graphics2D g2 = (Graphics2D) g;

      // Construct a rectangle and draw it
      Rectangle box = new Rectangle(5, 10, 20, 30);
      g2.draw(box);

      // Move rectangle 15 units to the right and 25 units down
      box.translate(15, 25);

      // Draw moved rectangle
      g2.draw(box);
   }
}


When the component is shown for the first time, the paintComponent method is called automatically.
The method is also called when the window is re-sized, or when it is shown again after it was hidden.
The Graphics class is primitive. The designers of Java created the Graphics2D class, which extends the Graphics class. Whenever the Swing toolkit calls the paintComponent method, it actually passes a parameter of type Graphics2D

import javax.swing.JFrame;

public class RectangleViewer
{
   public static void main(String[] args)
   {
      JFrame frame = new JFrame();

      frame.setSize(300, 400);
      frame.setTitle("Two rectangles");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      RectangleComponent component = new RectangleComponent();
      frame.add(component);

      frame.setVisible(true);
   }
}


Applets have two advantages. They don’t need separate component and viewer classes; you only implement a single class. And, more importantly, applets run inside a web browser, allowing you to place your creations on a web page for all the world to admire.

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JApplet;

/*
   An applet that draws two rectangles.
*/
public class RectangleApplet extends JApplet
{  
   public void paint(Graphics g)
   {  
      // Prepare for extended graphics
      Graphics2D g2 = (Graphics2D) g;

      // Construct a rectangle and draw it
      Rectangle box = new Rectangle(5, 10, 20, 30);
      g2.draw(box);

      // Move rectangle 15 units to the right and 25 units down
      box.translate(15, 25);

      // Draw moved rectangle
      g2.draw(box);
   }
}

Here is the simplest possible file to display the rectangle applet:






If you know HTML, you can proudly explain your creation, by adding text and more HTML tags:



 
Two rectangles

Here is my first applet:


To run the applet, you have two choices. You can use the applet viewer, a program that is included with the Java Software Development Kit from Sun Microsystems. You simply start the applet viewer, giving it the name of the HTML file that contains your applets:


appletviewer RectangleApplet.html


The applet viewer only shows the applet, not the HTML text (see the left figure).
You can also show the applet inside any Java-enabled web browser, such as Firefox or Safari. (If you use Internet Explorer, you probably need to configure it. By default, Microsoft supplies either an outdated version of Java or no Java at all. Go to the java.com web site and install the Java plugin.) The second figure shows the applet running in a browser. As you can see, both the text and the applet are displayed.


Drawing Text:
You often want to put text inside a drawing, for example, to label some of the parts. Use the drawString method of the Graphics2D class to draw a string anywhere in a window. You must specify the string and the x- and y-coordinates of the basepoint of the first character in the string. For example,


g2.drawString("Message", 50, 100);

message

colors

Colors


Color magenta = new Color(255, 0, 255);

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import javax.swing.JComponent;

/*
   A component that draws an alien face
*/
public class FaceComponent extends JComponent
{  
   public void paintComponent(Graphics g)
   {  
      // Recover Graphics2D 
      Graphics2D g2 = (Graphics2D) g;

      // Draw the head
      Ellipse2D.Double head = new Ellipse2D.Double(5, 10, 100, 150);
      g2.draw(head);

      // Draw the eyes
      g2.setColor(Color.GREEN);
      Rectangle eye = new Rectangle(25, 70, 15, 15);
      g2.fill(eye);
      eye.translate(50, 0);
      g2.fill(eye);

      // Draw the mouth
      Line2D.Double mouth = new Line2D.Double(30, 110, 80, 110);
      g2.setColor(Color.RED);
      g2.draw(mouth);

      // Draw the greeting
      g2.setColor(Color.BLUE);
      g2.drawString("Hello, World!", 5, 175);
   }
}


Exercise 1: In this exercise, you will explore a simple way of visualizing a Rectangle object. The setBounds method of the JFrame class moves a frame window to a given rectangle. Complete the following program to visually show the translate method of the Rectangle class: 



import java.awt.Rectangle; 
import javax.swing.JFrame; 
import javax.swing.JOptionPane; 

public class TranslateDemo 
{
 
  public static void main(String[] args) 
   {
    // Construct a frame and show it

    JFrame frame = new JFrame(); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 

    // Your work goes here:

    // Construct a rectangle and set the frame bounds 

    JOptionPane.showMessageDialog(frame, "Click OK to continue"); 

    // Your work goes here: 

    // Move the rectangle and set the frame bounds again
  }
} 

Action Listener – GUI

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
   An action listener that prints a message.
*/
public class ButtonListener implements ActionListener
{
   public void actionPerformed(ActionEvent event)
   {
      System.out.println("You clicked me!!!!");
   }            
}

import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
   This program demonstrates how to install an action listener.
*/
public class ButtonViewer
{  
   private static final int FRAME_WIDTH = 100;
   private static final int FRAME_HEIGHT = 60;

   public static void main(String[] args)
   {  
      JFrame frame = new JFrame();
      JButton button = new JButton("Click here if you dare!");
      frame.add(button);
     
      ActionListener listener = new ButtonListener();
      button.addActionListener(listener);

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

Screen Shot 2014-10-30 at 10.17.28 AM

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;

/**
   This component displays a circle that can be moved. 
*/
public class ShapeComponent extends JComponent
{  
   private static final int SQUARE_X = 100;
   private static final int SQUARE_Y = 100;
   private static final int SQUARE_WIDTH = 50;
   private static final int SQUARE_HEIGHT = 50;

   private Ellipse2D.Double circle;

   public ShapeComponent()
   {  
      // The rectangle that the paintComponent method draws
      circle = new Ellipse2D.Double(SQUARE_X, SQUARE_Y, SQUARE_WIDTH, SQUARE_HEIGHT);         
   }

   public void paintComponent(Graphics g)
   {  
      Graphics2D g2 = (Graphics2D) g;

      g2.draw(circle);
   }

   /**
      Moves the rectangle to the given location.
      @param x the x-position of the new location
      @param y the y-position of the new location
   */
   public void moveTo(int x, int y)
   {
      circle = new Ellipse2D.Double(x, y, SQUARE_WIDTH, SQUARE_HEIGHT);
      repaint();      
   }
} 

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import java.awt.Color;

/**
   This program displays a ShapeComponent.
*/
public class ShapeComponentViewer
{  
   private static final int FRAME_WIDTH = 300;
   private static final int FRAME_HEIGHT = 400;

   public static void main(String[] args)
   {        
      final ShapeComponent component = new ShapeComponent();

      // Add mouse press listener         

      class MousePressListener implements MouseListener
      {  
         public void mousePressed(MouseEvent event)
         {  
            int x = event.getX();
            int y = event.getY();
            component.moveTo(x, y);
         }

         // Do-nothing methods
         public void mouseReleased(MouseEvent event) {}
         public void mouseClicked(MouseEvent event) {}
         public void mouseEntered(MouseEvent event) {}
         public void mouseExited(MouseEvent event) {}
      }
         
      MouseListener listener = new MousePressListener();
      component.addMouseListener(listener);

      JFrame frame = new JFrame();
      frame.getContentPane().setBackground(new Color(255, 0, 0));
      frame.add(component);

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
} 

Classwork:
Use the resources given to create a new GUI application, YI_CrazyCircle.py and its JFrame to generate random colors background and random filled circles whenever you click the mouse on the window.
Hint: To be able to also change the background at random create a rectangle of size equivalent to the JFrame. Instead of creating two public classes, create one inner class, the JComponnet inside main so it can have access to the JFrame size.

ACSL Programming Project


December 11th, 2013

ACSL Programming Project due by Monday, December 16th

Duodecim Scripta

PROBLEM: Duodecim Scripta, 12 Lines, is an ancient Roman board game. It is played on a board as shown below with each of its two players starting with 15 markers on his home square. Each player’s markers are a different color. The object of the game is for a player to move all his markers to his opponent’s home square.

HOME-1	I	II	III	IV	V	VI	VII	VIII	IX	X	XI	XII
HOME-2	XXIV	XXIII	XXII	XXI	XX	XIX	XVIII	XVII	XVI	XV	XIV	XIII

The rules of the game are as follows:
1. For each turn, three number cubes are rolled. The markers are moved according to the result of the roll. A player can move one, two or three of his markers by using the result of the 3 number cubes or by combining them. A roll of a 5, a 4 and a 3 can be played as follows: move one marker 12 squares forward, or move one piece 9 squares forward and a second piece 3 squares forward, or move one piece 3 squares forward, a second piece 4 squares forward and a third piece 5 squares forward. The three number cube results can be combined in any of the many combinations possible to move one, two or three markers.

2. If a player’s marker is alone on a square and an opponent’s marker lands on the square, then the player’s marker must be placed back on his home square. If two or more markers are on one square, then the opponent may not land there. No more than five markers may occupy the same square.

Your task is to play a given result of a roll of the number cubes with the following priorities:

Your markers will start from HOME-1. Move as many of your markers as possible as far as possible off your home square. That is, if you can move all three markers, do so. If you can only move two markers using all three number cubes, move one of the markers as far from the home square as possible and move the second marker using the remaining number cube. Otherwise, move one marker using the highest sum possible. If no moves are possible off the home square print the word “none”.

INPUT: Given: how many of the numbered squares your markers occupy, the number of your markers at given locations, how many of the numbered squares your opponent occupies, the number of your opponent’s markers at given locations and the results of the number cube roll. Sample data 1 states that you have 3 occupied squares as follows: 4 markers at location 4, 5 markers at location 7, and 2 markers at location 10. Your opponent has 4 occupied squares as follows: 2 markers at location 9, 1 marker at location 13, 5 markers at location 15 and 3 markers at location 21. The results of the roll are 3, 4 and 5.

OUTPUT: Print the location of all your markers not on the Home-1 space. In the example above you can move all three markers with the following result: 1 marker at location 3, 5 at location 4, 1 at location 5, 5 at location 7, and 2 at location 10.

SAMPLE INPUT				SAMPLE OUTPUT

1.  3, 4,4,5,7,2,10,4,2,9,1,13,5,15,3,21,3,4,5		1.  1,3,5,4,1,5,5,7,2,10
2.  3,5,1,5,2,2,3,3,5,4,5,5,5,6, 1,2,3			2.  5,1,5,2,4,3
3.  3,5,1,5,2,2,3,3,5,4,5,5,5,6,3,6,4			3.  5,1,5,2,3,3,1,10