0% found this document useful (0 votes)
25 views37 pages

OOP2 Manuls 2020 2021

Uploaded by

almsryahmd182
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views37 pages

OOP2 Manuls 2020 2021

Uploaded by

almsryahmd182
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Hashemite University

Prince Al-HUssein bin ABDUllah II FacUlty for


Information Technology

Object Oriented Programming2

Lab Manual
Prepared by:

Miss. Manar Alrifaai Miss. Haneen Hijazi Miss Ayat Al Ahmad

1
Table of Contents

Contents
Table of Contents ............................................................................................... 2
Project#1 (Rectangle) .........................................................................................3
Project#2 (Account) ...........................................................................................4
Project#3 (Student) ...........................................................................................5
Project#4 (Course) .............................................................................................6
Project#5 (CD) ..................................................................................................8
Topic 2: Inheritance and Polymorphism ............................................................... 10
Project#6 (Shape) ............................................................................................ 10
Project#7 (Person) ........................................................................................... 13
Topic 3: Abstract Classes and Interfaces .............................................................. 14
Project#8 (Colorable – abstract class) ................................................................. 14
Project#9 (Colorable - interface)......................................................................... 15
Project#10 (Animal - Implementing Class Diagram) ............................................. 166
Sample Exam .................................................................................................. 16
Topic 4: Graphical User Interface GUI .................................................................. 21
Project#11 (Components).................................................................................. 21
Project#12a (FlowLayout).................................................................................. 22
Project#12b (GridLayout) .................................................................................. 22
Project#12c (BorderLayout) .............................................................................. 22
Project#13 (Microwave) .................................................................................... 23
Project#14 (Event Handling) .............................................................................. 24
Project#15 (Dollars) ......................................................................................... 25
Project#16 ...................................................................................................... 26
Project#17 ...................................................................................................... 26
Appendices...................................................................................................... 28
Appendix A: Course Syllabus .............................................................................. 28
Appendix B: Graphical User Interface (General Notes) ............................................ 30
Appendix C: General Notes on GUI ...................................................................... 31
Appendix D: GUI Classes Hierarchy ..................................................................... 32
Appendix E: Event Handling ............................................................................... 33
Appendix F: Read and Write in Java .................................................................... 34

2
Topic 1: Classes and Objects
Project#1 (Rectangle)

Create a project named Proj1, In Proj1 class create class named Rectangle. In the
Rectangle class:

1) Declare two double data fields named width and height that specify the width and
height of the rectangle. The default values are 1 for both width and height.

2) Declare a string data field named color that specifies the color of a rectangle.
Assume that all rectangles have the same color. The default color is
white.

3) Define a no-argument constructor that creates a default rectangle.

4) Define a two-arguments constructor that creates a rectangle with the specified


width and height.

5) Define get and set methods for all the width and height data fields. For
the width and height setters, check that the new values are non-negative.

6) Define a method named getArea() that calculates returns the rectangle area
(Hint: area=width*height).

7) Define a method named getPerimeter() that calculates and returns the rectangle
perimeter. (Hint: perimeter=2*width+2*height)

8) In the main method in the same class do the following:


a) Create a default rectangle named r1, then print its width, height, and color.
b) Change the width of the rectangle r1 to 10, then print the new value.
c) Create a Rectangle object r2 with width=4, and height=40, then print its
width, height, and color.
d) Assign the color “red” to all Rectangle objects.
e) Print the color of the rectangle r2.
f) Create a Rectangle object r3 with width=6, and height=50, then print its
width, height, and color.
g) Print the areas of the three rectangles r1, r2, and r3.
h) Print the perimeters of the three rectangles r1, r2, and r3.

3
Project#2 (Account)

1) Create Java project named project2. In the project2 create class named Account. In the Account
class do the following:
a) Declare an integer data field named id (default value= 0)
b) Declare a double data field named balance (default value= 0.0)
c) Declare a double data field named annualInterestRate (default value=0.0).
The annualInterest Rate is fixed for all accounts.
d) Declare a Date data field named name dateCreated that contains the date when the
account was created.(Hint :- use the following package java.util.Date)
e) Define a no-argument constructor that creates a default account.
f) Define the accessor and mutator methods for id, balance, and annualInterestRate.
g) Define the accessor method for the dateCreated.
h) Define a method named withdraw (double) that withdraws a specified amount
from the account.
i) Define a method named deposit (double) that deposits a specified amount to the account.

