Category Archives: Homework

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: RectangleComponent

November 5th, 2013

Classwork:
Exercise 5: Write a program,CurrentTime.java that uses a timer to print the current time once a second. Hint: The following code prints the current time:


Date now = new Date(); System.out.println(now);

The Date class is in the java.util package.

Exercise 6: Change the RectangleComponent, BouncingSqr.java for the animation program so that the rectangle bounces off the edges of the component rather than simply moving outside.

Homework:
Exercise 7: Write a program, AnimatedCar.java that animates a car so that it moves across a frame.

GUI: YI_TwoMovingCars.java

November 4th, 2014

Classwork/Homework:
1. Write a program, YI_MovingCar.java that animates a car so that it moves across a frame.
2. Write a program, YI_TwoMovingCars.java that animates two cars moving across a frame in opposite directions (but at different heights so that they don’t collide.)

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

/**
   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)
   {  
       
        /************   Inner Class Define Before is used  ***************************/
      
        /**
           An action listener that prints a message.
        */
        class ClickListener implements ActionListener
        {
           public void actionPerformed(ActionEvent event)
           {
              System.out.println("I was clicked.");
           }            
        }

       /************   Inner Class  End  ***************************/
       
       
       
       
      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);
      
      
      

   }
   


}

GUI: More on Event Listeners

Novermber 3rd, 2014

More on Event Listeners:

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 RectangleMovingComponent 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 RectangleMovingComponent()
   {  
      // 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 RectangleMovingComponent component = new RectangleMovingComponent();
      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();      
   }
}


Classwork/Homework:
Use the programs given to write a program, YI_BouncingBlock.java to make the block bounce when it reaches a all.

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

GUI – Car

October 28th, 2014

Input using a GUI:

import javax.swing.JFrame; 
import javax.swing.JOptionPane;

public class PaneInput {
    
    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);
        JOptionPane.showMessageDialog(frame, "Click OK to continue");

    }
}

Exercise:
1. Write a GUI application, YI_MyFlag.java and its JFrame class to draw your favorite flag.
Screen Shot 2014-10-28 at 1.51.02 PM

2. Write a GUI application, YI_Car.java and its JFrame class to draw a car like the one in the picture.
Screen Shot 2014-10-28 at 1.54.03 PM

3. Write a GUI application, YI_BullEye.java and its JFrame class to draw the picture.
Screen Shot 2014-10-28 at 1.56.35 PM

4. Write a GUI application, YI_OlympicRings.java and its JFrame class to draw famous rings.
Screen Shot 2014-10-28 at 1.56.51 PM

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

PClassic: Problem Set 4

Philadelphia Classic Spring 2014 Contest Problem Set

Screen Shot 2014-12-04 at 9.05.16 AM

Do problems 4 on in class and for homework.
Work with a partner. DO NOT LOOK FOR THE SOLUTIONS

Pay special attention to the following:
1. Make sure you read the instructions in the first 2 pages.
2. Read the problem many times before you get started.
3. Draft a plan on paper or a document before you start.
4. Test parts of the code before you develop the “whole” program.
5. Do not use outside help of any sort.
6. All students have to turn in the assignments to edmodo.com