Presentation is loading. Please wait.

Presentation is loading. Please wait.

Block 1 Unit 2 Basic Constructs in Java. Objectives create a simple object using a constructor; create and display a window frame on your computer screen;

Similar presentations


Presentation on theme: "Block 1 Unit 2 Basic Constructs in Java. Objectives create a simple object using a constructor; create and display a window frame on your computer screen;"— Presentation transcript:

1 Block 1 Unit 2 Basic Constructs in Java

2 Objectives create a simple object using a constructor; create and display a window frame on your computer screen; paint a message in a window; use data fields to store simple values; pause the execution of a program using the sleep method from the class Thread; refer to a super class using the reserved word super; build a simple animation using a loop.

3 Objectives create a small application that uses the Abstract Windowing Toolkit (AWT) and Swing packages to simulate movement in a window based on the Java develop Java programs with several classes using inheritance; define and use object constructors; represent a simple Java program as a class diagram; construct a Java program by accessing code held in files.

4 First Program FrameHeight Y axis = 400 -----------------> FrameWidth = 600 (X axis) The program places a graphical window on the user's screen

5 First Program The program consists of two classes. public class Application اسم الكلاس الذي بة دالة الـ main { public static void main(String[] args) { FirstWorld world = new FirstWorld();إنشاء كائن من نوع الصنف world.show(); نداء للدالة الموجودة في الكلاس الموروث منه } ملاحظة : - الصنف = الكلاس

6 First Program The main method is where an application begins executing. The method is declared public meaning that the method can be called from anywhere. It is declared static meaning that all instances of this class share this one method. void which means that this method does not return a value. We pass any command line arguments to the method in an array of Strings called args. In this simple program there aren't any command line arguments though

7 First Program import javax.swing.*; الباكج المسئولة عن الواجهة كما انشئت import java.awt.*; الباكج المسئولة عن الواجهة تبعا للنظام الذي يعمل public class FirstWorld extends JFrame وراثة خصائص الصنف JFrame { public FirstWorld() { setSize ( FrameWidth, FrameHeight);دوال موجودة في كلاس الأب setTitle ("MY FIRST WORLD"); } public static final int FrameWidth = 600;// final تعني ثابت public static final int FrameHeight = 400; public void paint(Graphics g) دالة في الصنف Jframe { g.drawString ("A Simple message", FrameWidth/2, FrameHeight/2); }

8 JFrame JFrame contain the feature of any frame window يَحتوي Jframe ميزّة أيّ نافذة إطارِ Such as minimize, moving and resize the window مثل يُقلّلُ، مؤثّرة وبحجم ثانيةً النافذة Usually we do not create an instance of JFrame (not doing anything meaningful) To design Frame window, we would define a sub class of JFrame عادة نحن لا نَخْلقُ حالةَ Jframe لتَصميم نافذةِ الإطارِ، نحن نُعرّفُ a فئة فرعية Jframe

9 public class FirstWorld extends JFrame extends keyword is used for inheritance, this means that Ballworld class inherited all methods in JFrame class (the parent class). And JFrame class is a subclass of Frame (Upper ) class تُمدّدُ كلمة دليليةُ مستعملةُ للميراثِ، هذا يَعْني بأنّ صنفَ Ballworld وَرثَ كُلّ الطرق في صنفِ Jframe (الصنف الأصل). وصنف Jframe a فئة فرعية مِنْ إطارِ (أعلى) صنف Notice that setTitle, setSize are define in JFrame

10 import import javax.swing.*; الباكج المسئولة عن الواجهة كما انشئت import java.awt.*; الباكج المسئولة عن الواجهة تبعا للنظام الذي يعمل In Java, GUI based programs are implemented by using classes the javax.swing and java.awt Difference:- Swing class behave same on different Operating system Swing Class support many new functionality يَتصرّفُ تحوّل الصنفِ نفسهَ على نظامِ التشغيل المختلفِ يَدْعمُ تحوّل الصنفِ العديد مِنْ الوظيفةِ الجديدةِ

11 Constructors The following statement create a new instance of the class FirstWorld, FirstWorld world = new FirstWorld( ); The new operator is followed by a class name indicating the type of object being created. This method called constructor. For each class there is a constructor. The constructor is the first method invoked when an object is created, and is responsible to guarantee that the objects are placed into a proper initial stat Class_name object _name create new object of type FirstWorld

12 Constructors.Differences between constructors and methods The name of the constructor matches the name of the class in which it appears. The constructor does not specify a return type. The use can never execute the constructor except as part of creating a new object. Similarities between constructors and methods Both can have arguments. Their body consists of a sequence of statements. Two examples are the methods: setSize and setTitle invoked in the FirstWorld constructor.

13 Concept public static final int FrameWidth = 600; public static final int FrameHeight = 400; These two statements declare new variables named: FrameWidth which is the window frame width = 600 and window height which is 400. 600 and 400 are measured in pixels. final: is a keyword means constant, this value could not be changed, so the window frame size is fixed unless you changed the previous width and height. static means that this variable is shared with all instances and exists until the end of execution.

14 Concept setSize(FrameWidth, FrameHeight): This method is found in the parent class Frame which is responsible to set the size of the window to specific width and height. In this case to 600 width and 400 height. This means that any point within the boundary of the window must have an x-value between [0,600] and a y-value between [0,400]. setTitle(“First World"): This method is found in Frame class, it is responsible to give the title for the created window

15 Concept The show method (inherited from JFrame) creates the window in which the action will take place. In order to draw the image shown in the window the show method invokes a method called paint passing as an argument a graphics (g) object. The programmer defines the appearance of the window by providing an implementation of the method paint.(clear the window frame)

16 Concept The graphics object passed as argument provides the ability to draw a host of items (e.g. lines, polygons and text). Hence, this object can be used to create a text Text drawn by drawString. Graphics and its method are contained in java.awt SEE Flow of Program On BOARD

17 Ball World

18 import java.awt.*; import javax.swing.JFrame; public class BallWorld extends JFrame { public static void main (String [ ] args) { BallWorld world = new BallWorld (Color.red); world.show (); for (int i = 0 ; i < 1000 ; i++) world.run(); System.exit(0); // halt program } public static final int FrameWidth = 600; public static final int FrameHeight = 400; private Ball aBall = new Ball (new Point(50,50), 20);

19 Ball World private BallWorld (Color ballColor) { setSize (FrameWidth, FrameHeight); setTitle ("Ball World"); aBall.setColor (ballColor); aBall.setMotion (3.0, 6.0);} public void paint (Graphics g) { super.paint(g); aBall.paint (g);} Public void run() { aBall.move(); Point pos = aBall.location(); If ((pos.x < aBall.radius()) || (pos.x > FrameWidth – aBall.radius())) aBall.reflectHorz();

20 Ball World If ((pos.y < aBall.radius()) || (pos.y > FrameHeight – aBall.radius())) aBall.reflectVert(); repaint(); try { Thread.sleep(50); } catch (InterruptedException e) {System.exit(0);} }

21 Ball World Unit 2, section 2 and Budd ch 5: This discusses the BallWorld program The BallWorld program, is related to draw a ball in a window, and is composed of 2 principal classes: Class BallWorld: which provides a window, where the drawn objects will appear. Class Ball: which represents a ball that is a color circle and moves inside the window frame. (which is created by the class BallWorld). الصنف BallWorld: الذي يُزوّدُ a نافذة، حيث الأجسام المَسْحُوبة سَتَظْهرُ. كرة صنفِ: الذي يُمثّلُ a كرة التي a دائرة لونِ ويَتحرّكُ داخل إطارِ النافذةَ. (الذي مَخْلُوقُ بالصنفِ BallWorld).

22 Ball World public class BallWorld extends JFrame: extends keyword is used for inheritance, this means that Ballworld class inherited all methods in JFrame class (the parent class ) BallWorld world = new BallWorld(Color.red); (actual argument), initial color for the new object is red

23 Ball World The constructor is the first method invoked when an object is created, and is responsible to guarantee that the objects are placed into a proper initial state. The arguments passed to the constructor are the arguments supplied in the new expression.

24 Ball World Data Fields In the above program there are three data fields public static final int FrameWidth = 600; public static final int FrameHeight = 400; private Ball aBall = new Ball (new Point(50,50), 20); ); public means that the variables being declared can be accessed (i.e. used directly) private can be used only within the bounds of the class description static means that there is only one instance of the data field shared by all the instances of the class. Data fields that are declared static and final behave as constants, because they exists in only one place and cannot change value. The identifier of such a data field is sometimes called a symbolic name.

25 Ball World public static final int FrameWidth = 600; public static final int FrameHeight = 400; These two statements declare new variables named: FrameWidth which is the window frame width = 600 and window height which is 400. 600 and 400 are measured in pixels. private Ball aBall = new Ball(new Point(50,50), 20): This will create a new object called aBall of type class Ball. Class Ball is found in awt package which is imported at the beginning of the program. The Ball constructor has an actual argument which is:

26 Ball World (new Point(50,50), 20), again this is a new object of type Point class. It will match the Ball constructor which is found in Ball class as follows: public Ball (Point lc, int r) {//constructor for new ball //ball centre at point loc, radius rad loc = lc; rad = r; } The fields inside the instance from the class

27 Ball World private BallWorld(Color ballColor): This is the constructor for class BallWorld. It is responsible to create a window with specific size, and give it a title. The formal arguments will have the values of the actual ones. In this case ballColor will be red because when we create the object, Color.red was used as an initial value. BallWorld world = new BallWorld(Color.red); // actual argument Pivate BallWorld(Color ballColor) //formal argument Formal argument: usually considered as local variables inside the method it has

28 Ball World setSize(FrameWidth, FrameHeight): This method is found in the parent class Frame which is responsible to set the size of the window to specific width and height. In this case to 600 width and 400 height. This means that any point within the boundary of the window must have an x-value between [0,600] and a y-value between [0,400]. setTitle("Ball World"): This method is found in Frame class, it is responsible to give the title for the created window. The result of calling these methods will be a window with these titles:

29 Ball World aBall.setColor(ballColor): a method to give a color to the ball, which is red in this case. After the call for this method, a Ball data fields will be: Loc  (50,50) Rad  20 Color  red changelnX  0.0 // horizontal change in ball position in one cycle changelnY  0.0 // vertical change in ball position in one cycle

30 Ball World aBall.setMotion(3.0, 6.0): Start the ball motion from these coordinators, x and y (horizontal and vertical) components of the motion direction. After this the datafileds values of aBall object are: Loc  (50,50) Rad  20 Color  red changelnX  3.0 changelnY  6.0

31 Ball World The show method (inherited from JFrame) creates the window in which the action will take place. In order to draw the image shown in the window the show method invokes a method called paint passing as an argument a graphics object. The graphics object passed as argument provides the ability to draw a host of items (e.g. lines, polygons and text). Hence, this object can be used to create a variety of graphical images. In our program the paint is implemented as follows public void paint (Graphics g) { super.paint(g); aBall.paint (g); }

32 Ball World Paint() method: calls 2 methods: Call paint method in the upper calss JFrame (super.paint(g)) to clear the window, and then call aBall.paint(g) to draw the ball itself The method invokes the paint method in the parent class JFrame. The method in the parent class erases any previous contents of the window. When a method Overrides (replaces) a similarly named method in the parent class, a technique must be provided to indicate that the method should invoke the inherited from the parent class by using super.method_name().

33 Ball World aBall.paint(g)  matching with paint() in class Ball, which is: public void paint (Graphics g) { g.setColor(color); g.fillOval(loc.x-rad, loc.y-rad, 2*rad, 2*rad); } fillOval method is a graphical method which has 4 arguments, that specify the position and size of a rectangle in which the oval shape will be painted. Loc.x-rad,loc.y-rad: represents the position of the top left corner of the rectangle. 2*rad,2*rad: this is the width and height of the rectangle. As a result the oval will be painted inside this rectangle Windo w x-direction x Y height width

34 Ball World for(int i = 0; i < 1000; i++) world.run(): invokes the run() method 1000 times. i =0: initial value for the condition i<1000: check if less than 1000 times then re do the body again i++: increment i by one (i = i+1). The run method instructs the ball to move and requests that window to be repainted. To do this the method invokes repaint; an application does not call the paint method directly, but only indirectly by requesting a repainting.

35 Ball World System.exit(0): this method stop the execution of the program. aBall.move(): move is a method in class Ball which in turn calls another method in calss Point to animate the ball. The move() method in Ball class is: public void move(){loc.translate((int)changeInX, (int)changeInY);} for more details look at Ball Class. Point pos = aBall.location(); if ((pos.x < aBall.radius()) || (pos.x > FrameWidth - aBall.radius())) aBall.reflectHorz(); if ((pos.y < aBall.radius()) || (pos.y > FrameHeight - aBall.radius())) aBall.reflectVert(); These instructions are used to guarantee that the motion is inside the window frame.

36 Ball World try{ Thread.sleep(50); } catch(InterruptedException e) {System.exit(0);} The animation of an object is achieved by: Painting the ball, then Clearing the window, And repainting the ball in a new position Repeating the whole process for a number of times

37 Ball World To achieve this as mentioned before, method repaint() call paint() which in turn first repiant()  paint()  super.paint() to clear the window  aBall.paint() to draw the ball. The idea is that, the run method simply sleep (pause) for half a second, calculate the new position, and then repeats this process for 1000 times before stopped. If any interruption happened, the execution will stop.

38 Ball World Graphical applications (e.g. repainting) are relatively slow. Hence, it is necessary to halt the program for a short period of time so that the graphics system can catch up. This is done using the command Thread.sleep(). This command will suspend the program for a small period of time (measured in milliseconds). The sleep method can raise an exception. Hence it must be surrounded by a try block.

39 Multiple Objects of the Same Class The class MultiBallWorld is similar to the BallWorld class except that it creates a collection of balls rather than just a single ball. To create this collection an array is used as follows: private Ball [] ballArray = new Ball [BallArraySize]; The array is a sequence of memory location. All these locations are accessed using the array name and the element position as: ballArray[0], ballArray[1],… 0 1 2 …………………. Size-1 ballArray

40 Multiple Objects of the Same Class where BallArraySize is a symbolic constant. Although the array is created the array elements cannot be accessed. Each array element must be individually created, once more using a new operation: for (int i = 0; i < BallArraySize; i++) { ballArray[i] = new Ball(new Point(10, 15), 5); ballArray[i].setColor (ballColor); ballArray[i].setMotion (3.0+i, 6.0-i); } Each ball is created, and then initialized. Hence, we have multiple instances of the same class each maintain their own separate data fields.

41 BallWorld project: Usually classes are grouped into a package. Classes can be partitioned into 3 groups: Application classes: central classes such as Ball, BallWorlds claases. Implementation classes: used in the implementation, Point Interface classes: to build HCI, such as JFrame.

42 Cannon Game Section 2.3: Cannon game This program shows the implementation of shooting cannon. In the cannon game you have: A cannon on the left portion of the user’s window, and A target on the right portion. The use can control (enter) the angle of elevation for the cannon and fire a cannonball. The main goal is to hit the target. Two games are presented: Simple game: user can enter one angle of the cannon and fire it. The second version: allow the user to change the angle several times and shoot until he may hit the target, this is done in the same execution.

43 Cannon Game The aim of this program is to introduce some Java features which are related to creation of graphical user interface. Below is some of Java features which are used in the cannon game, and its definitions. Inner class: is to place a class definition within another class definition. Public Class first // Outer class { …. Private class second //Inner class { …….} }

44 Cannon Game The Java event is based on the concept of listeners An eventdriven program will wait for an event, and then respond to it. In Java the technique used to wait for events is termed a listener. A listener is simply an object whose main responsibility is to wait for a specific event. When the event occurs, the listener wakes up, and performs the necessary action. To provide a platform independent way to halt our program, we define a listener and attach it to the close-box of a window.

45 Cannon Game Interface: is a description of behavior, it is a keyword such as class, and usually it is parent class which defines data fields as static, and provides the method names only without implementation code. Handling events (such as pressing a button, or moving slider) makes extensive use of interfaces which are stored in Java library. Such interfaces are said event- driven.

46 Interfaces vs. Inheritance Using inheritance, methods and data fields that are declared in the parent class may be used in the child class. Hence, the child class inherits the structure of the parent class. Using an interface, there is no implementation of the methods in the "parent interface“ at all. Instead, the parent simply defines the names of the methods which must then be implemented in the child class. Hence, a child class inherits a specification of methods from an interface, but no structure, no data fields, and no member functions. An interface can be used as a type name in an argument declared in a method header. The matching parameter value must then be an instance of a class that implements the interface.

47 Interfaces vs. Inheritance interface ActionListener //interface name: ActionListener { public void actionPerformed(ActionEvent); // method represents behavior which must be taken when the event happened. }

48 Cannon Game Clicking the mouse in the close-box for a window will generate a window event. To trap this condition, we need a listener specialized for window events. Now if you want to use this interface and define an implementation, you will create a child class and use the keyword implements (which is similar to extends) followed by the interface_name. ListenerInterface_name private class FireButtonListener implements ActionListener{ public void actionPerformed(ActionEvent evt){ aBall = cannon.fire(); }

49 Cannon Game In Cannon game, the listener is attached to a newly created button by the following code: Button fire = new Button(“fire”) //”fire” is the button label.. Fire.addActionListener(new FireButtonListener()); // the achtion In case of Button, the event of interest is the button pressed. To register your interest in when a button is pressed, you call Fire.addActionListener method. This method expects an arguments which is an object that implements ActionListener interface: Fire_ButtonListener. When you press the button, the message action Performed will be passed to the listener. ActionEvent evt: it is an event which is the press fire

50 Cannon Game For each primitive data type, int, float,.., the Java library defines wrapper class that can be use as an object int  wrapper class is Integer which holds integer values.. The usefulness of this Integer is the ability to convert a string value into integer. int x = Integer.valueOf(“hello”); Cast: a mechanism for changing the type of the value: (int) ((4.5+5.2)/2); //the result will be an integer


Download ppt "Block 1 Unit 2 Basic Constructs in Java. Objectives create a simple object using a constructor; create and display a window frame on your computer screen;"

Similar presentations


Ads by Google