j)
2) In the main() method do the following:
a) Create an account object (acc1) with (ID=1122, balance=1000, and annualInterestRate=5.5%)
b) Deposit 30, 40, and 50 to the account.
c) Withdraw 5, 4, and 2 from the account.
d) Print an account summary that shows account ID, annualInterestRate, balance, and the
date when the account was created.

4
Project#3 (Student)

Create a Java project named Proj3. In Proj3 do the following:


1. Create a class named Student. In the Student class do the following:
a. Declare the following data fields:
i. name: private string variable
ii. id: private Integer variable
iii. count: Private Integer variable contains the number of student.
b. Create a one-argument constructor that creates a student with the specified
“name”, each time a student is created the count variable is incremented by 1,
and is given an ID that equals to the value of count at that moment.

c. Create setName(name) method.

d. Create a default constructor, each time a student is created the count variable is
incremented by 1, and is given an ID that equals to the value of count at that
moment . [Hint:- read the name of student from user]

e. Create three get methods getName(), getID(), getNumOfStudents() that


returns the value of name, ID, and count respectively.

In the main() method do the following:


e. Display the initial number of students
f. Create three students s1, s2, and s3, named “haneen”, “manar” and
“ahmad” respectively.
g. Print the name and the ID for each student.
h. Create array of students with size 5 . Hint :- use default constructor to create all
objects within array.
i. Display the final number of students.

5
Project#4 (Course)

Create a Java project named Proj4. In Proj4 create a class named Course as follows:

Attributes:
  name: name of the Course.
  instructorName: name of the instructor of the course.

  studentsID: array containing ID of students.


  studentsGrades : array containing students’ grades.
 current: current number of students in the course.
Methods:
2. Course (name: String, size: int): initializes each course with its name, and sets the current
number of students to 0, is also instantiates the arrays (studentsID, studentsGrade) with
size size.
3. getNumberOfStudents () : returns number of students in the course.
4. setInstructorName (instname : String): set the course instructorName to the given value.
5. searchIndexOfStudent(stid : int) : returns the index of stid in array . If no matching stid
was found it returns -1.
6. addStudent(stid : int , stgd : int) : allows for adding a new student to the course with ID
stid and grade stgd. It returns true if the operation was done successfully, otherwise it
returns false.
7. display (grade : int) : displays information about students that have grade better or equal
to a given grade.
8. getSecondBestStudentID() : returns the student ID of the student that has the second
max grade in the course.

