Category Archives: Class work

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);
   }
}

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

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.

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