Title: Java Getting Started
1Java Getting Started
- Ching-Hong Tsai
- CSIE, National Chiao-Tung University
- chtsai_at_csie.nctu.edu.tw
2Introduction
- The Java Phenomenon
- The Hello World Applet
- The Hello World Application
3The Java Phenomenon
- Origins of Java
- Features of Java
- Java Applet and Application
4Origins of Java
- 1991 Sun Microsystems
- James Gosling
- Create programs to control consumer electronics
- C is not suitable
- From Oak to Java
- Early Project - Green Team
- Star Seven (7)
- In 2Q of 1995, Sun Microsystems officially
announced Java and HotJava
5What is Java?
- Java is a general-purpose, high-level programming
language. - The features of Java
- Java program is both compiled and interpreted.
- Write once, run anywhere
6Features of Java
- Simple
- Architecture-neutral
- Object-Oriented
- Distributed
- Compiled
- Interpreted
- Statically Typed
- Multi-Threaded
- Garbage Collected
- Portable
- High-Performance
- Robust
- Secure
- Extensible
- Well-Understood
7How Will Java Change My Life
- Get started quickly
- Write less code
- Write better code
- Develop programs faster
- Avoid platform dependencies with 100 pure Java
- Write once, run anywhere
- Distribute software more easily
8Java Applets and Applications
- Applet
- Run under a Java-Enabled Browser
- Stand-alone Applications
- Just like any programming languages
9Java Developer's Kit (I)
- Java's programming environment
- compiler
- interpreter
- debugger
- disassembler
- profiler
- more...
10Java Developer's Kit
Java Interpreter
Java Compiler
Compile
Run
Java Source
Java Bytecode
ltfilegt.java
ltfilegt.class
Java Disassembler
11Java Is Compiled and Interpreted
12Prepare and Execute Java
Internet
Verification
Your computer
Java ByteCode
Execution
Restricted Env.
13Write Once, Run Anywhere
14The Hello World Application
- Comments in Java Code
- Defining a Class
- The main() Method
- Using Classes and Objects
15Create a Java Source File
- HelloWorldApp/ The HelloWorldApp class
implements an application that simply displays
"Hello World!" to the standardoutput. /public
class HelloWorldApp public static void
main(String args) System.out.println("Hello
World!") //Display the string.
16Compile and Run
- Compile
- javac HelloWorldApp.java
- Run
- java HelloWorldApp
17Comments in Java Code
- / Text /
- / Documentation / (Used by javadoc tool)
- //Text (Ignore everything from // to the end of
the line)
18Defining a Class
- Define a class in Java
- class name .
- In Java, every method (function) and variable
exists within a class or an object. - Java does not support global functions or
variables. - The Hello World application has no variables
and has a single method named main.
19The main Method
- Each Java application must contain a main method
whose signature looks like this - public static void main(String args)
- Modifier in the main method
- public The main method can be called by any
object. - static The main method is a class method.
- void The main method does not return any value.
20Using Classes and Objects
- A class method or class variable is associated
with a particular class. - ltclass namegt.ltmethod/variable namegt
- An instance method or instance variable is
associated with a particular object (an instance
of a class) - ltinstance namegt.ltmethod/variable namegt
21The Hello World Applet
- Importing Classes and Packages
- Defining an Applet Subclass
- Implementing Applet Methods
- Running an Applet
22Create a Java Source File
- HelloWorld.javaimport java.applet.Appletimport
java.awt.Graphicspublic class HelloWorld
extends Applet public void paint(Graphics g)
g.drawString(Hello World!, 50, 25)
23Compile the Source File
- javac HelloWorld.java
- One file named HelloWorld.class is created if the
compilation is succeeds.
24Create an HTML File that Includes the Applet
- Hello.htmlltHTMLgtltHEADgtltTITLEgt A Simple Program
lt/TITLEgtlt/HEADgtltBODYgt Here is the output of my
programltAPPLET CODE"HelloWorld.class"
WIDTH150 HEIGHT60gtlt/APPLETgtlt/BODYgtlt/HTMLgt
25Import Classes and Packages
- Packages are used to group classes, similar to
the way libraries are used to group C functions. - Importing classes lets a program refer to them
later without any prefixes. - Within a package, all classes can refer to each
other without prefixes. - java.applet and java.awt packages are part of the
core Java API - You can also import entire packages
26Defining An Applet Subclass
- The extends keyword indicates the HelloWorld is a
subclass of the class whose name follows Applet. - The Applet class has the ability to respond to
browser requests and others. - An applet isnt restricted to defining just one
class.
27Implementing Applet Methods
- Every applet must implement one or more of the
init, start, and paint methods. - An applet can implement two more methods stop
and destroy. - An applet does not need to implement a main
method, like a Java Application.
28Running An Applet
- Use ltAPPLETgtlt/APPLETgt in a HTML file to refer to
an Java applet. - ltAPPLET CODEJava_Class WIDTHltNgt HEIGHTltMgt gt
29Without Import
- public class HelloWorld extends
java.applet.Applet public void
paint(java.awt.Graphics g)
g.drawString(Hello World!, 50, 25)
30Import Entire Packages
- HelloWorld.javaimport java.applet. import
java.awt. public class HelloWorld extends
Applet public void paint(Graphics g)
g.drawString(Hello World!, 50, 25)
31Object-Oriented Programming Concepts
- What are Objects?
- What are Classes?
- What are Messages?
- What is Inheritance?
32What Are Objects?
- Definition An object is a software bundle of
variables and related methods. - These real-world objects characteristics they
all have state and they all have behavior. - A software object
- maintains its state in variables
- implements its behavior with methods
33What Are Objects?
- For example
- dogs have state (name, color, breed, hungry)
- dogs have behavior (barking, fetching, and
slobbering on your newly cleaned slacks) - Bicycles have state (current gear, current pedal
cadence, two wheels, number of gears) - Bicycles have behavior (braking, accelerating,
slowing down, changing gears)
34What Are Objects?
- You can represent real-world objects using
software objects - You might want to represent real-world dogs as
software objects in an animation program - A real-world bicycle as a software object within
an electronic exercise bike
35Visual Representation of A Software Object
Variable
Method
36Software Bicycle
- Instance Variables and Instance Method
37Encapsulation
- Packaging an object's variables within the
protective custody of its methods - Methods surround and hide the object's center
from other objects. - Benefit of encapsulation
- Modularity
- Information hiding
38Encapsulation
- Change gears on your bicycle, you don't need to
know how the gear mechanism works, you just need
to know which lever to move - In many languages, including Java, an object can
choose to expose its variables to other objects
allowing those other objects to inspect and even
modify the variables.
39What Are Classes?
- Definition A class is a blueprint or prototype
that defines the variables and methods common to
all objects of a certain kind - An object is an instance of a certain class.
- After you've created the class, you must
instantiate it (create an instance of it) before
you can use it - The benefit of Classes Reusability
40What Are Classes?
- Class variables and class methods
- You can access class variables and methods from
an instance of the class or directly from a
class. - All instances share this variable. If one object
changes the variable, it changes for all other
objects of that type.
41Visual Representation of A Software Class
42What Are Messages?
- Software objects interact and communicate with
each other by sending messages to each other.
43Message Example
44More on Messages
- Components of a Message
- The object to whom the message is addressed (Your
Bicycle) - The name of the method to perform(changeGears)
- Any parameters needed by the method (low gear)
- Your Bicycle.changeGears(low gear)
45More on Messages
- The Benefits of Messages
- Messages passing supports all possible
interactions between objects (aside from direct
variable access) - Objects dont need to be in the same process or
even on the same machine to send and receive
messages.
46What is Inheritance?
- Inheritance allows classes to be defined in terms
of other classes - superclass and subclass
- Each subclass inherits variables and methods from
its superclass. - Subclasses can add variables and methods to the
ones they inherit from the superclass.
47What is Inheritance?
- Subclasses can also override inherited method and
provide specialized implementations for those
methods. - Inheritance or class hierarchy
- The inheritance tree, or class hierarchy, can be
as deep as needed. - Methods and variables are inherited down through
the levels
48Benefits of Inheritance
- Programmers can reuse the code in the superclass
many times. - Programmers can implement superclasses called
abstract classes - Abstract class defines generic behaviors
- Define and may partially implement the behavior
but much of the class is undefined and
unimplemented. Other programmers fill in the
details with specialized subclasses.
49Inheritance Example
50Java Programming Language Overview
- General Features of Java Programming Language
- Variables and Data Types
- Operators
- Expressions
- Control Flow Statements
- Introduction to Classes and Object
- Introduction to Java Classes
- The Life Cycle of an Object
51General Features of Java Programming Language
- Variables and Data Types
- Operators
- Expressions
- Control Flow Statements
- Array
52The Count Class
- import java.io.public class Count public
static void countChars(Reader in)
throws IOException int count 0
while (in.read() ! -1) count
System.out.println("Counted " count "
chars.")
53Running the countChars
- import java.io.public class Count // ...
countChars method omitted ...public static void
main(String args) throws Exceptionif
(args.length gt 1) countChars(new
FileReader(args0))else System.err.println("U
sage Count filename")
54Variables and Data Types
- Variable Declaration
- Data Type
- Variable
55Variable Declaration
- Variable Declaration
- Type of the variable
- Name of the variable
- The location of the variable declaration
determines its scope.
56Data Type
- Java is static-typed All variables must have a
type and have to be declared before use. - A variables' data type determines its value and
operation - Two categories of data types in Java
- primitive data type byte, short, int, long,
float.... - reference data type class, interface, array
57Primitive Data Types
- byte 8-bit
- short 16-bit
- int 32-bit
- long 64-bit
- float 32-bit floating point
- double 64-bit floating point
- char 16-bit Unicode
- boolean true/false
58Variable Names
- Java refers to a variable's value by its name.
- General Rule
- Legal Java identifier
- Not a keyword or a boolean literal
- Not the same name as another in the same scope
- Convention
- Variable names begin with a lowercase letter
- Class names begin with an uppercase letter
59Variable Scope
- The location of the variable declaration within
your program establishes its scope - Variable Scope
- Member variable
- Local variable
- Method parameter
- Exception-handler parameter
60Variable Scope
61Variable Initialization
- Local variables and member variables
- can be initialized with an assignment statement
when they're declared. - data type of the assignment statement must match.
- Method parameters and exception-handler
parameters - cannot be initialized in the same way as
local/member variables - The value for a parameter is set by the caller.
62Final Variables
- The value of a final variable cannot change after
it has been initialized. - You can view final variables as constants.
- Declaration and Initialization
- final int aFinalVar 0
- final int blankfinal . . .
blankfinal 0
63Literals (I)
- To represent the primitive types
- Integer
- Decimal Value
- Hexadecimal Value 0x... (0x1f 31)
- Octal Value 0... (07662)
- Floating Point
- 3.1415
- 6.1D2 (64-bit Double Default)
- 3.4F3 (32-bit Float)
64Literals (II)
- Characters
- ' ..... '
- '\t', '\n' (Escape Sequence)
- Strings
- "......."
- String Class (Not primitive data type)
65Operators
- Operators perform some function on operands.
- An operator also returns a value.
66Operators (I)
- Arithmetic Operators
- Binary , -, , /,
- Unary , -, op, op, op--, --op
- Relational Operators
- gt, gt, lt, lt, , ! (return true and false)
- Conditional Operators
- (AND), (OR), !(NOT), (AND), (OR)
- expression ? op1 op2
67Operators (II)
- Bitwise Operators
- gtgt, ltlt, gtgtgt, , ,,
- Assignment Operators
-
-
- -, , /, , , !, , ltlt, gtgt, gtgtgt
68Expressions
- Perform the work of a Java Program
- Perform the computation
- Return the result of the computation
69Expression
- An expression is a series of variables,
operators, and method calls that evaluates to a
single value. - Precedence
- Precedence Table
- Use (.....)
- Equal precedence
- Assignment Right to Left (a b c)
- Other Binary Operators Left to Right
70Expression
- postfix operators . (params) expr
expr-- - unary operators expr --expr expr
-expr ! - creation or cast new (type)expr
- multiplicative /
- additive -
- shift ltlt gtgt gtgtgt
- relational lt gt lt gt instanceof
- equality !
- bitwise AND
- bitwise exclusive OR
- bitwise inclusive OR
- logical AND
- logical OR
- conditional ?
- assignment - /
ltlt gtgt gtgtgt
71Control Flow Statement
- If Statements
- Loops
- Switch
- Break and Continue
72If Statements
- if (boolean) / ... / else if (boolean) /
... / else / ... / - The expression in the test must return a boolean
value - Zero('') can't be used to mean false, or
non-zero("...") to mean true
73Loops
- while (boolean expression) / ... /
- do / ... / while (boolean expression)
- for (expression booleanExpression expression)
/ ... /
74Switch
- switch (expression) case Constant1/ ...
/breakcase Constant2/ ...
/break....default/ ... /break
75Break and Continue
- Same meaning as in C
- A optional label can be used. Break/Continue with
the statement that is declared. - outer // labelfor (int j0 j lt 10 j)
/ Continue goes to here / for (int i0 i lt
20 i) if (i15) continue
outer // go to the outer loop
76Introduction to Java Classes and Objects
- Class templates for specifying the state and
behavior of an object at runtime - Object instances of a class
77Basic Structures of a Class
- A class consists of variables and methods.
- Example (Right Column)
- One variable firstVariable
- Two method setValue(nv) andgetValue()
- Access variables and methods
- ltObjectgt.ltvariablegt
- ltObjectgt.ltmethodgt(argument)
78Basic Structures of a Class
- public class FirstClass int firstVariable
0 public void setValue(int nv)
firstVariable nv public int getValue()
return firstVariable
79Basic Structures of a Class
80The Class Declaration
81Constructor
- A method in a class that initialize an instance
of an object before it's used. - The same name as the class but no return type
- Multiple Constructors the name name but
different arguments - Method Overloading
- Java Provides default constructors.
- The special variable, this, can be used inside a
method to refer to the object instance.
82Member Variables Declaration
83Instance and Local Variable
- Local variable is defined inside a block of code
or a method. - Example (Right Column)
- Instance Variable firstVariable
- Local Variable half
- public int getHalf() int half // local
variable half firstVariable / 2 return
half
84Methods
85Method Declaration
86Return a Value from a Method
- Use return operator in the method to return the
value. - Methods can return a primitive type or a
reference type. - The class of the returned object must be either a
subclass of or the exact class of the return type.
87Method Overload
- Signature of a Method return value, name,
parameter list - Method Overloading Use the same method name with
different arguments - Constructors can also be overloaded.
- this(parameters) Call another constructor
within a constructor
88Passing Information into a Method
- Argument types
- primitive and reference data type Yes
- method No
- Argument Names
- Can have the same name as one of the class's
member variable - Use this to refer to the member variable
- Primitive arguments are passed by value.
- Reference arguments are passed by reference.
89The Life Cycle of an Object
- Creating Objects
- Using Objects
- Cleaning Up Unused Objects
90Creating Objects
- Rectangle r new Rectangle(5,5,100,200)
- Declaration Rectangle r (Type name)
- Instantiation new
- Allocate memory for the object
- Initialize instance variables
- Call a constructor
- Initialization by Calling a Constructor
- Rectangle(5,5,100,200)
91Using Objects
- Manipulate or inspect its variables
- objectReference.variable
- r.x 50
- r.y 80
- Call its methods
- objectReference.methodName(argumentList)
- r.move(20,30)
- Java provides an access control mechanism whereby
classes can restrict or allow access to its
variables and methods.
92Controlling Access to Members of a Class
93Private
- class Alpha
- private int iamprivate
- private void privateMethod()
- System.out.println ("privateMethod")
-
- class Beta
- void accessMethod()
- Alpha a new Alpha()
- a.iamprivate 10
- a.privateMethod()
-
How About one Alpha object access the private
member of another Alpha object?
94Protected
- package Greek
- class Alpha
- protected int iamprotected
- protected void protectedMethod()
- System.out.println ("protectedMethod")
-
- package Greek
- class Gamma
- void accessMethod()
- Alpha a new Alpha()
- a.iamprotected 10
a.protectedMethod() -
-
95Protected (II)
- import Greek.
- package Latin
- class Delta extends Alpha
- void accessMethod(Alpha a, Delta d)
- a.iamprotected 10
- d.iamprotected 10
- a.protectedMethod()
- d.protectedMethod()
-
96Public
- package Greek
- public class Alpha
- public int iampublic
- public void publicMethod()
- System.out.println("publicMethod")
-
- import Greek.
- package Roman
- class Beta
- void accessMethod()
- Alpha a new Alpha()
- a.iampublic 10
a.publicMethod() -
97Package
- package Greek
- class Alpha
- int iampackage
- void packageMethod()
- System.out.println("packageMethod")
-
- package Greek
- class Beta
- void accessMethod()
- Alpha a new Alpha()
- a.iampackage 10
- a.packageMethod()
-
98Inhereitance in Java
- A mechanism you can use to create a new class by
extending the definition of another class - Increase the reusability of codes
- Single Inheritance
99Simple Class Hierarchy
Object
Vehicle
Building
Car
Bike
House
Office
Van
Truck
100More About Inheritance
- Use the extends keyword to create a subclass.
- Method Override
- Use method overriding when you need a subclass to
replace a method of its superclass. - Define a new method that replaces the superclass
method that has the same signature. - Calling Superclass Methods
- super.ltmethodgt(parameters)
- super(parameters) (Calling superclass
constructors)
101If-Example
- if (testscore gt 90) grade 'A' else if
(testscore gt 80) grade 'B' else if
(testscore gt 70) grade 'C' else if
(testscore gt 60) grade 'D' else
grade 'F'
102Switch-Example (I)
- int month . . .
switch (month) case 1
System.out.println("January") break
case 2 System.out.println("February")
break case 3 System.out.println(
"March") break case 4
System.out.println("April") break
case 5 System.out.println("May") break
case 6 System.out.println("June")
break case 7 System.out.println(
"July") break case 8
System.out.println("August") break
case 9 System.out.println("September")
break case 10 System.out.println(
"October") break case 11
System.out.println("November") break
case 12 System.out.println("December")
break
103Switch-Example (II)
- int monthint numDays. . .switch (month)
case 1case 3case 5case 7case 8case
10case 12 numDays 31 break
- case 4case 6case 9case 11 numDays
30 breakcase 2 if ( ((year 4 0)
!(year 100 0)) (year 400 0) )
numDays 29 else numDays 28
break
104Array
- Array
- Store lists of values
- Contiguous group of related memory locations
- Have the same name and the same type
- To refer to an element within the array
- a5, a7, aj1
- A subscript may be an integer or an integer
expression. - Java arrays always begin with element 0.
105Arrays (I)
- A single-dimensional array of ints
- int numbers new int10
- int numbers new int10
- A two-dimensional array of ints
- int matrixnew int510
- int matrixnew int510
- Initialize an array explicitly
- int numbers0,1,2,3
- int matrix0,1,0,1,2
106Arrays(II)
- A one-dimensional array of strings
- String myStrings new String20
- Another way to declare two-dimensional array
- int jnew int5 (j.length 5)j0
new int4 (j0.length 4)j1 new
int4 - To get the size of an array
- int q numbers.length
- A method returning an array of ints
- int returnArray() return new int10
- int returnArray() return new int10
107Declare / Allocate Arrays
- Allocate 12 elements for integer array c
- int c new int12 OR
- int c // Declares the arrayc new
int12 // Allocates the array - Initialize an array explicitly
- int numbers0,1,2,3
- To get the size of an array
- int q c.length // q will be 12
108Passing Arrays to Methods
- Arrays are passed to methods call-by-reference.
- Use the array name as the parameter
- modifyArray(hourlyTemperatures)
- void modifyArray(int b)
- Array elements are passed to methods either
call-by-value or call-by-reference, dependent on
their types.
109A Method Returns an Array
- Use the array name followed by the subscript as
the parameter - printElement(a5)
- A method returning an array of ints
- int returnArray() return new int10
110Multiple-Subscripted Arrays
- Java does not support multiple-subscript
directly. - Specify single-subscript arrays whose elements
are also single-subscript arrays.
111Multiple-Subscripted Arrays
- Examples
- int b 1, 2, 3, 4
- int bnew int510
- int jnew int5 (j.length 5) j0
new int4 (j0.length 4) j1
new int7 (j1.length7) - How About three or four dimension arrays?
112Applet Content
- Examples The Spot, Simple, SimpleClick,
ScrollingSimple Classes - Interface
- Life Cycle of an Applet
- Methods for MileStones
- Methods for Drawing and Event Handling
- UI Component
113The Spot Applet
- Subclass another class
- Implement an Interface
- MouseListener
114The Spot Applet
- Display a small spot when you click over the
applet with the mouse. - Take a look at the applet source code
115Extend a Class
- Applet Inheritance Hierarchy
- Code Reuse
- Responsibility
- Implement certain methods
- Override certain methods
- Responsibility of Applet's subclass
- Implement at least one init, start, or paint
116Implement an Interface
- An interface defines a protocol of behaviors
(methods) - How to get mouse events from AWT?
- Implement the MouseListener interface
- You can implement more than one interface in a
class. - If a class implements an interface, the class
must implement all of the methods in the
interface. - Inheritance and Interface
117The MouseListener Interface
- MouseListener defines the following methods
- mouseClicked(MouseEvent)
- mouseEntered(MouseEvent)
- mouseExited(MouseEvent)
- mousePressed(MouseEvent)
- mouseReleased(MouseEvent)
118Life Cycle of an Applet(I)
- The Simple Applet
- Loading the Applet
- An instance of the applet is created.
- The applet initializes itself.
- The applet starts running.
- Leaving and Returning to the applet's page
- The applet stops itself.
- The applet starts itself again.
119Life Cycle of an Applet (II)
- Reloading the Applet Unload and Load
- Unload stop and final cleanup
- Load See "Loading the Applet"
- Quitting the Browser
- stop
- final cleanup
120Methods for MileStones (I)
- init
- Initialize the applet each time it's loaded (or
reloaded). - start
- Start the applet's execution, such as when the
applet's loaded or when the user revisits a page
that contains the applet. - stop
- Stop the applet's execution, such as when the
user leaves the applet's page or quits the
browser. - destroy
- Perform a final cleanup in preparation for
unloading.
121Methods for MileStones (II)
- init
- Contain the code that you would normally put into
a constructor. - start
- Perform the applet's work or (more likely) starts
up one or more threads to perform the work. - If the applet responses to user actions, no need
for start - Stop
- Suspend the applet's execution, so that it
doesn't take up system resources when the user
isn't viewing the applet's page
122Methods for Drawing
- The two display methods an applet can override
- paint
- The basic display method. Draw the applet's
representation within a browser page. - update
- Use along with paint to improve drawing
performance. - The two methods define in AWT (Abstract Window
Toolkit) Component class.
123Method for Event Handling
- Applets inherits a group of event-handling
methods from the Component class. - Event-Specific Method
- mouseListener....
124Pre-Made UI Components(I)
- Buttons (java.awt.Button)
- Checkboxes (java.awt.Checkbox)
- Single-line text fields (java.awt.TextField)
- Larger text display and editing areas
(java.awt.TextArea) - Labels (java.awt.Label)
125Pre-Made UI Components(II)
- Lists (java.awt.List)
- Pop-up lists of choices (java.awt.Choice)
- Sliders and scrollbars (java.awt.Scrollbar)
- Drawing areas (java.awt.Canvas)
- Menus (java.awt.Menu, java.awt.MenuItem,
java.awt.CheckboxMenuItem) - Containers (java.awt.Panel, java.awt.Window and
its subclasses)
126Methods for Using UI
- Container Class
- Contain components
- Use layout managers to control the components'
onscreen positions - add
- Adds the specified Component.
- remove
- Removes the specified Component.
- setLayout
- Sets the layout manager.
- The ScrollingSimple Applet
127Abstract Window Toolkit (AWT)
- Introduction to AWT
- General Rules for Using AWT Components
- Components Introduction
- Layout Manager
- Writing Event Handlers
128Introduction to AWT
- Provides GUI components such as buttons, lists,
menus, and text areas. - Provide containers (such as windows and menu
bars) - Provide higher-level components (such as a dialog
for opening or saving files).
129AWT Components Inheritance
130How to Add a Component to a Container
- Components belong to a container.
- Container objects are also components.
- Windows, such as Frames and Dialog, are the
top-level containers. Don't need to be added to
containers. - Using add() to add a component to a container.
- You can't have one component in two containers.
131What the Component Class Provides
- Basic Drawing Support
- Event Handling
- Appearance control font
- Appearance control color
- Image handling
- Onscreen size an position control
132Change the Appearance and Behavior of Components
- The appearance of most components is
platform-specific. - You can make minor appearance changes, such as
the font and color. - Exception Canvas
- Using event handling to change the behaviors of
components.
133How to Use Components
- Buttons
- Checkbox
- Choice
- Label
- List
- Menus
- TextAreas and TextFields
- Scrollbars and Scroll Panes
134How to Use Containers
- Panel
- Frame
- Window
- Dialog
- Canvas
135Layout Manager
- Layout Manager controls the size and position of
components in a container.
136Layout Managers (I)
- The Layout Managers that JDK provides
- FlowLayout
- GridLayout
- BorderLayout
- CardLayout
- GridBagLayout
- Default Layout Manager
- Panel FlowLayout
- Window BorderLayout
- Use setLayout(Layout Manager) to specify the
layout manager used by a container
137Layout Managers (II)
138BorderLayout
- BorderLayout defines five areas north, south,
east, west, and center. - Put the space-hungry component in the center.
- Constructors
- BorderLayout()
- BorderLayout(int horizontalGap, int verticalGap)
- Add Components
- add(Direction, Component)
139CardLayout
- Use to manager two or more components that share
the same display space. - Add Components
- add(String name, Component comp)
- Methods to choose components shown in a
CardLayout - public void first(Container parent)
- public void next(Container parent)
- public void previous(Container parent)
- public void last(Container parent)
- public void show(Container parent, String name))
140FlowLayout
- Put components in a row if possible
- Constructors
- FlowLayout()
- FlowLayout(int alignment)
- FlowLayout.LEFT
- FlowLayout.CENTER
- FlowLayout.RIGHT
- FlowLayout(alignment, horizontalGap, verticalGap)
- add(component)
141GridLayout
- Place components in a grid of cells.
- Constructors
- GridLayout(int rows, int columns)
- GridLayout(rows, column, horizontalGap,
verticalGap) - add(component)
142GridBagLayout
- Place components in a grid of rows and columns,
allowing specified components to span multiple
rows or columns. - Specify layout constraints for each component.
- GridBagLayout gridbag new GridBagLayout()
- GridBagConstraints c new GridBagConstraints()
- setLayout(gridbag)
- gridbag.setConstraints(theComponent, c)
- add(theComponent)
143GridBagConstraints(I)
- gridx, gridy
- GridBagConstraints.RELATIVE (Default)
- gridwidth, gridheight (Default Value 1)
- GridBagConstraints.REMAINDER
- GridBagConstraints.RELATIVE
- fill
- GridBagConstraints.NONE (Default)
- GridBagConstraints.HORIZONTAL
- GridBagConstraints.VERTICAL
- GridBagConstraints.BOTH
144GridBagConstraints (II)
- ipadx, ipady (Default Value 0)
- insets (Default Value 0)
- anchor
- GridBagConstraints.CENTER(Default), NORTH,
NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST,
WEST, NORTHWEST - weightx, weighty(Default Value 0)
145More About Layout Manager
- Create a custom layout manager
- Doing without a layout manager (absolute
positioning)
146Event (I)
- New event model
- Events are generated by event sources.
- One or more listeners can register to be notified
about enents of a particular kind from a
particular source. - Event handler can be instances of any class.
147Event (II)
- Three bits of code
- public class MyClass implements
SomeKindOfListener - aComponent.addSomeKindOfListener(instanceOfMyClass
) - Implementation of the methods in the
SomeKindOfListener Handling standard AWT events
(eventstandard.html)
148More about Event
- Adapters
- MyClass extends MouseAdapter
.....someObject.addMouseListener(this) - Inner Class
- MyClass extends Applet .....someObject.addMouse
Listener(new MyAdapter))...class MyAdapter
extends MouseAdapter ....
149Threads of Control
- What Is a Thread
- A Simple Thread Example
- Thread Attributes
150What Is a Thread
- Definition A thread is a single sequential flow
of control within a program - Some texts use the name lightweight process
instead of thread - Takes advantage of the resources allocated for
that program and the program's environment
151A Simple Thread Example (I)
- class TwoThreadsTest
- public static void main
(String args) - new SimpleThread("Jamaica")
.start() - new SimpleThread("Fiji").st
art() -
-
- class SimpleThread extends Thread
- public SimpleThread(String
str) - super(str)
-
-
152A Simple Thread Example (II)
- public void run()
- for (int i 0 i lt 10
i) - System.out.println(i
" " getName()) - try
- sleep((int)(Math.ra
ndom() 1000)) - catch
(InterruptedException e) -
- System.out.println("DONE!
" getName()) -
-
153Thread Body
- All the action takes place in the thread body,
which is the thread's run() method. - Two ways to provide run() for a Java thread
- Subclass the Thread class defined in the
java.lang package and override the run() method - Provide a class that implements the Runnable
interface, also defined in the java.lang package
154Thread State (I)
155Thread State (II)
- New Thread
- Thread myThread new MyThreadClass()
- Runnable
- myThread.start()
- Not Runnable
- Someone invokes its sleep() method
- Someone invokes its suspend() method
- The thread uses its wait() method
- The thread is blocking on I/O
156Thread State (III)
- Dead
- natural causes
- public void run()
-
-
- by being killed (stopped)
- myThread.stop()
157Thread State (IV)
- IllegalThreadStateException
- For ExampleIllegalThreadStateException is thrown
when you invoke suspend() on a thread that is not
"Runnable" - The isAlive() Method
- false - thread is either a "New Thread" or "Dead
- true - thread is either "Runnable" or "Not
Runnable"
158Thread Priority
- You can also modify a thread's priority with the
setPriority() method - The chosen thread will run until one of the
following conditions is true - a higher priority thread becomes "Runnable"
- it yields, or its run() method exits
- on systems that support time-slicing, its time
allotment has expired
159Working with Shape and Text
- Graphics Contexts
- Graphics Objects
- The Coordinate System
- Drawing Text
160Related Inheritance Tree
Object
Polygon
Color
Graphics
Component
FontMetrics
Font
161Graphics Contexts and Graphics Objects
- A graphics context enables drawing on the screen
in Java. - A Graphics object manages a graphics context by
controlling how information is drawn. - Graphics Objects provide
- Drawing
- Font Manipulation
- Color Manipulation
162Graphics Object
- Lone argument to the paint() and update() methods
- Support two kinds of drawing
- Primitive Graphics (lines, rectangles, and texts)
- Images
- Provide the current drawing context
- Current drawing area
- Current drawing context
163The Coordinate System
164Drawing Text
- First consider whether you can use a
text-oriented Component, like the Label,
TextField, or TextArea - Drawing Text
- drawBytes(byte, length, x, y)
- drawChars(char, length, offset, length, x, y)
- drawString(str, x, y)
- TextXY.java
165Drawing Text
166Font Constants and Constructors
- Font Style Constants
- public final static int PLAIN
- public final static int BOLD
- public final static int ITALIC
- Constructor
- public Font (String s, // font nameint
style, // font styleint size) // font point
size - Font Name Courier, Helvetica, TimesRoman
167Font Methods
- Related Methods in Graphics Class
- public abstract void setFont(Font f)
- Related Methods in Font Class
- public int getStyle()
- public int getSize()
- public String getName()
- public String getFamily()
- public boolean isPlain()
- public boolean isBold()
- public boolean isItalic()
168FontMetrics (I)
- Getting Information about a Font
- FontDemo.java
- Information about a fonts vertical size
- getAscent(), getMaxAscent()
- getDescent(), getMaxDescent()
- getHeight()
- getLeading()
169FontMetrics (II)
170FontMetric (III)
- Information about a fonts horizontal size
- getMaxAdvance()
- bytesWidth(bytes, int, int)
- charWidth(int), charWidth(char)
- charsWidth(char, int, int)
- stringWidth(String)
- getWidths()
171Constructors
- Public Color (int r, // 0 - 255 red contentint
g, // 0 - 255 green contentint b // 0 - 255
blue content) - Public Color (float r, // 0.0 - 1.0 red
contentfloat g, // 0.0 - 1.0 green
contentfloat b // 0.0 - 1.0 blue content)
172Color Constant and Methods
- Color Constant
- orange, pink, cyan, magenta, yellow, black,
white, gray, lightGray, darkGray, red, green,
blue - public final Static Color
- Related Methods in Color Class
- public int getRed() //Return red content
- public int getGreen() //Return green content
- public int getBlue() //Return blue content
- Related Methods in Graphics Class
- public abstract Color getColor() //Return current
color - public abstract void setColor(Color c) //Set
current color
173Drawing Shapes
- Lines (drawLine())
- Rectangles (drawRect(), fillRect(), and
clearRect()) - Raised or lowered rectangles (draw3DRect() and
fill3DRect()) - Round-edged rectangles (drawRoundRect() and
fillRoundRect()) - Ovals (drawOval() and fillOval())
- Arcs (drawArc() and fillArc())
- Polygons (drawPolygon() and fillPolygon())
174Introduction to Exception Handling
- An exception is an event that occurs during the
execution of a program that disrupts the normal
flow of instructions.
175How to Find an Appropriate Exception Handler
- The set of methods in the call stack of the
method where the error occurred. - The type of the exception thrown is the same as
the type of exception handled by the handler. - The exception handler chosen is said to catch the
exception.
176Advantages of Exception Handling
- Separating error handling code from regular
code - Propagating errors up the call stack
- Grouping error types and error differentiation
177Grouping Exception Types
178Catch or Specify Requirement
- A method need to either catch or specify all
checked exceptions that can be thrown within the
scope of the method. - Exceptions that can be thrown by a method is part
of the methods public programming interface. - Exception Classification
- RunTime arithmetic, pointer, indexing exceptions
- Checked
179Exception Scope
- Exceptions that can be thrown within the scope of
the method - Exceptions that are thrown directly by the method
with Java's throw statement. - Exceptions that are thrown indirectly by the
method through calls to other methods
180Catching and Handling Exceptions (I) -- try
- The try Block
- Enclose the statements that might throw a
exception within a try block. - Define the scope of any exception handlers
associated with it - try Java statements
- A try statement must be accompanied by at least
one catch block or one finally block.
181Catching and Handling Exceptions (II) -- catch
- The catch Block
- Define exception handlers
- try . . . catch
(SomeThrowableObject variableName) Java
statements catch (SomeThrowableObject
variableName) Java statements
182Catching and Handling Exceptions (III) --finally
- The finally Block
- To clean up the state of the method before
allowing control to be passed to a different part
of the program. - Close files opened
- Eliminate duplicate code
183Throw Exceptions
- Specify the exceptions thrown by a method
- MethodName throws exception1, exception2...
- public void writeList throws IOException,
ArrayIndexOutOfBoundsExceptions .. - Throw a exception
- throw new exception()
- throw new IOException()
184Images, Animation, Sound
- Loading, Displaying, and Scaling Images
- Introduction to Animation Image Loop
- Graphics Double Buffering
- Using the MediaTracker to Monitor Image Loading
- Using a Separate Thread to Run Animation
- Loading and Playing Audio Clips
185Loading, Displaying and Scaling Images (I)
- LoadImageAndScale.java
- img getImage(getDocumentBase(), "T1.gif")
- 1st parameter Image location
- 2nd parameter Image file name
- Java supports GIF and JPEG image formats
- img.getWidth(ImageObserver)
- img.getHeight(ImageObserver)
186Loading, Displaying and Scaling Images (II)
- g.drawImage(img, 1, 1, this)
- drawImage is a Graphics method
- 2nd and 3rd parameters x and y coordinates to
put the image - 4th argument ImageObserver
- Let java automatically notify the ImageObserver
object to update the image as the remainder of
the image is loaded. - g.drawImage(img, 1, 200, width2, height2, this)
- 4th and 5th parameters the x, y scaling factors
187Introduction to AnimationAn Image Loop
- Store images in an array of images
- Use Thread.sleep(sleepTime) to sleep for a
fraction of a second before displaying the next
image. - Flicker
- repaint() gt update() gt paint()
- The update() method will draw a filled rectangle
the size of the applet in the current background
color. - repaint, update, and paint
- One separate thread is started by repaint()
188Graphics Double Buffering
- Basic Concept
- Create a blank Image
- Draw on the blank Image (Using methods of the
Graphics class) - Display the Image
- Create a graphics double buffer
- buffer createImage(width, height)
- gContext buffer.getGraphics()
189Using the MediaTracker to Monitor Image Loading
- MediaTracker
- Wait for an image or images to load before
allowing a program to continue - Determine if an error occurred while loading an
image - imageTracker new MediaTracker(ImageObserver)
- Method
- imageTracker.addImage(img, RegisterID)
- imageTracker.waitForID(RegisterID)
- imageTracker.checkID(RegisterID, boolean)
- Override update()
190Using a Separate Thread to Run an Animation
- Implement interface Runnable
- Implement the run method
- Thread method
- start()
- stop()
- suspend()
- resume()
191Loading and Playing Audio Clip
- Applet's Play method
- public void play(URL location, String
soundFileName) - public void play(URL soundURL)
- AudioClip
- getAudioClip(URL location, String soundFileName)
- play()
- loop()
- stop()
192Files and Streams
- Loading, Displaying, and Scaling Images
- Introduction to Animation Image Loop
- Graphics Double Buffering
- Using the MediaTracker to Monitor Image Loading
- Using a Separate Thread to Run Animation
- Loading and Playing Audio Clips
193Stream
A source can be from file, network, memory, or
other programs
194Algorithm for Read/Write
- Reading
- Open a stream
- While more information
- read information
- close the stream
- Writing
- Open a stream
- While more information
- write information
- close the stream
195Character Streams
196Byte Streams
197Examples
- Basic File I/O -- Copy.java
- Sequential-Access File CreateSeqFile.java,
ReadSeqFile.java, CreditInquiry.java - Random-Access File Record.java,
CreateRandFIle.java, WriteRandFile.java,
ReadRandFile.java - TransactionProcessor.java
- FileTest.java
198Networking
- TCP/UDP
- Port
- Manipulating URLs
199TCP/UDP
- TCP (Transport Control Protocol)
connection-based protocol that provides a
reliable flow of data between two computers. - UDP (User Datagram Protocol) protocol that sends
independent packets of data,called datagrams,
from one computer to another with no guarantees
about arrival.
200Port
Socket
Datagram
201Manipulating URLs
- java.net.URL
- How to open a URL By using a URL as an argument
to the showDocument method of class AppletContext - AppletContext Represent the applets environment
- Applet.getAppletContext() Return a AppletContext
object
202Read a File From a Server
- URL.openStream() Associate an InputStream with
the URL - Use traditional Stream input methods, like
readLine to read the contents of the file.
203Establishing a Simple Server (Stream Socket)
- Step1 Create a ServerSocket Object
- ServerSocket s new ServerSocket(port,
queueLength) - Step2 Create a Socket and Wait for a Connection
- Socket connect s.accept()
- Step3 Associate Input and Output Stream with the
Socket - connect.getInputStream
- connect.getOutputStream
- Step4 Process Connection
- Step5 Close Connection
204Establishing a Simple Client (Stream Socket)
- Step1 Create a Socket to make connection
- Socket connect new Socket(ServerName, port)
- Step2 Associate Input and Output Stream with the
Socket - connect.getInputStream
- connect.getOutputStream
- Step3 Process Connection
- Step4 Close Connection
205Datagrams
- Set up a DatagramSocket
- Send socket new DatagramSocket()
- Receive socket new DatagramSocket(port)
- Set up a Packet
- Send s new DatagramPacket(.Packet Info..)
- Receive r new DatagramPacket(data, length)
- Send/Receive
- socket.receive(packet)
- socket.send(packet)