6
Main:
public static void main(String[] args) {

Course c = new Course("CSC 111",10);

c.addStudent(1111, 95);
c.addStudent(1111, 95);
c.addStudent(2222, 85);
c.addStudent(3333, 75);
c.addStudent(4444, 65);
c.addStudent(5555, 55);

System.out.println("The number of Students in the course "+ c.getNumberOfStudents());


c.display(80);
System.out.println("The Id of the second best student is: "+c.getSecondBestStudentID());

7
Composition

Project#5 (CD)

Suppose you are working with audio CDs, where each CD has a title, an artist name, and a number of
tracks with different lengths.

Create a Java project named project5. . In this project do the following:

9. Create a class named Track with the following data fields:


a. A String data field named trackTitle contains the title if the track
b. An integer data field named minutes contains the minutes’ part of the duration
of the track.
c. An integer data field named seconds contains the seconds’ part of the duration
of the track.
d. A three-arguments constructor that sets the title, minutes, and seconds of
the track to the given values
e. Define the method getMinutes() that returns the minutes.
f. Define the method getSeconds() that returns the seconds.
10. Create a class named CD with the following data fields:
a. A String data field named artist contains the name of the CD’s artist.
b. A String data field named cdTitle contains the title of the CD.
c. A Track array name tracks, this array contains Track object which resembles all
the tracks included in the CD.
d. An integer counter variable named current, contains the actual number of
tracks in the CD.
e. Define a three-arguments constructor that sets the title, and the artist to the given
values, current to 0. It also instantiates the tracks array with the given numoftracks.
f. Define the method addTrack(Track) which adds a track to the tracks
array and increments the current by 1.
g. Define the method getTotalSeconds() that returns the length of the CD in Seconds.
h. Define the method printTotalTime() that prints the total length of the CD
in the following format mm:ss

8
11. In the Java main class, do the following:
a. Create a CD object named mycd with a title "Quran", artist name: "Affasi",
number of tracks 3.
b. Create three tracks:
  t1: (“doha”, 3 min, 20 sec)
  t2: ("zalzala", 4 min, 15 sec)

  t3: ("nas",1 min, 2 sec)

c. Add the three tracks t1, t2, t3 to the cd named mycd.
d. Print the total length of the CD. ( Hint use printTotalTime() method )

9
Topic 2: Inheritance and Polymorphism
Project#6 (Shape)

Examine the UML Diagram below and do the Following

Create a java project named Proj6. In this project:


12. Create a class named Shape, in the Shape class do the following:
a. Declare a protected data field named color of type String. The default color
for any shape is white.
b. Create a no-argument constructor that sets color for its default value.
c. Create a one-argument constructor that sets the color to the given value.
d. Define the method describe() that prints the statement “This is a shape!”
e. Define the method getArea() that prints the statement “Unknown shape,
cannot calculate area” and returns 0.0.
13. Create a class name Triangle that extends the Shape class, in the Triangle class do
the following:
a. Declare two private, double data fields named height and base. “The
default values: height=1, base=1”.
b. Create a no-argument constructor that sets height, base to their default values.
c. Create a two-arguments constructor that sets height, base to the given values.
d. Create a three-arguments constructor that sets height, base, and color to the
given values. “Hint: use the previously created two-argument constructor”.
e. Override the method describe() in the Shape class to print Shape description
then the statement “This is a Triangle”.

10
f. Define the method getArea() that calculates and returns the area of
a triangle (area=0.5*base*height).
14. Create a class named Circle that extends the Shape class, in the Circle class do the following:
a. Declare a private double data field named radius. “The default value radius=1.0”.
b. Create a no-argument constructor that sets radius for its default value.
c. Define the method setRadius(double) that sets the radius to the given value if it
is nonnegative, and to 0.0 otherwise.
d. Create a one-argument constructor that sets the radius to the given value. “Hint:
use the previously defined setRadius method”.
e. Create a two-arguments constructor that sets the radius and the color to the
given values. “Hint: use the previously created one-argument constructor”.
f. Define the method getRadius() that returns the radius of a circle.
g. Define the method getDiameter() that returns the daiameter of a circle.
“Hint: diameter= 2*radius”.
h. Override the method describe() in the Shape class to print Shape description
then the statement “This is a Circle”.
i. Override the method getArea() in the Shape class to calculate the area of a circle.
“Hint: area=PI*radius*radius”.
15. In the main method do the following:
a. Create a default Shape named s1, then print its color, description, and area.
b. Create a default triangle named t1, then print its color, description, and area.
c. Create a triangle t2 with (height=5, base=9, and color=”blue”).
d. Create a default circle named c1, then print its color, description,
radius, diameter, and area.
e. Create a default circle named c2, then print its color, description,
radius, diameter, and area.
f. Create Circle object named p and assign its reference to a variable of type shape.
g. Call describe() method using object p.
h. Try to print the diameter of object p using the getDiameter() method.
16. In the same project create a package named proj6_B. In this package, create a class
named Cylinder that extends Circle class. In the Cylinder class do the following:
a. Declare a private double data field named “height”, “default value is height=1.0”.
b. Create a no-argument constructor that sets height to its default value.
c. Create a two-arguments constructor that sets the height, radius to its given values.
d. Create a three-argument constructor that sets the height, radius, and color to
its given values. “Hint: use the previously created two-arguments constructor”.
e. Define the method setHeight(double) that sets the value of the height data field.
f. Define the method getHeight() that returns the value of the height data field.
g. Define the method getVolume() that calculates and returns the volume of a cylinder.
“Hint: volume=height* circle_area”.

11
17. In the main method do the following:
a. Create a default cylinder cy1, then print its height, base radius, base area,
and volume.
b. Create a cylinder cy2 with heigh=5.0, radius=2.0, and color=”pink”, then
print its height, base radius, base area, and volume.

12
Project#7 (Person)

Create a Java project named Proj7.


7. In Proj7, create a class named Person. In this class do the following:
a. Declare a private string data field named name
b. Create a no-argument constructor that sets the name to “Undefined name yet!”
c. Create a one-argument constructor that sets the name to the given value.
d. Define get and set methods for the name data field.
e. Define a method named writeOutput() that prints the name of the person.
f. Define a method named sameName(Person p2) that returns true if two Persons have
the same name, else it returns false (Hint: Ignore the case of the letter of the name).
8. Design a class named Student that extends Person. In the Student class do the following:

a. Declare a private integer data field named studentNumber .


b. Define a no-argument constructor that creates a default Student, set the value
of studentNumber to 0.
c. Define a two-arguments constructor that creates a Student with the
specified name and studentNumber.
d. Define a method named getStudentNumber() that returns the studentNumber
of this student.
e. Define a method named setStudentNumber() that set the studentNumber
of this student to the given value.
f. Define a method named reset (newName,newStudentNumber)that resets the
name and the studentNumber to the new given values.
g. Override the writeOutput() to print the name and the studentNumber.
h. Override the method equals(Object st2) to return true if the two Students are the
same (i.e. have same names and same studentNumbers), otherwise, it returns
false. “Hint: Use the previously created sameName(Person) method”.
i. Override the method equals(Student st2) to return true if the two Students are
the same (i.e. have same names and same studentNumbers), otherwise, it returns
false. “Hint: Use the previously created sameName(Person) method”
j. Override the method toString() to print the statement “This object is of class
” concatenated with the class name. “Hint: use the
getClass().getSimpleName() method”.

9. In the main () method, do the following:


a. Create a Student object s1, with name=”haneen” and studentNumber=2013020,
then print the name and the studentNumber using the writeOuput() method.
b. Reset the name and the studentNumber of Student s1 to (“ayat”, 2013015), then
print the name and the studentNumber using the writeOuput() method.
c. Create a Student object s2, with name=”manar” and studentNumber=2012050.
d. Check if students s1and s2 have the sameName.
e. Check if students s1and s2 are the same student ( i.e. with same names and same
sutdentNumbers)
f. Print the output of the method toString() for object s1

13
Topic 3: Abstract Classes and Interfaces
Project#8 (Colorable – abstract class)

Create a project named Proj8. In this project, do the following:

1. Create a class named Colorable.


2. Create a class named Circle that extends the Colorable class.
  In the Circle class, declare a private double data field named radius.

3. Create a class named Rectangle that extends the Colorable class.
 In the Rectangle class, declare two private double data fields named width
 and height.

4. The Colorable class contains an abstract method getArea() that returns a double area.
5. In the Circle class, implement the method getArea() to calculate the area of a circle.
“Hint: area= PI*radius*radius”.
6. In the Rectangle class, implement the method getArea() to calculate the area of a Rectangle.
“Hint: area=width*height”
7. In the main method
  Create a Circle object with a radius specified by the user.

  Print the area of the created circle.

  Create a Rectangle object with a width and a height specified by the user.

  Print the area of the created rectangle.

9. Modify the Colorable class, by implementing the method howToColor(Colorable). This
method takes a Colorable object as an argument and returns a string that describe the
color of that object; it returns “Red” for Circle objects, and “Yellow” for Rectangle objects.
(Hint: use the instanceof operator).
10. Modify the Main class by implementing the method printColor(Colorable). This method
takes a Colorable object as an argument and prints a string that describes the object’s
class name and its color. (Hint: use the getClass().getSimpleName() method).
11. In the main method, write suitable method calls to print the color of the
two created objects.

14
Project#9 (Colorable - interface)

Create a Java project named Proj9. In this project do the following:

1.Create an Interface named as Colorable ,this interface contains two methods

  
 getArea(), which returns a
double

howTo Color(), which returns a
  string
2. Create a class named Circle that implements the Colorable interfce.
 Circle class has an Integer data field named radius.

3.Create a class named Rectangle that implements the Colorable interface.


 Rectangle class has a two double data fields named width, height.

4.For Circle objects, the getArea() method calculates and returns the area of the circle
according to the formula (c_area= PI* radius^2).

5.For Rectangle objects, the getArea() method calculates and returns the area of the
rectangle according to the formula (r_area= width*height)
6.For Circle objects, the howToColor() method returns a String that colors the Circle according to its
area “Hint: using the getArea() method”. If the area of the circle is greater than 50, the return color
will be “Red”, else the color will be “Yellow”.
7.For Rectangle objects, the howToColor() method returns a String that colors the rectangle
according to the width the rectangle. If the width is greater than 50, the returned color will be
“Black”, else the color will be “White”.

8.Create a Main class. In the main class do the following.


o Define the method printObject(Colorable) that takes a array of
type Colorable as an argument and prints out:
  The index of the object

  Its class name

  Its area

 Its color
o In the main() method, do the following:
  Create an array of Colorable with size=2;

  Create a Circle object with a radius specified by the user.

  Create a Rectangle object with a width and a height specified by the user.

  Fill the array with the created objects.

Write a suitable call to the method printObjects(Colorable []) to
print information about the create objects.









15
Project#10 (Animal - Implementing Class Diagram)

Examine the following Class Diagram, then answer the following questions:

9. Create a Java project named Proj 10, and convert the above class diagram into
Java code. Methods behaviors are illustrated below:
a. Drink(): displays “drink water”
b. Move() [in Mammals] returns “Walk”
c. Move() [in Birds] returns “fly”
d. makeNoise() [in Finch] returns “beep”
e. makeNoise() [in Horse] returns “neigh”
f. descFuel() [in Horse] prints “No Fuel”
g. getType() [in Horse] returns “Horse”. “Hint: use the getClass() method”
h. beFriendly() [in Horse] prints “can live with humans”
10. Create a Java main class named Test, in the main() method do the following:
a. Create a Horse object named h1, and set its food to “oats”.
b. For this object display its: food, friendship, type, fuel, drink, noise, and move.
c. Create a Finch object named F1, and set its food to “seeds”.
d. For this object display its: food, drink, noise, and move.

16
Sample Exam

Hashemite University
Prince Al-Hussein bin Abdullah II Faculty
for Information Technology
Department of Computer Science

For Instructor Use


Course Name Object Oriented Programming 2/Lab

Course ID 151001212
Academic Year 2018/2019
Semester
Exam
Second Semester
Mid Exam 40
Date 14-3-2019
Time 9-11 AM

For Student Use


Student Name

Student ID

Instructor Name

Section ID
PC NO

For Instructor Use:


Question No. Learning Max. Score Student Score

Q1 /40

Total Score /40

17
Create Folder with your ID on the Desktop.
Q1- Within your ID Folder Create java project named Question1,
examine UML Diagram below and do the Following steps in Question 1.

A).Create inteface named PriceAdmin. The PriceAdmin contains the following methods.
1. Public double calcualtePrice() .

