CS代写 IAT 265 week 2 2

Classes, Motion, Encapsulation
School of Interactive Arts and Technology
______________________________________________________________________________________
SCHOOL OF INTERACTIVE ARTS + TECHNOLOGY [SIAT] | WWW.SIAT.SFU.CA

Copyright By PowCoder代写 加微信 powcoder

Class and Objects
Object-Oriented Programming (OOP) – Object and Client Program
– Encapsulation
– Data Hiding and Interfacing
Timer and Motion
– Java interface: ActionListener
January 17, 2022 IAT 265 week 2 2

Recap: Class & Object
Why objects?
 We live in a world full of objects
– Images, cars, remote controls, televisions,
employees, students, bugs, fishes, …
– Even for some abstract entity like bank account, it’s convenient to integrate its data and procedures
 OOP languages have the added capability to encapsulate objects’ properties and functions into one container – object
– The template for creating objects is called a class January 17, 2022 IAT 265 week 2 3

A Customer object wraps in all its Properties and Procedures
account_no
withdraw()
transfer()
January 17, 2022 IAT 265 4

What an object can offer?
 Attributes – data about What it is
– Properties/states of an object
e.g. Bug: sizes, color, location, speed, aliveness …
 Behaviors – procedures regarding What it can do:
– Capabilities of an object
e.g. Bug: move, collide, dodge, eat …
January 17, 2022 IAT 265 week 2 5

Classes and Objects
Class: A program entity that represents a blueprint (aka template) for a type of objects
– A Ball class is a piece of code, serving as a blueprint for creating Ball objects
Object: A runtime entity that combines attributes and behaviors
– A Ball object is a specific, visible form at runtime
One Ball class, many Ball objects
January 17, 2022 IAT 265 week 2 6

Courtesy to Building Java Programs (Chapter 8). S. Reges|M. 2013
instantiates
Blueprint Analogy
current song; volume; battery life;
iPod blueprint
power on/off
change station/song change volume choose random song
song = “1,000,000 Miles” volume = 17
battery life = 2.5 hrs
power on/off change station/song change volume choose random song
song = “Letting You” volume = 9
battery life = 3.41 hrs
power on/off change station/song change volume choose random song
song = “Discipline” volume = 24
battery life = 1.8 hrs
power on/off change station/song change volume choose random song
January 17, 2022 IAT 265 week 2

Defining a Class – Describing a type of objects
 A class is a construct that uses fields and methods to describe one type of objects at some abstraction level
 Fields: variables used to store data for every instance of the class (i.e. object)
– Each instance has its own values for its fields
 Methods: how you do things to or with an instance’s
 Constructors: special methods for creating instances of the class – instantiation. It has two features:
– a) same name as the class; b) no return type
January 17, 2022 IAT 265 week 2 8

Case Study: Ball
 Let’s design the class first:
 The UML here is drawn with ML Editor, which you can download for free at: VioletUmlEditor download
January 17, 2022 IAT 265 week 2 9

Recap: Java Classes for Rendering
 Two types of GUI elements:
To have a panel to draw graphic shapes on, we need to
extend JPanel to create our own BallPanel
To create a window for display graphics, we need
to work with JFrame as the top level container
January 17, 2022 IAT 265 10 • Source of the diagram: http://www.ntu.edu.sg/home/ehchua/programming/java/J4a_GUI.html#zz-2.2

