Easy Learning Java (2 Edition) Java For Beginners Guide Learn Easy and Fast by Yang Hu
Easy Learning Java (2 Edition) Java For Beginners Guide Learn Easy and Fast by Yang Hu
Java
(2 Edition)
YANG HU
Simple is the beginning of wisdom. This book briefly
explain the concept and vividly cultivate
programming interest, this book fast learn Java
object-oriented programming.
http://en.verejava.com
Copyright © 2020 Yang Hu
All rights reserved.
ISBN : 9798634831589
CONTENTS
1. Java JDK Installation
2. Set Java Environment Variables
3. The First Java Program
4. Basic Concepts of Java
4.1 Variable
4.2 Basic Data Types
4.3 Constant
4.4 Type Casting
5. Operator
5.1 Arithmetic Operator
5.2 Method
5.3 Class
5.4 Package
5.5 Increment and Decrement
5.6 Relational Operator
5.7 Logical Operators
6. Statements
6.1 If
6.2 Switch
6.3 While Loop
6.4 Do While Loop
6.5 While Loop Games
6.6 For Loop
6.7 Continue and Break
7. Java Array
7.1 One-Dimensional Array
7.2 Two-Dimensional Array
8. Java Object-Oriented
8.1 Class
8.2 Encapsulation
8.3 Constructor Method
8.4 Method Overload
8.5 Static Keyword
8.6 Inheritance
8.7 Method Override
8.8 Super Keyword
8.9 Polymorphism
8.10 Object Relationship One-to-One
8.11 Abstract Class
8.12 Interface
8.13 Enum
8.14 Internal Class
9. IDE Eclipse Installation
10. String
11. Primitive Types and Wrapper Classes
12. Object
13. Collection
13.1 ArrayList
13.2 LinkedList
13.3 Iterator
13.4 HashSet
13.5 HashMap
13.6 Generic
13.7 Random
14. Exception
15. File IO
15.1 File
15.2 FileInputStream
15.3 FileOutputStream
16. Java Thread
17. Canvas
17.1 Create GUI Window Application
17.2 Create Canvas
17.3 Graphics Draw on Canvas
18. Animation
19. Airplane Game
Java JDK Installation
Java: is an object-oriented programming language that produces software
for multiple platforms. When a programmer writes a Java application, the
compiled code (known as bytecode) runs on most operating systems (OS),
including Windows, Linux and Mac OS.
CLASSPATH= %JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar;.
3. PATH : is used define where the system can find the executables(.exe)
files and classpath is used to specify the location.
PATH= %JAVA_HOME%\bin
Click Ok Button
The following figure indicates that the environment variables are
successfully installed
Click Window Icon and then input cmd click cmd.exe to open command
window
Download Nodepad++.zip
http://en.verejava.com/download.jsp?id=1
Click Ok Button
Notepad++ installation successful
2. The first java program steps:
Type ' javac Hello.java ' and press enter to compile Hello.java to Hello.class
.
4. Type ' java Hello ' to run your program.
You will be able to see the result: I love Java printed on the window.
The java program is executed from top to bottom and from left to right
4. Explain in detail Hello.java
the class definition block for the java application, every application begins
with a class definition.
Hello is class name that the first letter need be capitalized, and the code for
each class appears between the opening and closing curly braces { }
Uses the System class from the core library to print the "I love Java"
message to standard output.
Core library (also known as the "Application Programming Interface", or
"API")
System . out . println ( "I love Java" );
Just remember these concepts first and will discuss them in detail later
Variable
Variable: a memory area allocated by the system to store data.
Open cmd Window type "javac Variable.java" and then type "java
Variable".
You will be able to see the result: Apple printed on the window.
2. The value of the variable can be changed.
Two forward slashes //: Single-line comments can be used to explain Java
code, Any text between // and the end of the line is ignored by Java (will
not be executed).
Open cmd Window type "javac Variable.java" and then type "java
Variable" run again .
3. Variable naming rules:
1.consisting of characters, underscores, $, numbers.
2.The first letter must be a character, _ or $, can not be a number.
3.The first letter needs to be lowercase.
4 . Cannot use a java keyword (reserved word) as a variable name.
Example:
Correct variable naming: name , age , _salary , peopleColor etc
Incorrect variable naming: 1234 , 2_name , a@mail, public, static etc
Open cmd Window type "javac Variable.java" and then type "java
Variable".
Basic Data Types
Java has 8 basic data types ( Also called primitive types ).
byte, short, int, long, float, double, char, boolean
double b1 = 10.1 ;
float b2 = 12.2f ; // add a f or F at the end
Open cmd type "javac DataType.java" and then type "java DataType "
.
3 . Character and Boolean ( char boolean ).
char: is a single character that enclosed in single quote marks, that is a
letter 'a' , a digit '9' , a punctuation mark '!' , a tab ' ' , a space ' ' etc.
Escape Sequences : A character preceded by a backslash (\) is an escape
sequence and has special meaning to the compiler.
\t Insert a tab in the text at this point.
\n Insert a newline in the text at this point.
Insert a single quote character in the text at
\'
this point.
Insert a double quote character in the text at
\"
this point.
Insert a backslash character in the text at
\\
this point.
boolean: boolean data type which can only take the values true or false .
boolean d1 = true ;
boolean d2 = false ;
System . out . println ( d1 );
System . out . println ( d2 );
}
}
Open cmd type "javac DataType.java" and then type "java DataType
".
Constant
Constant: A constant whose value cannot change once it has been
assigned.
1. the definition of a constant need be capitalized.
2. To define a constant, we just need to add the keyword final in front of
the variable.
final float PI = 3.14f ;
the value of PI cannot change once it has been assigned
1. Widening Casting
result = add ( 5 , 3 );
System . out . println ( result ); // result = 8
}
}
result = sub ( 4 , 2 );
System . out . println ( result ); // result = 2
result = multiply ( 4 , 2 );
System . out . println ( result ); // result = 8
result = divide ( 4 , 2 );
System . out . println ( result ); // result = 2
}
}
Open cmd type "javac TestMethod.java" and then type "java
TestMethod " .
Everything in Java is associated with classes and objects , along with its
attributes and methods . an object is created from a class.
We can create the class named Caculator , and then create 4 methods: add,
sub, multiply, divide in Caculator , so now we can use this to new objects.
1. Create a file in Nodepad++ : TestClass.java
Open cmd type "javac TestClass.java" and then type "java TestClass "
.
1. com/tool/ Caculator.java
Open cmd type "javac TestClass.java" and then type "java TestClass "
.
Increment and Decrement
Increment ++: unary operator increases the value of the variable by one.
Decrement --: unary operator decreases the value of the variable by one.
d=4;
System . out . println (++ d ); // = 5 increment 1 and then print d
d=4;
System . out . println ( d --); // = 4 print d and then decrement 1
d=4;
System . out . println (-- d ); // = 3 decrement 1 and then print d
int result = 10 ;
result = result + 1 ;
System . out . println ( result ); // = 11
result = 10 ;
result ++;
System . out . println ( result ); // = 11
result = 10 ;
result += 1 ;
System . out . println ( result ); // = 11
}
}
Open cmd type "javac Unary.java" and then type "java Unary " .
boolean b = true ;
System . out . println ( b ); // = true
System . out . println ( 1 > 2 && b ); // = false
System . out . println ( 2 > 1 && b ); // = true
boolean b1 = true ;
System . out . println ( b1 ); // = true
System . out . println ( 2 > 1 || b1 ); // = true
System . out . println ( 1 > 2 || b1 ); // = true
}
}
Open cmd type "javac Logical2.java" and then type "java Logical2" .
if ( condition1 ) {
// block of code to be executed if condition1 is true
} else if ( condition2 ) {
// block of code to be executed if the condition1 is false and condition2
is true
} else {
// block of code to be executed if the condition1 is false and condition2
is false
}
Score example:
if score == 5 : Excellent
else if score == 4 : Good
else : Need to catch up
1. Create a IfStatement.java
if ( score == 5 ){
System . out . println ( "Excellent" );
} else if ( score == 4 ){
System . out . println ( "Good" );
} else {
System . out . println ( "Need to catch up" );
}
}
}
Open cmd type "javac IfStatement .java" and then type "java
IfStatement " .
Result:
Excellent
if ( score == 5 ){
System . out . println ( "Excellent" );
} else if ( score == 4 ){
System . out . println ( "Good" );
} else {
System . out . println ( "Need to catch up" );
}
}
}
Open cmd type "javac IfStatement .java" and then type "java
IfStatement " .
Switch
switch: switch statement to select one of many code blocks to be executed.
switch ( expression ) {
case a :
// code block
break ;
case b :
// code block
break ;
default :
// code block
}
switch ( score ) {
case 5 :
System . out . println ( "Excellent" );
break ;
case 4 :
System . out . println ( "Good" );
break ;
default :
System . out . println ( "Need to catch up" );
}
Create SwitchStatement.java
Open cmd type "javac SwitchStatement .java" and then type "java
SwitchStatement " .
While Loop
while loop: loops through a block of code as long as a specified condition
is true
while ( condition ) {
// code block to be executed
}
do {
// code block to be executed
}
while ( condition );
Open cmd type "javac DoWhile.java" and then type "java DoWhile "
.
While Loop Games
Statement 1 is executed one time before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed every time after the code block has been executed.
Open cmd type "javac ForLoop.java" and then type "java ForLoop "
.
Result: 0 , 1 , 2 ,
For Loop Print Ball
Open cmd type "javac PrintBall.java" and then type "java PrintBall "
.
Result:
********
********
********
********
********
********
********
********
Continue and Break
break: can be used to jump out of a loop.
continue: breaks one iteration and continues with the next iteration in the
loop.
1. Create BreakLoop.java
when i==1 jumps out of the loop:
Result:
0
2. Create ContinueLoop.java
when i==1 breaks current iteration and continues with the next iteration.:
To declare an array, define the variable type with square brackets, create an
array of integers
int [] scores ;
scores. length: how many elements an array has, use the length property
Result:
90,70,50,80,60,85,
Two-Dimensional Array
Two-Dimensional array: is an array containing one or more arrays.
To create a two-dimensional array, add each array within its own set of
curly braces:
Result:
10 20 30
40 50 60
70 80 90
Class
class: is a user defined blueprint or prototype from which objects are
created.
Everything in Java is associated with classes and objects , along with its
attributes and methods . an object is created from a class.
We can create the class named Person , There are two attributes in the
Person: name, age and then create a method: say() in Person , so now we
can use this to new objects.
// Define a Person class, There are two attributes: name , age and a
method: say()
class Person {
String name ;
int age ;
To achieve Encapsulation:
Declare the variables of a class as private.
Provide public setter and getter methods to set and get the values of
variables.
Example:
Declare the name and age as private in Person class
Provide public setName(String name) and String getName() to set and
get the values of name .
Provide public setAge(String age) and String getAge() to set and get the
values of age .
Note:
1. The variables defined in the class are called member variables.
2. The variables defined in the method are called local variables.
class Person {
// Declare the name and age as private
private String name ;
private int age ;
The constructor name must match the class name, and it cannot have a
return type. All classes have constructors by default: if you do not create a
class constructor yourself, Java creates one for you.
Example:
Define a Person class
Create a constructor method without parameter: Person()
Create a constructor method with two parameter: Person(String name, int
age)
1. Create file: TestConstructor.java
class Person {
private String name ;
private int age ;
public Person () {
System . out . println ( "constructor method without parameter is
called" );
}
Example:
Define a Caculator class
Define an add method: int add( int a, int b)
Define anther add method with the same name but different parameter
types:
double add( double a, double b)
1. Create a file: TestOverLoad.java
class Caculator {
Result:
30
31.0
Static Keyword
static : if static variable is created which is shared across all objects of the
class. This means all objects share the same variable.
Example 1:
Create User class contain no static member variable: count
Create 2 objects user1 and user2 and then user1.count++ ,
user2.count++
class User {
public int count ;
}
Example 2:
Create User class contain static member variable: count
Create 2 objects user1 and user2 and then user1.count++ ,
user2.count++
class User {
public static int count ;
}
Example 1: 2 users have their own variable count
Example 2: 2 users share the same static variable count
1. Create a file: TestNoStatic.java
class User {
public int count ;
}
class User {
public static int count ;
Result:
User Count : 2
User Count : 2
Inheritance
Inheritance: is a mechanism in which one object acquires all the attributes
and method of a parent object.
Example:
Student inherit the Person
Step:
1.Class: Student, Person
2. Relationship: Student extends Person
3. Attributes: Person attributes ( name , age )
4. Methods: Person actions ( say )
Note:
1. The subclass cannot access the private attribute,method of the parent
class
2. The subclass can access the protected , public attribute,method of the
parent class.
1. Create a file: TestInheritence.java
Result:
Person can speaking
2. The calling sequence of the constructor method in the inheritance
relationship
class Person {
public Person () {
System . out . println ( "Parent class Person is created" );
}
public Student () {
System . out . println ( "Child class Student is created" );
}
}
Result:
Parent class Person is created
Child class Student is created
Person can speaking
Method Override
Override:
the child class overwrites the method of the parent class, the instance of the
child class will call the method of child class, not call the method of the
parent class.
Example:
1. Create a parent class: Person , there is a method: say()
2. Create a child class: ChineseStudent , there is the same method: say()
3. Create a child class: AmericaStudent , there is the same method: say()
class Person {
Result:
Speak Chinese
Speak English
Super Keyword
super: can be used to refer parent class instance variable.
Example:
1. Create a parent class: Person , there is a method: say()
3. Create a child class: AmericaStudent , there is the same method: say()
AmericaStudent say() will override Person say(), the instance of the child
class will call the method: say() of child class, not call the method: say() of
the parent class. If you want to call the method: say() of the parent class.
You need call like: super.say().
class Person {
public void say () {
System . out . println ( "Person speaking" );
}
}
Example:
1. Create a parent class: Person , there is a method: say()
2. Create a child class: Student , there is the same method: say() override
Person say()
there is anther method: study()
class Person {
public void say () {
System . out . println ( "Person speaking" );
}
}
Result:
Student speak english
Student speak english
Student study
Object Relationship One-to-One
1. Example:
Baby can eat one fruit
Analysis:
1. Class: Baby , Fruit
2. Relationship: Fruit One-to-One belong to Baby
3. Attributes: Baby (fruit)
4. Methods: Baby eat(Fruit fruit)
class Fruit {
private String name ;
class Baby {
private Fruit fruit ; // Fruit belong to Baby
Result:
Baby eat Red Apple
Baby eat Black Grape
Abstract Class
abstract class: is a class that is declared abstract . Abstract classes cannot
be instantiated, but Its child class can be instantiated.
Example:
Father told his son to buy some fruit
Analysis:
1. Abstract class: Father
2. Implementation class: Son
3. Relationship: Son inherits Dad
4. Method: buy() the father told his son to buy fruit, but father not to buy
The son fulfills his father to buy fruit, this means method: buy() have an
implementation
//father called his son to buy fruit, but father not buy
public abstract void buy ( String fruit );
}
f . buy ( "Apples" );
}
}
Result:
Example:
Father is working now, so told his son to buy some fruit
Analysis
1. Method: Father have two method: work() and abstract buy()
Result:
Father is working now.
Dad, Dad, I bought some : Apples
Interface
interface: is a different way to achieve abstraction that is used to group
related methods with empty body, the child class must be implemented the
interface and its empty method.
Example:
The boss hires employees to work
Analysis:
1. interface: Boss
2. Implementation class: Employee
3. Relationship: Employee implements Boss
4. Method: work() the boss hires employees to work, boss not to do this
work.
interface Boss {
public void work ();
}
interface Boss {
Result:
Notes:
1. The implementation of the method is not allowed in the interface.
2. The methods are all public by default in the interface.
3. The attributes are public static in the interface.
4. The child class must implement all the declaration methods in the
interface.
2. Child classe can only inherit one class , but can implement multiple
interfaces.
Example:
The boss hires employees to work, and then managers let employees
learn business.
Analysis:
1. interface: Boss, Manager
2. Implementation class: Employee
3. Relationship: Employee implements Boss, Manager
4. Method: work() the boss hires employees to work, boss not to do this
work.
learn() the manager let employees to learn, manager not to
learn.
Create a file: TestInterface.java
interface Boss {
//boss hires employees to work, boss not to do this work.
public void work ();
}
interface Manager {
//the manager let employees to learn, manager not to learn.
public void learn ();
}
}
}
Result:
Employee start to work
Employee start to learn business
Enum
enum: is a special data type that enables for a variable to be a set of
predefined constants. The variable must be equal to one of the values that
have been predefined for it.
Example:
Draw circles of different color
Analysis:
1. enum: Color ( RED , GREEN, BLUE )
2. class: Circle
3. Method: draw() draw circles of different color.
enum Color {
RED , GREEN , BLUE
}
1. Create a file: TestEnum.java
class Circle {
//draw circles of different color.
public void draw ( Color color ) {
String colorName = "" ;
if ( color == Color . RED ) {
colorName = "Red" ;
} else if ( color == Color . GREEN ) {
colorName = "Green" ;
} else if ( color == Color . BLUE ) {
colorName = "Blue" ;
}
System . out . println ( "draw " + colorName + " circle" );
}
}
Result:
draw Red circle
draw Green circle
draw Blue circle
Internal Class
Inner classe: are a security mechanism. if we have the class as a member of
other class, then the inner class can be made private.
Example:
Mother pregnanted, Baby eat food from the mother
Analysis:
1. Class: Mother , Baby
2. Relationship: Baby in Mother
3. Method: Mother eat(food) , Baby eat() from Mother
First define the Mother class, then define the Baby class inside the
Mother class
class Mother {
public void eat ( String food ) {
class Baby {
public void eat () {
}
}
}
1. Create a file: TestInnerClass.java
class Mother {
private String food ;
Result:
Mother eat Apple
Baby absorb nutrients from the mother's Apple
IDE Eclipse Installation
Now it’s the right time to move on to using the IDE( Eclipse ), because
you have learned basic knowledge and experience in Java.
https://www.eclipse.org/downloads/
or
http://en.verejava.com/download.jsp?id=1
2. Double click eclipse.exe to Open
3. Double click eclipse.exe to Open
Workspace: contains resources such as: Projects, Files, Folders etc. The
workspace has a hierarchical structure. Projects are at the top level of the
hierarchy and inside them you can have files and folders.
Click OK Button
4. Create a new Java Project Click File -> New -> Project
5. Select Java Project and then click Next button
6. Enter the Project name: test and then click Finish button
7. Project: test has a hierarchical structure.
1. String Comparison
equals() method and the == operator is used to compare two String.
str1 and str2 point to the same "hello" object in the string pool, so equals()
and == is true
Replace all || to ,
Result: David,30,Male,Married
Result: true
Result: true
5. int indexOf( char ch):
find the first index of the ch in string from left to right. The index of the
string starts at 0
Result: 2
Result: 8
7. String trim():
Remove whitespace from both sides of a string.
Result: .mp4
Result: .video
10. String [] split( String regex):
Split a string into an array with regex
Result:
Language=100
Math =98
Physics=95
11. toLowerCase():
Converts all of the characters to lower case
12. toUpperCase():
Converts all of the characters to upper case
Notes:
StringBuilder offer an advantage and better performance. if you need to
concatenate a large number of strings, appending to a StringBuilder is more
efficient .
Primitive Types and Wrapper Classes
Wrapper class: is a class whose object wraps or contains primitive data
types. When we create an object to a wrapper class, we can store primitive
data types. we can wrap a primitive value into a wrapper class object.
Result: 20
Result:
20
1000.5
Result:
20
1000.5
Object
Object: is the root of the class hierarchy. Every class has Object as a parent
class. So all objects are the children of Object.
class Cat {
private String name ;
Result:
test.Cat@1f1fba0
2. Create a class: Cat
we define toString() method in Cat, our Overridden toString() method will
be calle d
Create test file: TestObject.java
class Cat {
private String name ;
1. add(Object o):
add an element at the end of the list
Result:
100
David
2. int size():
return the number of elements in the list.
Result:
100,David,25.5,
List Result:
100,Grace,
void clear():
remove all of the elements from list.
list.clear();
System. out .println(list.isEmpty()); // true
}
6. List add custom objects: Person
import java.util.*;
class Person {
private String name ;
private int age ;
Result:
name = David , age = 20
name = Joseph , age = 30
name = Grace , age = 40
LinkedList
LinkedList: is a collection which can contain many objects of the same
type, just like the ArrayList. The LinkedList class has all of the same
methods as the ArrayList class because they both implement the List
interface.
the different is ArrayList class has a regular array inside it. The LinkedList
has a link to the first container and each container has a link to the next and
has a link to the prev in the list.
addLast(Object o):
Add an item to the end of the list.
list.addFirst( "Grace" );
list.addLast( "Renia" );
Result:
Grace
David
Joseph
Renia
2. Object getFirst():
Get the item at the beginning of the list
Object getLast():
Get the item at the end of the list
Result:
First: Grace
Last: Joseph
3. Object removeFirst():
Remove an item from the beginning of the list.
removeLast():
Remove an item from the end of the list
list.removeFirst();
list.removeLast();
Result:
David
Iterator
Iterator: is an interface which belongs to collection framework. It allows
us to traverse the collection, access the data element.
1. boolean hasNext():
It returns true if Iterator has more element to iterate.
Object next():
It returns the next element in the collection until the hasNext()method
return true.
Result:
Washington , James , Abraham ,
HashMap
HashMap: is a Map based collection class that is used for storing Key =
value pairs, it does not return the keys and values in the same order.
1. put(Object key, Object value):
Inserts key value mapping into the map.
2. Set keySet():
It returns the Set of the keys fetched from the map.
Result:
married=false
age=20
name=David
salary=12000
Generic
Generic: methods and generic classes enable programmers to specify, with
a single method declaration, or with a single class declaration, , or with
types declaration. Generics also provide compile-time type safety that
allows you to catch invalid types at compile time.
public T getAge() {
return age ;
}
Result:
30
80
2. Use a generic for List: ArrayList<String>
Result:
Faith
Danie
Mathew
import java.util.*;
class Customer {
private String name ;
private int age ;
Result:
Grace , 25
Renia , 30
Rebeka , 28
Random
Random: is used to generate random numbers. Random class in java.util
package.
rn.nextInt(n):
returns a random number between 0 and n-1.
import java.util.Random;
Result:
9, 3, 9, 0, 4, 1, 0, 3, 4, 5,
import java.util.Random;
Result:
0,3,4,5,7,8,
try {
//Statements that may cause an exception
} catch (Exception e) {
//Handling exception
}
1. If a/b , and b = 0 , will throw an exception: ArithmeticException .
Result:
Divisor cannot be 0
If a/b , and b != 0
Result:
2
finally
If a/b , and b = 0
Result:
Divisor cannot be 0
Finally
mkdirs():
Creates the directory named by pathname.
import java.io.*;
Result:
2. String getAbsolutePath():
Returns the absolute form of this pathname.
Result: java
4. boolean exists():
Tests whether the file or directory exists.
Result: true
5. boolean isDirectory():
Tests whether is a directory.
Result: true
Result:
7. boolean createNewFile():
Creates a new, empty file only if a file with this name does not yet exist.
Result:
8. String getAbsolutePath():
Returns the absolute form of this pathname.
Result: c:\java_new\test.txt
9. String getName():
Returns the name of the file.
Result: test.txt
10. boolean exists():
Tests whether the file or directory exists.
Result: true
Result: true
Result: true
FileInputStream
FileInputStream: obtains input bytes from a file. It is used for reading
byte-oriented data such as image data, audio, video etc.
import java.io.*;
Result:
every
2 . if you want to read all data from file: C:/java/english.txt
Need to repeatly read 5 bytes of data append to StringBuilder until the
end of the file return -1 .
Result:
every day is good day
FileOutputStream
FileOutputStream: is an output stream used for writing data to a file.
import java.io.*;
try {
os = new FileOutputStream( new File( "c:/java/test.txt" ));
//directory must exist
String content = "good morning" ;
byte [] data = content.getBytes(); //convert String to byte[]
os.write(data); // write data to file
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
os.close(); //Close the output stream
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Java Thread
Thread: is a single sequential flow of control within a program.
the CPU allocates to each thread for a period of time to execute.
Output Result:
import javax.swing.*;
public class AirplaneGame {
public static void main(String[] args) {
JFrame frame = new JFrame( "Java GUI Application" );
frame.setSize(300,300);
frame.setVisible( true );
}
}
There are several ways to create graphics in Java; we can create Canvas
inherit from JPanel, A Canvas is a blank rectangular area of the screen onto
which the application can draw.
1. Create a Canvas inherit from JPanel and then add this canvas to the
center of JFrame.
1. Create a file : AirplaneGame.java in Eclipse
this.setLayout(null): must set layout null
this.setBackground(Color c): set the background color in a JPanel
import javax.swing.*;
import java.awt.*;
When we want to draw our own graphics on the screen, we should put our
graphics code inside the paintComponent() method in JPanel . The system
calls it directly. So our Canvas need to override this paintComponent()
method to perform our graphics code.
public Canvas(){
this .setLayout( null );
this .setBackground(Color. WHITE );
}
g.drawLine(x1, y1, x2, y2): takes four integers values that represent the
start (x1, y1) and end (x2, y2) coordinate of the line.
import javax.swing.*;
import java.awt.*;
import java.awt.*;
import javax.swing.*;
class Canvas extends JPanel{
public Canvas(){
this .setLayout( null );
this .setBackground(Color. WHITE );
}
import java.awt.*;
import javax.swing.*;
http://en.verejava.com/download.jsp?id=1
Project test/images
draw images/blue_plane.png on canvas.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
Analysis:
1. Class: EnemyPlane , Canvas
2. Relationship:
2.1 Enemy plane draw on the top of Canvas: This means
EnemyPlane belong to Canvas
3. Attributes:
3.1 Enemy plane load image : this mean EnemyPlane has image and
the width and height of image attribute.
3.2 Enemy plane draw on Canvas: this mean Sprite has x,y
coordinates.
4. Methods:
4.1 Enemy plane need load image : we can create a class ImageUtil
and a method BufferedImage loadImage(String imagePath) to load image,
we can create a constructor method EnemyPlane(int x, int y, String
imagePath) pass the imagePath and then call the loadImage(String
imagePath) to load image .
public Canvas() {
enemyPlane = new EnemyPlane(100, 0, "images/enemy.png" );
}
ImageUtil.java
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
}
Create a class: EnemyPlane.java
EnemyPlane.java
import java.awt.Graphics;
import java.awt.image.BufferedImage;
public Canvas() {
this .setLayout( null );
this .setBackground(Color. WHITE );
this .requestFocus();
enemyPlane = new EnemyPlane(100, 0, "images/enemy.png" );
canvasThread = new CanvasThread();
canvasThread .start(); // start thread the run() method call
automatically
}
AirplaneGame.java
import java.awt.*;
import javax.swing.*;
Result:
Airplane Game
In this chapter i will demonstrate how to make a basic 2D game in Java
by writing a basic Airplane game.
Step:
1 . Create blue plane and then draw on the center of the bottom of the
screen.
2 . Press up, down, left, and right keys to move the blue plane
3 . Press enter key to fire a bullet from the top center of the blue plane and
move up
4 . If the bullet flies out of the top of the screen and the bullet disappears,
press enter key can relaunch
5 . Enemy plane appear randomly from the top of the screen and move
down
6 . If the enemy’s plane flies out of the bottom of the screen, the enemy’s
plane disappears and reappears randomly from the top of the screen.
7 . If the bullet hits the enemy’s plane, the enemy plane explode and
disappear
Analysis:
1. Class : BluePlane , EnemyPlane , Bullet , Canvas
2. Relationship: In the game BluePlane, EnemyPlane, and Bullet are
called Sprite
Because they have the same attributes and methods, We can define Sprite as
an abstract class , BluePlane , EnemyPlane , and Bullet inherit the attribute
and methods from Sprite. All the Sprite will draw and move on Canvas .
3. Attributes:
3.1 All the Sprite will draw on Canvas . So Sprite has x,y coordinates,
image and the width and height of image.
3.2 Sprite will appear randomly and may disappear, so it has visible
attribute. BluePlane, EnemyPlane, and Bullet inherit these attributes
3.3 Canvas also have the width and height, we can define:
canvasWidth and canvasHeight .
4. Methods:
4.1 Sprite need load image : we can create a class ImageUtil and a
method BufferedImage loadImage(String imagePath) to load image, we can
create a constructor method Sprite(int x, int y, String imagePath) pass the
imagePath and then call the loadImage(String imagePath) to load image .
4.2 Sprite draw on Canvas: we can create a method draw(Graphics
g).
4.3 Sprite moves: we can create a method move(int distanceX, int
distanceY) distanceX, int distanceY indicates the distance moved in the X
and Y axis .
4.4 the bullet hits the enemy’s plane: we can create a method
collideWith(Sprite sprite).
4.5 The attribute x, y, width, height, visible has its own public getter
and setter methods
bullet collided with the enemy plane
The absolute value of the difference between the center coordinates of the
two pictures is less than the sum of half of their width and height, we think
they have an intersection and they are collided
public Canvas() {
this .setLayout( null );
this .setBackground(Color. WHITE );
this .requestFocus();
bluePlane .draw(g);
bullet .draw(g);
enemyPlane .draw(g);
}
4.7 Press up, down, left, and right keys to move the blue plane: We
want to add mouse and key listeners to a Canvas: this.addKeyListener(new
KeyAdapter()) . When we press any keys the method keyPressed(KeyEvent
e) will called automatically.
4.10 If the bullet flies out of the top of the screen and the bullet
disappears
Set visible=false : .
4.11 Enemy’s plane appear randomly from the top of the screen
and move down:
4.12 When the enemyplane move out of the canvas, the enemy
plane need be destroyed set visible = false :
4.13 If the bullet hits the enemy plane, bullet and enemy plane
explode and disappear:
4.14 Sprite moves on Canvas: We need define a inner class
CanvasThread inherit from Thead in Canvas, there is a run() method. we
can define " while (true) " where we repeatedly call draw(Graphics g) and
move(int distanceX, int distanceY) to change the position of the enemy
plane and then we call repaint() , which forces to call the
paintComponent(Graphics g) method to paint again the canvas.
The final class diagram:
Create a Java Project: test, and then create a class: ImageUtil
ImageUtil.java
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
Sprite.java
import java.awt.Graphics;
import java.awt.image.BufferedImage;
public abstract class Sprite{
protected int x ;
protected int y ;
protected int width ;
protected int height ;
protected BufferedImage image ;
protected boolean visible ;
BluePlane.java
Bullet.java
}
Create a class: Canvas.java
Canvas.java
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import javax.imageio.ImageIO;
import javax.swing.*;
bluePlane .draw(g);
bullet .draw(g);
enemyPlane .draw(g);
bulletMove();
enemyPlaneMove();
collide();
}
}
Create a class: AirplaneGame.java
AirplaneGame.java
import java.awt.*;
import javax.swing.*;
Result:
Thanks for learning
https://www.amazon.com/dp/B086SPBJ87
https://www.amazon.com/dp/B08BWT6RCT
If you enjoyed this book and found some benefit in reading this, I’d like to
hear from you and hope that you could take some time to post a review on
Amazon. Your feedback and support will help us to greatly improve in
future and make this book even better.
http://www.amazon.com/review/create-review?&asin=B086PN1CJ6
Different country reviews only need to modify the amazon domain
name in the link:
www.amazon.co.uk
www.amazon.de
www.amazon.fr
www.amazon.es
www.amazon.it
www.amazon.ca
www.amazon.nl
www.amazon.in
www.amazon.co.jp
www.amazon.com.br
www.amazon.com.mx
www.amazon.com.au