B).Create interface Named VehcileAdmin. The VehcileAdmin contain the following methods
1. Public void DescribeCar().

C).Create class named Wheel . In Class Wheel do the following .


1. Declare Private integer data field named size that represents the size of wheel.
2. Declare Private String data field named Color . Note :all wheels have the same color at any time.
3. Create Assessors and mutators methods for size and color data fields.

D).Create class named Engine. In Class Engine do the following .


1. Declare Private integer data field named Powerengine .
2. Create setter and getter method for powerengine datafield.

E).Create package Named q1_b, within this package create class named Seat and do the following
1. Create empty default constructor.
18

18
F).Create class Named vehicle that implements PriceAdmin interface and Vehcile
Admin interface. In Class Vehcile
do the following:-
1. Declare protected wheel array named warr[4] with size four.
2. Declare protected seat array named sarr[5] with size five.
3. Declare engine object named e.
4. Create default constructor . Hint within default constructor using loops complete the deceleration of war[]
array and sarr[] array to represent actual object arrays.
5. Override to String method to return the name of the class.

F).Create class Named car that extends the vehcile class. In Class Car
do the following:-
1. Declare protected integer named carcount with default value zero .Hint each time the car is created
carcount must be incremented by one.
2. Declare protected String array named manfuctrurename filled with the following list
{"Toyota","Nissan","Honda","Hondai"} . Note the list of manfuctrurename array is unified for all cars .
3. Create default constructor.
4. Override toString() method . toString() method must return the String returned from toString() in
the super class concatenated with “2019” . Hint :- invoke toString() in the superclass.
F).Create class Named vancar that extends car. In Class vancar do the following:-
1. Override calculatePrice() to return the price of car. The base price of all cvanars is 35000 JD.
If the powerenginee of car is less than or equal 1500 JD the tax will be 14% and 1000 JD will be added to the
total price.
If the powerenginee of car is equal 2000 the tax will be 16% and 1500 JD will be added to the total price.
Otherwise the tax will be 18% and 2000 JD will be added to the total price.
2. Override DescribeCar() method to print the calculated price of car .
3. Overload equals(vancar r) method. equals method will return true if the vancars have the sameprice and r
is instanceof vancar, otherwise will return false.
F).Create class Named Sportcar that extends car class. In Class Car do the following:-
1. Declare private integer data field named modelyear.
2. Declare private integer data field named modelnumber.
3. create default constructor.
4. create one argument constructor that takes specified model modelyear.
5. create two arguments constructor that takes specified model modelyear and specified model number.
Hint :- use previous created constructor.
6. Override calculatePrice() to return the price of car. The base price of all sport cars is 2000 JD and the tax is 20%.
7. Override DescribeCar() method to print the modelnumber and modelyear of car.
8. Override equals(Object) method. Equals will return true if sportcars have the same value of powerengine.
Otherwise the method will return false.

