Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Block1 –unit 2
Case study
Budd 5-6
ENG : Ghada Farouk
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 superclass using the reserved word super;
• build a simple animation using a loop.
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 graphics model;
• develop Java programs with several classes using
inheritance;
• define and use object constructors;
• define constants in Java;
• represent a simple Java program as a class
diagram;
• construct a Java program by accessing code held in
files.
First Program
package unit2_1;
public class Application اسم الكالس الذي بة دالة الـmain
{
public static void main(String[] args)
{
FirstWorld world = new FirstWorld(); إنشاء كائن من نوع الصنف
world.show(); نداء للدالة الموجودة في الكالس الموروث منه
}
}
- : مالحظة
=الصنف = الكالسClass
the main method.
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.
The Java AWT is an example of a software framework. The
idea of a framework is to provide the structure of a
program but no application-specific details
package unit2_1;
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;
public static final int FrameHeight = 400;
final تعني ثابت
public void paint(Graphics g) دالة في الصنفJframe
{
g.drawString ("A Simple message", FrameWidth/2 , FrameHeight/2);
}
}
Case Study
Ball World
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 (); // show my frame
for (int i = 0 ; i < 1000 ; i++)
world.run(); // there the ball will move.
System.exit(0); // halt program
}
Ball World
public static final int FrameWidth = 600;
public static final int FrameHeight = 400;
private Ball aBall = new Ball (new Point(50,50), 20);
private BallWorld (Color ballColor) {
setSize (FrameWidth, FrameHeight);
setTitle ("Ball World");
aBall.setColor (ballColor);
aBall.setMotion (3.0, 6.0);// dx , dy.
}
The fields inside the
instance from the
class
Ball World
public void paint (Graphics g) {
super.paint(g); // for calling base class pain, and not
entering an endless loop.
aBall.paint (g);
}
Public void run() {
aBall.move();
Point pos = aBall.location();
If ((pos.x < aBall.radius()) ||
(pos.x > FrameWidth – aBall.radius()))
aBall.reflectHorz();
Ball World
If ((pos.y < aBall.radius()) ||
(pos.y > FrameHeight – aBall.radius()))
aBall.reflectVert();
repaint( );// calling set of procedures paint is one of
them
try { // for dealing with errors.
Thread.sleep(50); // halt for 50 sec to see the
motion.
}
catch (InterruptedException e) {System.exit(0);}
}
}
P(x,y) = Point(50,50) start point
Try statement:
try{
a series o stataments;
}
catch (someExceptionClass e){
handle the exception;
}
What is threading? Thread class
Difference between repaint() and paint (Graphics g) methods
•Paint: is provided by the programmer and
invoked by the browser when the window
contents need to be redrawn
•Repaint: invoked by the programmer when the
window contents need to be redrawn.
Having two different frames
public class BallWorld extends JFrame{
public static void main (String [] args){
BallWorld world = new BallWorld(Color.red);
world.show();
BallWorld world2 = new BallWorld(Color.yellow);
world2.show();
for(int i = 0; i < 1000; i++){
world.run();
world2.run();
}
Study P.79 multi balls in the same frame.
Private Ball [ ] balls = new Ball [10];//Array of objects
g.fillOval(location.x-radius, location.y-radius,2*radius, 2*radius);
this keyword:
This.setTitle(“Ball World”);
Boolean operators:
<
While statement:
While (boolean expression){
expression series;
}
>
<=
Math class:
>=
Math.radom()
==
Math.sin(double )
!=
Math.cos(double)
Logical operators:
Logical and
&&
Logical or
||
Logical not
!
Math.PI
++ and – operators:
exp-- , exp++
--exp, ++ exp
BallWorld project:
Case Study
Cannon Game
1- Block 1 p.14 Flying disc instead of ball.
2- Cannon game
–
–
–
–
Cannon class.
Target class.
Cannon ballclass.
Main class = CannonGame class
Cannon Game:
Wrapper class
Integer class: (Wrapper class)
static Integer valueOf(String s)
// Returns an Integer object holding the value of the specified String.
int intValue()
// Returns the value of this Integer as an int
Integer(int value)
//Constructs a newly allocated Integer object that represents the
specified int value.
A vector class can’t be of int type so we create a wrapper class for the
int type called Integer, now I can create a vector of Integer objects.
Wrapper class 2
Public class Square{
private int side;
public Square (int s1) { side = s1; }
public int get_Side () { return side; }
public set_Side (int y) { side = y; }
}
Public class my_Square{
Private Square S;
Public my_Square (int L) {S = new Square (L); }
get_Side () { return S. get_Side (); }
}
My_Square here is a wrapper class that hide the implementation of
Square and reuse the members of that class by its way.
What is an interface?
•An interface is a description of behaviour.
•An interface can be used as a type name in an argument declared in a
methods header And the matching parameter must be an instance ( in
main ) of a class that implements the interface.
Interface interface_name { header of the interface functions.}
Void fn_name (interface_name x1){ x1.a_fn_in_interface( ) } feature of
substitutability
•A class that implements an interface must provide method definition for
all the interface methods.
interface interface_name{
//Methods with no bodies
}
Class class_name impelements interface_name{
}
Class WindowAdapter :
java.awt.event.WindowAdapter
public abstract class WindowAdapter extends Object implements
WindowListener
void windowClosing(WindowEvent e)
//Invoked when the user attempts to close the window from the
window's system menu.
Class Jframe:
Methods inherited from class java.awt.Window
public void addWindowListener(WindowListener l)1
//Adds the specified window listener to receive window events from
this window.
import java.awt.event.*;
public class CloseQuit extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
//in CannonWorld class
public CannonWorld() {
setSize(FrameWidth, FrameHeight);
setTitle("Cannon World");
addWindowListener(new CloseQuit());
//add graphical objects and their listeners
JButton fire = new JButton("fire");
fire.addActionListener(new FireButtonListener());
getContentPane().add("North", fire);
slider.addAdjustmentListener(new JScrollBarListener());
getContentPane().add("East", slider);
}
BorderLayout:
It is the default layout manager.
BorderLayout arranges a container's
components in areas named North,
South, East, West, and Center. These
are
BorderLayout's
placement
constraints.
•The components in North and South
are given their preferred height and
are stretched across the full width of
the container.
•The components in East and West
are given their preferred width and
are stretched vertically to fill the
space between the North and South
areas.
• The component in the Center
expands to fill all remaining space.
What is an inner class?
A class within a class
Allowed to access their surrounding environment (data field
and methods).
The inside class can access the outside class member.
Are used frequently in building listener objects for handling
events.
JButton class:
javax.swing.JButton
JButton(String text)
//Creates a button with text.
public void addActionListener(ActionListener l)
//Adds an ActionListener to the button.
ActionListener interface:
java.awt.event
Has only one method
void actionPerformed(ActionEvent e)
//Invoked when an action occurs.
Class ActionEvent: java.awt.event.ActionEvent
Class Jframe: javax.swing.JFrame
Container getContentPane()
// Returns the contentPane object for this frame.
Class Container: java.awt.Container
Component add(String name, Component comp)
//Adds the specified component to this container.
//in CannonWorld class
.
.
public CannonWorld() {//constructor
setSize(FrameWidth, FrameHeight);
setTitle("Cannon World");
addWindowListener(new CloseQuit());
//add graphical objects and their listeners
JButton fire = new JButton("fire");
fire.addActionListener(new FireButtonListener());
getContentPane().add("North", fire);
slider.addAdjustmentListener(new JScrollBarListener());
getContentPane().add("East", slider);
}
// the following is an inner class for CannonWorld class
private class FireButtonListener implements ActionListener{
public void actionPerformed(ActionEvent evt){
aBall = cannon.fire();
}
}
.
.
Class JScrollBar :
javax.swing.JScrollBar
JScrollBar(int orientation, int value, int extent, int min, int max)
//Creates a scrollbar with the specified orientation, value, extent, minimum, and
maximum.
//orientation can be given one of the following values:
//JScrollBar.VERTICAL, JScrollBar.HORIZONTAL
int getValue()
// Returns the scrollbar's value.
void addAdjustmentListener(AdjustmentListener l)
// Adds an AdjustmentListener
Interface AdjustmentListener: java.awt.event
void adjustmentValueChanged(AdjustmentEvent e)
// Invoked when the value of the adjustable has changed.
Class AdjustmentEvent:
java.awt.event.AdjustmentEven
//in CannonWorld class
private JScrollBar slider = new JScrollBar(JScrollBar.VERTICAL, 45,5,0, 90);
public CannonWorld() {
setSize(FrameWidth, FrameHeight);
setTitle("Cannon World");
addWindowListener(new CloseQuit());
//add graphical objects and their listeners
JButton fire = new JButton("fire");
fire.addActionListener(new FireButtonListener());
getContentPane().add("North", fire);
slider.addAdjustmentListener(new JScrollBarListener());
getContentPane().add("East", slider);
}
// the following is an inner class for CannonWorld class
private class JScrollBarListener implements AdjustmentListener{
public void adjustmentValueChanged(AdjustmentEvent e){
int angle = slider.getValue();
cannon.setAngle(angle);
message = "Angle: " + angle;
repaint();
}
}
CannonGame
import java.awt.*;
import javax.swing.*;
public class CannonGame extends JFrame {
public static void main (String [] args) {
CannonGame world = new
CannonGame(Integer.valueOf(args[0]));
world.show();
while(true){world.run();}
}
public CannonGame (Integer theta) {
setSize(FrameWidth, FrameHeight);
CannonGame
setTitle("Cannon Game");
cannon.setAngle(theta.intValue());
message = "Angle = " + theta;
aBall = cannon.fire();
}
public static final int FrameWidth = 600;
public static final int FrameHeight = 400;
private Cannon cannon = new Cannon(new Point(20,
FrameHeight -10));
CannonGame
private CannonTarget target = new CannonTarget(new
Point(FrameWidth - 100, FrameHeight -12));
private Ball aBall;
private String message;
public void paint (Graphics g) {
super.paint(g);
cannon.paint(g);
target.paint(g);
if(aBall != null) aBall.paint(g);
g.drawString(message, FrameWidth/2,
FrameHeight/2);
}
CannonGame
private void moveCannonBall() {
aBall.move();
if (aBall.location().y > FrameHeight){
if (target.hitTarget(aBall.location().x))
message = "You Hit It!";
else message = "Missed!";
aBall = null;
}
CannonGame
}
public void run(){
if(aBall != null) moveCannonBall();
repaint();
try{ Thread.sleep(50);} catch(Exception e)
{System.exit(0);}
}
}