├── Chapter 1
├── Example 1
│ ├── .classpath
│ ├── .project
│ ├── .settings
│ │ └── org.eclipse.jdt.core.prefs
│ └── src
│ │ ├── MainPackage
│ │ └── MainClass.java
│ │ └── OtherPackage
│ │ └── OtherClass.java
├── Listing 1.0.java
├── Listing 1.1.java
└── Listing 1.2.java
├── Chapter 2
├── Listing 2.0.java
├── Listing 2.1.java
├── Listing 2.2.java
├── Listing 2.3.java
├── Listing 2.4.java
├── Listing 2.5.java
├── Listing 2.6.java
├── Listing 2.7.java
├── Listing 2.8.java
└── Listing 2.9.java
├── Chapter 3
├── Listing 3.0.java
├── Listing 3.1.java
├── Listing 3.10.java
├── Listing 3.11.java
├── Listing 3.12.java
├── Listing 3.2.java
├── Listing 3.3.java
├── Listing 3.4.java
├── Listing 3.5.java
├── Listing 3.6.java
├── Listing 3.7.java
├── Listing 3.8.java
└── Listing 3.9.java
├── Chapter 4
├── Listing 4.0.java
├── Listing 4.1.java
├── Listing 4.2.java
├── Listing 4.3.java
└── Listing 4.4.java
├── Chapter 5
├── Listing 5.0.java
├── Listing 5.1.java
├── Listing 5.2.java
├── Listing 5.3.java
├── Listing 5.4.java
├── Listing 5.5.java
├── Listing 5.6.java
└── Listing 5.7.java
├── Chapter 6
├── Listing 6.0.java
├── Listing 6.1.java
├── Listing 6.2.java
├── Listing 6.3.java
├── Listing 6.4.java
└── Listing 6.5.java
├── Chapter 7
├── CalculatorApp
│ ├── .classpath
│ ├── .project
│ ├── .settings
│ │ └── org.eclipse.jdt.core.prefs
│ ├── miglayout-src.zip
│ ├── miglayout15-swing.jar
│ └── src
│ │ └── calculatorApp
│ │ └── MainWindow.java
├── Listing 7.0.java
├── Listing 7.1.java
├── Listing 7.10.java
├── Listing 7.2.java
├── Listing 7.3.java
├── Listing 7.4.java
├── Listing 7.5.java
├── Listing 7.6.java
├── Listing 7.7.java
├── Listing 7.8.java
└── Listing 7.9.java
├── Chapter 8
├── Listing 8.0.java
├── Listing 8.1.java
├── Listing 8.10.java
├── Listing 8.11.java
├── Listing 8.12.java
├── Listing 8.13.java
├── Listing 8.14.java
├── Listing 8.15.java
├── Listing 8.16.java
├── Listing 8.17.java
├── Listing 8.18.java
├── Listing 8.19.java
├── Listing 8.2.java
├── Listing 8.20.java
├── Listing 8.21.java
├── Listing 8.22.java
├── Listing 8.23.java
├── Listing 8.24.java
├── Listing 8.25.java
├── Listing 8.26.java
├── Listing 8.27.java
├── Listing 8.28.java
├── Listing 8.29.java
├── Listing 8.3.java
├── Listing 8.4.java
├── Listing 8.5.java
├── Listing 8.6.java
├── Listing 8.7.java
├── Listing 8.8.java
├── Listing 8.9.java
└── SpaceRacer
│ ├── .classpath
│ ├── .project
│ ├── .settings
│ └── org.eclipse.jdt.core.prefs
│ ├── graphics
│ └── spaceracer.png
│ └── src
│ ├── Animation.java
│ ├── Baddie.java
│ ├── Bullet.java
│ ├── Engine2D.java
│ ├── GameObject.java
│ ├── HPTimer.java
│ ├── Keyboard.java
│ ├── MainClass.java
│ ├── Player.java
│ ├── SpriteSheet.java
│ ├── Star.java
│ └── Wall.java
├── README.md
└── cover.png
/Chapter 1/Example 1/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/Chapter 1/Example 1/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | Example 1 Packages
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Chapter 1/Example 1/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.8
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.source=1.8
12 |
--------------------------------------------------------------------------------
/Chapter 1/Example 1/src/MainPackage/MainClass.java:
--------------------------------------------------------------------------------
1 | package MainPackage;
2 |
3 | // import OtherPackage.*;
4 | import OtherPackage.OtherClass;
5 |
6 | public class MainClass {
7 | public static void main(String[] args) {
8 | OtherClass o = new OtherClass();
9 | o.SayHello();
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/Chapter 1/Example 1/src/OtherPackage/OtherClass.java:
--------------------------------------------------------------------------------
1 | package OtherPackage;
2 |
3 | public class OtherClass {
4 | public void SayHello() {
5 | System.out.println("Nope, can't be bothered, say it yourself!");
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/Chapter 1/Listing 1.0.java:
--------------------------------------------------------------------------------
1 | package MainPackage;
2 |
3 | public class MainClass {
4 | public static void main(String[] args) {
5 | System.out.println("This class belongs to the MainPackage package!");
6 | }
7 | }
--------------------------------------------------------------------------------
/Chapter 1/Listing 1.1.java:
--------------------------------------------------------------------------------
1 | package OtherPackage;
2 |
3 | public class OtherClass {
4 | public void SayHello() {
5 | System.out.println("Nope, can't be bothered, say it yourself!");
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/Chapter 1/Listing 1.2.java:
--------------------------------------------------------------------------------
1 | package MainPackage;
2 |
3 | // import OtherPackage.*;
4 | import OtherPackage.OtherClass;
5 |
6 | public class MainClass {
7 | public static void main(String[] args) {
8 | OtherClass o = new OtherClass();
9 | o.SayHello();
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/Chapter 2/Listing 2.0.java:
--------------------------------------------------------------------------------
1 | import java.io.File;
2 | import java.io.FileNotFoundException;
3 | import java.io.PrintWriter;
4 |
5 | public class MainClass {
6 | public static void main(String[] args) throws FileNotFoundException {
7 |
8 | // Create a file:
9 | File myFile = new File("Example.txt");
10 |
11 | // Create a writer using the file
12 | PrintWriter writer = new PrintWriter(myFile);
13 |
14 | // Write a line of text to the file
15 | writer.println("This is some example text!");
16 |
17 | // Close the writer
18 | writer.close();
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Chapter 2/Listing 2.1.java:
--------------------------------------------------------------------------------
1 | import java.io.File;
2 | import java.io.FileNotFoundException;
3 | import java.io.PrintWriter;
4 |
5 | public class MainClass {
6 | public static void main(String[] args) {
7 |
8 | // Create a file:
9 | File myFile = new File("Example.txt");
10 |
11 | // Surround all file manipulation with try/catch
12 | try {
13 | // Create a writer using the file
14 | PrintWriter writer = new PrintWriter(myFile);
15 |
16 | // Write a line of text to the file
17 | writer.println("This is some example text!");
18 |
19 | // Close the writer
20 | writer.close();
21 |
22 | }
23 | catch (FileNotFoundException e) {
24 | // File could not be opened, show an error message:
25 | System.out.println("The file could not be opened.");
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Chapter 2/Listing 2.2.java:
--------------------------------------------------------------------------------
1 | import java.io.FileWriter;
2 | import java.io.IOException;
3 | import java.io.PrintWriter;
4 |
5 | public class MainClass {
6 | public static void main(String[] args) {
7 | try {
8 | // Create a file writer with the "append" parameter as "true":
9 | FileWriter file = new FileWriter("Example.txt", true);
10 |
11 | // Create a writer object from the file:
12 | PrintWriter writer = new PrintWriter(file);
13 |
14 | // Write some new text:
15 | writer.println("This text will be added to the end!");
16 |
17 | // Close the writer:
18 | writer.close();
19 | }
20 | catch (IOException e) {
21 | e.printStackTrace();
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Chapter 2/Listing 2.3.java:
--------------------------------------------------------------------------------
1 | import java.io.File;
2 | import java.io.FileNotFoundException;
3 | import java.io.PrintWriter;
4 |
5 | public class MainClass {
6 | public static void main(String[] args) {
7 | File file = new File("test.txt");
8 | try {
9 | PrintWriter out = new PrintWriter(file);
10 | // Writing Text
11 | out.println("Be good. If you can't be good, be lucky!\n\t~ Alan Davis");
12 |
13 | // Characters/floats/Boolean/doubles are all written in
14 | // human readable form:
15 | out.println( 129 ); // Integers
16 | out.println( 2.7183f ); // Floats
17 | out.println( true ); // Boolean
18 | out.println( 1.618034 ); // Double
19 | // Close writers after using them so they can be opened by
20 | // other programs:
21 | out.close();
22 | }
23 | catch (FileNotFoundException e) {
24 | System.out.println("File not found: " + e.getMessage());
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Chapter 2/Listing 2.4.java:
--------------------------------------------------------------------------------
1 | // \n causes a new line:
2 | System.out.print("First line\nSecondline!");
3 |
4 | // \t inserts a tab, i.e. a small block of whitespace
5 | System.out.print("This will be separated from\tThis with a tab!");
6 |
7 | // Use \" to write " and \' to write '
8 | System.out.print("Then Jenny said, \"It\'s above the fridge\".");
9 |
10 | // To print a slash
11 | System.out.print("\\ wears a top hat!");
12 |
13 |
14 | // Some systems require \r\n in order to use a new line.
15 | // Other systems will read this as two new lines, i.e. one
16 | // carriage return and one new line, both of which look the same.
17 | System.out.print("New\r\nLine!");
18 |
--------------------------------------------------------------------------------
/Chapter 2/Listing 2.5.java:
--------------------------------------------------------------------------------
1 | import java.io.File;
2 | import java.io.FileNotFoundException;
3 | import java.util.Scanner;
4 |
5 | public class MainClass {
6 | public static void main(String[] args) {
7 | File file = new File("test.txt");
8 |
9 | try {
10 | // Create a scanner from our file:
11 | Scanner in = new Scanner(file);
12 |
13 | // Read the first two lines into a string:
14 | String s = in.nextLine() + in.nextLine();
15 |
16 | // Reading variables:
17 | int i = in.nextInt();
18 | float f = in.nextFloat();
19 | boolean b = in.nextBoolean();
20 | double d = in.nextDouble();
21 |
22 | // Close the scanner:
23 | in.close();
24 |
25 | // Print out the results:
26 | System.out.println(
27 | "String: " + s + "\n" +
28 | "int: " + i + "\n" +
29 | "float: " + f + "\n" +
30 | "boolean: " + b + "\n" +
31 | "double: " + d );
32 | }
33 | catch (FileNotFoundException e) {
34 | e.printStackTrace();
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Chapter 2/Listing 2.6.java:
--------------------------------------------------------------------------------
1 | import java.io.Serializable;
2 |
3 | public class Animal implements Serializable {
4 | // Member variables
5 | float height;
6 | String name;
7 | boolean extinct;
8 |
9 | // Constructor
10 | public Animal(String name, float height, boolean extinct) {
11 | this.name = name;
12 | this.height = height;
13 | this.extinct = extinct;
14 | }
15 |
16 | // Output method
17 | public void print() {
18 | System.out.println("Name: " + name + "\n" +
19 | "Height: " + height + "\n" +
20 | "Extinct: " + extinct + "\n");
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Chapter 2/Listing 2.7.java:
--------------------------------------------------------------------------------
1 | import java.io.File;
2 | import java.io.FileNotFoundException;
3 | import java.io.FileOutputStream;
4 | import java.io.IOException;
5 | import java.io.ObjectOutputStream;
6 | import java.io.Serializable;
7 |
8 | public class MainClass implements Serializable {
9 | public static void main(String[] args) throws FileNotFoundException, IOException {
10 |
11 | // Create some animals from our Serializable class:
12 | Animal stego = new Animal("Stegosaurus", 12.5f, true);
13 | Animal croc = new Animal("Crocodile", 3.2f, false);
14 | Animal mozzie = new Animal("Mosquito", 0.2f, false);
15 |
16 | // Output to the console:
17 | stego.print();
18 | croc.print();
19 | mozzie.print();
20 |
21 | // Specify the name of our file:
22 | File file = new File("animals.dat");
23 |
24 | // Create a FileOutputStream for writing to the file
25 | FileOutputStream fileOutput = new FileOutputStream(file);
26 |
27 | // Create object output stream to write serialized objects
28 | // to the file stream:
29 | ObjectOutputStream objectOutput = new ObjectOutputStream(fileOutput);
30 |
31 | // Write our objects to the stream:
32 | objectOutput.writeObject(stego);
33 | objectOutput.writeObject(croc);
34 | objectOutput.writeObject(mozzie);
35 |
36 | // Close the streams:
37 | objectOutput.close();
38 | fileOutput.close();
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Chapter 2/Listing 2.8.java:
--------------------------------------------------------------------------------
1 | import java.io.File;
2 | import java.io.FileInputStream;
3 | import java.io.FileNotFoundException;
4 | import java.io.IOException;
5 | import java.io.ObjectInputStream;
6 | import java.io.Serializable;
7 |
8 | public class MainClass implements Serializable {
9 | public static void main(String[] args) throws FileNotFoundException, IOException {
10 |
11 | // Specify the name of our file:
12 | File file = new File("animals.dat");
13 |
14 | // Declare an array to hold the animals we read:
15 | Animal[] animals = new Animal[3];
16 |
17 | // Create a file and an object input stream:
18 | FileInputStream fileInput = new FileInputStream(file);
19 | ObjectInputStream objectInput = new ObjectInputStream(fileInput);
20 |
21 | // Read the objects from the file:
22 | try {
23 | animals[0] = (Animal) objectInput.readObject();
24 | animals[1] = (Animal) objectInput.readObject();
25 | animals[2] = (Animal) objectInput.readObject();
26 |
27 | // Close the streams:
28 | objectInput.close();
29 | fileInput.close();
30 | }
31 | catch (ClassNotFoundException e) {
32 | e.printStackTrace();
33 | }
34 | // Print the objects:
35 | System.out.println("Objects read from file: ");
36 | for(int i = 0; i < 3; i++) {
37 | animals[i].print();
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Chapter 2/Listing 2.9.java:
--------------------------------------------------------------------------------
1 | import java.io.EOFException;
2 | import java.io.File;
3 | import java.io.FileInputStream;
4 | import java.io.FileNotFoundException;
5 | import java.io.FileOutputStream;
6 | import java.io.IOException;
7 | import java.io.ObjectInputStream;
8 | import java.io.ObjectOutputStream;
9 | import java.io.Serializable;
10 | import java.util.ArrayList;
11 |
12 | public class MainClass implements Serializable {
13 | public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
14 | // Specify the name of our file:
15 | File file = new File("animals.dat");
16 |
17 | // Declare an array to hold the animals we read:
18 | ArrayList animals = new ArrayList();
19 |
20 | // Create a file and an object input stream:
21 | FileInputStream fileInput = new FileInputStream(file);
22 |
23 | ObjectInputStream objectInput = new ObjectInputStream(fileInput);
24 | try {
25 | // Read all the animals specified in the file,
26 | // storing them in an array list:
27 | for(;;) {
28 | animals.add((Animal) objectInput.readObject());
29 | }
30 | }
31 | catch (EOFException e) {
32 | // We do not have to do anything here, this is the normal
33 | // termination of the loop above when all objects have
34 | // been read.
35 | }
36 |
37 | // Close the streams:
38 | objectInput.close();
39 | fileInput.close();
40 | for(Animal a: animals) {
41 | a.print();
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Chapter 3/Listing 3.0.java:
--------------------------------------------------------------------------------
1 | // Abstract parent class:
2 | public abstract class GameObject {
3 | // Abstract method:
4 | public abstract void move();
5 | }
6 |
--------------------------------------------------------------------------------
/Chapter 3/Listing 3.1.java:
--------------------------------------------------------------------------------
1 | public class NPC extends GameObject {
2 | public void move() {
3 | System.out.println(
4 | "The shopkeeper wanders around aimlessly...");
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/Chapter 3/Listing 3.10.java:
--------------------------------------------------------------------------------
1 | public class MainClass {
2 | public static void main(String[] args) {
3 | // Define some object:
4 | GameObject someObject = new Player();
5 |
6 | // Test if the first object is a GameObject?
7 | if(someObject instanceof GameObject)
8 | System.out.println("Object is a GameObject!");
9 | else
10 | System.out.println("Not a GameObject...");
11 |
12 | // Test if it is a Player?
13 | if(someObject instanceof Player)
14 | System.out.println("Object is a Player!");
15 | else
16 | System.out.println("Not a Player...");
17 |
18 |
19 | // Test if it is an NPC?
20 | if(someObject instanceof NPC)
21 | System.out.println("Object is a NPC!");
22 | else
23 | System.out.println("Not an NPC...");
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Chapter 3/Listing 3.11.java:
--------------------------------------------------------------------------------
1 | public class Point implements Comparable {
2 | // Member variables:
3 | public double x, y;
4 |
5 | // Constructor
6 | public Point(double x, double y) {
7 | this.x = x;
8 | this.y = y;
9 | }
10 |
11 | // Print out some info about the point:
12 | public void print() {
13 | System.out.println("X: " + x + " Y: " + y + " Mag: " +
14 | Math.sqrt(x*x+y*y));
15 | }
16 |
17 | public int compareTo(Object o) {
18 | // Firstly, if the second object if not a point
19 | if(!(o instanceof Point))
20 | return 0;
21 |
22 | // Cast the other point:
23 | Point otherPoint = (Point) o;
24 |
25 | // Compute the absolute magnitude of each point from the origin:
26 | Double thisAbsMag = Math.sqrt(x * x + y * y);
27 | Double otherPointAbsMag =Math.sqrt(otherPoint.x * otherPoint.x +
28 | otherPoint.y * otherPoint.y);
29 |
30 | return thisAbsMag.compareTo(otherPointAbsMag);
31 |
32 |
33 | /*
34 | // Note: Double.compareTo does something like the following:
35 |
36 | // If this object has a greater magnitude:
37 | if(thisAbsMag > otherPointAbsMag) return 1;
38 |
39 | // If this object a smaller magnitude:
40 | if(thisAbsMag < otherPointAbsMag) return -1;
41 |
42 | // If the object's magnitudes are equal:
43 | return 0;
44 | */
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Chapter 3/Listing 3.12.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.Collections;
3 |
4 | public class MainClass {
5 | public static void main(String[] args) {
6 | // The total number of points in the demo:
7 | int numberOfPoints = 5;
8 |
9 | // Create a list of random points:
10 | ArrayList points = new ArrayList();
11 | for(int i = 0; i < numberOfPoints; i++)
12 | points.add(new Point(Math.random() * 100,
13 | Math.random() * 100));
14 |
15 | // Print the unsorted points:
16 | System.out.println("Unsorted: ");
17 | for(int i = 0; i < numberOfPoints; i++)
18 | points.get(i).print();
19 |
20 |
21 | // Sorting a collection of Comparable objects:
22 | Collections.sort(points);
23 |
24 | // Print the sorted points:
25 | System.out.println("Sorted: ");
26 | for(int i = 0; i < numberOfPoints; i++)
27 | points.get(i).print();
28 |
29 |
30 | // Sort the items in reverse order (from largest to smallest):
31 | points.sort(Collections.reverseOrder());
32 |
33 | // Print the points sorted in reverse:
34 | System.out.println("Sorted in Reverse: ");
35 | for(int i = 0; i < numberOfPoints; i++)
36 | points.get(i).print();
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Chapter 3/Listing 3.2.java:
--------------------------------------------------------------------------------
1 | public class Player extends GameObject {
2 | public void move() {
3 | System.out.println("It is the player's move...");
4 | // Poll the keyboard or read the mouse movements etc.
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/Chapter 3/Listing 3.3.java:
--------------------------------------------------------------------------------
1 | public class MainClass {
2 | public static void main(String[] args) {
3 | // Create 5 objects in our game
4 | GameObject[] gameObjects = new GameObject[5];
5 |
6 | // First object is the player
7 | gameObjects[0] = new Player();
8 |
9 | // OPtehr objects are NPC's
10 | for(int i = 1; i < 5; i++) {
11 | gameObjects[i] = new NPC();
12 | }
13 |
14 | // Call move for all objects in the game
15 | for(int i = 0; i < 5; i++) {
16 | gameObjects[i].move();
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Chapter 3/Listing 3.4.java:
--------------------------------------------------------------------------------
1 | // Abstract parent class:
2 | public abstract class GameObject {
3 | // Member variables:
4 | int x, y;
5 |
6 | // Non-abstract method:
7 | public void print() {
8 | System.out.println("Position: " + x + ", " + y);
9 | }
10 |
11 | // Abstract method:
12 | public abstract void move();
13 | }
14 |
--------------------------------------------------------------------------------
/Chapter 3/Listing 3.5.java:
--------------------------------------------------------------------------------
1 | public class MainClass {
2 | public static void main(String[] args) {
3 | // Same code as before
4 |
5 |
6 | // Call print for all objects in the game
7 | for(int i = 0; i < 5; i++) {
8 | gameObjects[i].print();
9 | }
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/Chapter 3/Listing 3.6.java:
--------------------------------------------------------------------------------
1 | public class Player extends GameObject {
2 | public void move() {
3 | System.out.println("It is the player's move...");
4 | // Poll the keyboard or read the mouse movements etc.
5 | }
6 |
7 | @Override
8 | public void print() {
9 | System.out.println("Player position: " + x + ", " + y);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/Chapter 3/Listing 3.7.java:
--------------------------------------------------------------------------------
1 | // Abstract parent class:
2 | public abstract class GameObject {
3 | // Member variables:
4 | int x, y;
5 |
6 | // Constructor
7 | public GameObject() {
8 | // Set the x and y:
9 | x = y = -1;
10 | }
11 |
12 | // Non-abstract method:
13 | public void print() {
14 | System.out.println("Position: " + x + ", " + y);
15 | }
16 |
17 | // Abstract method:
18 | public abstract void move();
19 | }
20 |
--------------------------------------------------------------------------------
/Chapter 3/Listing 3.8.java:
--------------------------------------------------------------------------------
1 | public class Player extends GameObject {
2 |
3 | // Constructor
4 | public Player() {
5 | x = y = 100; // Start the player at 100x100
6 | }
7 |
8 | public void move() {
9 | System.out.println("It is the player's move...");
10 | // Poll the keyboard or read the mouse movements etc.
11 | }
12 |
13 | @Override
14 | public void print() {
15 | System.out.println("Player position: " + x + ", " + y);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Chapter 3/Listing 3.9.java:
--------------------------------------------------------------------------------
1 | // Constructor
2 | public Player() {
3 | // Call the parent's constructor
4 | super();
5 |
6 | x = y = 100; // Start the player at 100x100
7 | }
8 |
--------------------------------------------------------------------------------
/Chapter 4/Listing 4.0.java:
--------------------------------------------------------------------------------
1 | public class MainClass {
2 | // Parent class
3 | static class OutputLyrics {
4 | public void output() {
5 | System.out.println("No lyrics supplied...");
6 | }
7 | }
8 |
9 | public static void main(String[] args) {
10 |
11 | // Create a normal instance from the OutputLyrics class
12 | OutputLyrics regularInstance = new OutputLyrics();
13 |
14 | // Anonymous Inner Class
15 | OutputLyrics anonymousClass = new OutputLyrics() {
16 | public void output() {
17 | System.out.println(
18 | "Desmond has a barrel at the market place.");
19 | }
20 | };
21 |
22 | // Call the output methods:
23 | regularInstance.output();
24 |
25 | // And using the anonymous class:
26 | anonymousClass.output();
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Chapter 4/Listing 4.1.java:
--------------------------------------------------------------------------------
1 | // Anonymous Inner Class
2 | OutputLyrics anonymousClass = new OutputLyrics() {
3 | public void output() {
4 | System.out.println(
5 | "Desmond has a barrel at the market place.");
6 | }
7 | };
8 |
--------------------------------------------------------------------------------
/Chapter 4/Listing 4.2.java:
--------------------------------------------------------------------------------
1 | public class MainClass {
2 |
3 | // Parent class
4 | static class MathOperation {
5 | public int operation(int a, int b) {
6 | return 0;
7 | }
8 | }
9 |
10 | // Method which takes an object of MathOperation as a parameter
11 | static int performOperation(int a, int b, MathOperation op) {
12 | return op.operation(a, b);
13 | }
14 |
15 | public static void main(String[] args) {
16 | // Some variables
17 | int x = 100;
18 | int y = 97;
19 |
20 | // Call the PerformOperation function with addition:
21 | int resultOfAddition = performOperation(x, y,
22 | // Anonymous inner class used as a parameter
23 | new MathOperation() {
24 | public int operation(int a, int b) {
25 | return a + b;
26 | }
27 | });
28 |
29 | // Call the PerformOperation function with subtraction:
30 | int resultOfSubtraction = performOperation(x, y,
31 | // Anonymous inner class used as a parameter
32 | new MathOperation() {
33 | public int operation(int a, int b) {
34 | return a - b;
35 | }
36 | });
37 |
38 | // Output Addition: 197
39 | System.out.println("Addition: " + resultOfAddition);
40 |
41 | // Output Subtraction: 3
42 | System.out.println("Subtraction: " + resultOfSubtraction);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Chapter 4/Listing 4.3.java:
--------------------------------------------------------------------------------
1 | int resultOfAddition = performOperation(x, y,
2 | // Anonymous inner class used as a parameter
3 | new MathOperation() {
4 | public int operation(int a, int b) {
5 | return a + b;
6 | }
7 | });
8 |
--------------------------------------------------------------------------------
/Chapter 4/Listing 4.4.java:
--------------------------------------------------------------------------------
1 | public class MainClass {
2 |
3 | // Parent interface
4 | interface MathOperation {
5 | public int operation(int a, int b);
6 | }
7 |
8 | // Method which takes an object of MathOperation as a parameter
9 | static int performOperation(int a, int b, MathOperation op) {
10 | return op.operation(a, b);
11 | }
12 |
13 | public static void main(String[] args) {
14 | // Some variables
15 | int x = 100;
16 | int y = 97;
17 |
18 | // Call the PerformOperation function with addition:
19 | int resultOfAddition = performOperation(x, y,
20 | // Anonymous inner class used as a parameter
21 | new MathOperation() {
22 | public int operation(int a, int b) {
23 | return a + b;
24 | }
25 | });
26 |
27 | // Call the PerformOperation function with subtraction:
28 | int resultOfSubtraction = performOperation(x, y,
29 | // Anonymous inner class used as a parameter
30 | new MathOperation() {
31 | public int operation(int a, int b) {
32 | return a - b;
33 | }
34 | });
35 |
36 | // Output Addition: 197
37 | System.out.println("Addition: " + resultOfAddition);
38 |
39 | // Output Subtraction: 3
40 | System.out.println("Subtraction: " + resultOfSubtraction);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Chapter 5/Listing 5.0.java:
--------------------------------------------------------------------------------
1 | public class MainClass {
2 | public static void main(String[] args) {
3 | // Define Thready objects:
4 | Thready t1 = new Thready("Ned");
5 | Thready t2 = new Thready("Kelly");
6 |
7 | // Start the threads:
8 | t1.initThread();
9 | t2.initThread();
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/Chapter 5/Listing 5.1.java:
--------------------------------------------------------------------------------
1 | public class Thready implements Runnable {
2 |
3 | // Private member variables:
4 | private Thread thread;
5 | private String name;
6 |
7 | // Constructor:
8 | public Thready(String name) {
9 | this.name = name;
10 |
11 | System.out.println("Created thread: " + name);
12 | }
13 |
14 | // Init and start thread method:
15 | public void initThread() {
16 | System.out.println("Initializing thread: " + name);
17 |
18 | thread = new Thread(this, name);
19 |
20 | thread.start();
21 | }
22 |
23 | // Overriden run method:
24 | public void run() {
25 | // Print initial message:
26 | System.out.println("Running thread: " + name);
27 |
28 | // Count to 10:
29 | for(int i = 0; i < 10; i++) {
30 | System.out.println("Thread " + name + " counted " + i);
31 |
32 | try {
33 | // Wait for 1 second:
34 | Thread.sleep(1000);
35 | }
36 | catch (Exception e) {
37 | System.out.println("Error: " + e.getMessage());
38 | }
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Chapter 5/Listing 5.2.java:
--------------------------------------------------------------------------------
1 | public class MainClass {
2 | public static void main(String[] args) {
3 | // Create three threads:
4 | Thready t1 = new Thready("Ned");
5 | Thready t2 = new Thready("Kelly");
6 | Thready t3 = new Thready("Pole");
7 |
8 | // init and run the threads
9 | t1.initThread();
10 | t2.initThread();
11 | t3.initThread();
12 |
13 | // Wait for the threads to finish:
14 | while(t1.isRunning()) {
15 | }
16 |
17 | while(t2.isRunning()) {
18 | }
19 |
20 | while(t3.isRunning()) {
21 | }
22 |
23 | // Check what the counter is:
24 | System.out.println("All done!" + Thready.getJ());`
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Chapter 5/Listing 5.3.java:
--------------------------------------------------------------------------------
1 | public class Thready implements Runnable {
2 |
3 | // A shared resource:
4 | public class Counter {
5 | private int j;
6 |
7 | public Counter() {
8 | j = 0;
9 | }
10 |
11 | public int getJ() {
12 | return j;
13 | }
14 | }
15 |
16 | // Thready member variables
17 | private Thread thread;
18 | private String name;
19 | private boolean running = true;
20 |
21 | // Static shared resource:
22 | private static Counter counter = null;
23 |
24 | // Getters:
25 | public static int getJ() {
26 | return counter.getJ();
27 | }
28 |
29 | public boolean isRunning() {
30 | return running;
31 | }
32 |
33 | // Constructor
34 | public Thready(String name) {
35 | // Create the shared resource
36 | if(counter == null)
37 | counter = new Counter();
38 |
39 | // Assign name
40 | this.name = name;
41 |
42 | // Print message
43 | System.out.println("Created thread: " + name);
44 | }
45 |
46 | public void initThread() {
47 | // Print message
48 | System.out.println("Initializing thread: " + name);
49 |
50 | // Create thread
51 | thread = new Thread(this, name);
52 |
53 | // Call run
54 | thread.start();
55 | }
56 |
57 | public void run() {
58 | for(int q = 0; q < 10000; q++) {
59 | counter.j++; // RACE CONDITION!!!
60 | }
61 |
62 | running = false;
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/Chapter 5/Listing 5.4.java:
--------------------------------------------------------------------------------
1 | public void run() {
2 | for(int q = 0; q < 10000; q++) {
3 | synchronized (counter) {
4 | counter.j++;
5 | }
6 | }
7 | running = false;
8 | }
9 |
--------------------------------------------------------------------------------
/Chapter 5/Listing 5.5.java:
--------------------------------------------------------------------------------
1 | public void run() {
2 | synchronized (counter) {
3 | for(int q = 0; q < 10000; q++) {
4 |
5 | counter.j++;
6 | }
7 | }
8 | running = false;
9 | }
10 |
--------------------------------------------------------------------------------
/Chapter 5/Listing 5.6.java:
--------------------------------------------------------------------------------
1 | // MainClass.java
2 | public class MainClass {
3 | public static void main(String[] args) {
4 | // Define some threads:
5 | Thready thread0 = new Thready(0);
6 | Thready thread1 = new Thready(1);
7 | // set the value to factor:
8 | Thready.x = 36847153;
9 | // Start the threads:
10 | thread0.start();
11 | thread1.start();
12 |
13 | // Wait for the threads to finish
14 | while(thread0.isAlive()) { }
15 | while(thread1.isAlive()) { }
16 | // Print out the factors the threads found:
17 | System.out.println(
18 | "Smallest Factor found by thread0: " + thread0.smallestFactor);
19 | System.out.println(
20 | "Smallest Factor found by thread1: " + thread1.smallestFactor);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Chapter 5/Listing 5.7.java:
--------------------------------------------------------------------------------
1 | // The class Extends the Thread class
2 | public class Thready extends Thread {
3 | // Shared resource
4 | public static int x;
5 | public int id;
6 | // Smallest factor found by this thread:
7 | public int smallestFactor = -1;
8 |
9 | // Constructor
10 | public Thready(int id) {
11 | this.id = id;
12 | }
13 |
14 | // run method
15 | public void run() {
16 | // Figure out the root:
17 | int rootOfX = (int)Math.sqrt(x) + 1;
18 |
19 | // Figure out the start and finish points:
20 | int start = (rootOfX / 2) * id;
21 | int finish = start + (rootOfX / 2);
22 |
23 | // If the number is even:
24 | if(x % 2 == 0) {
25 | smallestFactor = 2;
26 | return;
27 | }
28 | // Don't check 0 and 1 as a factor:
29 | if(start == 0 || start == 1)
30 | start = 3;
31 |
32 | // Only check odd numbers:
33 | if(start % 2 == 0)
34 | start++;
35 |
36 | // Try to find a factor
37 | for(int i = start; i < finish; i+=2) {
38 | if(x % i == 0) {
39 | smallestFactor = i;
40 | break;
41 | }
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Chapter 6/Listing 6.0.java:
--------------------------------------------------------------------------------
1 | import java.awt.*;
2 | import javax.swing.*;
3 |
4 | public class MainClass extends JFrame{
5 | // Main method
6 | public static void main(String[] args) {
7 | MainClass mainWindow = new MainClass();
8 | }
9 |
10 | // Constructor
11 | public MainClass() {
12 | // Set the size of the window
13 | this.setSize(640, 480);
14 |
15 | // Set the app to close when the window closes
16 | this.setDefaultCloseOperation(EXIT_ON_CLOSE);
17 |
18 | // Set the window to visible
19 | this.setVisible(true);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Chapter 6/Listing 6.1.java:
--------------------------------------------------------------------------------
1 | // Constructor
2 | public MainClass() {
3 | // Create a JPanel
4 | JPanel panel = new JPanel(new FlowLayout());
5 |
6 | // Add some controls:
7 | panel.add(new JLabel("Test Button: "));
8 | panel.add(new JButton("Click me!"));
9 |
10 | // Set the current content pane to the panel:
11 | this.setContentPane(panel);
12 |
13 |
14 | // Set the size of the window
15 | this.setSize(640, 480);
16 |
17 | // Set the app to close when the window closes
18 | this.setDefaultCloseOperation(EXIT_ON_CLOSE);
19 |
20 | // Set the window to visible
21 | this.setVisible(true);
22 | }
23 |
--------------------------------------------------------------------------------
/Chapter 6/Listing 6.2.java:
--------------------------------------------------------------------------------
1 | JButton btn = new JButton("Initial Text");
2 |
3 | // Useful control methods:
4 | btn.setText("New text!"); // Set the text on the button
5 | String text = btn.getText(); // Read the current text
6 | btn.setVisible(false); // Hide the control from view
7 | btn.setVisible(true); // Show the control
8 | btn.setMargin(new Insets(100, 100, 100, 100)); // Set margins
9 | Dimension dim = btn.getSize();// Read the size of the control
10 | btn.setBackground(Color.BLUE);// Set the background color
11 | btn.setForeground(Color.WHITE);// Set the foreground/text color
12 | btn.setEnabled(false);// Disable interactions with the control
13 | btn.setEnabled(true); // Enable interactions with the control
14 |
15 | // Depending on the layout manager, these may do nothing:
16 | btn.setSize(new Dimension(10, 10)); // Set size of the control
17 |
18 | // Set size and position of the control:
19 | btn.setBounds(new Rectangle(20, 20, 200, 60));
20 |
--------------------------------------------------------------------------------
/Chapter 6/Listing 6.3.java:
--------------------------------------------------------------------------------
1 | import java.awt.*;
2 | import java.awt.event.ActionEvent;
3 | import java.awt.event.ActionListener;
4 |
5 | import javax.swing.*;
6 |
7 | public class MainClass extends JFrame implements ActionListener {
8 | // Main method
9 | public static void main(String[] args) {
10 | MainClass mainWindow = new MainClass();
11 | }
12 |
13 | // Constructor
14 | public MainClass() {
15 | // Create a JPanel
16 | JPanel panel = new JPanel(new FlowLayout());
17 |
18 | // Add some controls:
19 | panel.add(new JLabel("Test Button: "));
20 | JButton btnClickMe = new JButton("Click me!");
21 | panel.add(btnClickMe);
22 |
23 | // Set the current content pane to the panel:
24 | this.setContentPane(panel);
25 |
26 | // Set this as the current action listener for the button
27 | btnClickMe.addActionListener(this);
28 |
29 | // Set the size of the window
30 | this.setSize(640, 480);
31 |
32 | // Set the app to close when the window closes
33 | this.setDefaultCloseOperation(EXIT_ON_CLOSE);
34 |
35 | // Set the window to visible
36 | this.setVisible(true);
37 | }
38 |
39 | // Method inherited from the ActionListener interface:
40 | public void actionPerformed(ActionEvent e) {
41 | // Show a message box:
42 | JOptionPane.showMessageDialog(null,
43 | "You clicked on the button!");
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Chapter 6/Listing 6.4.java:
--------------------------------------------------------------------------------
1 | import java.awt.*;
2 | import java.awt.event.ActionEvent;
3 | import java.awt.event.ActionListener;
4 |
5 | import javax.swing.*;
6 |
7 | public class MainClass extends JFrame {
8 | // Main method
9 | public static void main(String[] args) {
10 | MainClass mainWindow = new MainClass();
11 | }
12 |
13 | // Constructor
14 | public MainClass() {
15 | // Create a JPanel
16 | JPanel panel = new JPanel(new FlowLayout());
17 |
18 | // Add some controls:
19 | panel.add(new JLabel("Test Button: "));
20 | JButton btnClickMe = new JButton("Click me!");
21 | panel.add(btnClickMe);
22 |
23 | // Set the current content pane to the panel:
24 | this.setContentPane(panel);
25 |
26 | // ActionListener as anonymous class:
27 | btnClickMe.addActionListener(new ActionListener() {
28 | public void actionPerformed(ActionEvent e) {
29 | // Show a message box:
30 | JOptionPane.showMessageDialog(null,
31 | "You clicked on the button!");
32 | }
33 | });
34 |
35 | // Set the size of the window
36 | this.setSize(640, 480);
37 |
38 | // Set the app to close when the window closes
39 | this.setDefaultCloseOperation(EXIT_ON_CLOSE);
40 |
41 | // Set the window to visible
42 | this.setVisible(true);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Chapter 6/Listing 6.5.java:
--------------------------------------------------------------------------------
1 | import java.awt.*;
2 | import java.awt.event.ActionEvent;
3 | import java.awt.event.ActionListener;
4 | import javax.swing.*;
5 |
6 | public class MainClass extends JFrame implements ActionListener {
7 | public static void main(String[] args) {
8 | MainClass m = new MainClass();
9 | m.run();
10 | }
11 |
12 | // Declare txtInput
13 | private JTextArea txtInput;
14 |
15 | private void run() {
16 | // Create a new border layout and main panel for controls
17 | BorderLayout layoutManager = new BorderLayout();
18 | JPanel mainPanel = new JPanel(layoutManager);
19 | this.setDefaultCloseOperation(EXIT_ON_CLOSE);
20 | this.setSize(500, 500);
21 | this.setContentPane(mainPanel);
22 | this.setVisible(true);
23 |
24 | // Set margins around control in layout
25 | layoutManager.setHgap(25);
26 | layoutManager.setVgap(25);
27 |
28 | // Create buttons
29 | JButton btnTop = new JButton("Page Start");
30 | JButton btnBottom = new JButton("Page End");
31 | JButton btnLeft = new JButton("Line Start");
32 | JButton btnRight = new JButton("Line End");
33 |
34 | // Add the buttons to panel
35 | mainPanel.add(btnTop, BorderLayout.PAGE_START);
36 | mainPanel.add(btnBottom, BorderLayout.PAGE_END);
37 | mainPanel.add(btnLeft, BorderLayout.LINE_START);
38 | mainPanel.add(btnRight, BorderLayout.LINE_END);
39 |
40 | // Create and add a text area
41 | txtInput = new JTextArea(5, 10);
42 | txtInput.setText("Click a button!");
43 | JScrollPane jsp = new JScrollPane(txtInput);
44 | txtInput.setEditable(false);
45 | mainPanel.add(jsp, BorderLayout.CENTER);
46 |
47 | // Add action listeners to respond to button clicks
48 | btnTop.addActionListener(this);
49 | btnBottom.addActionListener(this);
50 | btnLeft.addActionListener(this);
51 | btnRight.addActionListener(this);
52 |
53 | // Redraw all controls to ensure all are visible
54 | this.validate();
55 | }
56 |
57 | // Action performed prints the clicked button's text to the
58 | // txtOutput control
59 | public void actionPerformed(ActionEvent arg0) {
60 | txtInput.append("You clicked " +
61 | ((JButton)arg0.getSource()).getText() +
62 | "\n");
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/Chapter 7/CalculatorApp/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Chapter 7/CalculatorApp/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | CalculatorApp
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Chapter 7/CalculatorApp/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.8
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.source=1.8
12 |
--------------------------------------------------------------------------------
/Chapter 7/CalculatorApp/miglayout-src.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SyncfusionSuccinctlyE-Books/Java-Succinctly-Part-2/522496f8238a024c63d5bf4f4e692f2b8fb8e4a1/Chapter 7/CalculatorApp/miglayout-src.zip
--------------------------------------------------------------------------------
/Chapter 7/CalculatorApp/miglayout15-swing.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SyncfusionSuccinctlyE-Books/Java-Succinctly-Part-2/522496f8238a024c63d5bf4f4e692f2b8fb8e4a1/Chapter 7/CalculatorApp/miglayout15-swing.jar
--------------------------------------------------------------------------------
/Chapter 7/CalculatorApp/src/calculatorApp/MainWindow.java:
--------------------------------------------------------------------------------
1 | package calculatorApp;
2 |
3 | import java.awt.EventQueue;
4 |
5 | import javax.swing.JFrame;
6 | import java.awt.BorderLayout;
7 | import javax.swing.JTextField;
8 | import java.awt.Font;
9 | import javax.swing.SwingConstants;
10 | import javax.swing.JButton;
11 | import java.awt.event.ActionListener;
12 | import java.awt.event.ActionEvent;
13 | import javax.swing.JPanel;
14 | import java.awt.GridBagLayout;
15 | import java.awt.GridBagConstraints;
16 | import java.awt.Insets;
17 | import java.awt.Component;
18 | import javax.swing.Box;
19 | import java.awt.Dimension;
20 |
21 | public class MainWindow {
22 |
23 | private JFrame frame;
24 | private JTextField txtOutput;
25 | private JButton button;
26 | private JButton button_1;
27 | private JButton button_2;
28 | private JButton button_3;
29 | private JButton button_4;
30 | private JButton button_5;
31 | private JButton button_6;
32 | private JButton button_7;
33 | private JButton button_8;
34 | private JButton button_9;
35 | private JButton button_10;
36 | private JButton button_11;
37 | private JButton button_12;
38 | private JButton btnX;
39 | private JButton button_13;
40 | private JButton button_14;
41 | private JButton btnF;
42 | private JButton btnF_1;
43 | private JButton btnF_2;
44 | private JButton btnF_3;
45 | private JButton btnF_5;
46 | private JButton btnF_6;
47 | private JButton btnF_7;
48 | private JButton btnF_8;
49 | private JButton btnF_4;
50 | private JButton btnF_9;
51 | private JButton btnF_10;
52 | private JButton btnF_11;
53 | private JButton btnF_12;
54 | private JButton btnF_13;
55 | private JButton btnF_14;
56 | private JButton btnF_15;
57 | private JButton btnF_16;
58 | private JButton btnF_17;
59 |
60 | // State variables
61 | private int state = 0; // 0 to first number, 1 for second
62 | private int operator = 0; // 0 means unknown
63 | private double number1 = 0.0; // Variable for parsing 1st operand
64 | private double number2 = 0.0; // Variable for parsing 2nd operand
65 | private double[] memory = new double[5]; // For memory functions
66 |
67 | /**
68 | * Launch the application.
69 | */
70 | public static void main(String[] args) {
71 | EventQueue.invokeLater(new Runnable() {
72 | public void run() {
73 | try {
74 | MainWindow window = new MainWindow();
75 | window.frame.setVisible(true);
76 | } catch (Exception e) {
77 | e.printStackTrace();
78 | }
79 | }
80 | });
81 | }
82 |
83 | /**
84 | * Create the application.
85 | */
86 | public MainWindow() {
87 | initialize();
88 | }
89 |
90 | /**
91 | * Initialize the contents of the frame.
92 | */
93 | private void initialize() {
94 | frame = new JFrame();
95 | frame.setBounds(100, 100, 381, 560);
96 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
97 | frame.getContentPane().setLayout(new BorderLayout(0, 0));
98 |
99 | txtOutput = new JTextField();
100 | txtOutput.setHorizontalAlignment(SwingConstants.TRAILING);
101 | txtOutput.setEditable(false);
102 | txtOutput.setFont(new Font("Tahoma", Font.PLAIN, 24));
103 | frame.getContentPane().add(txtOutput, BorderLayout.NORTH);
104 | txtOutput.setColumns(10);
105 |
106 | JPanel panel = new JPanel();
107 | frame.getContentPane().add(panel, BorderLayout.CENTER);
108 | GridBagLayout gbl_panel = new GridBagLayout();
109 | gbl_panel.columnWidths = new int[] {30, 30, 0, 0, 0, 0, 30, 30, 30, 30};
110 | gbl_panel.rowHeights = new int[] {50, 0, 0, 0, 0, 50, 0, 0, 0, 0, 0, 0, 0, 0};
111 | gbl_panel.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
112 | gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
113 | panel.setLayout(gbl_panel);
114 |
115 | btnF = new JButton("SIN");
116 | btnF.setToolTipText("Compute the Sine of an angle");
117 | btnF.addActionListener(new ActionListener() {
118 | public void actionPerformed(ActionEvent e) {
119 | number1 = Double.parseDouble(txtOutput.getText());
120 | number1 = Math.sin(number1);
121 | txtOutput.setText("" + number1);
122 | }
123 | });
124 | btnF.setFont(new Font("Tahoma", Font.PLAIN, 10));
125 | GridBagConstraints gbc_btnF = new GridBagConstraints();
126 | gbc_btnF.fill = GridBagConstraints.BOTH;
127 | gbc_btnF.insets = new Insets(0, 0, 5, 5);
128 | gbc_btnF.gridx = 2;
129 | gbc_btnF.gridy = 1;
130 | panel.add(btnF, gbc_btnF);
131 |
132 | btnF_1 = new JButton("COS");
133 | btnF_1.setToolTipText("Compute the Cosine of an angle");
134 | btnF_1.setFont(new Font("Tahoma", Font.PLAIN, 10));
135 | GridBagConstraints gbc_btnF_1 = new GridBagConstraints();
136 | gbc_btnF_1.fill = GridBagConstraints.BOTH;
137 | gbc_btnF_1.insets = new Insets(0, 0, 5, 5);
138 | gbc_btnF_1.gridx = 3;
139 | gbc_btnF_1.gridy = 1;
140 | panel.add(btnF_1, gbc_btnF_1);
141 |
142 | btnF_2 = new JButton("TAN");
143 | btnF_2.setToolTipText("Compute the Tangent of an angle");
144 | btnF_2.setFont(new Font("Tahoma", Font.PLAIN, 10));
145 | GridBagConstraints gbc_btnF_2 = new GridBagConstraints();
146 | gbc_btnF_2.fill = GridBagConstraints.BOTH;
147 | gbc_btnF_2.insets = new Insets(0, 0, 5, 5);
148 | gbc_btnF_2.gridx = 4;
149 | gbc_btnF_2.gridy = 1;
150 | panel.add(btnF_2, gbc_btnF_2);
151 |
152 | btnF_3 = new JButton("^");
153 | btnF_3.addActionListener(new ActionListener() {
154 | public void actionPerformed(ActionEvent arg0) {
155 | operator = 4; // 4 is power
156 | number1 = Double.parseDouble(txtOutput.getText());
157 | txtOutput.setText("");
158 | }
159 | });
160 | btnF_3.setToolTipText("Computes the power of one number to another");
161 | btnF_3.setFont(new Font("Tahoma", Font.PLAIN, 24));
162 | GridBagConstraints gbc_btnF_3 = new GridBagConstraints();
163 | gbc_btnF_3.fill = GridBagConstraints.HORIZONTAL;
164 | gbc_btnF_3.insets = new Insets(0, 0, 5, 5);
165 | gbc_btnF_3.gridx = 5;
166 | gbc_btnF_3.gridy = 1;
167 | panel.add(btnF_3, gbc_btnF_3);
168 |
169 | btnF_4 = new JButton("f");
170 | btnF_4.setFont(new Font("Tahoma", Font.PLAIN, 24));
171 | GridBagConstraints gbc_btnF_4 = new GridBagConstraints();
172 | gbc_btnF_4.fill = GridBagConstraints.HORIZONTAL;
173 | gbc_btnF_4.insets = new Insets(0, 0, 5, 5);
174 | gbc_btnF_4.gridx = 6;
175 | gbc_btnF_4.gridy = 1;
176 | panel.add(btnF_4, gbc_btnF_4);
177 |
178 | btnF_10 = new JButton("f");
179 | btnF_10.setFont(new Font("Tahoma", Font.PLAIN, 24));
180 | GridBagConstraints gbc_btnF_10 = new GridBagConstraints();
181 | gbc_btnF_10.fill = GridBagConstraints.HORIZONTAL;
182 | gbc_btnF_10.insets = new Insets(0, 0, 5, 5);
183 | gbc_btnF_10.gridx = 7;
184 | gbc_btnF_10.gridy = 1;
185 | panel.add(btnF_10, gbc_btnF_10);
186 |
187 | btnF_5 = new JButton("STR");
188 | btnF_5.addActionListener(new ActionListener() {
189 | public void actionPerformed(ActionEvent e) {
190 | operator = 5;
191 | number1 = Double.parseDouble(txtOutput.getText());
192 | }
193 | });
194 | btnF_5.setToolTipText("Store the current value to a memory");
195 | btnF_5.setFont(new Font("Tahoma", Font.PLAIN, 10));
196 | GridBagConstraints gbc_btnF_5 = new GridBagConstraints();
197 | gbc_btnF_5.fill = GridBagConstraints.BOTH;
198 | gbc_btnF_5.insets = new Insets(0, 0, 5, 5);
199 | gbc_btnF_5.gridx = 2;
200 | gbc_btnF_5.gridy = 2;
201 | panel.add(btnF_5, gbc_btnF_5);
202 |
203 | btnF_6 = new JButton("f");
204 | btnF_6.setFont(new Font("Tahoma", Font.PLAIN, 24));
205 | GridBagConstraints gbc_btnF_6 = new GridBagConstraints();
206 | gbc_btnF_6.fill = GridBagConstraints.HORIZONTAL;
207 | gbc_btnF_6.insets = new Insets(0, 0, 5, 5);
208 | gbc_btnF_6.gridx = 3;
209 | gbc_btnF_6.gridy = 2;
210 | panel.add(btnF_6, gbc_btnF_6);
211 |
212 | btnF_7 = new JButton("f");
213 | btnF_7.setFont(new Font("Tahoma", Font.PLAIN, 24));
214 | GridBagConstraints gbc_btnF_7 = new GridBagConstraints();
215 | gbc_btnF_7.fill = GridBagConstraints.HORIZONTAL;
216 | gbc_btnF_7.insets = new Insets(0, 0, 5, 5);
217 | gbc_btnF_7.gridx = 4;
218 | gbc_btnF_7.gridy = 2;
219 | panel.add(btnF_7, gbc_btnF_7);
220 |
221 | btnF_8 = new JButton("f");
222 | btnF_8.setFont(new Font("Tahoma", Font.PLAIN, 24));
223 | GridBagConstraints gbc_btnF_8 = new GridBagConstraints();
224 | gbc_btnF_8.fill = GridBagConstraints.HORIZONTAL;
225 | gbc_btnF_8.insets = new Insets(0, 0, 5, 5);
226 | gbc_btnF_8.gridx = 5;
227 | gbc_btnF_8.gridy = 2;
228 | panel.add(btnF_8, gbc_btnF_8);
229 |
230 | btnF_9 = new JButton("f");
231 | btnF_9.setFont(new Font("Tahoma", Font.PLAIN, 24));
232 | GridBagConstraints gbc_btnF_9 = new GridBagConstraints();
233 | gbc_btnF_9.fill = GridBagConstraints.HORIZONTAL;
234 | gbc_btnF_9.insets = new Insets(0, 0, 5, 5);
235 | gbc_btnF_9.gridx = 6;
236 | gbc_btnF_9.gridy = 2;
237 | panel.add(btnF_9, gbc_btnF_9);
238 |
239 | btnF_11 = new JButton("f");
240 | btnF_11.setFont(new Font("Tahoma", Font.PLAIN, 24));
241 | GridBagConstraints gbc_btnF_11 = new GridBagConstraints();
242 | gbc_btnF_11.fill = GridBagConstraints.HORIZONTAL;
243 | gbc_btnF_11.insets = new Insets(0, 0, 5, 5);
244 | gbc_btnF_11.gridx = 7;
245 | gbc_btnF_11.gridy = 2;
246 | panel.add(btnF_11, gbc_btnF_11);
247 |
248 | btnF_12 = new JButton("M0");
249 | btnF_12.addActionListener(new ActionListener() {
250 | public void actionPerformed(ActionEvent e) {
251 | if(operator == 5)
252 | memory[0] = number1;
253 | else
254 | txtOutput.setText("" + memory[0]);
255 | }
256 | });
257 | btnF_12.setFont(new Font("Tahoma", Font.PLAIN, 10));
258 | GridBagConstraints gbc_btnF_12 = new GridBagConstraints();
259 | gbc_btnF_12.fill = GridBagConstraints.BOTH;
260 | gbc_btnF_12.insets = new Insets(0, 0, 5, 5);
261 | gbc_btnF_12.gridx = 2;
262 | gbc_btnF_12.gridy = 3;
263 | panel.add(btnF_12, gbc_btnF_12);
264 |
265 | btnF_13 = new JButton("M1");
266 | btnF_13.setFont(new Font("Tahoma", Font.PLAIN, 10));
267 | GridBagConstraints gbc_btnF_13 = new GridBagConstraints();
268 | gbc_btnF_13.fill = GridBagConstraints.BOTH;
269 | gbc_btnF_13.insets = new Insets(0, 0, 5, 5);
270 | gbc_btnF_13.gridx = 3;
271 | gbc_btnF_13.gridy = 3;
272 | panel.add(btnF_13, gbc_btnF_13);
273 |
274 | btnF_14 = new JButton("M2");
275 | btnF_14.setFont(new Font("Tahoma", Font.PLAIN, 10));
276 | GridBagConstraints gbc_btnF_14 = new GridBagConstraints();
277 | gbc_btnF_14.fill = GridBagConstraints.BOTH;
278 | gbc_btnF_14.insets = new Insets(0, 0, 5, 5);
279 | gbc_btnF_14.gridx = 4;
280 | gbc_btnF_14.gridy = 3;
281 | panel.add(btnF_14, gbc_btnF_14);
282 |
283 | btnF_15 = new JButton("M3");
284 | btnF_15.setFont(new Font("Tahoma", Font.PLAIN, 10));
285 | GridBagConstraints gbc_btnF_15 = new GridBagConstraints();
286 | gbc_btnF_15.fill = GridBagConstraints.BOTH;
287 | gbc_btnF_15.insets = new Insets(0, 0, 5, 5);
288 | gbc_btnF_15.gridx = 5;
289 | gbc_btnF_15.gridy = 3;
290 | panel.add(btnF_15, gbc_btnF_15);
291 |
292 | btnF_16 = new JButton("M4");
293 | btnF_16.setFont(new Font("Tahoma", Font.PLAIN, 10));
294 | GridBagConstraints gbc_btnF_16 = new GridBagConstraints();
295 | gbc_btnF_16.fill = GridBagConstraints.BOTH;
296 | gbc_btnF_16.insets = new Insets(0, 0, 5, 5);
297 | gbc_btnF_16.gridx = 6;
298 | gbc_btnF_16.gridy = 3;
299 | panel.add(btnF_16, gbc_btnF_16);
300 |
301 | btnF_17 = new JButton("C");
302 | btnF_17.addActionListener(new ActionListener() {
303 | public void actionPerformed(ActionEvent arg0) {
304 | txtOutput.setText("");
305 | operator = -1;
306 | }
307 | });
308 | btnF_17.setToolTipText("Clear the output");
309 | btnF_17.setFont(new Font("Tahoma", Font.PLAIN, 24));
310 | GridBagConstraints gbc_btnF_17 = new GridBagConstraints();
311 | gbc_btnF_17.fill = GridBagConstraints.HORIZONTAL;
312 | gbc_btnF_17.insets = new Insets(0, 0, 5, 5);
313 | gbc_btnF_17.gridx = 7;
314 | gbc_btnF_17.gridy = 3;
315 | panel.add(btnF_17, gbc_btnF_17);
316 |
317 | button = new JButton("7");
318 | button.addActionListener(new ActionListener() {
319 | public void actionPerformed(ActionEvent arg0) {
320 | txtOutput.setText(txtOutput.getText() + "7");
321 | }
322 | });
323 | button.setFont(new Font("Tahoma", Font.PLAIN, 24));
324 | GridBagConstraints gbc_button = new GridBagConstraints();
325 | gbc_button.fill = GridBagConstraints.HORIZONTAL;
326 | gbc_button.insets = new Insets(0, 0, 5, 5);
327 | gbc_button.gridx = 2;
328 | gbc_button.gridy = 7;
329 | panel.add(button, gbc_button);
330 |
331 | button_1 = new JButton("8");
332 | button_1.addActionListener(new ActionListener() {
333 | public void actionPerformed(ActionEvent e) {
334 | txtOutput.setText(txtOutput.getText() + "8");
335 | }
336 | });
337 | button_1.setFont(new Font("Tahoma", Font.PLAIN, 24));
338 | GridBagConstraints gbc_button_1 = new GridBagConstraints();
339 | gbc_button_1.fill = GridBagConstraints.HORIZONTAL;
340 | gbc_button_1.insets = new Insets(0, 0, 5, 5);
341 | gbc_button_1.gridx = 3;
342 | gbc_button_1.gridy = 7;
343 | panel.add(button_1, gbc_button_1);
344 |
345 | button_2 = new JButton("9");
346 | button_2.addActionListener(new ActionListener() {
347 | public void actionPerformed(ActionEvent e) {
348 | txtOutput.setText(txtOutput.getText() + "9");
349 | }
350 | });
351 | button_2.setFont(new Font("Tahoma", Font.PLAIN, 24));
352 | GridBagConstraints gbc_button_2 = new GridBagConstraints();
353 | gbc_button_2.fill = GridBagConstraints.HORIZONTAL;
354 | gbc_button_2.insets = new Insets(0, 0, 5, 5);
355 | gbc_button_2.gridx = 4;
356 | gbc_button_2.gridy = 7;
357 | panel.add(button_2, gbc_button_2);
358 |
359 | button_14 = new JButton("+");
360 | button_14.addActionListener(new ActionListener() {
361 | public void actionPerformed(ActionEvent e) {
362 | operator = 0;
363 | number1 = Double.parseDouble(txtOutput.getText());
364 | txtOutput.setText("");
365 | }
366 | });
367 | button_14.setFont(new Font("Tahoma", Font.PLAIN, 24));
368 | GridBagConstraints gbc_button_14 = new GridBagConstraints();
369 | gbc_button_14.fill = GridBagConstraints.HORIZONTAL;
370 | gbc_button_14.insets = new Insets(0, 0, 5, 5);
371 | gbc_button_14.gridx = 7;
372 | gbc_button_14.gridy = 7;
373 | panel.add(button_14, gbc_button_14);
374 |
375 | button_3 = new JButton("4");
376 | button_3.addActionListener(new ActionListener() {
377 | public void actionPerformed(ActionEvent e) {
378 | txtOutput.setText(txtOutput.getText() + "4");
379 | }
380 | });
381 | button_3.setFont(new Font("Tahoma", Font.PLAIN, 24));
382 | GridBagConstraints gbc_button_3 = new GridBagConstraints();
383 | gbc_button_3.fill = GridBagConstraints.HORIZONTAL;
384 | gbc_button_3.insets = new Insets(0, 0, 5, 5);
385 | gbc_button_3.gridx = 2;
386 | gbc_button_3.gridy = 8;
387 | panel.add(button_3, gbc_button_3);
388 |
389 | button_4 = new JButton("5");
390 | button_4.addActionListener(new ActionListener() {
391 | public void actionPerformed(ActionEvent e) {
392 | txtOutput.setText(txtOutput.getText() + "5");
393 | }
394 | });
395 | button_4.setFont(new Font("Tahoma", Font.PLAIN, 24));
396 | GridBagConstraints gbc_button_4 = new GridBagConstraints();
397 | gbc_button_4.fill = GridBagConstraints.HORIZONTAL;
398 | gbc_button_4.insets = new Insets(0, 0, 5, 5);
399 | gbc_button_4.gridx = 3;
400 | gbc_button_4.gridy = 8;
401 | panel.add(button_4, gbc_button_4);
402 |
403 | button_5 = new JButton("6");
404 | button_5.addActionListener(new ActionListener() {
405 | public void actionPerformed(ActionEvent e) {
406 | txtOutput.setText(txtOutput.getText() + "6");
407 | }
408 | });
409 | button_5.setFont(new Font("Tahoma", Font.PLAIN, 24));
410 | GridBagConstraints gbc_button_5 = new GridBagConstraints();
411 | gbc_button_5.fill = GridBagConstraints.HORIZONTAL;
412 | gbc_button_5.insets = new Insets(0, 0, 5, 5);
413 | gbc_button_5.gridx = 4;
414 | gbc_button_5.gridy = 8;
415 | panel.add(button_5, gbc_button_5);
416 |
417 | button_13 = new JButton("-");
418 | button_13.addActionListener(new ActionListener() {
419 | public void actionPerformed(ActionEvent e) {
420 | operator = 1;
421 | number1 = Double.parseDouble(txtOutput.getText());
422 | txtOutput.setText("");
423 | }
424 | });
425 | button_13.setFont(new Font("Tahoma", Font.PLAIN, 24));
426 | GridBagConstraints gbc_button_13 = new GridBagConstraints();
427 | gbc_button_13.fill = GridBagConstraints.HORIZONTAL;
428 | gbc_button_13.insets = new Insets(0, 0, 5, 5);
429 | gbc_button_13.gridx = 7;
430 | gbc_button_13.gridy = 8;
431 | panel.add(button_13, gbc_button_13);
432 |
433 | button_6 = new JButton("1");
434 | button_6.addActionListener(new ActionListener() {
435 | public void actionPerformed(ActionEvent e) {
436 | txtOutput.setText(txtOutput.getText() + "1");
437 | }
438 | });
439 | button_6.setFont(new Font("Tahoma", Font.PLAIN, 24));
440 | GridBagConstraints gbc_button_6 = new GridBagConstraints();
441 | gbc_button_6.fill = GridBagConstraints.HORIZONTAL;
442 | gbc_button_6.insets = new Insets(0, 0, 5, 5);
443 | gbc_button_6.gridx = 2;
444 | gbc_button_6.gridy = 9;
445 | panel.add(button_6, gbc_button_6);
446 |
447 | button_7 = new JButton("2");
448 | button_7.addActionListener(new ActionListener() {
449 | public void actionPerformed(ActionEvent e) {
450 | txtOutput.setText(txtOutput.getText() + "2");
451 | }
452 | });
453 | button_7.setFont(new Font("Tahoma", Font.PLAIN, 24));
454 | GridBagConstraints gbc_button_7 = new GridBagConstraints();
455 | gbc_button_7.fill = GridBagConstraints.HORIZONTAL;
456 | gbc_button_7.insets = new Insets(0, 0, 5, 5);
457 | gbc_button_7.gridx = 3;
458 | gbc_button_7.gridy = 9;
459 | panel.add(button_7, gbc_button_7);
460 |
461 | button_8 = new JButton("3");
462 | button_8.addActionListener(new ActionListener() {
463 | public void actionPerformed(ActionEvent e) {
464 | txtOutput.setText(txtOutput.getText() + "3");
465 | }
466 | });
467 | button_8.setFont(new Font("Tahoma", Font.PLAIN, 24));
468 | GridBagConstraints gbc_button_8 = new GridBagConstraints();
469 | gbc_button_8.fill = GridBagConstraints.HORIZONTAL;
470 | gbc_button_8.insets = new Insets(0, 0, 5, 5);
471 | gbc_button_8.gridx = 4;
472 | gbc_button_8.gridy = 9;
473 | panel.add(button_8, gbc_button_8);
474 |
475 | btnX = new JButton("x");
476 | btnX.addActionListener(new ActionListener() {
477 | public void actionPerformed(ActionEvent e) {
478 | operator = 2;
479 | number1 = Double.parseDouble(txtOutput.getText());
480 | txtOutput.setText("");
481 | }
482 | });
483 | btnX.setFont(new Font("Tahoma", Font.PLAIN, 24));
484 | GridBagConstraints gbc_btnX = new GridBagConstraints();
485 | gbc_btnX.fill = GridBagConstraints.HORIZONTAL;
486 | gbc_btnX.insets = new Insets(0, 0, 5, 5);
487 | gbc_btnX.gridx = 7;
488 | gbc_btnX.gridy = 9;
489 | panel.add(btnX, gbc_btnX);
490 |
491 | button_9 = new JButton("0");
492 | button_9.addActionListener(new ActionListener() {
493 | public void actionPerformed(ActionEvent e) {
494 | txtOutput.setText(txtOutput.getText() + "0");
495 | }
496 | });
497 | button_9.setFont(new Font("Tahoma", Font.PLAIN, 24));
498 | GridBagConstraints gbc_button_9 = new GridBagConstraints();
499 | gbc_button_9.fill = GridBagConstraints.HORIZONTAL;
500 | gbc_button_9.insets = new Insets(0, 0, 5, 5);
501 | gbc_button_9.gridx = 2;
502 | gbc_button_9.gridy = 10;
503 | panel.add(button_9, gbc_button_9);
504 |
505 | button_10 = new JButton(".");
506 | button_10.addActionListener(new ActionListener() {
507 | public void actionPerformed(ActionEvent e) {
508 | txtOutput.setText(txtOutput.getText() + ".");
509 | }
510 | });
511 | button_10.setFont(new Font("Tahoma", Font.PLAIN, 24));
512 | GridBagConstraints gbc_button_10 = new GridBagConstraints();
513 | gbc_button_10.fill = GridBagConstraints.HORIZONTAL;
514 | gbc_button_10.insets = new Insets(0, 0, 5, 5);
515 | gbc_button_10.gridx = 3;
516 | gbc_button_10.gridy = 10;
517 | panel.add(button_10, gbc_button_10);
518 |
519 | button_11 = new JButton("=");
520 | button_11.addActionListener(new ActionListener() {
521 | public void actionPerformed(ActionEvent e) {
522 | // Read number 2:
523 | number2 = Double.parseDouble(txtOutput.getText());
524 | // Result variable
525 | double result = 0.0;
526 |
527 | // Compute the result based on the operator:
528 | switch (operator) {
529 | case 0: result = number1 + number2; break;
530 | case 1: result = number1 - number2; break;
531 | case 2: result = number1 * number2; break;
532 | case 3: result = number1 / number2; break;
533 |
534 | default: result = 0.0; break;
535 | }
536 |
537 | // Special Functions
538 | if(operator == 4)result = Math.pow(number1, number2);
539 |
540 | // Save the result to the output
541 | txtOutput.setText("" + result);
542 | }
543 | });
544 | button_11.setFont(new Font("Tahoma", Font.PLAIN, 24));
545 | GridBagConstraints gbc_button_11 = new GridBagConstraints();
546 | gbc_button_11.fill = GridBagConstraints.HORIZONTAL;
547 | gbc_button_11.gridwidth = 3;
548 | gbc_button_11.insets = new Insets(0, 0, 5, 5);
549 | gbc_button_11.gridx = 4;
550 | gbc_button_11.gridy = 10;
551 | panel.add(button_11, gbc_button_11);
552 |
553 | button_12 = new JButton("/");
554 | button_12.addActionListener(new ActionListener() {
555 | public void actionPerformed(ActionEvent e) {
556 | operator = 3;
557 | number1 = Double.parseDouble(txtOutput.getText());
558 | txtOutput.setText("");
559 | }
560 | });
561 | button_12.setFont(new Font("Tahoma", Font.PLAIN, 24));
562 | GridBagConstraints gbc_button_12 = new GridBagConstraints();
563 | gbc_button_12.fill = GridBagConstraints.HORIZONTAL;
564 | gbc_button_12.insets = new Insets(0, 0, 5, 5);
565 | gbc_button_12.gridx = 7;
566 | gbc_button_12.gridy = 10;
567 | panel.add(button_12, gbc_button_12);
568 | }
569 |
570 | }
571 |
--------------------------------------------------------------------------------
/Chapter 7/Listing 7.0.java:
--------------------------------------------------------------------------------
1 | package calculator;
2 |
3 | import java.awt.EventQueue;
4 |
5 | import javax.swing.JFrame;
6 |
7 | public class MainWindow {
8 |
9 | private JFrame frame;
10 |
11 | /**
12 | * Launch the application.
13 | */
14 | public static void main(String[] args) {
15 | EventQueue.invokeLater(new Runnable() {
16 | public void run() {
17 | try {
18 | MainWindow window = new MainWindow();
19 | window.frame.setVisible(true);
20 | } catch (Exception e) {
21 | e.printStackTrace();
22 | }
23 | }
24 | });
25 | }
26 |
27 | /**
28 | * Create the application.
29 | */
30 | public MainWindow() {
31 | initialize();
32 | }
33 |
34 | /**
35 | * Initialize the contents of the frame.
36 | */
37 | private void initialize() {
38 | frame = new JFrame();
39 | frame.setBounds(100, 100, 450, 300);
40 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/Chapter 7/Listing 7.1.java:
--------------------------------------------------------------------------------
1 | private JButton btnF_15;
2 | private JButton btnF_16;
3 | private JButton btnF_17;
4 |
5 | // State variables
6 | private int state = 0; // 0 to for first number, 1 for second
7 | private int operator = 0; // 0 means unknown
8 | private double number1 = 0.0; // Variable for parsing 1st operand
9 | private double number2 = 0.0; // Variable for parsing 2nd operand
10 | private double[] memory = new double[5]; // For memory functions
11 |
12 | /**
13 | * Launch the application.
14 | */
15 | public static void main(String[] args) {
16 | EventQueue.invokeLater(new Runnable() {
17 | public void run() {
18 | try {
19 | MainWindow window = new MainWindow();
20 | window.frame.setVisible(true);
21 | } catch (Exception e) {
22 | e.printStackTrace();
23 | }
24 | }
25 | });
26 | }
27 |
--------------------------------------------------------------------------------
/Chapter 7/Listing 7.10.java:
--------------------------------------------------------------------------------
1 | btnF_12 = new JButton("M0");
2 | btnF_12.addActionListener(new ActionListener() {
3 | public void actionPerformed(ActionEvent e) {
4 | if(operator == 5)
5 | memory[0] = number1;
6 | else
7 | txtOutput.setText("" + memory[0]);
8 | }
9 | });
10 |
--------------------------------------------------------------------------------
/Chapter 7/Listing 7.2.java:
--------------------------------------------------------------------------------
1 | button = new JButton("7");
2 | button.addActionListener(new ActionListener() {
3 | public void actionPerformed(ActionEvent arg0) {
4 | txtOutput.setText(txtOutput.getText() + "7");
5 | }
6 | });
7 |
--------------------------------------------------------------------------------
/Chapter 7/Listing 7.3.java:
--------------------------------------------------------------------------------
1 | button_14 = new JButton("+");
2 | button_14.addActionListener(new ActionListener() {
3 | public void actionPerformed(ActionEvent e) {
4 | operator = 0;
5 | number1 = Double.parseDouble(txtOutput.getText());
6 | txtOutput.setText("");
7 | }
8 | });
9 |
--------------------------------------------------------------------------------
/Chapter 7/Listing 7.4.java:
--------------------------------------------------------------------------------
1 | button_11 = new JButton("=");
2 | button_11.addActionListener(new ActionListener() {
3 | public void actionPerformed(ActionEvent e) {
4 | // Read number 2:
5 | number2 = Double.parseDouble(txtOutput.getText());
6 |
7 | // Result variable
8 | double result = 0.0;
9 |
10 | // Compute the result based on the operator:
11 | switch (operator) {
12 | case 0: result = number1 + number2; break;
13 | case 1: result = number1 - number2; break;
14 | case 2: result = number1 * number2; break;
15 | case 3: result = number1 / number2; break;
16 |
17 | default: result = 0.0; break;
18 | }
19 |
20 | // Save the result to the output
21 | txtOutput.setText("" + result);
22 | }
23 | });
24 |
--------------------------------------------------------------------------------
/Chapter 7/Listing 7.5.java:
--------------------------------------------------------------------------------
1 | btnF_17 = new JButton("C");
2 | btnF_17.addActionListener(new ActionListener() {
3 | public void actionPerformed(ActionEvent arg0) {
4 | txtOutput.setText("");
5 | operator = -1;
6 | }
7 | });
8 |
--------------------------------------------------------------------------------
/Chapter 7/Listing 7.6.java:
--------------------------------------------------------------------------------
1 | btnF = new JButton("SIN");
2 | btnF.setToolTipText("Compute the Sine of an angle");
3 | btnF.addActionListener(new ActionListener() {
4 | public void actionPerformed(ActionEvent e) {
5 | number1 = Double.parseDouble(txtOutput.getText());
6 | number1 = Math.sin(number1);
7 | txtOutput.setText("" + number1);
8 | }
9 | });
10 |
--------------------------------------------------------------------------------
/Chapter 7/Listing 7.7.java:
--------------------------------------------------------------------------------
1 | btnF = new JButton("SIN");
2 | btnF_3 = new JButton("^");
3 | btnF_3.addActionListener(new ActionListener() {
4 | public void actionPerformed(ActionEvent arg0) {
5 | operator = 4; // 4 is power
6 | number1 = Double.parseDouble(txtOutput.getText());
7 | txtOutput.setText("");
8 | }
9 | });
10 |
--------------------------------------------------------------------------------
/Chapter 7/Listing 7.8.java:
--------------------------------------------------------------------------------
1 | button_11 = new JButton("=");
2 | button_11.addActionListener(new ActionListener() {
3 | public void actionPerformed(ActionEvent e) {
4 | // Read number 2:
5 | number2 = Double.parseDouble(txtOutput.getText());
6 | // Result variable
7 | double result = 0.0;
8 |
9 | // Compute the result based on the operator:
10 | switch (operator) {
11 | case 0: result = number1 + number2; break;
12 | case 1: result = number1 - number2; break;
13 | case 2: result = number1 * number2; break;
14 | case 3: result = number1 / number2; break;
15 |
16 | default: result = 0.0; break;
17 | }
18 |
19 | // Special Functions
20 | if(operator == 4)result = Math.pow(number1, number2);
21 |
22 | // Save the result to the output
23 | txtOutput.setText("" + result);
24 | }
25 | });
26 |
--------------------------------------------------------------------------------
/Chapter 7/Listing 7.9.java:
--------------------------------------------------------------------------------
1 | btnF_5 = new JButton("STR");
2 | btnF_5.addActionListener(new ActionListener() {
3 | public void actionPerformed(ActionEvent e) {
4 | operator = 5;
5 | number1 = Double.parseDouble(txtOutput.getText());
6 | }
7 | });
8 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.0.java:
--------------------------------------------------------------------------------
1 | import java.awt.EventQueue;
2 | import javax.swing.JFrame;
3 |
4 | public class MainClass extends JFrame {
5 | public static void main(String[] args) {
6 | EventQueue.invokeLater(new Runnable() {
7 | @Override
8 | public void run() {
9 | MainClass m = new MainClass(640, 480);
10 | }
11 | });
12 | }
13 |
14 | private MainClass(int windowWidth, int windowHeight) {
15 | setSize(windowWidth, windowHeight); // Set window size
16 | setLocationRelativeTo(null); // Default location
17 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit on close
18 | setVisible(true);
19 | // Create and add the engine JPanel:
20 | final Engine2D engine = new Engine2D(windowWidth, windowHeight, 30);
21 | add(engine);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.1.java:
--------------------------------------------------------------------------------
1 | import java.awt.Color;
2 | import java.awt.Graphics;
3 | import java.awt.Graphics2D;
4 | import java.awt.event.ActionEvent;
5 | import java.awt.event.ActionListener;
6 | import javax.swing.JPanel;
7 | import javax.swing.Timer;
8 |
9 | public class Engine2D extends JPanel implements ActionListener {
10 | // Width and height of the window
11 | private int width, height;
12 |
13 | // Constructor
14 | public Engine2D(int windowWidth, int windowHeight, int fps) {
15 | width = windowWidth;
16 | height = windowHeight;
17 | Timer timer = new Timer(1000/fps, this);
18 | timer.start();
19 | }
20 |
21 | // This event is called when the timer fires at the specified fps
22 | public void actionPerformed(ActionEvent e) {
23 | update(0.0, 0.0);
24 | repaint();
25 | }
26 |
27 | //
28 | public void paintComponent(Graphics g) {
29 | super.paintComponent(g);
30 | render((Graphics2D) g);
31 | }
32 |
33 | private void update(double timeTotal, double timeDelta) {
34 | }
35 |
36 | private void render(Graphics2D g) {
37 | // Clear the screen to blue
38 | g.setBackground(Color.DARK_GRAY);
39 | g.clearRect(0, 0, width, height);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.10.java:
--------------------------------------------------------------------------------
1 | public class Animation {
2 | private double speed, startTime;
3 | private int firstFrame, frameCount;
4 | private int currentFrame;
5 | private boolean isComplete = false;
6 | private boolean looping;
7 |
8 | // Constructor for looping/multiframe animation
9 | public Animation(double speed, double startTime, int firstFrame,
10 | int frameCount, boolean looping) {
11 | this.speed = speed;
12 | this.startTime = startTime;
13 | this.firstFrame = firstFrame;
14 | this.frameCount = frameCount;
15 |
16 | // Reset
17 | currentFrame = firstFrame;
18 | isComplete = false;
19 | this.looping = looping;
20 | }
21 |
22 | // Constructor for single frame animation
23 | public Animation(int frame) {
24 | speed = 1.0;
25 | startTime = 0.0;
26 | firstFrame = frame;
27 | frameCount = 1;
28 | // Reset
29 | currentFrame = firstFrame;
30 | isComplete = false;
31 | this.looping = true;
32 | }
33 |
34 | // Compute the current frame and the
35 | // isComplete boolean
36 | public void update(double timeTotal) {
37 | double elapsedTime = timeTotal - startTime;
38 | currentFrame = (int)(elapsedTime / speed);
39 |
40 | if(currentFrame < 0) currentFrame = 0;
41 |
42 | // If the frame is past the end of the animation,
43 | // set it to the last frame
44 | if(currentFrame >= frameCount) {
45 | // If the animation does not loop, set it to the final
46 | // frame indefinitely
47 | if(!looping)
48 | currentFrame = firstFrame + frameCount - 1;
49 | // If the animation is looping,
50 | // set it back to the first frame
51 | else {
52 | currentFrame = firstFrame;
53 | startTime = timeTotal;
54 | }
55 |
56 | isComplete = true;
57 | }
58 |
59 | // Otherwise, the current frame is the first frame +
60 | // however many frames we've played so far:
61 | else
62 | currentFrame += firstFrame;
63 | }
64 |
65 | // Returns the current frame
66 | public int getCurrentFrame() {
67 | return currentFrame;
68 | }
69 |
70 | // Determines if the animation has played all frames
71 | public boolean getIsComplete() {
72 | return isComplete;
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.11.java:
--------------------------------------------------------------------------------
1 | import java.awt.Graphics2D;
2 | public abstract class GameObject {
3 | // Position
4 | public double x, y;
5 |
6 | // Is the object visible?
7 | private boolean visible = true;
8 |
9 | // The object's animation
10 | private Animation animation = null;
11 |
12 | // Abstract Update and Render
13 | public void update(double timeTotal, double timeDelta) {
14 | if(animation != null)
15 | animation.update(timeTotal);
16 | }
17 |
18 | // Render the animation with the current frame if it exists and
19 | // is visible
20 | public void render(Graphics2D graphics, SpriteSheet sprites) {
21 | if(visible && animation != null)
22 | sprites.render(graphics, animation.getCurrentFrame(),
23 | (int)x, (int)y);
24 | }
25 |
26 | // Getters and setters
27 | public double getX() {
28 | return x;
29 | }
30 |
31 | public double getY() {
32 | return y;
33 | }
34 |
35 | public boolean getVisible() {
36 | return visible;
37 | }
38 |
39 | public void setVisible(boolean visible) {
40 | this.visible = visible;
41 | }
42 |
43 | public Animation getAnimation() {
44 | return animation;
45 | }
46 |
47 | public void setAnimation(Animation animation) {
48 | this.animation = animation;
49 | }
50 |
51 | // Location tests:
52 | // Test if the object is outside the screen to the left
53 | public boolean isOffScreenLeft() {
54 | return x < -16;
55 | }
56 | // Test if the object is outside the screen to the right
57 | public boolean isOffScreenRight() {
58 | return x >= 320;
59 | }
60 | // Test if the object is outside the screen at the top
61 | public boolean isOffScreenTop() {
62 | return y < -16;
63 | }
64 | // Test is the object is outside the screen at the bottom
65 | public boolean isOffScreenBottom() {
66 | return y >= 240;
67 | }
68 |
69 | // Compute the distance between the objects
70 | public double getDistance(GameObject o) {
71 | // Faster, but less accurate detection:
72 | // return Math.abs(o.x - x) + Math.abs(o.y - y);
73 |
74 | // More accurate, but slow version:
75 | return Math.sqrt((o.x - x) * (o.x - x) +
76 | (o.y - y) * (o.y - y));
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.12.java:
--------------------------------------------------------------------------------
1 | import java.awt.Graphics2D;
2 |
3 | public class Star extends GameObject {
4 | double speed;
5 |
6 | public Star() {
7 | // Begin the stars in a random location:
8 | x = Math.random() * 320.0;
9 | y = Math.random() * 240.0;
10 |
11 | // Set the stars to a random speed:
12 | speed = Math.random() * 30.0 + 30;
13 | }
14 |
15 | public void update(double timeTotal, double timeDelta) {
16 | // Call the parent update
17 | super.update(timeTotal, timeDelta);
18 |
19 | // Move the star left
20 | x -= speed * timeDelta;
21 |
22 | // Reset the star on the right when it goes off screen
23 | if(isOffScreenLeft()) {
24 | x = 320.0; // Just outside the right-hand edge
25 | y = Math.random() * 240.0 - 16; // Random Y location
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.13.java:
--------------------------------------------------------------------------------
1 | // The GameObjects array list:
2 | ArrayList gameObjects = new ArrayList();
3 |
4 | // Constructor
5 | public Engine2D(int windowWidth, int windowHeight, int fps) {
6 | width = windowWidth;
7 | height = windowHeight;
8 |
9 | // Load the sprites
10 | sprites = new SpriteSheet("graphics/spaceracer.png", 32, 32);
11 |
12 | // Create 100 stars
13 | for(int i = 0; i < 100; i++) {
14 | Star s = new Star();
15 | s.setAnimation(new Animation(Math.random() * 2 + 0.2, Math.random(), 5, 3, true));
16 | gameObjects.add(s);
17 | }
18 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.14.java:
--------------------------------------------------------------------------------
1 | private void update(double timeTotal, double timeDelta) {
2 | // Update the game objects:
3 | for(GameObject o: gameObjects)
4 | o.update(timeTotal, timeDelta);
5 | }
6 |
7 | private void render(Graphics2D g) {
8 | // Clear the screen to blue
9 | g.setBackground(Color.DARK_GRAY);
10 | g.clearRect(0, 0, width, height);
11 |
12 | // Render the game objects:
13 | for(GameObject o: gameObjects)
14 | o.render(g, sprites);
15 | }
16 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.15.java:
--------------------------------------------------------------------------------
1 | import java.awt.Graphics2D;
2 |
3 | public class Wall extends GameObject {
4 | public Wall(double x, double y) {
5 | this.x = x;
6 | this.y = y;
7 |
8 | this.setAnimation(new Animation(4));
9 | }
10 |
11 | // Move the wall to the left
12 | public void update(double timeTotal, double timeDelta) {
13 | super.update(timeTotal, timeDelta);
14 |
15 | x -= 80 * timeDelta;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.16.java:
--------------------------------------------------------------------------------
1 | // The GameObjects array list:
2 | ArrayList gameObjects = new ArrayList();
3 |
4 | // Wall variables
5 | double nextWallGenerationTime = 1.0;
6 | Random wallRNG = new Random(); // Any argument will
7 | // cause walls to be generated with the same pattern
8 | // every time!
9 |
10 | // Constructor
11 | public Engine2D(int windowWidth, int windowHeight, int fps) {
12 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.17.java:
--------------------------------------------------------------------------------
1 | private void update(double timeTotal, double timeDelta) {
2 | // Generate new walls:
3 | if(timeTotal >= nextWallGenerationTime) {
4 | // Add 0.5 seconds to the wall generation time
5 | nextWallGenerationTime += 0.5;
6 | for(int i = 0; i < 14; i++) {
7 | if(wallRNG.nextInt(3) == 0) {
8 | gameObjects.add(new Wall(640, i * 32));
9 | }
10 | }
11 | }
12 |
13 | for(int i = 0; i < gameObjects.size(); i++) {
14 | GameObject o = gameObjects.get(i);
15 | o.update(timeTotal, timeDelta);
16 |
17 | // If the object is a wall:
18 | if(o instanceof Wall) {
19 | if(o.isOffScreenLeft()) {
20 | // Delete as they go off the screen to the left
21 | gameObjects.remove(i);
22 | i--;
23 | continue;
24 | }
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.18.java:
--------------------------------------------------------------------------------
1 | import java.awt.Graphics2D;
2 | import java.util.Random;
3 |
4 | public class Baddie extends GameObject {
5 | private double startY;
6 |
7 | private double frequency;
8 | private double amplitude;
9 |
10 | // Constructor
11 | public Baddie(double x, double y) {
12 | this.x = x;
13 | this.y = y;
14 |
15 | startY = y;
16 |
17 | // Create random frequency and amplitude
18 | Random r = new Random();
19 | frequency = r.nextDouble() * 2.0 + 2.0;
20 | amplitude = r.nextDouble() * 45 + 45;
21 |
22 | // Set the animation:
23 | this.setAnimation(new Animation(2));
24 | }
25 |
26 | // Move the baddie to the left
27 | public void update(double timeTotal, double timeDelta) {
28 | super.update(timeTotal, timeDelta);
29 |
30 | x -= 60 * timeDelta;
31 |
32 | y = startY + (Math.sin(timeTotal * frequency) * amplitude);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.19.java:
--------------------------------------------------------------------------------
1 | // Wall variables
2 | double nextWallGenerationTime = 1.0;
3 | Random wallRNG = new Random(); // Any argument will
4 | // cause walls to be generated with the same pattern
5 | // every time!
6 |
7 | // Baddie variables
8 | double nextBaddieGenerationTime = 2.0;
9 | Random baddieRNG = new Random();
10 |
11 | // Constructor
12 | public Engine2D(int windowWidth, int windowHeight, int fps) {
13 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.2.java:
--------------------------------------------------------------------------------
1 | import java.awt.Graphics2D;
2 | import java.awt.image.BufferedImage;
3 | import java.io.File;
4 | import java.io.IOException;
5 | import javax.imageio.ImageIO;
6 |
7 | public class SpriteSheet {
8 |
9 | private BufferedImage bmp; // The loaded image
10 | private int spritesAcross = -1;// Number of sprites across the image
11 | private int totalSprites; // Total sprites in the image
12 | private int spriteWidth, spriteHeight;// width/height of each sprite
13 |
14 | // Constructor
15 | public SpriteSheet(String filename,int spriteWidth,int spriteHeight) {
16 | // Load the bitmap
17 | try {
18 | bmp = ImageIO.read(new File(filename));
19 | }
20 | catch(IOException e) {
21 | // File not found
22 | spritesAcross = -1;
23 | return;
24 | }
25 | // Save the sprite width and height
26 | this.spriteWidth = spriteWidth;
27 | this.spriteHeight = spriteHeight;
28 | // spritesAcross is used to compute the
29 | // source rectangles when rendering
30 | spritesAcross = bmp.getWidth() / this.spriteWidth;
31 | // totalSprites is used to ensure we're not
32 | // trying to render sprites which do not exist
33 | totalSprites = spritesAcross * (bmp.getHeight() / spriteHeight);
34 | }
35 |
36 | // This method can be used to test if the sprites loaded
37 | public Boolean isValid() {
38 | return spritesAcross != -1;
39 | }
40 |
41 | public void render(Graphics2D g, int spriteIndex, int x, int y) {
42 | // Make sure the sprite is actually on our spriteSheet
43 | if(spriteIndex >= totalSprites) return;
44 | // Compute the source x and y
45 | int srcX = (spriteIndex % spritesAcross) * spriteWidth;
46 | int srcY = (spriteIndex / spritesAcross) * spriteHeight;
47 | // Draw the image
48 | g.drawImage(bmp,
49 | x, // Destination x1
50 | y, // Destination y1
51 | x + spriteWidth, // Destination x2
52 | y + spriteHeight, // Destination y2
53 | srcX, // Source x1
54 | srcY, // Source y1
55 | srcX + spriteWidth, // Source x2
56 | srcY + spriteHeight,// Source y2
57 | null); // Observer
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.20.java:
--------------------------------------------------------------------------------
1 | private void update(double timeTotal, double timeDelta) {
2 | // Generate new walls:
3 | if(timeTotal >= nextWallGenerationTime) {
4 | // Add 0.5 second to the wall generation time
5 | nextWallGenerationTime += 0.5;
6 |
7 | for(int i = 0; i < 14; i++) {
8 | if(wallRNG.nextInt(3) == 0) {
9 | gameObjects.add(new Wall(320, i * 32));
10 | }
11 | }
12 | }
13 |
14 | // Generate new Baddies
15 | if(timeTotal >= nextBaddieGenerationTime) {
16 | // Death wave:
17 | //nextBaddieGenerationTime += baddieRNG.nextDouble() * 0.2 + 0.1;
18 | // Normal wave:
19 | nextBaddieGenerationTime += baddieRNG.nextDouble() * 4.0 + 0.5;
20 |
21 | gameObjects.add(new Baddie(320,baddieRNG.nextInt(280)-40));
22 | }
23 |
24 | for(int i = 0; i < gameObjects.size(); i++) {
25 | GameObject o = gameObjects.get(i);
26 | o.update(timeTotal, timeDelta);
27 |
28 | // If the object is a wall, or a baddie:
29 | if(o instanceof Wall || o instanceof Baddie) {
30 | if(o.isOffScreenLeft()) {
31 | // Delete if they go off the screen to the left
32 | gameObjects.remove(i);
33 | i--;
34 | continue;
35 | }
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.21.java:
--------------------------------------------------------------------------------
1 | import java.awt.event.KeyEvent;
2 | import java.awt.event.KeyListener;
3 |
4 | public class Keyboard implements KeyListener {
5 | // 256 key states: true means the key is down
6 | // false means the key is up
7 | private boolean[] keyStates = null;
8 |
9 | // The only instance of this class is the following
10 | // private, static instance:
11 | private static Keyboard staticInstance = null;
12 |
13 | // Private Constructor:
14 | private Keyboard() {
15 | keyStates = new boolean[256];
16 | }
17 |
18 | // Public init method which creates the
19 | // static key states if they do not exist
20 | public static void init() {
21 | staticInstance = new Keyboard();
22 |
23 | reset();
24 | }
25 |
26 | public static Keyboard getInstance() {
27 | return staticInstance;
28 | }
29 |
30 | // Set all key states to false
31 | public static void reset() {
32 | for(int i = 0; i < 256; i++)
33 | staticInstance.keyStates[i] = false;
34 | }
35 |
36 | // Test if a key is down
37 | public static boolean isKeyDown(int keyCode) {
38 | return staticInstance.keyStates[keyCode & 255];
39 | }
40 |
41 | // Set a key to down; true
42 | public void keyPressed(KeyEvent e) {
43 | staticInstance.keyStates[e.getKeyCode() & 255] = true;
44 | }
45 |
46 | // Set a key to up; false
47 | public void keyReleased(KeyEvent e) {
48 | staticInstance.keyStates[e.getKeyCode() & 255] = false;
49 | }
50 |
51 | // Extra, unused method from KeyListener interface
52 | public void keyTyped(KeyEvent e) { }
53 | }
54 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.22.java:
--------------------------------------------------------------------------------
1 | private MainClass(int windowWidth, int windowHeight) {
2 | setSize(windowWidth, windowHeight); // Set window size
3 | setLocationRelativeTo(null); // Default location
4 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit on close
5 | setVisible(true);
6 |
7 | // Init the static singleton keyboard:
8 | Keyboard.init();
9 |
10 | // Add a keylistener
11 | addKeyListener(Keyboard.getInstance());
12 |
13 |
14 | // Create and add the engine JPanel:
15 | final Engine2D engine = new Engine2D(windowWidth, windowHeight, 30);
16 | add(engine);
17 | }
18 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.23.java:
--------------------------------------------------------------------------------
1 | public class Player extends GameObject {
2 | double shipSpeed = 320.0;
3 |
4 | public Player(double x, double y) {
5 | // Set the x/y
6 | this.x = x; this.y = y;
7 |
8 | // Set the animation
9 | this.setAnimation(new Animation(0.1, 0.0, 0, 2, true));
10 | }
11 |
12 | public void update(double timeTotal, double timeDelta) {
13 | // Call parent's update:
14 | super.update(timeTotal, timeDelta);
15 |
16 | //Up/Down
17 | if(Keyboard.isKeyDown(40)) y += shipSpeed * timeDelta;
18 | if(Keyboard.isKeyDown(38)) y -= shipSpeed * timeDelta;
19 |
20 | // Left/Right
21 | if(Keyboard.isKeyDown(37)) x -= shipSpeed * timeDelta;
22 | if(Keyboard.isKeyDown(39)) x += shipSpeed * timeDelta;
23 |
24 | // Make sure the player is on the screen:
25 | if(x < 0) x = 0;
26 | if(y < 0) y = 0;
27 | if(x > 320 - 32.0) x = 320 - 32.0;
28 | if(y > 240 - 32.0) y = 240 - 32.0;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.24.java:
--------------------------------------------------------------------------------
1 | Random baddieRNG = new Random();
2 |
3 | // Player variables:
4 | Player player;
5 | boolean playerExploded = false;
6 |
7 | // Constructor
8 | public Engine2D(int windowWidth, int windowHeight, int fps) {
9 | width = windowWidth;
10 | height = windowHeight;
11 |
12 | // Load the sprites
13 | sprites = new SpriteSheet("graphics/spaceracer.png", 16, 16);
14 |
15 | // Create 100 stars
16 | for(int i = 0; i < 100; i++) {
17 | Star s = new Star();
18 | s.setAnimation(new Animation(Math.random() * 2 + 0.2, Math.random(), 5, 3, true));
19 | gameObjects.add(s);
20 | }
21 |
22 | // Create the player:
23 | player = new Player(16.0, 100.0);
24 | gameObjects.add(player);
25 |
26 | // Start the HPTimer
27 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.25.java:
--------------------------------------------------------------------------------
1 | private void update(double timeTotal, double timeDelta) {
2 | // Generate new walls:
3 | if(timeTotal >= nextWallGenerationTime) {
4 | nextWallGenerationTime += 0.5;// Add 0.5 second to the wall generation time
5 |
6 | for(int i = 0; i < 14; i++) {
7 | if(wallRNG.nextInt(3) == 0) {
8 | gameObjects.add(new Wall(320, i * 32));
9 | }
10 | }
11 | }
12 |
13 | // Generate new Baddies
14 | if(timeTotal >= nextBaddieGenerationTime) {
15 | // Death wave:
16 | //nextBaddieGenerationTime += baddieRNG.nextDouble() * 0.2 + 0.1;
17 | // Normal wave:
18 | nextBaddieGenerationTime += baddieRNG.nextDouble() * 4.0 + 0.5;
19 |
20 | gameObjects.add(new Baddie(320, baddieRNG.nextInt(280)-40));
21 | }
22 |
23 | for(int i = 0; i < gameObjects.size(); i++) {
24 | GameObject o = gameObjects.get(i);
25 | o.update(timeTotal, timeDelta);
26 |
27 | // If the object is a wall, or a baddie:
28 | if(o instanceof Wall || o instanceof Baddie) {
29 |
30 | // Test if the wall/baddie has hit the player:
31 | if(o.getDistance(player) < 14 && !playerExploded) {
32 | player.setAnimation(new Animation(0.5, hpTimer.timeTotal(), 8, 4, false));
33 | playerExploded = true;
34 | }
35 |
36 | if(o.isOffScreenLeft()) {
37 | // Delete if they go off the screen to the left
38 | gameObjects.remove(i);
39 | i--;
40 | continue;
41 | }
42 | }
43 | }
44 |
45 |
46 | // When the explosion animation for the payer is finished, destroy all walls and baddies
47 | // and reset the player:
48 | if(playerExploded && player.getAnimation().getIsComplete()) {
49 | player.x = 16;
50 | player.y = 100;
51 | playerExploded = false;
52 | player.setAnimation(new Animation(0.1, 0.0, 0, 2, true));
53 | for(int i = 0; i < gameObjects.size(); i++) {
54 | if(gameObjects.get(i) instanceof Wall ||gameObjects.get(i) instanceof Baddie) {
55 | gameObjects.remove(i);
56 | i--;
57 | }
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.26.java:
--------------------------------------------------------------------------------
1 | import java.awt.Graphics2D;
2 |
3 | public class Bullet extends GameObject {
4 |
5 | // Constructor
6 | public Bullet(double x, double y) {
7 | this.x = x;
8 | this.y = y;
9 |
10 | // Set the animation
11 | this.setAnimation(new Animation(3));
12 | }
13 |
14 | // Move the bullet to the right
15 | public void update(double timeTotal, double timeDelta) {
16 | super.update(timeTotal, timeDelta);
17 |
18 | x += 800 * timeDelta;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.27.java:
--------------------------------------------------------------------------------
1 | boolean playerExploded = false;
2 |
3 | // Bullet variables
4 | double lastBulletTime = 0.0;
5 | double bulletCreationSpeed = 0.25; // 4 bullets per second
6 |
7 | // Constructor
8 | public Engine2D(int windowWidth, int windowHeight, int fps) {
9 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.28.java:
--------------------------------------------------------------------------------
1 | // Create bullets
2 | if(Keyboard.isKeyDown(32) &&
3 | hpTimer.timeTotal() - lastBulletTime >
4 | bulletCreationSpeed && !playerExploded) {
5 | gameObjects.add(new Bullet(player.x, player.y));
6 | lastBulletTime = hpTimer.timeTotal();
7 | }
8 |
9 | // When the explosion animation for the payer is finished, destroy all walls and baddies
10 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.29.java:
--------------------------------------------------------------------------------
1 | for(int i = 0; i < gameObjects.size(); i++) {
2 | GameObject o = gameObjects.get(i);
3 | o.update(timeTotal, timeDelta);
4 |
5 | // If this object is a bullet:
6 | if(o instanceof Bullet) {
7 | // Delete the bullet if it goes off the screen
8 | // to the right
9 | if(o.isOffScreenRight()) {
10 | gameObjects.remove(i);
11 | i--;
12 | continue;
13 | }
14 |
15 | // Check all baddies for collisions:
16 | for(int j = 100; j < gameObjects.size(); j++) {
17 | GameObject g = gameObjects.get(j);
18 | // If this is a baddie:
19 | if(g instanceof Baddie) {
20 | // If the baddie has hit the bullet:
21 | if(o.getDistance(g) < 14) {
22 | // Remove the baddie:
23 | gameObjects.remove(j);
24 | j--;
25 | i--;
26 | }
27 | }
28 | }
29 | }
30 |
31 | // If the object is a wall, or a baddie:
32 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.3.java:
--------------------------------------------------------------------------------
1 | // Width and height of the window
2 | private int width, height;
3 |
4 | private SpriteSheet sprites;
5 |
6 | // Constructor
7 | public Engine2D(int windowWidth, int windowHeight, int fps) {
8 | width = windowWidth;
9 | height = windowHeight;
10 |
11 | // Load the sprites:
12 | sprites = new SpriteSheet("graphics/spaceracer.png", 16, 16);
13 |
14 | // Start the render/update loop
15 | Timer timer = new Timer(1000/fps, this);
16 | timer.start();
17 | }
18 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.4.java:
--------------------------------------------------------------------------------
1 | // Temporary test, delete this line after making
2 | // sure the program animates:
3 | static int x = 0;
4 |
5 | private void render(Graphics2D g) {
6 | // Clear the screen to blue
7 | g.setBackground(Color.DARK_GRAY);
8 | g.clearRect(0, 0, width, height);
9 |
10 | // Temporary test:
11 | sprites.render(g, x % 2, x, 0);
12 | x++;
13 | }
14 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.5.java:
--------------------------------------------------------------------------------
1 | public void render(Graphics2D g, int spriteIndex, int x, int y) {
2 | // Make sure the sprite is actually on our spriteSheet
3 | if(spriteIndex >= totalSprites) return;
4 | // Compute the source x and y
5 | int srcX = (spriteIndex % spritesAcross) * spriteWidth;
6 | int srcY = (spriteIndex / spritesAcross) * spriteHeight;
7 | // Draw the image
8 | g.drawImage(bmp,
9 | x*2, // Destination x1
10 | y*2, // Destination y1
11 | (x + spriteWidth)*2, // Destination x2
12 | (y + spriteHeight)*2, // Destination y2
13 | srcX, // Source x1
14 | srcY, // Source y1
15 | srcX + spriteWidth, // Source x2
16 | srcY + spriteHeight,// Source y2
17 | null); // Observer
18 | }
19 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.6.java:
--------------------------------------------------------------------------------
1 | public class HPTimer {
2 | // Member variables
3 | long startTime, lastTime, currentTime;
4 |
5 | // Set the start, last and current times to now:
6 | public void reset() {
7 | startTime = System.currentTimeMillis();
8 |
9 | // You can also use nano time:
10 | //startTime = System.nanoTime();
11 |
12 | lastTime = startTime;
13 | currentTime = startTime;
14 | }
15 |
16 | // Reset teh timer
17 | public void start() {
18 | reset();
19 | }
20 |
21 | // Record the current time
22 | public void update() {
23 | lastTime = currentTime;
24 | currentTime = System.currentTimeMillis();
25 |
26 | // If using nano time:
27 | //currentTime = System.nanoTime();
28 | }
29 |
30 | // Return the time since the last call to update
31 | public double timeDelta() {
32 | double d = (double) currentTime - (double) lastTime;
33 | d /= 1000.0;
34 |
35 | // If using nano time:
36 | // d /= 1000000000.0;
37 | return d;
38 | }
39 |
40 | // Return the time since the last call to reset
41 | public double timeTotal() {
42 | double d = (double) currentTime - (double) startTime;
43 | d /= 1000.0;
44 |
45 | // If using nano time:
46 | //d /= 1000000000.0;
47 | return d;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.7.java:
--------------------------------------------------------------------------------
1 | private SpriteSheet sprites;
2 |
3 | private HPTimer hpTimer;
4 |
5 | // Constructor
6 | public Engine2D(int windowWidth, int windowHeight, int fps) {
7 | width = windowWidth;
8 | height = windowHeight;
9 | // Load the sprites
10 | sprites = new SpriteSheet("graphics/spaceracer.png", 16, 16);
11 |
12 | // Start the HPTimer
13 | hpTimer = new HPTimer();
14 | hpTimer.start();
15 |
16 | // Start the render/update loop
17 | Timer timer = new Timer(1000/fps, this);
18 | timer.start();
19 | }
20 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.8.java:
--------------------------------------------------------------------------------
1 | // This event is called when the timer fires at the specified fps
2 | public void actionPerformed(ActionEvent e) {
3 | // Read the most up-to-date time:
4 | hpTimer.update();
5 |
6 | // Pass HPTimer's times to our update method:
7 | update(hpTimer.timeTotal(), hpTimer.timeDelta());
8 |
9 | repaint();
10 | }
11 |
--------------------------------------------------------------------------------
/Chapter 8/Listing 8.9.java:
--------------------------------------------------------------------------------
1 | // Temporary test, delete this line after making
2 | // sure the program animates:
3 | static double x = 0;
4 |
5 | private void render(Graphics2D g) {
6 | // Clear the screen to blue
7 | g.setBackground(Color.DARK_GRAY);
8 | g.clearRect(0, 0, width, height);
9 |
10 | // Temporary test:
11 | sprites.render(g, (int)x % 2, (int)x, 0);
12 | x+=hpTimer.timeDelta();
13 | }
14 |
--------------------------------------------------------------------------------
/Chapter 8/SpaceRacer/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/Chapter 8/SpaceRacer/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | Graphics2D
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Chapter 8/SpaceRacer/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.8
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.source=1.8
12 |
--------------------------------------------------------------------------------
/Chapter 8/SpaceRacer/graphics/spaceracer.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SyncfusionSuccinctlyE-Books/Java-Succinctly-Part-2/522496f8238a024c63d5bf4f4e692f2b8fb8e4a1/Chapter 8/SpaceRacer/graphics/spaceracer.png
--------------------------------------------------------------------------------
/Chapter 8/SpaceRacer/src/Animation.java:
--------------------------------------------------------------------------------
1 | public class Animation {
2 | private double speed, startTime;
3 | private int firstFrame, frameCount;
4 | private int currentFrame;
5 | private boolean isComplete = false;
6 | private boolean looping;
7 |
8 | // Constructor for looping/multiframe animation
9 | public Animation(double speed, double startTime, int firstFrame,
10 | int frameCount, boolean looping) {
11 | this.speed = speed;
12 | this.startTime = startTime;
13 | this.firstFrame = firstFrame;
14 | this.frameCount = frameCount;
15 |
16 | // Reset
17 | currentFrame = firstFrame;
18 | isComplete = false;
19 | this.looping = looping;
20 | }
21 |
22 | // Constructor for single frame animation
23 | public Animation(int frame) {
24 | speed = 1.0;
25 | startTime = 0.0;
26 | firstFrame = frame;
27 | frameCount = 1;
28 | // Reset
29 | currentFrame = firstFrame;
30 | isComplete = false;
31 | this.looping = true;
32 | }
33 |
34 | // Compute the current frame and the
35 | // isComplete boolean
36 | public void update(double timeTotal) {
37 | double elapsedTime = timeTotal - startTime;
38 | currentFrame = (int)(elapsedTime / speed);
39 |
40 | if(currentFrame < 0) currentFrame = 0;
41 |
42 | // If the frame is past the end of the animation,
43 | // set it to the last frame
44 | if(currentFrame >= frameCount) {
45 | // If the animation does not loop, set it to the final
46 | // frame indefinitely
47 | if(!looping)
48 | currentFrame = firstFrame + frameCount - 1;
49 | // If the animation is looping,
50 | // set it back to the first frame
51 | else {
52 | currentFrame = firstFrame;
53 | startTime = timeTotal;
54 | }
55 |
56 | isComplete = true;
57 | }
58 |
59 | // Otherwise, the current frame is the first frame +
60 | // however many frames we've played so far:
61 | else
62 | currentFrame += firstFrame;
63 | }
64 |
65 | // Returns the current frame
66 | public int getCurrentFrame() {
67 | return currentFrame;
68 | }
69 |
70 | // Determines if the animation has played all frames
71 | public boolean getIsComplete() {
72 | return isComplete;
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/Chapter 8/SpaceRacer/src/Baddie.java:
--------------------------------------------------------------------------------
1 | import java.awt.Graphics2D;
2 | import java.util.Random;
3 |
4 | public class Baddie extends GameObject {
5 | private double startY;
6 |
7 | private double frequency;
8 | private double amplitude;
9 |
10 | // Constructor
11 | public Baddie(double x, double y) {
12 | this.x = x;
13 | this.y = y;
14 |
15 | startY = y;
16 |
17 | // Create random frequency and amplitude
18 | Random r = new Random();
19 | frequency = r.nextDouble() * 2.0 + 2.0;
20 | amplitude = r.nextDouble() * 45 + 45;
21 |
22 | // Set the animation:
23 | this.setAnimation(new Animation(2));
24 | }
25 |
26 | // Move the baddie to the left
27 | public void update(double timeTotal, double timeDelta) {
28 | super.update(timeTotal, timeDelta);
29 |
30 | x -= 60 * timeDelta;
31 |
32 | y = startY + (Math.sin(timeTotal * frequency) * amplitude);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Chapter 8/SpaceRacer/src/Bullet.java:
--------------------------------------------------------------------------------
1 | import java.awt.Graphics2D;
2 |
3 | public class Bullet extends GameObject {
4 |
5 | // Constructor
6 | public Bullet(double x, double y) {
7 | this.x = x;
8 | this.y = y;
9 |
10 | // Set the animation
11 | this.setAnimation(new Animation(3));
12 | }
13 |
14 | // Move the bullet to the right
15 | public void update(double timeTotal, double timeDelta) {
16 | super.update(timeTotal, timeDelta);
17 |
18 | x += 800 * timeDelta;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Chapter 8/SpaceRacer/src/Engine2D.java:
--------------------------------------------------------------------------------
1 | import java.awt.Color;
2 | import java.awt.Graphics;
3 | import java.awt.Graphics2D;
4 | import java.awt.event.ActionEvent;
5 | import java.awt.event.ActionListener;
6 | import java.util.ArrayList;
7 | import java.util.Random;
8 |
9 | import javax.swing.JPanel;
10 | import javax.swing.Timer;
11 |
12 | public class Engine2D extends JPanel implements ActionListener {
13 | // Width and height of the window
14 | private int width, height;
15 |
16 | private SpriteSheet sprites;
17 |
18 | private HPTimer hpTimer;
19 |
20 | // The GameObjects array list:
21 | ArrayList gameObjects = new ArrayList();
22 |
23 | // Wall variables
24 | double nextWallGenerationTime = 1.0;
25 | Random wallRNG = new Random(); // Any argument will
26 | // cause walls to be generated with the same pattern
27 | // every time!
28 |
29 | // Baddie variables
30 | double nextBaddieGenerationTime = 2.0;
31 | Random baddieRNG = new Random();
32 |
33 | // Player variables:
34 | Player player;
35 | boolean playerExploded = false;
36 |
37 | // Bullet variables
38 | double lastBulletTime = 0.0;
39 | double bulletCreationSpeed = 0.25;
40 |
41 | // Constructor
42 | public Engine2D(int windowWidth, int windowHeight, int fps) {
43 | width = windowWidth;
44 | height = windowHeight;
45 |
46 | // Load the sprites
47 | sprites = new SpriteSheet("graphics/spaceracer.png", 16, 16);
48 |
49 | // Create 100 stars
50 | for(int i = 0; i < 100; i++) {
51 | Star s = new Star();
52 | s.setAnimation(new Animation(Math.random() * 2 + 0.2, Math.random(), 5, 3, true));
53 | gameObjects.add(s);
54 | }
55 |
56 | // Create the player:
57 | player = new Player(16.0, 100.0);
58 | gameObjects.add(player);
59 |
60 | // Start the HPTimer
61 | hpTimer = new HPTimer();
62 | hpTimer.start();
63 |
64 | // Start the render/update loop
65 | Timer timer = new Timer(1000/fps, this);
66 | timer.start();
67 | }
68 |
69 |
70 | // This event is called when the timer fires at the specified fps
71 | public void actionPerformed(ActionEvent e) {
72 | // Read the most up-to-date time:
73 | hpTimer.update();
74 |
75 | // Pass HPTimer's times to our update method:
76 | update(hpTimer.timeTotal(), hpTimer.timeDelta());
77 |
78 | repaint();
79 | }
80 |
81 |
82 | //
83 | public void paintComponent(Graphics g) {
84 | super.paintComponent(g);
85 | render((Graphics2D) g);
86 | }
87 |
88 | private void update(double timeTotal, double timeDelta) {
89 | // Generate new walls:
90 | if(timeTotal >= nextWallGenerationTime) {
91 | nextWallGenerationTime += 0.5; // Add 0.5 second to the wall generation time
92 |
93 | for(int i = 0; i < 14; i++) {
94 | if(wallRNG.nextInt(3) == 0) {
95 | gameObjects.add(new Wall(320, i * 32));
96 | }
97 | }
98 | }
99 |
100 | // Generate new Baddies
101 | if(timeTotal >= nextBaddieGenerationTime) {
102 | // Death wave:
103 | //nextBaddieGenerationTime += baddieRNG.nextDouble() * 0.2 + 0.1;
104 | // Normal wave:
105 | nextBaddieGenerationTime += baddieRNG.nextDouble() * 4.0 + 0.5;
106 |
107 | gameObjects.add(new Baddie(320, baddieRNG.nextInt(280)-40));
108 | }
109 |
110 | for(int i = 0; i < gameObjects.size(); i++) {
111 | GameObject o = gameObjects.get(i);
112 | o.update(timeTotal, timeDelta);
113 |
114 | // If this object is a bullet:
115 | if(o instanceof Bullet) {
116 | // Delete the bullet if it goes off the screen
117 | // to the right
118 | if(o.isOffScreenRight()) {
119 | gameObjects.remove(i);
120 | i--;
121 | continue;
122 | }
123 |
124 | // Check all baddies for collisions:
125 | for(int j = 100; j < gameObjects.size(); j++) {
126 | GameObject g = gameObjects.get(j);
127 | // If this is a baddie:
128 | if(g instanceof Baddie) {
129 | // If the baddie has hit the bullet:
130 | if(o.getDistance(g) < 14) {
131 | // Remove the baddie:
132 | gameObjects.remove(j);
133 | j--;
134 | i--;
135 | }
136 | }
137 | }
138 | }
139 |
140 | // If the object is a wall, or a baddie:
141 | if(o instanceof Wall || o instanceof Baddie) {
142 |
143 | // Test if the wall/baddie has hit the player:
144 | if(o.getDistance(player) < 14 && !playerExploded) {
145 | player.setAnimation(new Animation(0.5, hpTimer.timeTotal(), 8, 4, false));
146 | playerExploded = true;
147 | }
148 |
149 | if(o.isOffScreenLeft()) {
150 | // Delete if they go off the screen to the left
151 | gameObjects.remove(i);
152 | i--;
153 | continue;
154 | }
155 | }
156 | }
157 |
158 | // Create bullets
159 | if(Keyboard.isKeyDown(32) &&
160 | hpTimer.timeTotal() - lastBulletTime >
161 | bulletCreationSpeed && !playerExploded) {
162 | gameObjects.add(new Bullet(player.x, player.y));
163 | lastBulletTime = hpTimer.timeTotal();
164 | }
165 |
166 |
167 | // When the explosion animation for the payer is finished, destroy all walls and baddies
168 | // and reset the player:
169 | if(playerExploded && player.getAnimation().getIsComplete()) {
170 | player.x = 16;
171 | player.y = 100;
172 | playerExploded = false;
173 | player.setAnimation(new Animation(0.1, 0.0, 0, 2, true));
174 | for(int i = 0; i < gameObjects.size(); i++) {
175 | if(gameObjects.get(i) instanceof Wall ||gameObjects.get(i) instanceof Baddie) {
176 | gameObjects.remove(i);
177 | i--;
178 | }
179 | }
180 | }
181 | }
182 |
183 | private void render(Graphics2D g) {
184 | // Clear the screen to blue
185 | g.setBackground(Color.DARK_GRAY);
186 | g.clearRect(0, 0, width, height);
187 |
188 | // Render the game objects:
189 | for(GameObject o: gameObjects)
190 | o.render(g, sprites);
191 | }
192 | }
193 |
--------------------------------------------------------------------------------
/Chapter 8/SpaceRacer/src/GameObject.java:
--------------------------------------------------------------------------------
1 | import java.awt.Graphics2D;
2 |
3 | public abstract class GameObject {
4 | // Position
5 | public double x, y;
6 |
7 | // Is the object visible?
8 | private boolean visible = true;
9 |
10 | // The object's animation
11 | private Animation animation = null;
12 |
13 | // Abstract Update and Render
14 | public void update(double timeTotal, double timeDelta) {
15 | if(animation != null)
16 | animation.update(timeTotal);
17 | }
18 |
19 | // Render the animation with the current frame if it exists and
20 | // is visible
21 | public void render(Graphics2D graphics, SpriteSheet sprites) {
22 | if(visible && animation != null)
23 | sprites.render(graphics, animation.getCurrentFrame(),
24 | (int)x, (int)y);
25 | }
26 |
27 | // Getters and setters
28 | public double getX() {
29 | return x;
30 | }
31 |
32 | public double getY() {
33 | return y;
34 | }
35 |
36 | public boolean getVisible() {
37 | return visible;
38 | }
39 |
40 | public void setVisible(boolean visible) {
41 | this.visible = visible;
42 | }
43 |
44 | public Animation getAnimation() {
45 | return animation;
46 | }
47 |
48 | public void setAnimation(Animation animation) {
49 | this.animation = animation;
50 | }
51 |
52 | // Location tests:
53 | // Test if the object is outside the screen to the left
54 | public boolean isOffScreenLeft() {
55 | return x < -16;
56 | }
57 |
58 | // Test if the object is outside the screen to the right
59 | public boolean isOffScreenRight() {
60 | return x >= 320;
61 | }
62 |
63 | // Test if the object is outside the screen at the top
64 | public boolean isOffScreenTop() {
65 | return y < -16;
66 | }
67 |
68 | // Test is the object is outside the screen at the bottom
69 | public boolean isOffScreenBottom() {
70 | return y >= 240;
71 | }
72 |
73 | // Compute the distance between the objects
74 | public double getDistance(GameObject o) {
75 | // Faster, but less accurate detection:
76 | // return Math.abs(o.x - x) + Math.abs(o.y - y);
77 |
78 | // More accurate, but slow version:
79 | return Math.sqrt((o.x - x) * (o.x - x) +
80 | (o.y - y) * (o.y - y));
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/Chapter 8/SpaceRacer/src/HPTimer.java:
--------------------------------------------------------------------------------
1 |
2 | public class HPTimer {
3 | // Member variables
4 | long startTime, lastTime, currentTime;
5 |
6 | // Set the start, last and current times to now:
7 | public void reset() {
8 | startTime = System.currentTimeMillis();
9 |
10 | // You can also use nano time:
11 | //startTime = System.nanoTime();
12 |
13 | lastTime = startTime;
14 | currentTime = startTime;
15 | }
16 |
17 | // Reset teh timer
18 | public void start() {
19 | reset();
20 | }
21 |
22 | // Record the current time
23 | public void update() {
24 | lastTime = currentTime;
25 | currentTime = System.currentTimeMillis();
26 |
27 | // If using nano time:
28 | //currentTime = System.nanoTime();
29 | }
30 |
31 | // Return the time since the last call to update
32 | public double timeDelta() {
33 | double d = (double) currentTime - (double) lastTime;
34 | d /= 1000.0;
35 |
36 | // If using nano time:
37 | // d /= 1000000000.0;
38 | return d;
39 | }
40 |
41 | // Return the time since the last call to reset
42 | public double timeTotal() {
43 | double d = (double) currentTime - (double) startTime;
44 | d /= 1000.0;
45 |
46 | // If using nano time:
47 | //d /= 1000000000.0;
48 | return d;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/Chapter 8/SpaceRacer/src/Keyboard.java:
--------------------------------------------------------------------------------
1 | import java.awt.event.KeyEvent;
2 | import java.awt.event.KeyListener;
3 |
4 | public class Keyboard implements KeyListener {
5 | // 256 key states: true means the key is down
6 | // false means the key is up
7 | private boolean[] keyStates = null;
8 |
9 | // The only instance of this class is the following
10 | // private, static instance:
11 | private static Keyboard staticInstance = null;
12 |
13 | // Private Constructor:
14 | private Keyboard() {
15 | keyStates = new boolean[256];
16 | }
17 |
18 | // Public init method which creates the
19 | // static key states if they do not exist
20 | public static void init() {
21 | staticInstance = new Keyboard();
22 |
23 | reset();
24 | }
25 |
26 | public static Keyboard getInstance() {
27 | return staticInstance;
28 | }
29 |
30 | // Set all key states to false
31 | public static void reset() {
32 | for(int i = 0; i < 256; i++)
33 | staticInstance.keyStates[i] = false;
34 | }
35 |
36 | // Test if a key is down
37 | public static boolean isKeyDown(int keyCode) {
38 | return staticInstance.keyStates[keyCode & 255];
39 | }
40 |
41 | // Set a key to down; true
42 | public void keyPressed(KeyEvent e) {
43 | staticInstance.keyStates[e.getKeyCode() & 255] = true;
44 | }
45 |
46 | // Set a key to up; false
47 | public void keyReleased(KeyEvent e) {
48 | staticInstance.keyStates[e.getKeyCode() & 255] = false;
49 | }
50 |
51 | // Extra, unused method from KeyListener interface
52 | public void keyTyped(KeyEvent e) { }
53 | }
--------------------------------------------------------------------------------
/Chapter 8/SpaceRacer/src/MainClass.java:
--------------------------------------------------------------------------------
1 | import java.awt.EventQueue;
2 | import javax.swing.JFrame;
3 |
4 | public class MainClass extends JFrame {
5 | public static void main(String[] args) {
6 | EventQueue.invokeLater(new Runnable() {
7 | @Override
8 | public void run() {
9 | MainClass m = new MainClass(640, 480);
10 | }
11 | });
12 | }
13 |
14 | private MainClass(int windowWidth, int windowHeight) {
15 | setSize(windowWidth, windowHeight); // Set window size
16 | setLocationRelativeTo(null); // Default location
17 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit on close
18 | setVisible(true);
19 |
20 | // Init the static singleton keyboard:
21 | Keyboard.init();
22 |
23 | // Add a keylistener
24 | addKeyListener(Keyboard.getInstance());
25 |
26 |
27 | // Create and add the engine JPanel:
28 | final Engine2D engine = new Engine2D(windowWidth, windowHeight, 30);
29 | add(engine);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Chapter 8/SpaceRacer/src/Player.java:
--------------------------------------------------------------------------------
1 | public class Player extends GameObject {
2 | double shipSpeed = 320.0;
3 |
4 | public Player(double x, double y) {
5 | // Set the x/y
6 | this.x = x; this.y = y;
7 |
8 | // Set the animation
9 | this.setAnimation(new Animation(0.1, 0.0, 0, 2, true));
10 | }
11 |
12 | public void update(double timeTotal, double timeDelta) {
13 | // Call parent's update:
14 | super.update(timeTotal, timeDelta);
15 |
16 | //Up/Down
17 | if(Keyboard.isKeyDown(40)) y += shipSpeed * timeDelta;
18 | if(Keyboard.isKeyDown(38)) y -= shipSpeed * timeDelta;
19 |
20 | // Left/Right
21 | if(Keyboard.isKeyDown(37)) x -= shipSpeed * timeDelta;
22 | if(Keyboard.isKeyDown(39)) x += shipSpeed * timeDelta;
23 |
24 | // Make sure the player is on the screen:
25 | if(x < 0) x = 0;
26 | if(y < 0) y = 0;
27 | if(x > 320 - 32.0) x = 320 - 32.0;
28 | if(y > 240 - 32.0) y = 240 - 32.0;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Chapter 8/SpaceRacer/src/SpriteSheet.java:
--------------------------------------------------------------------------------
1 | import java.awt.Graphics2D;
2 | import java.awt.image.BufferedImage;
3 | import java.io.File;
4 | import java.io.IOException;
5 | import javax.imageio.ImageIO;
6 |
7 | public class SpriteSheet {
8 |
9 | private BufferedImage bmp; // The loaded image
10 | private int spritesAcross = -1;// Number of sprites across the image
11 | private int totalSprites; // Total sprites in the image
12 | private int spriteWidth, spriteHeight;// width/height of each sprite
13 |
14 | // Constructor
15 | public SpriteSheet(String filename,int spriteWidth,int spriteHeight) {
16 | // Load the bitmap
17 | try {
18 | bmp = ImageIO.read(new File(filename));
19 | }
20 | catch(IOException e) {
21 | // File not found
22 | spritesAcross = -1;
23 | return;
24 | }
25 | // Save the sprite width and height
26 | this.spriteWidth = spriteWidth;
27 | this.spriteHeight = spriteHeight;
28 | // spritesAcross is used to compute the
29 | // source rectangles when rendering
30 | spritesAcross = bmp.getWidth() / this.spriteWidth;
31 | // totalSprites is used to ensure we're not
32 | // trying to render sprites which do not exist
33 | totalSprites = spritesAcross * (bmp.getHeight() / spriteHeight);
34 | }
35 |
36 | // This method can be used to test if the sprites loaded
37 | public Boolean isValid() {
38 | return spritesAcross != -1;
39 | }
40 |
41 | public void render(Graphics2D g, int spriteIndex, int x, int y) {
42 | // Make sure the sprite is actually on our spriteSheet
43 | if(spriteIndex >= totalSprites) return;
44 | // Compute the source x and y
45 | int srcX = (spriteIndex % spritesAcross) * spriteWidth;
46 | int srcY = (spriteIndex / spritesAcross) * spriteHeight;
47 | // Draw the image
48 | g.drawImage(bmp,
49 | x*2, // Destination x1
50 | y*2, // Destination y1
51 | (x + spriteWidth)*2, // Destination x2
52 | (y + spriteHeight)*2, // Destination y2
53 | srcX, // Source x1
54 | srcY, // Source y1
55 | srcX + spriteWidth, // Source x2
56 | srcY + spriteHeight,// Source y2
57 | null); // Observer
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/Chapter 8/SpaceRacer/src/Star.java:
--------------------------------------------------------------------------------
1 | import java.awt.Graphics2D;
2 |
3 | public class Star extends GameObject {
4 | double speed;
5 |
6 | public Star() {
7 | // Begin the stars in a random location:
8 | x = Math.random() * 320.0;
9 | y = Math.random() * 240.0;
10 |
11 | // Set the stars to a random speed:
12 | speed = Math.random() * 30.0 + 30;
13 | }
14 |
15 | public void update(double timeTotal, double timeDelta) {
16 | // Call the parent update
17 | super.update(timeTotal, timeDelta);
18 |
19 | // Move the star left
20 | x -= speed * timeDelta;
21 |
22 | // Reset the star on the right when it goes off screen
23 | if(isOffScreenLeft()) {
24 | x = 320.0; // Just outside the right-hand edge
25 | y = Math.random() * 240.0 - 16; // Random Y location
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Chapter 8/SpaceRacer/src/Wall.java:
--------------------------------------------------------------------------------
1 | import java.awt.Graphics2D;
2 |
3 | public class Wall extends GameObject {
4 | public Wall(double x, double y) {
5 | this.x = x;
6 | this.y = y;
7 |
8 | this.setAnimation(new Animation(4));
9 | }
10 |
11 | // Move the wall to the left
12 | public void update(double timeTotal, double timeDelta) {
13 | super.update(timeTotal, timeDelta);
14 |
15 | x -= 80 * timeDelta;
16 | }
17 |
18 | // Determines if the ships has collided with this wall
19 | public boolean collisionWithShip(double shipX, double shipY) {
20 | double dist = Math.abs(x - shipX) + Math.abs(y - shipY);
21 |
22 | return dist < 10;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Java Succinctly Part 2
2 | This is the companion repo for [*Java Succinctly Part 2*](https://www.syncfusion.com/ebooks/Java_Succinctly_Part_2) by Christopher Rose. Published by Syncfusion.
3 |
4 | [](https://www.syncfusion.com/ebooks/Java_Succinctly_Part_2)
5 |
6 | ## Looking for more _Succinctly_ titles?
7 |
8 | Check out the entire library of more than 130 _Succinctly_ e-books at [https://www.syncfusion.com/ebooks](https://www.syncfusion.com/ebooks).
9 |
--------------------------------------------------------------------------------
/cover.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SyncfusionSuccinctlyE-Books/Java-Succinctly-Part-2/522496f8238a024c63d5bf4f4e692f2b8fb8e4a1/cover.png
--------------------------------------------------------------------------------