E) In the main class , do the following


1. Print the initial number of cars .
2. Declare car array with size 3 named cararr[].
3. Fill first element with vancar.
4. Invoke toString method with previous object of array.
5. Fill second element with sportcar.
6. Fill third element with vancar.
7. Change the color of all wheels to “gray”.

19
8. Define method within main class named searchmodel(String m ), the search method is looking for within the
manfuctrurename array that has been declared within car class. if the m string has been foundwithin array
the index of element will be returned otherwise -1 will be returned . Hint:- use equalIgnoreCase() method.
9. Invoke search method to look for “Honda”.
10. Print the final number of cars.

Good Luck

20
Topic 4: Graphical User Interface GUI
Hint: See Appendix C

Project#11 (Components)

Create the following GUI. You do not have to provide any functionality. (Hint: use the flow layout)

 Add additional radio button (caption : Italic ) after bold radio.


 Add two check boxes(caption(c1) : Orange, caption (c2): Pink) respectively after previous
created italic radio button.
 Create group button g1, add radio buttons to g1.
 Create group Button g2, add checkboxes to g2.

21
Project#12a (FlowLayout)

Use Flow Layout manager to create the following GUI.

Project#12b (GridLayout)

Use Grid Layout manager to create the following GUI.

Project#12c (BorderLayout)