Create Window and Panel
//Responsibility: creating window frame to hold the panel object
class BallApp extends JFrame { public BallApp(String title) {
super(title); this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
BallPane ballPane = new BallPane(); this.add(ballPane);
this.pack(); //window’s size is set
//by packing to BallPane’s size
this.setVisible(true);
//Driver method for project running
public static void main(String[] args){
} new BallApp(“BallApp”);
//Responsibility: creating canvas for
rendering objects
class BallPane extends JPanel{
// fields for properties
public final static int PAN_WIDTH = 600;
public final static int PAN_HEIGHT = 450;
public BallPane() {
// call JPanel’s constructor
// set panel’s preferred size
this.setPreferredSize(new
}Dimension(PAN_WIDTH, PAN_HEIGHT)); void paintComponent(Graphics g){
// call JPanel’s method for
clearing background
super.paintComponent(); IAT 265 week 2 11

Ex: Define the Ball class
class Ball{
// fields for properties
private int xPos;
private int yPos;
private int ballW;
private int ballH;
private Color ballColor;
// method to draw the ball that needs a
Graphics object for drawing
public void drawBall (Graphics g) {
g.setColor(ballColor);
g.fillOval(xPos, yPos, ballW, ballH);
// constructor: initialize fields with
fixed values
public Ball() {
ballW = 50;
ballH = 50;
//make it center at the panel’s center
xPos = (BallPane.PAN_WIDTH-ballW)/2; yPos = (BallPane.PAN_HEIGHT-ballH)/2; ballColor = Color.RED;
class BallPane{
…//constants for panel sizes
public final static int PAN_WIDTH = 600;
public final static int PAN_HEIGHT = 450;
January 17, 2022
IAT 265 week 2 12

Golden Rule 1 for Object Communication
 To pass a value from one object to another, make them static constants
– They can the be accessed by another object by its class name
 Applicable only to insensitive constants in strict encapsulation context – will be penalized if used otherwise in this course
January 17, 2022 IAT 265 week 2 13

Use the Ball Class
to create ball objects
 A class defines a type – our Ball class is a user defined type
 You can now declare variables using the class and initialize them with a
new instance of it (new + constructor(…) )
private Ball ball, ball1, ball2, ball3;
public BallPane(){
ball = new Ball();
ball1 = new Ball();
ball2 = new Ball();
ball3 = new Ball();
void paintComponent(Graphics g) {
super.paintComponent(g);
ball.drawBall(g);
ball1.drawBall(g);
ball2.drawBall(g);
ball3.drawBall(g);
January 17, 2022
IAT 265 week 2 14

The result …
 Why there is only one ball displayed?
January 17, 2022 IAT 265 week 2 15

What if we want to have balls …
 which have different locations, sizes, shapes, and colors like the followings?
January 17, 2022 IAT 265 week 2 16

Let’s change the code design by …
Overloading the Ball constructor with parameters for: – x, y coordinates
– width and height
Recap: what is overloading?
So that we can pass in different arguments to these
parameters to create ball objects with different locations, sizes, shapes, and colors
January 17, 2022 IAT 265 week 2 17

Golden Rule 2 for Object Communication
 To pass in data owned by another object, use parameters
– Those data will then be passed in as arguments when the method is being called
– Universally applicable to any communication between different objects
January 17, 2022 IAT 265 week 2 18

Codify per the updated design
class Ball{
// fields for properties
private int xPos;
private int yPos;
private int ballW;
private int ballH;
private Color ballColor;
// constructor: initialize
fields with fixed values
public Ball() {
// constructor: initialize fields
with parameters
public Ball(int x, int y, int w,
int h, Color c){
ballW = w;
ballH = h;
ballColor = c;
// method to draw the ball
public void drawBall (Graphics g) {
g.setColor(ballColor);
g.fillOval(xPos, yPos, ballW,
//same as before
January 17, 2022
IAT 265 week 2 19

Use the new Constructor to create ball objects
 We’ll first call the old constructor to create a red ball at the screen center
 Then call the overloaded constructor to create three ball objects with
different locations, sizes, shapes, and colors
Private Ball ball, ball1, ball2, ball3;
public BallPane(){
ball = new Ball(); //still call the old constructor ball1 = new Ball(100, 100, 100, 100, Color.BLUE);
ball2 = new Ball(400, 100, 100, 100, Color.BLUE);
ball3 = new Ball(200, 300, 200, 50, Color.MAGENTA);
void paintComponent(Graphics g) {
super.paintComponent(g);
ball.drawBall(g);
ball1.drawBall(g);
ball2.drawBall(g);
ball3.drawBall(g);
January 17, 2022
IAT 265 week 2 20

Notes to Parameters
 As you can see, methods without parameter give us convenience in terms of their defining and calling, but have to work with fixed values  limiting their functionality
 Methods with parameters, although more demanding in definition and invocation, provide more flexible functionalities
– Arguments for parameters are used to effect the methods’ functionalities and generate different outcomes
January 17, 2022 IAT 265 week 2 21

Summary on Class & Object
– To describe a type of objects – define a class
• Fields: hold an object’s data: properties/states
• Constructors:
– special methods used to instantiate objects from a class – Features: a) same name as the class; b) no return type
• Methods: allow objects to do things
– To create (instantiate) and use an object:
• Declare a reference variable using a class as the type
• Initialize it with an instance of the class (=new constructor(…))
• Call the object’s methods following the pattern: referenceVariable.method(…)
– Constructors and methods can be overloaded – same name different parameters
– A method can effect its functionality and/or output by way of parameters
January 17, 2022 IAT 265 week 2 22

 The basic idea behind animation:
– Draw a graphical image as a frame over and over
with slight changes from one frame to another
 The changes may be one or more of the followings:
– Displacement (motion)
– Size, orientation, color, shape etc.
 In every frame
1. Update objects’ state (location, direction of
movement, orientation, shape, color) 2. Display modified objects (redraw)

Timer-based Animation
 Swing library provides a Timer class specifically for GUI based animation
– javax.swing.Timer*
* Please note Java has another Timer class: java.util.Timer, which works differently and is a more general-purpose timer. Swing timer is a more appropriate choice for GUI based animation

How Java Timer works
 javax.swing.Timer works like a metronome:
– Once it’s started, it ticks away …
– For each tick, certain actions that we
can specify are performed
 To understand how this works, you
need to know Java Event Model
– We’ll use a ball object’s motion as an
example to demonstrate
January 17, 2022 IAT 265 week 2 25

Java Event Model
 Some source object (aka trigger, e.g. timer, mouse, keyboard, button, window, etc.) fires Events
– Events: timer ticks, clicks a mouse, types a key, presses a button, selects a menu item, opens a window, …
 Any object interested in hearing about a particular event can register itself with the source object as a listener
 When the event happens, JRE notifies the listeners automatically
 Each listener decides how it will respond with its specially defined method(s) – event handler(s)

Java Event Model
Registered to trigger to listen to its events

When it comes to Motion
Registered to timer to listen to ticks fired by timer
action listener

Specifically how can we make a ball move?
 We need to have:
– A Timer object to fire ticks
– An ActionListener instance that registers itself to the Timer object
– The ActionListener instance listens to the ticks and responds by updating the ball’s position and then repaint
it• In our example, we have BallPanel and Ball objects. Which one should we make an instance of ActionListener?
• JPanel Component (BallPanel specifically). Why?
January 17, 2022 IAT 265 29

About ActionListener
 How can we turn a component, such as the BallPanel, into an action listener?
– Any Java component can become an action listener by implementing the ActionListener interface
– The interface here is referring to another Java construct (beyond superclass) used for inheritance/polymorphism
January 17, 2022 IAT 265 30

Java interface
 We will cover interface along the line of inheritance/polymorphism in more detail in the future. For now just the basics to help us understand ActionListener
 An interface is a class-like construct that declares methods without any implementation. E.g. we can define an interface as follows:
public interface Mover { void move();
boolean changeGear(int newGear); }
 As you can see, an interface by itself is ”useless”, as it doesn’t have
any method body with code to be executed
– Forittofunction,theremustbesomeclasstoimplementitandALL
the methods it declares – with either concrete, executable code or dummy implementation

Class and Interface
 An Interface provides a description of a role declared with some
capabilities (via method declarations)
 A class can choose to implement the interface to assume the role and thereby possess these capabilities – by implementing all the methods declared by the interface with executable code
public class MountainBike extends Bicycle implements Mover { …
void move() {
xPox += xSpeed; }
boolean changeGear(int newGear) {
gear =newGear }
 By implementing an interface, it’s like a class having signed a contract, enforcing itself to have the functionalities as specified by the interface32

ActionListener –
a built-in Java interface
 Defined in java.awt.event package as follows: public interface ActionListener extends EventListener{
void actionPerformed(ActionEvent e);
 So any class that declares itself “implements” the ActionListener interface must implement the
method it declared
– By doing so, an object of the class becomes an ActionListener instance,andtherebycanregisteritselftoa timer to listen to its ticks

To make a ball move …
Make BallBanel implements the ActionListener interface, and include a Timer object and a Ball object
– So that BallBanel becomes an action listener, and thereby can register itself to the timer to listen to its ticks, and then respond by updating Ball object’s position and repaint it
To make the ball move, it should include speed attribute and define a move() method along with a “helper ” (private) method detectWall()
Aggregation is about one object be included as a field of another – forming a whole-part relationship
UML notation for implements (a dashed line with an open arrow) an interface (notice the direction)

Codify per the Design
class BallPanel extends JPanel implements ActionListener{
private Ball ball
private Timer timer;
//constructors
public BallPanel() {
setPreferredSize(new
Dimension(600, 450));
setBackground(Color.white); ball = new Ball();
…//create and start timer timer = new Timer(33,null); timer.start();
//All the rest is the same as
//implements the method declared
by ActionListener
//register BallPanel to timer
timer.addActionListener(this);
//Ball’s move() will be called
for each tick of timer
ball.move();
//update the display after
repaint(); }
January 17, 2022
public void
actionPerformed(ActionEvent e){

Notes to Swing Timer
 Here is Swing Timer’s constructor
– Timer(int delay, ActionListener listener)
• delay – time interval (in milliseconds) between every two ticks, which is the reversal of framerate
– framerate = 1000/delay, to have a framerate of 30fps delay = 33
• listener – an initial ActionListener instance passed in when a Timer object is created, can be null if none or add some later
January 17, 2022 IAT 265 36

Notes to Swing Timer (1)
There are two ways to register an ActionListener object to a Timer object
The former only allows to have one listener registered, the latter allows to have as many as you want
– By passing in as an argument when a Timer object is created, e.g.: //Passing BallPanel to timer when it’s created
timer = new Timer(33,this);
– By calling Timer’s method addActionListener(ActionListener listener) :
//no initial listener passed in
timer = new Timer(33,null);
//register BallPanel to timer
timer.addActionListener(this);
January 17, 2022 IAT 265 37

implements interface
 Although Java allows a class to ”extends” from a single class only, however, it allows it to ”implements” as many interfaces as necessary, as long as they are delimited with “,”
 This is a nice feature, as it will allow our program to have animations and mouse interactions simultaneously, e.g.:
class BallPanel extends JPanel implements ActionListener, MouseListener {
… //Need to implement here all methods declared by both interfaces
January 17, 2022 IAT 265 38

on Timer-Based Motion
 To create animations, you need to use a Swing Timer object – javax.swing.Timer(ratherthanjava.util.Timer)
 Timer-based animation is based on Java Event Model
– Timerobjectfiresticks,ActionListenerobjectscanregistertotheTimer object to listen to its ticks, and respond by updating the objects’ positions and then repaint it
 To make any object a timer listener, e.g. the JPanel instance, make it “implements” the ActionListener interface
 An Interface is a Java construct that provides a description of a role with some capabilities – via method declarations without implementation
– Aclasscanchoosetoimplementaninterfacetoassumetheroleand thereby provide the capabilities as declared
January 17, 2022 IAT 265 39

Random Behavior
 There is often a need to have some values randomly fluctuate within a range of values
– E.g. a random location on the screen
or a random speed within the <0, maxSpeed>
January 17, 2022 IAT 265 week 2 40

Math.random()
 Returns values between <0.0,1.0>  To get a value x within
– x = a+ Math.random()*(b-a)
ball1 = new Ball(100, 100, 100, 100, Color.BLUE,
(int)(1+ Math.random()*5)); //within <1, 6>
ball2 = new Ball(400, 100, 100, 100, Color.BLUE,
(int)(-2.0 + Math.random()*4)); //within <-2.0, 2.0>  Demo
January 17, 2022 IAT 265 week 2 41

Questions for Java’s
paint method
public void paintComponent(Graphics g)
 If you check the case studies,
do you see anywhere it gets called?
 If not, what triggers it to operate in the window environment?
January 17, 2022 IAT 265 week 2 42

Painting Mechanism of AWT and Swing
 System-triggered painting when:
– the component (the JPanel object) is first made visible on
– The component (the JPanel object) is resized
– So in this sense, it is a call-back method (i.e. called by the system based on some events)
 Application-triggered painting :
– when objects (like the balls in our case studies) get updated, program calls repaint() which calls paintComponent() implicitly
 So paintComponent() method is only a semi-call-back
the screen
January 17, 2022 IAT 265 week 2 43

AWT/Swing Painting Guidelines
 For Java programs, all paint code (draw/fill) should be placed or called within the component’s paintComponent() method
 Don’t call paintComponent() method directly anywhere in your program
– It’ll be either called by the system when the component is displayed for the first time or resized
– Or by calling the repaint() method in your program when objects’ states get changed
January 17, 2022 IAT 265 week 2 44

Encapsulation
 With Data Hiding
January 17, 2022 IAT 265 week 2 45

Object-Oriented Programming (OOP)
 Object-Oriented Programming (OOP): about creating programs that perform their actions via int

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com