main() function - cypress collegestudents.cypresscollege.edu/cis244/lc01.pdffor example, if the...
TRANSCRIPT
1
Java Game Programming - Penn P. Wu, PhD
Lecture #1 Java Basics for Game Programming
Java Basics The source code of a generic Java application consists of three primary components: the class
definition, a main() function, and the statements that define behaviors of the application.
The following is a simple code that creates an application for the command-line interface (not a
Windows desktop application). It demonstrates how these three basic components are used to
build a Java application. A Java source code must be compiled by the compiler (javac.exe)
before being execution in the Java Virtual Machine (JVM). The line numbers, 01, 02, …, and
11, are not part of the source code. They are used by the instructor to indicate the sequence of
statements. It is necessary to note that all Java source files must have extentsion “.java”.
01 // Filename: MyJava.java
02 import javax.swing.JOptionPane;
03
04 public class MyJava
05 {
06 public static void main(String args[])
07 {
08 JOptionPane.showMessageDialog(null, "Java Game");
09 System.exit(0); // terminate the app immediately
10 }
11 }
Java has a very special convention that needs programmers’ attention. The “identifier” (name of
the file) of the Java source file must be exactly the same as the identifier of the the class that has
the main() function. In the above example, the identifier of the class is “MyJava”; therefore, the
identifier of the source file must be “MyJava.java”, where “.java” is the file extension. By the
way, a java source file can contain one or more classes, yet only one can contain the “main”
function. In Java, the main function is the entry point of the program which is called at program
startup to determine how to initialize the entire program. The output is a GUI dialog box as
shown below.
The first line (line led by 01) is a “comment” and is used to provide reference to the
programmer only. In terms of programming, comments are the placing of human readable
descriptions inside a computer programs detailing what the Code is doing. Comments are
ignored by the compiler and have no effect on the program but are useful to other programmers
as coding references.
// Filename: MyJava.java
The second line (02) “imports” the javax.swing.JOptionPane class which provides tools to
create simple dialog box as GUI applications. In Java, the “import” keyword is used to access
tools provided by Java (particularly classes and interfaces) and make their members available
and accessible to the current source code, without specifying fully qualified package names.
The above code uses the showMessageDialog() method to display a string in a message
dialog box.
import javax.swing.JOptionPane;
2
Java Game Programming - Penn P. Wu, PhD
The program begins with the class definition statement. A “class”, in any generic Java program,
is a container of specification that describes how the Java program would be executed. A class
is a block code enclosed by a pair of “{“ and “}” signs. A Java source file may contains two or
more classes; however, only one of them is the primary class (the one that has a main()
function), while others are supportive classes. The following illustrates the basic form of a class
definition in Java.
AccessModifier class Name
{
statements
}
The keyword class begins the class definition for a class followed by the identifier (name) of
the class. The statements (Java code) for each class reside between the opening and closing
curly braces. The identifier (name) of class must be the exactly same as the name of source file.
For example, if the class name is “MyJava”, the source file must be named “MyJava.java”.
Java has three access modifiers: public, private, and protected. They control access to a member
of a given class. The private acsess is most restricted, it allows only the class objects in which it
is declared can access it. The protected access is typically used for a super-class to allow read-
only access from an object of sub-class. The public access does not enforce any restriction. By
the way, public is the default; therefore, the following are technically the same code.
Specify to use public Defaulted to use public public class MyJava { } class MyJava { }
Each Java program must have a main() function, which is the starting point of the program,
meaning it is where the execution of entire application starts. This main() function typically
describes how to subsequently execute all the other codes of the Java program. It is a linguistic
requirement to declare the main() function as public in Java; therefore, JVM can easily access
and execute it. In the case that a Java program does not contain at least one main() function, the
JVM will throw a NoSuchMethodException:main message if it does not find the main()
function of in any class of a given Java program.
public static void main(String[] args){ ..... }
The main() function typically takes a single argument which is an array of elements of type
String. The name of this array is “args”. This array is a communication mechanism through
which the runtime system can pass information from the console (or the JVM) to the
application.
The three keywords in the above statement: public, static, and void. The keyword
“public” is one of the three basic access modifiers in Java: private, protected, and
public. Any method or variable declared as public can be accessed from objects outside of the
class. By setting the main() function to public, JVM can easily access and execute it. The main()
function in Java is declared as static; therefore, it can be invoked by the runtime engine
without having to instantiate an instance of the parent class. According to Java API document,
the main() function is better to have a void return type because a Java program is excuted in
JVM and does not directly interact with the operating system.
The System.exit(0) statement is optional, but useful. It forces the JVM to terminate the
program immediately. With it, JVM can decide when and how it should terminate a program.
Most of the Java programs presented in this course will elide this statement.
Many books use console codes to teach Java programming. The following is the console version
3
Java Game Programming - Penn P. Wu, PhD
of the above code. It is necessary to note that, throughout this course, most sample codes are
written as GUI (graphical user interface) application, not console applications.
public class MyJava
{
public static void main(String args[])
{
System.out.println("Welcome to Java Game Programming!");
System.exit(0); // terminate the app immediately
}
}
The following statement uses the println() method of the System class from the core library
to output a string literal, the “Welcome to Java Game Programming!” message, to standard
output.
System.out.println("Welcome to Java Game Programming!");
Another method to display output on the console screen is the print() method. The difference
between print() and println() method is that println() adds a new line to the end of
message while print() does not insert a new line. These two methods are designed for console
environment, this is probably the only lecture for students to use them throughout this course.
System.out.print("Welcome to Java Game Programming!");
The above “MyJava.class” byte code constitutes an individual Java program; however, it is a
console program. The term “console program” means that its output will only be display in a
command-line interface, such as Microsoft Windows’ Command Prompt, the DOS Prompt, or
the Linux terminal. Only GUI-based application can display output in a Window form (or
similar GUI interfaces) in a Windows desktop. The following compares a console program with
an GUI program. They both display a message “Java Game”.
Console GUI C:\User>java MyJava
Welcome to Java Game
Programming!
C:\User>java MyJava
It is probably more enjoyable to write GUI-based Java game applications compared to console
applications. Througout this course, the instructor will only use GUI codes as demonstrations to
guide students to create Java game codes. Java GUI application can run either as stand-alone or
as applets. Two later lectures will discuss how to create standalone- and applet-based Java
games in details. The following is the GUI-version.
import javax.swing.JOptionPane;
public class MyJava
{
public static void main(String args[])
{
JOptionPane.showMessageDialog(null, "Welecome to Java Game
Programming!");
}
}
The above example is very simple GUI application, which only uses a generic dialog box to
display the results. Starting from the next section, the instructor will gradually gear towards
4
Java Game Programming - Penn P. Wu, PhD
more advanced GUI applications. In addition to the javax.swing.JOptionPane class, GUI
components such as JLabel will be used to display the output. The following illustrates how to
declare and create an empty instance, named “label1”, of the javax.swing.JLabel class. An
“empty” instance means it does not have any default content.
JLabel label1 = new JLabel();
In Java, the syntax to declare a GUI component is:
GUIClass objectID;
The following is the syntax to create an instance of the GUI component, where “new” is a
keyword. The actual creation of an instance is done by the constructor. A “constructor” is a
special kind of class method which is only used to create an instance of a class. A class
constructor typically has the same identifier as the class, but followed by a pair of parentheses.
The constructor of the JLabel class, for example, is JLabel().
objectID = new GUIClass();
Programmers frequently combine the declaration and instantiation (creating an instance) into
one single-line statement, as shown below.
GUIClass objectID = new GUIClass();
Many classes of GUI components provide options of constructors. The following lists three
popular forms of JLabel() constructor. They are used frequently in this course. By the way,
another frequently used GUI component is JButton. Later sections will discuss how to use
JButton.
Options Description
JLabel() Creates a JLabel instance with no content (and no image).
JLabel(string) Creates a JLabel instance with the specified text.
JLabel(image) Creates a JLabel instance with the specified image.
A JLabel object can display either text, an image, or both. However, a label does not react to
input events. Interestingly, JLable does not support new line “\n”. Instead, it requires the use of
HTML tags to break lines. In the following, the strings are surrounded with <html>..</html>
and break the lines with <br>. The following is the GUI version of the above console code. It
use a JLabel to display a multiple-line text within the showMessageDialog window.
import javax.swing.JOptionPane;
import javax.swing.JLabel;
public class MyJava
{
public static void main(String args[])
{
String str = "<html>";
str += "<u>This is an underlined line.</u><br>";
str += "<i>This is an italicized line.</i><br>";
str += "<s>This is a striked out line.</s><br>";
str += "</html>";
JLabel label1 = new JLabel(str);
JOptionPane.showMessageDialog( null, label1 );
}
5
Java Game Programming - Penn P. Wu, PhD
}
Conents in a JLabel can be formatted using HTML tags, such as <u> for underline, <i> for
itacic, and <s> for striked-out. A sample ouput looks:
Java Compiler,
and using Java
virtual machine
to execute Java
games
Java source codes must be named with an extension “.java” such as MyJava.java. A source
file is where the programmer writes and saves the game codes. The Java compiler
(javac.exe), available for downloading at Oracle’s web site (http://www.oracle.com), is
what a Java programmer needs to use to compile the source code into Java byte codes (object
codes). In Java, a bytecode is the computer object code that is processed by the Java virtual
machine. The Java virtual machine then serves as the intermediary between the Java program
and the hardware processor. The syntax to compile a source code to a byte code is:
javac FileName.java
The following illustrates how to compile a source file named “MyJava.java” in a Windows
Command Prompt.
c:\Users\user>javac MyJava.java
All Java byte codes have an extension .class; therefore, they are also known as “class files”.
The above compilation command, if succeeds, will produce a new class file (or byte code)
named “MyJava.class”. A Java byte code can be executed by running the “java.exe”
command in the Java Virtual Machine (JVM). The syntax is (.exe is optional):
java.exe ClassFileName
The following illustrates how to execute a Java byte code named MyJava.class in a Windows
Command Prompt. It is necessary to note that the “.class” file extension is not used.
c:\Users\user>java MyJava
Throughout this course, be sure not to type the .class extension when testing Java byte codes.
The following example is an incorrect statement, which will cause an arror message.
java MyJava.class
With respect to the MyJava.java source file (above), the output of this “java MyJava”
command should look:
Java Variable
and primitive
data types
Variables are objects that do not have a fixed value or somethings that continuously change
their values. For example, the value of a digital clock, because its value may change every
second. Game values are typically represented by variables, such as game score. Java has some
fundamental rules to declare an object as variable and designate a name to represent it. The
following is the generic form of syntax.
dataType VariableName = value;
6
Java Game Programming - Penn P. Wu, PhD
Variable names are case-sensitive and must not be a keyword or reserved word. The convention,
however, is to always begin your variable names with a letter, not “$” or “_”.
Table: Java keywords/reserved words
abstract continue for new switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
The Java programming language is sensitive to data type, which means that all variables must
first be declared with a data type before they can be used. The primary reason of declaring a
variable’s data type is to let the computer know what size of physically memory it should
reserved for the variable to use. When declaring a variable x as int type, the computer will find a
32-bit space in memory to be used by the variable. The following table illustrates commonly
seen primitive data types. The term “primitive” means they are provided by the Java language
core.
Table: Primitive data type
Type Description Example int a 32-bit signed integer 1, 457, -39
float a single-precision 32-bit IEEE 754 floating point 3.1415
double a double-precision 64-bit IEEE 754 floating
point
3.1415
char a single 16-bit Unicode character '\u0000'
string a combination of characters apple, jennifer
Boolean a data that can only have two possible values:
true and false
boolean x = false;
The following declares a variable as the int type.
int x;
Once declared, a variable can be assigned a value of the same type. The following assigns 1 to
x. Both 1 and x are int type.
x = 1;
In Java, variable declaration and the assignment of initial value can be organized into one single
statement. The following declares an integer variable x with an initial value of 1, all in one
single statement.
int x = 1;
The following is a complete code that demonstrates how to actually declare numerical variables
and assign value to them.
public class MyJava
{
public static void main(String args[])
{
int x; // declaration
x = 1; // assign value
7
Java Game Programming - Penn P. Wu, PhD
int y = 4; // declare and assign
}
}
Generally speaking, any whole number, positive or negative, between -2,147,483,648 and
2,147,483,647 falls into the definition of the “int” type. Both short and long are two special
subsets of int data type. The short data type is a 16-bit signed integer, which has a minimum
value of -32,768 and a maximum value of 32,767 (inclusive). The long data type is a 64-bit
integer for representing a very large integer. Throughout this course, declare non-fractional
value as int type is functionally sufficient. No need to use these two data types.
Any numbers with fractional part, such as 3.1415, are the floating-point values, and should be
declared as either “float” or “double” type. The term “double” is defined as “double of float”,
which means if a float type takes 16 bits, a double type will take 32 bits. It is necessary to note
that Java frequently require programmers to place a “F” or “f” mark next to a float value. Either
“F” or “f” is the valid indicator of float value. The Java compiler will return an error message if
either “F” or “f” is not present. Interestingly, Java does not require any suffix if a value is
declared as double.
public class MyJava
{
public static void main(String args[])
{
double PI = 3.1415;
float area = 6.25F;
float circumference = 5.31f;
}
}
Java supports the use of “scientific notation” when a fractional value is too large or too small. In
the following example, 6.22-e23 is 6.22×10-23 and 1.03e15 is 1.03×1015. By the way, the letter
“e” represents the “natural logarithm”.
double a = 6.22e-23 * 1.03e15;
Interestingly, Java supports both “E” and “e”. The following works exactly the same way as the
above.
double a = 6.22E-23 * 1.03e15;
The char data type is for declaring a single 16-bit Unicode character, as shown below. A single
character, such as letter, must be enclosed by a pair of single quotes.
char c = 'A';
The following causes a syntax error because the value of a char type must be enclosed by a pair
of single quotes, not double quotes.
char a = "A";
Java supports the strings type through the java.lang.String class, which requires
programmers to enclose a string with a pair of double quotes, as illustrated below.
String s = "this is a string";
The following also causes a syntax error because string literals must be enclosed by double
quotes.
8
Java Game Programming - Penn P. Wu, PhD
String s = 'this is a string';
The Boolean data type has only two possible values: true and false (sometimes represents as 1
and 0). Use this data type for simple flags that track true/false conditions. The following
declares a Boolean variable, named “IsTrue”, that holds the result of (3>5) which is false.
Boolean IsTrue = (3>5);
Basic operators An operator, in Java, is a special symbol that can call a pre-programmed tool to perform a
specific operation (such as addition and multiplication) on one or more operands and then
returning a result. The following is the generic syntax:
operand1 operator operand2
Throughout this course, students will frequently use three basic categories of Java operators:
arithmetic, relational (including equality), and logical operators.
Arithmetic operators perform basic arithmetic operations that involve the calculation of
numeric values represented by literals, variables, other expressions, function and property calls,
and constants. The following table list five basic arithmetic operators. By the way, a modulus
operator (%) divides the value of one expression by the value of another, and returns the
remainder.
Operator Description Examples + Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
Arithmetic operators can only work on int, double, or float types of data. In the following
example, there are two variables, x and y, of int type. The instructor declares a string variable,
str, to store the result of arithmetic operations.
public class MyJava
{
public static void main(String args[])
{
int x = 15;
int y = 3;
String str = (x+y) + "\n";
str += (x-y) + "\n";
str += (x*y) + "\n";
str += (x/y) + "\n";
str += (x%y) + "\n";
System.out.print(str);
}
}
The following is the output.
C:\Users>java Myjava
18
12
45
5
9
Java Game Programming - Penn P. Wu, PhD
The following is the GUI version. For this point on, the instructor will start to use only GUI
applications for demonstrations.
import javax.swing.JOptionPane;
import javax.swing.JLabel;
public class MyJava
{
public static void main(String args[])
{
String str = "<html>";
int x = 15;
int y = 3;
str += (x+y) + "<br>"; // 18
str += (x-y) + "<br>"; // 12
str += (x*y) + "<br>"; // 45
str += (x/y) + "<br>"; // 5
str += (x%y) + "<br>"; // 0
str += "</html>";
JLabel label1 = new JLabel(str);
JOptionPane.showMessageDialog( null, label1 );
}
}
The output looks:
The following is the JFrame version of the above code. The javax.swing.JFrame class
provides tools to create a Windows form-like GUI application (known as a “frame”). A later
lecture will discuss how to create a “frame” in details. This example code also uses the
setText() method of JLabel to set the text of JLabel to the specified string.
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Container;
public class MyJava
{
public static void main(String[] args)
{
JFrame form1 = new JFrame();
form1.setSize(300, 200);
form1.setVisible(true);
form1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cont = form1.getContentPane();
cont.setLayout(null);
JLabel label1 = new JLabel();
label1.setBounds(10, 10, 100, 100);
10
Java Game Programming - Penn P. Wu, PhD
cont.add(label1);
String str = "<html>";
int x = 15;
int y = 3;
str += (x+y) + "<br>"; // 18
str += (x-y) + "<br>"; // 12
str += (x*y) + "<br>"; // 45
str += (x/y) + "<br>"; // 5
str += (x%y) + "</html>"; // 0
label1.setText(str);
}
}
The equality and relational operators determine if one operand is greater than, less than, equal
to, or not equal to another operand. The majority of these operators will probably look familiar
to you as well. Be sure to distinguish the difference between the “assignment” (=) and “equal
to” (==”) signs. Be sure to use "==", not "=", when testing if two primitive values are equal.
Operator Description Example == equal to x == y
!= not equal to x != y
> greater than x > y
>= greater than or equal to x >= y
< less than x < y
<= less than or equal to x <= y
When compare two values, relational operators return either true or false, not 1 or 0. For
example,
import javax.swing.JOptionPane;
import javax.swing.JLabel;
public class MyJava
{
public static void main(String args[])
{
String str = "<html>";
int x = 5;
int y = 3;
str += (x==y) + "<br>"; // false
str += (x!=y) + "<br>"; // true
str += (x>y) + "<br>"; // true
str += (x>=y) + "<br>"; // true
str += (x<y) + "<br>"; // false
str += (x<=y) + "<br>"; // false
str += "</html>";
JLabel label1 = new JLabel(str);
JOptionPane.showMessageDialog( null, label1);
}
}
11
Java Game Programming - Penn P. Wu, PhD
The output looks:
Two frequently used logical operators (also known as conditional operators) are the && and ||
operators. They perform Conditional-AND and Conditional-OR operations on two boolean
expressions.
Opeator Description Example && Conditional-AND (x > 4) && (y >4)
|| Conditional-OR (x > 4) || (y >4)
The following example demonstrates how to use the conditional operators.
import javax.swing.JOptionPane;
import javax.swing.JLabel;
public class MyJava
{
public static void main(String args[])
{
String str = "<html>";
int x = 5;
int y = 3;
str += ((x > 4) && (y >4)) + "<br>"; // false
str += ((x > 4) || (y >4)) + "<br>"; // true
str += "</html>";
JLabel label1 = new JLabel(str);
JOptionPane.showMessageDialog(null, label1);
}
}
Type casting in
Java
Java is type-sensitive; therefore, type casting is often necessary in order to obtain expected
results. Type casting means to change a data of one type into another temporarily. In the
following example, the expression is (5/3). The expected result is 1.666666666666667;
however, the division operator does not produce expected result, it actually returns 1.
import javax.swing.JOptionPane;
public class MyJava
{
public static void main(String args[])
{
String str = (5/3) + ""; // why 1?
JOptionPane.showMessageDialog(null, str);
}
}
How could 5/3=1? This is because both the x and y variables are declared as int type (integers,
12
Java Game Programming - Penn P. Wu, PhD
which means whole number or a numerical values that cannot have fractional part); therefore,
the result of calculation is still an int type. The arithmetic calculation must ignore the fractional
part because the “int” data type does not allow fractional part. A temporary type casting can
solve this problem. In the following example, during executation both 5 and 3 will be
temporarily converted to the double type (which is a numerical value that allows fractional
values); therefore, the result is double type.
import javax.swing.JOptionPane;
public class MyJava
{
public static void main(String args[])
{
String str = ((double) 5 / (double) 3) + ""; //
1.666666666666667
JOptionPane.showMessageDialog(null, str);
}
}
The following illustrates the syntax of type casting in Java. It is necessary to enclose the data
type by a pair of parentheses.
(newType) variable
Type casting only changes the data type temporarily. After calculation, all involved data return
to their original types, as demonstrated in the following example.
import javax.swing.JOptionPane;
import javax.swing.JLabel;
public class MyJava
{
public static void main( String args[] )
{
String str = "<html>Before casting:<br>";
str += (5/3) + "<br><br>"; //1
str += "Casting<br>";
str += ((double) 5 / (double) 3) + "<br><br>"; // 1.6...
str += "After casting<br>";
str += (5/3) + "<br>"; // 1
str += "</html>";
JLabel label1 = new JLabel(str);
JOptionPane.showMessageDialog(null, label1);
}
}
The output looks:
13
Java Game Programming - Penn P. Wu, PhD
The Java API provide a set of parsing methods for convert a string to other data types. The
following table lists commonly used methods for converting string to numerical values. By the
way, both float and double allows numerical values to have fractional parts. The main
differences is that float is a single precision floating-point value, which the double type doubles
the single precision. In other words, float has less precision than double.
Type-to-be Method
int Integer.parseInt(string)
float Float.parseFloat(string)
double Double.parseDouble(string)
short Short.parseShort(string)
long Long.parseLong(string)
byte Byte.parseByte(string)
All use entries collected from the keyboards, regardless how they look to a human eye, are
treated as strings by the computer. If a user enters three character 3, 5, and 2. It is not treated as
a numerical value, 352, but a string “352” by the computer. The following demonstrates how to
use the showInputDialog() method of the JOptionPane class to take string inputs from the
user, convert the string to float type, perform an arithematic calculation, and then display the
result of a division operation in a dialog window.
import javax.swing.JOptionPane;
public class MyJava
{
public static void main(String[] args)
{
String n1 = JOptionPane.showInputDialog("Enter 1st value: ");
String n2 = JOptionPane.showInputDialog("Enter 2nd value: ");
float result = Float.parseFloat(n1) / Float.parseFloat(n2);
JOptionPane.showMessageDialog(null, result);
}
}
The output looks:
and and
Java Control
Flow Statements
Control flow statements (or conditional statements) can break up a sequential flow of execution
with decision making based on pre-defined condition. The condition is typically a Boolean
expression that can only be either false or true (cannot be both at the same time). The if
structure is probably the most frequently used control structure. As shown below, the if
statement decides what to respond based on evaluation result of the Boolean expression. The
following illustrates the simplest form of an if structure in Java, where condition is a Boolean
expression and statements are Java code to be excuted when the Boolean expression returns
true.
14
Java Game Programming - Penn P. Wu, PhD
if (condition)
{
//statements
}
In the following, the condition (x > 4) can yield boolean results: true or false. When the user
enters 5, the expression (x > 4) is true, the dialog displays “Bravo”.
import javax.swing.JOptionPane;
public class MyJava
{
public static void main(String[] args)
{
String str = JOptionPane.showInputDialog("Enter a number [1-
9]");
int x = Integer.parseInt(str);
if (x > 4)
{
JOptionPane.showMessageDialog(null, "Bravo!");
}
}
}
The above code has a logical problem. When the user enters 3 which is less than 4, the
expression (x>4) becomes is a false statement. Interestingly, the above code will not have any
response because it does not specify what to do when the expression is evaluated to be false. A
variation of the if statement, if..else, can solve this problem. The following illustrates the syntax.
if (condition)
{
statements for true
}
else
{
statements for false
}
The following is a complete code. The “else” part of code will be executed when the user enters
3, 2, or any value that makes the (x>4) expression false.
import javax.swing.JOptionPane;
public class MyJava
{
public static void main(String[] args)
{
String str = JOptionPane.showInputDialog("Enter a number [1-
9]");
int x = Integer.parseInt(str);
if (x > 4)
{
JOptionPane.showMessageDialog(null, "Bravo!");
}
else
{
JOptionPane.showMessageDialog(null, "No!");
15
Java Game Programming - Penn P. Wu, PhD
}
}
}
When there are more than two possible conditions, it will take a series of if..then..else
statements (known as “else if ladder”) to develop a good logic. In the following example, there
are four else..if statements in the if structure. By the way, the statement (x = x%5) uses the
modulus operator (%) to limits the possible outcomes to 0, 1, 2, 3, and 4. The modulus
operator (also known as remainder operator) performs an integer division that divides n1 by n2
and returns only the remainder (r).The setBackground() method can set the background of a
JLabel control.
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import java.awt.Color;
public class MyJava
{
public static void main(String[] args)
{
JLabel label1 = new JLabel("Give me a background color.");
label1.setOpaque(true);
int x = Integer.parseInt(JOptionPane.showInputDialog("Enter a
number"));
x = x%5;
if (x == 0) { label1.setBackground(Color.magenta); }
else if (x == 1) { label1.setBackground(Color.yellow); }
else if (x == 2) { label1.setBackground(Color.green); }
else if (x == 3) { label1.setBackground(Color.pink); }
else if (x == 4) { label1.setBackground(Color.orange); }
else { }
JOptionPane.showMessageDialog(null, label1);
}
}
The following are samples of outcomes.
x = 25 x = 31 x = 47 x = 78 x = 64
x%5 = 0 x%5 = 1 x%5 = 2 x%5 = 3 x%5 = 4
The switch..case structure allows programmer to pre-defined conditions and dynamically
decide the execution path. Java switch..case structures work with the char and int types.
public void actionPerformed(ActionEvent e)
{
switch (x)
{
case 400: x=0; label1.setBackground(Color.magenta); break;
case 300: label1.setBackground(Color.green); break;
case 200: label1.setBackground(Color.yellow); break;
case 100: label1.setBackground(Color.blue); break;
}
x++;
label1.setBounds(x,10,10,10);
Why does 15%6 = 1?
16
Java Game Programming - Penn P. Wu, PhD
}
The Chinese Zodiac is based on a twelve-year cycle, each year in that cycle relates to an animal
sign. These animal signs are the rat, ox, tiger, rabbit, dragon, snake, horse, sheep, monkey,
rooster, dog and pig. The following example uses the western solar calendar to determine the
year of “sign”; however, in China, the zodiac is supposed to be calculated based on the Chinese
lunar. Since the Chinese Zodiac only adopts twelve different animals, the instructor uses the
expression y%12 for calculation. This is because a given year value (such as 1997), under the
modulus calculation of (y%12), can only return twelve possible values (0, 1, 2, 3, …, 11).
The coding logic, on the other hand, is based on a very simple inference and reasoning. For
example, the year 2000 was a dragon year. Since 2000%12=8, then any given year y must be a
dragon year if and only if y%12=8.
Year y%12 Zodiac Sign
1996 1996%12=4 Rat
1997 1996%12=5 Ox
1998 1996%12=6 Horse
1999 1996%12=7 Rabbit
2000 2000%12=8 Dragon
2001 2001%12=9 Snake
2002 2002%12=10 Horse
2003 2003%12=11 Goat
2004 2004%12=0 Monkey
2005 2005%12=1 Rooster
2006 2006%12=2 Dog
2007 2006%12=3 Pig
The complete code looks:
import javax.swing.JOptionPane;
public class MyZodiac
{
public static void main(String args[]) throws Exception
{
String zodiac = "";
int y = Integer.parseInt(JOptionPane.showInputDialog("What
year were you born?"));
switch (y%12)
{
case 0: zodiac = "Monkey"; break;
case 1: zodiac = "Rooster"; break;
case 2: zodiac = "Dog"; break;
case 3: zodiac = "Pig"; break;
case 4: zodiac = "Rat"; break;
case 5: zodiac = "Ox"; break;
case 6: zodiac = "Horse"; break;
case 7: zodiac = "Rabbit"; break;
case 8: zodiac = "Dragon"; break;
case 9: zodiac = "Snake"; break;
case 10: zodiac = "Horse"; break;
case 11: zodiac = "Goat"; break;
}
17
Java Game Programming - Penn P. Wu, PhD
JOptionPane.showMessageDialog(null, zodiac);
}
}
The for statement provides a compact way to repetitively perform a number of similar tasks.
The following illustrates a general form of the for structure in Java, where the initialValue is a
variable (such as i) that is assigned the first possible value, the terminalValue is a Boolean
expression (such as i<10) that define the last possible value, and increment defines how the
value of i increase or decrease.
for (initialValue; terminalValue; increment)
{
..............
}
The following table provides four examples to illustrates four different cases.
Example Explanation for (int i=4; i<14; i++)
{
}
• init_value = 4
• term_value = 13 (because i<14)
• increment = 1
for (int i=11; i<=24; i+=3)
{
}
• init_value = 11
• term_value = 24 (because i<=24)
• increment = 3
for (int i=15; i>=1; i--)
{
}
• init_value = 15
• term_value = 1 (because i>=24)
• increment = -1 (or decrement = 1)
for (int i=55; i>11; i-=4)
{
}
• init_value = 55
• term_value = 12 (because i>11)
• increment = -4 (or decrement = 4)
The following code demonstrates how to use a for loop to create 11 JLabel controls and place
them in a JPanel. A JPanel is a container that can host one or more GUI components. The
add() method can insert GUI components to a JPanel. The setBackground() method sets
the background color of a GUI component; however, the setOpaque() methods must be set to
true in order to force the GUI component to paint every pixel within its background.
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Color;
public class MyJava
{
public static void main(String[] args)
{
JPanel pane1 = new JPanel();
for (int i=0; i<=10; i++)
{
JLabel label = new JLabel(String.valueOf(i));
label.setOpaque(true);
label.setBackground(Color.orange);
18
Java Game Programming - Penn P. Wu, PhD
pane1.add(label);
}
JOptionPane.showMessageDialog(null, pane1);
}
}
A sample output looks:
The while loop structure continually executes a block of statements as long as a particular
condition is true. Its syntax can be expressed as:
while (condition)
{
.......
}
The while statement evaluates a Boolean expression, such as (x > 4). If the condition evaluates
to true, the while statement executes the statement(s) in the while block; otherwisem, the entire
while loop is terminated and the control is handed over to the next statement outside the while
loop. In the following example, i starts with a value 15. The while loop evalues if the express
(i>2) is true. If true, the iteration continutes to display the current value of i, substract 1 from the
current value of i, and then checks if the express (i>2) is true. The repetition continues till (i>2)
is false. Apparently, a while loop also supports the three basic components: initialValue,
terminalValue, and increment/decrement.
i=15;
while (i>2)
{
System.out.println(i);
i--;
}
The increment/decrement in a while loop may be omitted due to the programming logic. The
following is a very simple number guessing game. It will continue to ask users to enter a
number from 1 to 9 until the entry matches with the value of rn. The condition to test is (x !=
rn), where x is the value given by the user and rn is assigned by the JVM. The instructor ues
the currentTimeMillis() method of the java.lang.System class to return the current time in
milliseconds (e.g. 1349333576102). The modulus operator will limit the possible value of rn to
0, 1, 2, 3, 4, 5, 6, 7, and 8. The instructors then adds 1 to the value of rn to change its range to 1
~ 9.
import javax.swing.JOptionPane;
public class MyJava
{
public static void main(String[] args)
{
long rn = (System.currentTimeMillis()%9) + 1;
int x = Integer.parseInt(JOptionPane.showInputDialog("Enter a
number [1-9]"));
19
Java Game Programming - Penn P. Wu, PhD
while (x != rn)
{
x = Integer.parseInt(JOptionPane.showInputDialog("Try another
number [1-9]"));
}
JOptionPane.showMessageDialog(null, "Correct!");
}
}
The following example uses a while loop to create eight JButton controls. The initial value of
the counter variable i is 0 (as specified by int i=0), the terminal value is 7 (as specified by i
<= 7), and i increments by 1. By the way, javax.swing.JButton class provides tools to
create clickable buttons.
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.Color;
public class MyJava
{
public static void main(String[] args)
{
JPanel pane1 = new JPanel();
int i=0;
while (i <= 7)
{
JButton button = new JButton(i + "");
button.setOpaque(true);
button.setBackground(Color.green);
pane1.add(button);
i++;
}
JOptionPane.showMessageDialog(null, pane1);
}
}
The output looks:
Java interfaces The Java language comes with many tools for Java programmers to use: Java classes and Java
interfaces. Most tools provided by Java are organized into Java classes that define an specifc
data type with fields and methods to be used by the Java programmers. The JOptionPane class,
for example, provides predefined dialog boxes that are small graphical window that displays a
message to the user or requests input. By “importing” such Java class, programmers can
immediately use methods, such as showMessageDialog(), provided by the JOptionPane class.
import javax.swing.JOptionPane;
............
JOptionPane.showMessageDialog(null, pane1);
A Java “interface” is a collection of abstract methods created to be implemented by other Java
classes without the need to instantiate. In other words, an interface is a group of related methods
20
Java Game Programming - Penn P. Wu, PhD
with empty bodies (can be called “dummy methods”).
A Java interface is not a class; all methods of an interface do not perform any work because
they are just pre-defined “empty” methods. Java interfaces must be implemented by Java
programmers. “Implementing” methods of an interface is similar to “importing” methods from a
parent class, except “implementing” does not require instantiation of the parent class, yet it
requires re-defining of the demanded methods. For example, ActionListener is a frequently
used interface. It defines empty methods for the programmers to implement. The following
demonstrantes how to create a new class named “ButtonListener” which uses the “implements”
keyword to “implement” the ActionListener interface. The ActionListener interface requires
the programmer to re-define its “actionPerformed” method in order to produce results.
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
statusLabel.setText("Ok Button Clicked.");
}
}
Programmers can create custom-made interfaces. The following is an example of a custom-
made interface. It creates an instance of the javax.swing.ImageIcon class named “m1”,
loads an image file from the designated URL, and then uses both getIconWidth() and
getIconHeight() methods to retrieve the image’s width and height.
interface MyImage
{
ImageIcon m1 = new ImageIcon("skull.gif");
int w = m1.getIconWidth();
int h = m1.getIconHeight();
}
To use this custom-made interface, a Java programmer must use the “implements” keyword in
a class declaration. In the followng example, the “MyJava” class implements the “MyImage”
interface.
public class MyJava implements MyImage { .... }
Similar to a class inheritance, all the members defined in an interface can be immediately
inherited, which means the entire code of “MyImage” are logically merged into the “MyJava”
class. The following is the complete code. The “MyImage” is a block shareable code, it can be
saved as a separated file to become an individual Java interface.
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Color;
import javax.swing.ImageIcon;
interface MyImage
{
ImageIcon m1 = new ImageIcon("skull.gif");
int w = m1.getIconWidth();
int h = m1.getIconHeight();
}
public class MyJava implements MyImage
{
public static void main(String[] args)
{
21
Java Game Programming - Penn P. Wu, PhD
JLabel label1 = new JLabel(m1);
JOptionPane.showMessageDialog(null, label1);
}
}
The following is the non-implementation version. The difference is that the bald-faced lines are
private property of the main() function, they are not shareable, not to mention accessible by the
external.
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Color;
import javax.swing.ImageIcon;
public class MyJava
{
public static void main(String[] args)
{
ImageIcon m1 = new ImageIcon("skull.gif");
int w = m1.getIconWidth();
int h = m1.getIconHeight();
JLabel label1 = new JLabel(m1);
JOptionPane.showMessageDialog(null, label1);
}
}
Java organized many of its tools (as part of the language core) as individual interfaces. These
Java interfaces typically contain abstract (empty) methods to be inherited and overridden by
programmer. An interface often assorts with another to maximize its functionality. The
java.awt.event.ActionListener is one of the typical interface. It is necessary to import
both java.awt.event.ActionListener and java.awt.event.ActionEvent classes. A
later lecture will discuss these two classes in details.
...........
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
There are two ways to “implement” the ActionListerner interface. The first way is to create an
additional class (named “MyListener”) that uses the “implements” keyword to inherit the
ActionListerner interface, then override the actionPerformed() method which will be
called when the user clicks a designated button. The following is an example that demonstrates
how to create a custom-made class to inherit tools provided by a Java interface. The
getSource() method returns the object on which the event initially occurred.
...........
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
((JButton) e.getSource()).setBackground(Color.red);
}
}
The above MyListener class is a supporting class; therefore, programmers can create an
insance of it and add it as a listener to the button:
JButton button = new JButton();
22
Java Game Programming - Penn P. Wu, PhD
..........
MyListener listener1 = new MyListener();
button.addActionListener(listener1);
It is possible to create an instance of MyListener within addActionListener() method. The
following demonstrates this short-hand way.
JButton button = new JButton();
..........
button.addActionListener(new MyListener());
The following is the complete code.
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MyJava
{
public static void main(String[] args)
{
JPanel pane1 = new JPanel();
int i=0;
while (i <= 7)
{
JButton button = new JButton(i + "");
button.setOpaque(true);
button.setBackground(Color.green);
button.addActionListener(new MyListener());
pane1.add(button);
i++;
}
JOptionPane.showMessageDialog(null, pane1);
}
}
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
((JButton) e.getSource()).setBackground(Color.red);
}
}
Another way is to have the class directly implement the ActionListener interface, create the
GUI components inside the default constructor of the class, and then override the
actionPerformed() method inside that class. Since the addActionListener() method will
reference to the ActionListener interface through the MyJava class, the keyword “this” is thus
used to represent the MyJava class.
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
23
Java Game Programming - Penn P. Wu, PhD
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MyJava implements ActionListener
{
public MyJava()
{
JPanel pane1 = new JPanel();
int i=0;
while (i <= 7)
{
JButton button = new JButton(i + "");
button.setOpaque(true);
button.setBackground(Color.green);
button.addActionListener(this);
pane1.add(button);
i++;
}
JOptionPane.showMessageDialog(null, pane1);
}
public void actionPerformed(ActionEvent e)
{
((JButton) e.getSource()).setBackground(Color.red);
}
public static void main(String[] args)
{
new MyJava();
}
}
Throughout this course, students will have several opportunities to explode how these two ways
work in handling events.
Object-oriented
programming
Java game codes are more complicated than the above sample codes. They are often written as
object-oriented codes. The so-called “object-oriented programming” is a programming model
that focuses on describing “state” and “behavior” of an identifiable object rather than building
procedural statements to produce results.
In terms of the object-oriented paradigm, “class” and “object” are the two fundamental
concepts. A “class” describes the type of objects while objects are instances of the class. In the
following example, the “MyJava” class contains one method named “ShowXY()” as well as
two fields: x and y. A “field” is a variable of the class. A class “method” is a function defined
for objects of the class to use. Both methods and fields are “members” of the class.
“Encapsulation” is the term that describes the action of grouping related fields, properties,
methods, and other members into one single class for objects of the class to use.
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MyJava
{
public int x; // field
public int y;
24
Java Game Programming - Penn P. Wu, PhD
public void ShowXY() // method
{
JOptionPane.showMessageDialog(null, x + ", " + y);
}
public MyJava() // default constructor
{
x = 10;
y = 10;
}
public MyJava(int _x, int _y) // constructor
{
x = _x;
y = _y;
}
public static void main(String[] args)
{
MyJava g1 = new MyJava(); // create an instance named g1
g1.ShowXY();
g1.x++;
g1.y++;
JOptionPane.showMessageDialog(null, g1.x + ", " + g1.y);
MyJava g2 = new MyJava(12, 12); // another instance named g2
g2.ShowXY();
}
}
Before using the class members, an instance of the class must be created. The act of declaring
and creating an object is called “instantiation”. The following demonstrates how to “declare”
an instance, and then actually create the instance. Once the instance is created, it becomes an
individual object of the class, and the class defines the “data type” of the object.
MyJava g1; // declare
g1 = new MyJava(); // create
It is quiet common to declare and create an instance in one single statement. In the above code,
instantiation is done by the following statement, where “g1” is an instance of the MyJava class
and is the name of an object. Technically, the following statement is saying “g1 is a MyJava”.
MyJava g1 = new MyJava();
Object-oriented programming uses the following formats to access class members, after
instantiation. It is necessary to note that the dot (.) is the required separator between the object
ID and the member identifier.
Field Method objectID.FieldName objectID.MethodName()
The following demonstrates how the g1 object uses the ShowXY() method.
g1.ShowXY();
The following illustrates how g1 uses the class fields: x and y. By the way, ++ is the increment
operator which adds 1 to the current values of x and y.
g1.x++;
25
Java Game Programming - Penn P. Wu, PhD
g1.y++;
A class can have constructors. A constructor in a class is a special type of subroutine to be
called to actually create object. All constructor in a class must have the same identifier as the
class. In the following statements, MyJava is the identifier of a class while MyJava() and
MyJava(int _x, int _y) are two forms of constructor of the MyJava class. Both _x and _y are
parameters. A parameter is a variable of a constructor or a method.
public class MyJava
{
......
public MyJava() { ... }
......
public MyJava(int _x, int _y) { ... }
......
}
An object-oriented class in Java typically has a “default constructor”, which is a no-parameter
constructor. When multiple forms of constructor exist in a class, only the matching constructor
is automatically called whenever a class instantiation happens, to create an instance of the class.
The MyJava(int _x, int _y) constructors is call when the users specify parameters.
Having multiple forms that can be used interchangeably is known as “polymorphism”.
MyJava g1;
g1 = new MyJava(); // call default constructor
........
MyJava g2 = new MyJava(12, 12); // call constructor
Classes often have some commonalities. It might be a good idea to extract all the common part
of code from every classes to form a new class. The class with all the common codes can then
be accessed by all other classes to save coding effots. Object-oriented programming allows
classes (called sub-classes) to inherit members of another class (called super-class). In the
following example, the “Alients” class is a super-class which contain one public field named
“planet”. Both the “Martians” and “Saturnian” classes can inherit the “planet” field through
the “inheritance” relationship. Inheritance describes the ability to create new classes based on
an existing class. The syntax for creating a sub-class is simple. At the beginning of the sub-class
declaration, add the “extends” keyword followed by the name of super-class. In the following
example, all the coding details are provided by the “Alients” class.
//File name: StarWar
class Alients
{
public String planet;
public String target;
public void attack()
{
System.out.println(planet + " destroyed " + target);
}
}
class Martians extends Alients { }
class Saturnian extends Alients { }
public class StarWar
{
public static void main(String[] args)
{
26
Java Game Programming - Penn P. Wu, PhD
Martians m1 = new Martians();
m1.planet = "Mars";
m1.target = "Saturn";
m1.attack();
Saturnian s1 = new Saturnian();
s1.planet = "Saturn";
s1.target = "Mars";
s1.attack();
}
}
A sample output looks:
C:\Users\user>java StarWar
Mars destroyed Saturn
Saturn destroyed Mars
Late lectures will discuss and demonstrates how object-oriented programming applies to Java
game programming.
Java’s
Coordinate
System
To program Java games, students must understand how Java handles its coordinate system on a
computer. The term “coordinates” refers to a set of values that show an exact position.
Throughout this course, students will frequently encounter two types of coordinate: desktop
coordinate and JFrame coordinate. It is necessary to understand how coordinate systems
determines the locations of GUIs (graphical user interfaces). By the way, both desktop and
JFrame coordinates use the monitor screen’s resolution as scales. The following is a sample
code that uses the java.awt.Dimension class to find the resolution of the current Windows
desktop.
import javax.swing.JOptionPane;
import java.awt.Dimension;
import java.awt.Toolkit;
public class MyJava
{
public static void main(String[] args)
{
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
Double width = d.getWidth();
Double height = d.getHeight();
JOptionPane.showMessageDialog(null, width + ", " + height);
}
}
The following is sample output, which means (a) horizontally there are 1600 lines and (b)
vertically there are 900 lines on the screen.
In a computer’s desktop, which is a 2-dimensional rectangular area, coordinates can be
expressed as (x, y). The desktop’s current resolution, such as 1600×900, determines the “scale”
of the coordinate. A 1600×900 resolution means that there are 1,600 units per horizontal lines,
and 900 units per vertical lines. Each unit on a computer screen is known as a pixel.
27
Java Game Programming - Penn P. Wu, PhD
A GUI-based Java application, which is typically created by using the JFrame class (a later
lecture will discuss it in details), is usually place in a viewable location of a desktop. In the
above figure, the Java application is placed at a location (350, 170) of the desktop. By the way,
the upper-leftmost point of the JFrame represent the location of the entire JFrame-based
application.
All the game objects hosted by the JFrame; however, uses the coordinate defined by the JFrame.
A JFrame typically has a inner border that defines the content area. The upper left-most point of
the innser border is the (0, 0) point. All game object hosted by the JFrame have their (x, y)
defined as x- and y-distance from this (0, 0) point.
A GUI-based Java application may contain several GUI controls, such as text fields, buttons,
checkboxes, and so on. Controls are placed inside the viewable area of a JFrame or JPanel of
the JFrame. These controls must use the JFrame coordinate system. In the above figure, there
are nine Label controls. The first one is placed at (0, 0) of the JFrame’s viewable area. By
default the upper-leftmost point of the JFrame’s viewable area has the coordinate (0, 0). As in
mathematics, a coordinate set is paired with an x and a y value representing the horizontal and
vertical place respectively. The only difference is that, in the GUI coordinately system, the y
axis has it value increase positively from up to down.
In Java, if a square has a location (50, 100), then it is placed at the
Color Several of the above sample codes use the setBackground() method to set the background
color of a GUI component, as illustrated below.
(x, y)
(0, 0) x axis
y axis
(350, 170)
900 units
1,600 units
(350, 170)
(50, 100)
(0, 0) x axis
y axis
(0,0)
28
Java Game Programming - Penn P. Wu, PhD
label1.setBackground(Color.green);
The java.awt.Color class create new colors; therefore, it is necessary to import it.
imports java.awt.Color;
Color is used frequently in GUI programming. Java allows the creation of up to 24 million
different colors. Human eyes have three kinds of neurons, each primarily respond to red, green,
and blue, the computer graphics naturally adopt the RGB system. Every of the three color
elements, r, g, and b, is represented by a number from 0 to 255. For example, Red is (255, 0, 0),
Green is (0, 255, 0), Blue is (0, 0, 255), White is (255, 255 ,255), and Black is (0,0,0). The
Color constructor has a syntax of:
new Color(int r, int g, int b)
The values of each color must be in the range 0-255 with 0 being least possible value and 255
being the largest possible value. The following creates a new color object that is a combination
of red, green, and blue.
Color c = new Color(255, 255, 240);
label1.setBackground(c);
The Color class provides some color names. The followings are some sample color names. Color.black Color.lightGray Color.cyan Color.orange
Color.blue Color.magenta Color.darkGray Color.pink
Color.white Color.red Color.green
Color.yellow Color.gray Color.brown
The Color class declares methods and constants for manipulating colors in a Java program.
Table: Color constant and RGB values
Color constant Color RGB value public final static Color RED red 255, 0, 0
public final static Color GREEN green 0, 255, 0
public final static Color BLUE blue 0, 0, 255
public final static Color ORANGE orange 255, 200, 0
public final static Color PINK pink 255, 175, 175
public final static Color CYAN cyan 0, 255, 255
public final static Color MAGENTA magenta 255, 0, 255
public final static Color YELLOW yellow 255, 255, 0
public final static Color BLACK black 0, 0, 0
public final static Color WHITE white 255, 255, 255
public final static Color GRAY gray 128, 128, 128
public final static Color LIGHT_GRAY light gray 192, 192, 192
public final static Color DARK_GRAY dark gray 64, 64, 64
The following example demonstrates how to set foreground and background of a GUI
component. While the setBackground() method sets the background color of a GUI
component, the setForeground() method sets the color of text of the GUI component.
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.Color;
public class MyJava
{
public static void main(String[] args)
{
29
Java Game Programming - Penn P. Wu, PhD
JButton button1 = new JButton("Java is fun.");
button1.setOpaque(true);
button1.setBackground(Color.blue);
button1.setForeground(Color.white);
JOptionPane.showMessageDialog(null, button1);
}
}
Review
Questions
1. Given the following statement, which statement is correct?
//import javax.swing.JOptionPane;
class MyJava { }
A. The JOptionPane class will be imported to the MyJava class.
B. The JOptionPane class will not be imported to the MyJava class.
C. The JOptionPane specifies that MyJava is a sub-class of JOptionPane.
D. The JOptionPane specifies that MyJava is a super-class of JOptionPane.
2. If a Java application is named "MyJava.java", __.
A. Its byte code (class file) is named "MyJava.class".
B. In its source code, there is a class named "MyJava".
C. If there is a default constructor, the constructor's name is "MyJava()".
D. All of the above
3. Which is the correct way to declare a variable named "x" of the float type and assign an initial
value 4.172 to it in Java?
A. x = (float) 4.172;
B. x = 4.172F;
C. float x = 4.172f;
D. float x = 4.172;
4. The output of the following is __.
int x = 15;
int y = 3;
JOptionPane.showMessageDialog(null, (x%y));
A. 15%3
B. x%y
C. 0
D. 0.5
5. The output of the following is __.
int x = 5;
int y = 3;
JOptionPane.showMessageDialog(null, (x/y));
A. 1
B. 1.666666666666667
C. 5/3
D. x/y
6. The output of the following is __.
int x = 5;
int y = 3;
JOptionPane.showMessageDialog(null, (x!=y));
30
Java Game Programming - Penn P. Wu, PhD
A. 1
B. true
C. yes
D. correct
7. Which is a Java keyword and you should avoid using it as a variable name?
A. school
B. kent
C. const
D. fractional
8. If you have a numerical data "6.25", which Java data type will you choose to declare a
varaible for it?
A. int
B. double
C. string
D. fractional
9. The x variable is originally declared as in integer (int). Which is the correct way of type
casting in Java?
A. (double) x;
B. x (double);
C. double x;
D. x double;
10. Given the followng code, which statement is correct?
label1.setBounds(50,100,20,20);
A. The width of label1 is 100
B. The height of label1 is 50
C. The y-coordiante of label1 is 50
D. The x-coordinate of label1 is 50
31
Java Game Programming - Penn P. Wu, PhD
Lab #1 Java Basics for Game Programming
Configuration #1: Installing Java JDK and Configuration
1. Use Internet Explorer to visit
http://www.oracle.com/technetwork/java/javase/downloads/index.html site. Click the “JDK”
button to download the JDK file. Be sure to choose the one that match with the type of your operating systems.
OS File Name
Windows jdk-9.0.1_windows-x64_bin.exe
Mac OS X x64 jdk-9.0.1_osx-x64_bin.dmg
Linux jdk-9.0.1_linux-x64_bin.rpm
Be sure to check the Oracle web for the newest list of file names.
2. Launch the JDK installation file (e.g. jdk-9.0.1_windows-x64_bin.exe).
3. Click Next till the installation begins, wait till the “Custom Setup” window appears.
4. Write down the path of the “Install to:” column (e.g. “C:\Program Files\Java\”). Click Next. wait till the
installation completes, and then click Close.
32
Java Game Programming - Penn P. Wu, PhD
5. Open the “Advanced system settings” box according to one of the following operating systems. Skip to
Configuration #2 if you do not have administrator priviledge to complete this step.
OS Procedures
Windows 10 1. Right click the Start menu ( ) and then click “System”.
2. In the search column, type “Advanced system settings”, and then click on “View
advanced system settings”.
Windows 8.1 1. Press Windows ( ) + C.
2. Click Settings and then Control Panel.
3. On the popping up window, click System icon.
4. Click the “Advanced system settings” link.
Windows 7 1. Click the start menu.
2. Right click “My Computer”, and then select “Properties”.
3. Click the “Advanced system settings” link.
7. Click “Advanced” tab.
8. Click “Enviroment Variables..”.
Windows 10 Other version of Windows
1. In the “User variables for user” windows, as shown below, 1. Simply find the PATH variable under
33
Java Game Programming - Penn P. Wu, PhD
select the PATH variable, and then click the “Edit...”
button of the “System variables” section.
2. In the “Edit environement variable” window, click the
“New” button, and then add the correct path (such as
C:\Program Files\Java\jdk-9.0.1\bin;). Be sure
to add a semicolon (;) between the existing entry and the
new entry.
3. Click OK to close all opened windows.
the “System Variables” section, and then
click the “Edit” button.
2. In the Edit windows, modify PATH by
adding the correct value (e.g. C:\Program Files\Java\jdk-
9.0.1\bin;). Be sure to add a
semicolon (;) between the existing entry
and the new entry.
3. Click OK to close all opened windows.
9. Launch the Windows’ Command Prompt. (visit
http://pcsupport.about.com/od/commandlinereference/f/open-command-prompt.htm for
instructions). The prompt is similar to following, where user might be your user id. C:\users\user>
10. Type javac.exe (or simply java) and press [Enter]. Verify the result. If the configuration has completed
successfully, skip to Configuration #3. If the configuration has failed, return to step #6. If you do not have the
priviledge to modify the system setting, simply proceed to Configuraiton #2.
Configuration succeeded Configuration failed C:\users\user>javac.exe
Usage: javac <option> <source files>
where possible options include:
-g Generate all debugging info
-g:none Generate no debugging info
................
................
-X Print a synopsis of nonstanrd options
-J<flag> Pass <flag> directly to the runtime system
C:\users\user>javac.exe
'javac' is not recognized as an
internal or external command,
operable program or batch file.
Configuration #2: (Ignore this section if you successfully completed Configuration #1)
34
Java Game Programming - Penn P. Wu, PhD
1. Open a Command Prompt (visit http://pcsupport.about.com/od/commandlinereference/f/open-
command-prompt.htm for instructions). The prompt is similar to following, where user might be your user id.
C:\Users\user>
2. In the prompt, type md C:\javagame to make a new directory named “C:\javagame”.
C:\Users\user>md C:\javagame
3. In the prompt, type cd C:\javagame and press [Enter] to change to C:\javagame directory.
C:\Users\user>cd C:\javagame
C:\javagame>
4. Type notepad 1.bat and press [Enter] to create a new batch file named “1.bat” with Notepad.
C:\javagame>Notepad 1.bat
5. In the Notepad window, type in the correct path. If the your path is different from the one in the following
bordered area, be sure to use the correct one.
PATH = %PATH%;C:\Program Files\Java\jdk-9.0.1\bin;
6. Save and exit the 1.bat file. You should return to the C:\javagame directory. You need this 1.bat file
throughout the entire course. Do not delete it.
C:\javagame>
7. In the prompt, type 1.bat and press [Enter] to execute the batch file. A sample output looks similar to the
following. Check to make sure the JDK path is added to the system path.
C:\javagame>1.bat
C:\javagame>PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\system32\wbem;C:\altera\
quartus60\bin;.......;C:\Program Files\Java\jdk-9.0.1\bin;
8. Type javac.exe (or simply java) and press [Enter]. If the following message appears, proceed to
Configuration #3. Otherwise, read Appendix A for remedy.
C:\javagame>javac.exe
Usage: javac <option> <source files>
where possible options include:
-g Generate all debugging info
-g:none Generate no debugging info
................
................
-X Print a synopsis of nonstanrd options
-J<flag> Pass <flag> directly to the runtime system
Configuration #3:
1. Unchecking hide extension option based on the operating systems.
(For Windows 10/8 Users Only) (For Windows 7/Vista Users Only)
1. Launch the Windows Explorer.
2. Click “View”.
3. Check the “File name extension” option.
1. Launch the Windows Explorer.
2. Click “Folders and search options”
3. Click the View tab, and then uncheck the
“Hide extensions for known file types”
option.
35
Java Game Programming - Penn P. Wu, PhD
4. Proceed to Preparation #1 now.
4. Click OK. Proceed to Preparation #1 now.
2. Open a Command Prompt (visit http://pcsupport.about.com/od/commandlinereference/f/open-
command-prompt.htm for instructions). The prompt is similar to following, where user might be your user id.
C:\Users\user>
3. In the prompt, type md C:\javagame to make a new directory named “C:\javagame”.
C:\Users\user>md C:\javagame
4. In the prompt, type cd C:\javagame and press [Enter] to change to C:\javagame directory.
C:\Users\user>cd C:\javagame
C:\javagame>
Learning Activity #1: Refresh your memory
1. Be sure to complete the Configuration #3 before proceed to the next steps.
2. Open the Command Prompt, and type cd c:\javagame and press [Enter] to change to the C:\javagame
directory.
C:\Users\user>cd C:\javagame
C:\javagame>
3. In the C:\javagame directory, type notepad lab1_1.java and press [Enter] to use Notepad to create a new
text file named “lab1_1.java” under the C:\javagame directory.
C:\javagame>notepad lab1_1.java
4. In the Notepad window type in the following contents (be sure to replace YourFullname with the correct one):
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
public class lab1_1
{
public static void main(String[] args)
{
36
Java Game Programming - Penn P. Wu, PhD
JPanel pane1 = new JPanel();
JLabel label1 = new JLabel("Welcome to Java Game programming!");
JButton button1 = new JButton("Click me");
pane1.add(label1);
pane1.add(button1);
JOptionPane.showMessageDialog(null, pane1, "lab1_1/YourFullName",
JOptionPane.INFORMATION_MESSAGE );
}
}
5. Type javac lab1_1.java and press [Enter] to compile it. If the Java compiler (javac.exe) returns no error
message, the compilation succeeds.
C:\javagame>javac lab1_1.java
6. Type dir lab1_1.* and press [Enter] to display a list of file with the name “lab1_1”. The output looks similar
to:
C:\javagame>dir lab1_1.*
Volume in drive C has no label.
Volume Serial Number is 84AF-8E2B
Directory of C:\javagame
10/17/2015 02:25 PM <DIR> .
10/17/2015 02:25 PM <DIR> ..
10/17/2015 02:25 PM 424 lab1_1.class
10/17/2015 02:25 PM 118 lab1_1.java
4 File(s) 593 bytes
2 Dir(s) 67,924,176,896 bytes free
7. Type java lab1_1 and press [Enter] to execute only the byte code (class file). The java.exe program execute
the byte code.
C:\javagame>java lab1_1
8. A sample output looks:
9. Download the “assignment template”, and rename it to lab1.doc if necessary. Capture a screen shot similar to
the above figure and then paste it to a Word document named “lab1.doc” (or .docx). If you do not have Micrsoft
Word installed in you system, you can use whatever word processor software to copy and paste the screen shots,
and then save as .pdf file.
Learning Activity #2:
1. Download and unzip the labfile1.zip file (available in Blackboard) to C:\javagame directory. This file contains
the “skull.gif” graphic file.
2. In the C:\javagame directory, type notepad lab1_2.java and press [Enter] to create a new text file named
“lab1_2.java”, save it under the C:\javagame directory.
.class file is the byte code, which is the
object code (machine readable code) of
the Java program.
.java file is the source code.
37
Java Game Programming - Penn P. Wu, PhD
C:\javagame>notepad lab1_2.java
3. Type the following contents (be sure to replace YourFullname with the correct one):
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Color;
import javax.swing.ImageIcon;
interface MyImage // custom-made interface
{
ImageIcon m1 = new ImageIcon("skull.gif");
int w = m1.getIconWidth();
int h = m1.getIconHeight();
}
public class lab1_2 implements MyImage
{
public static void main(String[] args)
{
JPanel pane1 = new JPanel();
pane1.setBackground(Color.white);
JLabel label1 = new JLabel(m1);
pane1.add(label1);
JOptionPane.showMessageDialog(null, pane1, "lab1_2/YourFullName",
JOptionPane.INFORMATION_MESSAGE );
}
}
4. Type javac lab1_2.java and press [Enter] to compile the source code to a Java class file.
C:\javagame>javac lab1_2.java
5. Type java lab1_2 and press [Enter] to test the program.
C:\javagame>java lab1_2
6. A sample output looks:
7. Capture a screen shot similar to the above figure and then paste it to a Word document named “lab1.doc”
(or .docx).
Learning Activity #3:
1. In the the C:\javagame directory, type notepad lab1_3.java and press [Enter] to create a new text file
named “lab1_3.java” with the following contents (be sure to replace YourFullname with the correct one):
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
38
Java Game Programming - Penn P. Wu, PhD
public class lab1_3
{
JButton button1; // global
int x = 0;
public lab1_3()
{
button1 = new JButton("Click me.");
button1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
x++;
button1.setText("You clicked me " + x + " times.");
}
});
JOptionPane.showMessageDialog(null, button1, "lab1_3/YourFullName",
JOptionPane.INFORMATION_MESSAGE);
}
public static void main(String[] args)
{
new lab1_3();
}
}
2. Type javac lab1_3.java and press [Enter] to compile the source code to a Java class file.
3. Type java lab1_3 and press [Enter] to test the program. Click the white area inside the form few tiems.
and
4. Capture a screen shot similar to the above figure and then paste it to a Word document named “lab1.doc”
(or .docx).
Learning Activity #4:
1. In the C:\javagame directory, use Notepad to create a new text file named “lab1_4.java” with the following
contents:
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class lab1_4
{
public static void main(String[] args)
{
JPanel pane1 = new JPanel();
int i=0;
while (i <= 7)
{
JButton button = new JButton(i + "");
39
Java Game Programming - Penn P. Wu, PhD
button.setOpaque(true);
button.setBackground(Color.green);
button.addActionListener(new MyListener());
pane1.add(button);
i++;
}
JOptionPane.showMessageDialog(null, pane1, "lab1_4/YourFullName",
JOptionPane.INFORMATION_MESSAGE);
}
}
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
((JButton) e.getSource()).setBackground(Color.red);
}
}
2. Compile the source code to a Java class file.
3. Type java lab1_4 and press [Enter] to test the program. The skull move from left to right and constantly
changes its color.
and
4. Capture a screen shot similar to the above figure and then paste it to a Word document named “lab1.doc”
(or .docx).
Learning Activity #5:
1. In the C:\javagame directory, use Notepad to create a new text file named “lab1_5.java” with the following
contents:
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class lab1_5 implements ActionListener
{
public lab1_5()
{
JPanel pane1 = new JPanel();
for (int i=0; i<=10; i++)
{
JButton button = new JButton(String.valueOf(i));
button.setOpaque(true);
button.addActionListener(this);
switch (i)
{
case 0: button.setBackground(Color.yellow); break;
case 1: button.setBackground(Color.green); break;
40
Java Game Programming - Penn P. Wu, PhD
case 2: button.setBackground(Color.white); break;
case 3: button.setBackground(Color.blue); break;
case 4: button.setBackground(Color.red); break;
case 5: button.setBackground(Color.pink); break;
case 6: button.setBackground(Color.magenta); break;
case 7: button.setBackground(Color.gray); break;
case 8: button.setBackground(Color.cyan); break;
case 9: button.setBackground(Color.orange); break;
case 10: button.setBackground(new Color(24, 149, 210)); break;
}
pane1.add(button);
}
JOptionPane.showMessageDialog(null, pane1, "lab1_5/YourFullName",
JOptionPane.INFORMATION_MESSAGE);
}
public void actionPerformed(ActionEvent e)
{
((JButton) e.getSource()).setBackground(Color.black);
((JButton) e.getSource()).setForeground(Color.white);
}
public static void main(String[] args)
{
new lab1_5();
}
}
2. Compile the source code to a Java class file.
3. Type java lab1_5 and press [Enter] to test the program.
and
4. Capture a screen shot similar to the above figure and then paste it to a Word document named “lab1.doc”
(or .docx).
Submittal
1. Upon complete all the learning activities, create a zip file named lab1.zip with only the following files in it.
• lab1_1.class
• lab1_2.class
• lab1_3.class
• lab1_4.class
• lab1_5.class
• lab1.doc (or docx or .pdf) [You may receive zero point if this file is missing]
2. Upload the zipped file.
Programming Exercise 01:
1. Use Notepad to create a new text file named “ex01.java” with the following lines. Be sure to change
YourFullName to the correct one.
/* Student: YourFullName
File name: ex01.java */
41
Java Game Programming - Penn P. Wu, PhD
2. Next to the above lines, write a Java code that will create a JButton control in a message dialog. Use the JButton
to display your full name, set the background color of the JButton to orange, add an action listener to the the
JButton such that its background color will change to red whining being clicked. [hint: showMessageDialog()]
3. Compile and test the program. A sample output looks:
and
4. Download the “programming exercise template”, and rename it to ex01.doc if necessary. Capture a screen shot
similar to the above figure and then paste it to a Word document named “ex01.doc” (or .docx).
5. Compress the source file (ex01.java), bytecode (ex01.class), and Word document (ex01.doc or docx or .pdf) to
a .zip file named “ex01.zip”. Upload the .zip file.
Appendix A: Remedy
1. Use a web browser to download the http://students.cypresscollege.edu/cis244/files/jdk.zip
file and extract its content to a local drive or a USB flash drive. Record the drive name: __________ (e.g. “C”
or “F”).
2. Open a Command Prompt.
C:\Users\user>
3. Type x: and press [Enter] to change to the drive (replace “x” with the correct drive name). The following use
“F” as example.
C:\Users\user>f:
F:\>
4. Type dir jdk* and press [Enter] to verify the existence of the JDK. If you can find the “jdk-9.0.1”, then the
jdk is ready for you to use.
F:\>dir jdk*
Volume in drive F is ANDROID-X86
Volume Serial Number is B0D8-B24A
Directory of F:\java
08/30/2015 09:36 PM <DIR> jdk-9.0.1
0 File(s) 0 bytes
1 Dir(s) 5,955,026,944 bytes free
5. Type 1.bat and press [Enter] to temporarily set the path. A sample output looks:
F:\>1.bat
F:\javagame>
6. If the prompr indicates that you are now in the “javagame” directory, you can return to condifuerion #3.
Otherwise, contact the instructor for help.