Use Border Layout manager to create the following GUI.

22
Project#13 (Microwave)

Create the following GUI for the front of a microwave oven. You do not have to provide any
functionality.

23
Topic 5: Event Handling

Project#14 (Event Handling)

Create the following GUI. When the user enters a text in the textfield and click on the button "Show
on text area", the text is displayed on the text area. When the user clicks on "Show on message
box" the text is displayed on a message box.

a) Using the current class


b) Using the inner class
c) Using the anonymous inner class

24
Project#15 (Dollars)

Write a program that converts US dollars into Canadian dollars, as shown in the following figure.
The program let the user enter an amount in US dollars and display it equivalent value in Canadian
dollars when clicking the Convert button. One dollar is 1.5 Canadian dollars.

Home Work :- add another Button at the center of bottom panel Named Clear. Clear Button clears the
text fields and prepare the Converter system to new operation.

25
Project 16

Design the GUI illustrated in the figures and Follow the guidelines below to make the GUI interactive .

Hints :-

  The bee.png and Flowers.png have been copied on the desktop .
 The background color of JButtons , JRadioButtons : PINK .
  Border Style: Titled Border, Line border .
  Include The Radio buttons within one ButtonGroup .
  Size of GUI 600,600.
 Copy the bee.png and flower.png to your folder that contain your solution.

