Monthly Archives: January 2020

GUI: Moving Car “Animation”

Courtesy from Lachlan:


/* Lachlan McCarty
 * 11-16-14
 * 1.8.0_25
 * LM_MovingCar.java
 * Write a program, YI_MovingCar.java that animates a car 
 * so that it moves across a frame.
 */

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JComponent;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LM_MovingCar {

	private final int FRAME_WIDTH = 450;
	private final int FRAME_HEIGHT = 100;
	private final int DELAY = 100;
	private final LM_MovingCarComponent component = new LM_MovingCarComponent();
	private final JFrame frame = new JFrame();
	
	public LM_MovingCar() {
		frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
		frame.setTitle("Moving Car");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		frame.add(component);
		
		frame.setVisible(true);
		
		ActionListener listener = new LM_TimerListener();
		Timer t = new Timer(DELAY, listener);
		t.start();
	}
	
	public static void main(String[] args) {
		new LM_MovingCar();
	}
	
	private class LM_TimerListener implements ActionListener {
		public void actionPerformed(ActionEvent event) {
			component.increaseCoor(1,0);
		}
	}
	
	private class LM_MovingCarComponent extends JComponent {
		private final int MULTIPLIER = 2; //ok to change
		private int xpadding = 10; // ok to change
		private int ypadding = 10; // ok to change
		private int CAR_WIDTH = 60*MULTIPLIER; // do not change
		private int CAR_HEIGHT = 40*MULTIPLIER; // do not change
	
		public void paintComponent(Graphics g) {
			Graphics2D g2 = (Graphics2D) g;
			// turn on antialiasing so it doesn't look like crap
			RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
													RenderingHints.VALUE_ANTIALIAS_ON);
			g2.setRenderingHints(rh);
			
			g2.drawRect(0*MULTIPLIER+xpadding,10*MULTIPLIER+ypadding,60*MULTIPLIER,10*MULTIPLIER);
			g2.drawOval(10*MULTIPLIER+xpadding,20*MULTIPLIER+ypadding,10*MULTIPLIER,10*MULTIPLIER);
			g2.drawOval(40*MULTIPLIER+xpadding,20*MULTIPLIER+ypadding,10*MULTIPLIER,10*MULTIPLIER);
			g2.drawPolygon(new int[]{10*MULTIPLIER+xpadding,20*MULTIPLIER+xpadding,40*MULTIPLIER+xpadding,50*MULTIPLIER+xpadding},
							new int[]{10*MULTIPLIER+ypadding,0*MULTIPLIER+ypadding,0*MULTIPLIER+ypadding,10*MULTIPLIER+ypadding}, 4);
		}
		
		public void increaseCoor(int x, int y) {
			if (xpadding+x+CAR_WIDTH <= FRAME_WIDTH) xpadding += x;
			if (ypadding+y+CAR_HEIGHT <= FRAME_HEIGHT) ypadding += y;
			repaint();
		}
	}
}

Screen Shot 2014-11-25 at 1.43.16 PM

GUI: House.java

Classwork:

Exercise:

  1. Write a GUI application, YI_House.java and its JFrame class to draw a house and the sun like the one in the picture.

house
NOTE: You can have only one class.
Extra credit: Draw a person like the one in the picture.

Homework: finish up this assignment

GUI: Dialog boxes

Classwork:
Write an OOD application, YI_WordValue.java to calculate the value of a word in the Scrabble game. Prompt the user for a word and display it worth using the table below:
Screen Shot 2015-02-11 at 12.19.37 PM

Write the tester class using a dialog box for user input.

Using dialog boxes
The JOptionPane class has the static showInputDialog method of t and supply the string that
prompts the input from the user.

Some examples:
String input = JOptionPane.showInputDialog(“Enter a word:”);
That method returns a String object.

You can also display output in a dialog box:
JOptionPane.showMessageDialog(null, “Word value: ” + worth);

Screen Shot 2015-02-18 at 11.10.45 AM

Any time you invoke the showInputDialog or showMessageDialog method in a program that
does not show any other frame windows, you need to add a line

System.exit(0);

to the end of your main method.

The showInputDialog method starts a user interface thread to handle user input. When the main method reaches the end, that thread is still running, and your program won’t exit automatically.

Calling the static method exit() from the System class, will force the program to exit. The parameter is the program’s status code. Zero represents a successful execution.


Screen Shot 2015-02-11 at 12.59.39 PM

Exit code is

0 when execution went fine;
1, -1, whatever != 0 when some error occurred, you can use different values for different kind of errors.

GUI: Rectangle moving component

More on Event Listeners:
Classwork:

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


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

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: Car Flag Bulls Eye

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

  1. 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

  2. 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

  3. 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


Screen Shot 2014-10-28 at 1.43.03 PM

How did Zach Yazdani combine the two classes?
You need to have both methods: paintComponent(Graphics g) and main in one file

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;
import javax.swing.JFrame;
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);  
      g2.draw(new Ellipse2D.Double(200,200,40,100));
      g2.draw(new Line2D.Double(50,30,200,100));
      g2.drawPolygon(new int [] {10,20,30}, new int [] {100,20,100}, 3);
    }
       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);
    }
}
//See attached Programs

GUI: JFrame

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-28 at 5.47.35 AM

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.

GUI – DialogDemo.java

Check edmodo.com for questions on content.

import javax.swing.JOptionPane;


/* 1.4 example used by DialogDemo.java. */
class DialogViewer1{
   public static void main(String[] args) {
       JOptionPane.showMessageDialog(null, "Hello, World!"); System.exit(0);
    }
}
import javax.swing.JOptionPane;

public class DialogViewer2 {
    public static void main(String[] args) {
    
        String name = JOptionPane.showInputDialog("What is your name?"); 
        System.out.println(name);
        System.exit(0);

    }
 }

Homework: Prepare for more questions including JOptionPane.

GUI: Action Listener

ActionEvent, ActionListener, and MouseListener

Screen Shot 2015-10-28 at 8.17.50 PM

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-11-03 at 10.10.30 AM

Screen Shot 2015-10-28 at 8.53.39 PM

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 circle 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.java and its JFrame to generate random colors background and random filled circles wherever you click the mouse on the window. PLEASE INCLUDE SCREEN SHOT OF YOUR WORK.
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.

Q4 Grades and Assignments

I hope you and your family are well.
Q4 assignments and projects must be in by June 11th since I must submit all grades by June 16th.
Submit whatever you have done by that date preferably before if possible. 
 
Any submitted assignment with issues should have a description of the problem in the first line of your documentation.
If you cannot complete an assignment, email me and let me know about it. I am flexible and open to suggestions. Talk to me!!
 
 
After June 11th,
 
Stay healthy. Stay safe.

mrs.e

❤️