Label L1

Color : PINK

Label L2
Color: YELLOW

Label L3 :
Flowers.png

26
Guidelines :-

 Load Image Button :- Loads bee.png image L2 . 

 Change Font Button :-Sets the font L1 to be : Calibari", BOLD and ITALIC ,16 . 
 Exit : Exits the application, also when the user presses the keyboard key E. 
 Clear Selection : Clears the selection of radio buttons and ComboBox.

 Left Radio Button:- Sets the left alignment : [Text within L1 and Image within L2]. 
 Center Radio Button:- Sets the center alignment : [Text within L1 and Image within L2]. 

 Right Radio Button:- Sets the right alignment : [Text within L1 and Image within L2]. 
 Set line Border (ComboBox) :- Sets the line border(color : black , thickness : 5) for L2 

 Set Titled Border :- Sets Titled Border (bee image ) for L2. 

 Set suitable toolTipText for exit, change font, Exit and Clear selection buttons. 

27
Project 17 (Files)
Design the GUI illustrated in the figures and Follow the guidelines below to make the GUI
interactive.

Import Button : - Read File (Saved within your Project) line by line and import it in the TextArea.
Export Button:- Export the text within TextArea into text file (text file will be saved
within your folder)

28
Project 18 : Error Handling Simple example
Write the following codes within Java environment and study the
outputs of the code.
class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
/* We suspect that this block of statement can throw
* exception so we handled it by placing these statements
* inside try and handled the exception in catch block
*/
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch (ArithmeticException e) {
/* This block will only execute if any Arithmetic exception
* occurs in try block
*/
System.out.println("You should not divide a number by zero");
}
catch (Exception e) {
/* This is a generic Exception handler which means it can handle
* all the exceptions. This will execute if the exception is not
* handled by previous catch blocks.
*/
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
}
}

29
Appendices Appendix A: Course Syllabus

Hashemite University

Prince Al-Hussein bin Abdullah II Faculty for Information


Technology
Department of Computer Science and its Applications

Course Syllabus

Year: 2020-2021 Semester: (1)

Credit Hours
Course No. Course Title Designation Prerequisite Co-requisite
Lectures /Lab.
Object Oriented
191001213 Programming 2 Required - 151001212 1/0
Lab

Instructor Name E-mail Office No. Office ext. Office Hours


nd Sun, Tues, Thu
Mrs. Ayat Al-ahmad [email protected] 2 Floor-3 - (11:00-12:00)

Coordinator's Name: Mrs. Ayat Al Ahmad

This course presents a practical introduction to object oriented


programming, exemplified by Java. This is a practical course where
students complete a set of programming assignments using Netbeans; the
Course Description leading JAVA integrated development environment (IDE). Several object
oriented programming concepts are introduced in this course including
classes, objects, inheritance, abstract classes, interfaces, polymorphism,
and object oriented graphical user interfaces using SWING.

a) Textbook(s):
th
1. Introduction to JAVA programming – Comprehensive Version, Y. Daniel Liang, 8
edition, Pearson Education, 2010
b) References:
1. www.java.sun.com

28
30
th
2. Deitel & Deitel, Java: How to Program, 9 edition , Prentice Hall, 2011.

Course Learning and Outcomes CLOs


1. Apply object oriented programming concepts including classes, objects, inheritance, polymorphism,
abstractc classes, and interfaces in designing Java Applications. (2)
2. Design Gaphical User Inteface using Java API classes (2)
3. Create interactive application using event handling techniques( 2)
4. Apply exception handling concept to handle run-time errors (2)
Addressed Student Learning Outcomes (SLOs)

Course
No. of Contact
Topic Details ILO Reference
Weeks hours*
number
1. Objects and Classes 1 Ch8 3 9
2. Inheritance and Polymorphism 1 Ch11 4 12
3. Abstract Classes and Interfaces 1 Ch14 2 6
4. GUI Basics 2 Ch12 2 6
5. Event-Driven Programming 3 Ch16 2 6
6. Exception Handling 4 Ch13 1 3
Total 14 42

Assessment method Grade Comments


Mid Exam 30 Covers Topics 8,11 and 14.
Quiz 20 Covers topics12 .
Final Exam 50 Covers all topics .
Total 100

31
Appendix B: Graphical User Interface (General Notes)
In order to create a Java GUI, you have to follow the following guidelines:

1) Create a java frame, consider the following code:


import javax.swing.*;
Public class First extends JFrame{

{ First f=new First();


f.setSize(400,300);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // to stop the program
execution when the frame is closed
f.setLocationRelativeTo(null) ;
f.setTitle(“First Program”);}
}
2) Create the Java components
a. It is preferred the declaration in the class, and the instantiation in the constructor,
consider the following code:
import javax.swing.*;
Public class First extends JFrame{
Public First(){
JButton Okbtn
Super(“First Program”); // or f.setTitle(“First Program”); in main
// Add Button into the frame
JButton okbtn = new JButton(“OK”);
}
3) Define the general layout of the frame (flow layout, grid layout, border layout) “in
the constructor”
 FlowLayout: setLayout(new FlowLayout(FlowLayout.LEFT,10,20));
 BorderLayout: setLayout(new BorderLayout(5,10));
 GridLayout: setLayout(new GridLayout(3,2,5,5));
4) Create panels if necessary and define their layout.
i. Default layout for JFRame is BorderLayout
ii. Default layout for JPanel is FlowLayout
5) Add each component to the frame “in the constructor”:
import javax.swing.*;
Public class First extends
JFrame{ Public First(){
JButton Okbtn
Super(“First Program”); // or f.setTitle(“First Program”); in main
// Add Button into the frame JButton
okbtn = new JButton(“OK”);
add(okbtn);
}

32
Appendix C: General Notes on GUI
In order to create a Java GUI, you have to follow the following guidelines:

6) Create a java frame, consider the following code:


import javax.swing.*;
Public class First extends JFrame{

{ First f=new First();


f.setSize(400,300);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // to stop the program
execution when the frame is closed
f.setLocationRelativeTo(null) ;
f.setTitle(“First Program”);}
}
7) Create the Java components
a. It is preferred the declaration in the class, and the instantiation in the constructor,
consider the following code:
import javax.swing.*;
Public class First extends JFrame{
Public First(){
JButton Okbtn
Super(“First Program”); // or f.setTitle(“First Program”); in main
// Add Button into the frame
JButton okbtn = new JButton(“OK”);
}
8) Define the general layout of the frame (flow layout, grid layout, border layout) “in
the constructor”
 FlowLayout: setLayout(new FlowLayout(FlowLayout.LEFT,10,20));
 BorderLayout: setLayout(new BorderLayout(5,10));
 GridLayout: setLayout(new GridLayout(3,2,5,5));
9) Create panels if necessary and define their layout.
i. Default layout for JFRame is BorderLayout
ii. Default layout for JPanel is FlowLayout
10) Add each component to the frame “in the constructor”:
import javax.swing.*;
Public class First extends
JFrame{ Public First(){
JButton Okbtn
Super(“First Program”); // or f.setTitle(“First Program”); in main
// Add Button into the frame JButton
okbtn = new JButton(“OK”);
add(okbtn);
}

33
Appendix D: GUI Classes Hierarchy

34
Appendix E: Event Handling

35
Appendix F: Read and Write in Java
import java.io.*;

class FileRead

{ public static void main(String args[])

try{

// Open the file that is the first

FileInputStream fstream = new FileInputStream("m.txt");

DataInputStream in = new DataInputStream(fstream);

BufferedReader br = new BufferedReader(new InputStreamReader(in));

String strLine;

//Read File Line By Line

while ((strLine = br.readLine()) != null) {

// Print the content on the console


System.out.println (strLine);

//Close the input stream

in.close();

catch (Exception e){//Catch exception if any

System.err.println("Error: " + e.getMessage());

Read and Write in Java

36
import java.io.*;

class FileWrite

{ public static void main(String args[])


{ try{

// Create file

FileWriter fstream = new FileWriter("m.txt");

BufferedWriter out = new BufferedWriter(fstream);

out.write("Hello to Java \n");

out.append("Hello to Java");

//Close the output stream

out.close();

catch (Exception e){//Catch exception if any

System.err.println("Error: " + e.getMessage());

37

You might also like