You are on page 1of 105

/


JAVA


1.
1.1 Java
1.2 Java
1.3 Java Applet
1.4 Internet Java

2.
2.1 Java
2.2 Java
2.3 Java
2.4 (Inheritance)
2.5 (overloading)
2.6 (constructors)
2.7 (Finalization)
2.8 (access specifiers)
2.9 (Modifiers)
2.10 Casting
2.11
2.12 (Polymorfism)
2.13 (Interfaces)
2.14 (Packages)

3. - -
3.1 Java
3.2 , literals, ,
3.3
3.4 (Strings)
3.5
3.6

19

4. (Exceptions)

31

5. Applets Java
5.1 Applets
5.2 Applets Web
5.3 , X
5.3.1 Graphics
5.3.2 Fonts
5.3.3 Color
5.3.4

33

6. Threads
6.1 Threads
6.2 H Threads
6.3 Threads Applets
6.4 Threads

41

6.5 Threads
7. Abstract Windowing Toolkit (AWT)
7.1 GUI
7.2 GUI
7.3 GUI (GUI Events)
7.4 Adapter
7.5 applet EQ

47

8. Swing (Swing GUIs)


8.1 Top-Level Swing Containers Components
8.2 Event Handlers
8.3 Swing Threads
8.3.1 invokeLater

59

9. Animation Java
9.1 Animation
9.2 animation loop
9.3 animation
9.4

69

10. / Streams
10.1
10.2 System
10.3 System
10.4 DataInput Stream
10.5 DataOutput Stream

75

11. Java
11.1 Uniform Resource Locator (URL)
11.1.1 URL (relative)
11.1.2 URL
11.1.3 MalformedURLException
11.1.4 URL
11.1.5 URL
11.1.6 URL
11.1.7 URLConnection
11.1.8 URLConnection

78

11.2 Sockets
11.2.1 Client Server
11.2.2 Client Server TCP sockets
11.2.3 Socket
11.2.4 ServerSocket
11.2.5 Datagrams
11.2.6 UDP Datagrams
11.2.7 DatagramSocket
11.2.8 DatagramPacket

86

Java

1.

Internet World-Wide Web


.
Java, Sun microsystems TM.
Java
.
Java
( C++).
applets (applet =

HTML Web Browser).
Interpreted . java compiler
(bytecode)
. interpreter
(=) bytecode .
java bytecodes
, ,
java interpreter. java bytecode
, ( Kilobytes). .
(distributed). Java
.
sites.
(secure). , ' Java
applet
.
multithreaded. Java threads.
, Java runtime
system (interpreter) (scheduler),
threads
. .
multimedia . Java
multimedia .
.

1.1

Java

Java
Java 2 Platform Standard Edition (J2SE), Sun microsystems.
Java J2SE Java 2 5.0.
javac
compiler Java. command-line : javac
< >. javac
, . :
< >.class.
java interpreter Java. : java <>,
java
myClass java myClass.class.
javaw
( Windows 95/NT) java
shell .
jdb
Java debuger.
javah
C files stub files .
C,
.
javap
Java disassembler.
javadoc
documentation.

.

Java

appletviewer

applets Java. stand-alone , ,
appletviewer java javaw.

1.2

Java

Java
(stand-alone application).
HelloWorldApp.java
:
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); //Display the string.
}
}
Compile Java compiler:
javac HelloWorldApp.java
compiler HelloWorldApp.class
Java interpreter:
java HelloWorldApp
"Hello World!"

1.3

Java Applet
Java applet.

HelloWorld.java
:
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString("Hello world!", 50, 25);
}
}
Compile Java compiler:
javac HelloWorld.java
compiler HelloWorld.class
HTML Hello.html Applet.
directory HelloWorldApp.class.

Java

<HTML>
<HEAD>
<TITLE> A Simple Program </TITLE>
</HEAD>
<BODY>
Here is the output of my program:
<APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>
HTML Java-enabled browser Internet Explorer
"Hello World!" browser.

1.4

Internet Java

Internet
Java.
Java Tutorial:
http://java.sun.com/docs/books/tutorial/

.
.
Java API :
http://java.sun.com/j2se/1.5/docs/api/index.html

Java. Application Programming Interface Java (Java API)
Java
(), .
Java Platform:
http://java.sun.com/j2se/1.5.0/download.jsp
Java 1.1.

Java. JRE
(Java Runtime Environment) Web Browser
. JRE Web Browser java applets.

Java

Java

2.

, (OOP - Object Oriented Programming),



. OOP
(objects)
()
.
user interfaces
...

User Interface - 1

User Interface - 2

Us
.
2 UI ( ).
,
UI 2 UI .

(class) .
. - , (instances)
instantiation.

'

.
.
( ).

2.1

JAVA

< >
< >
< >
...
,
main() C. ,
,
.
interpreter .
:

JAVA.

Java

2.2

JAVA



. .
`
C
PASCAL. instance variables
.
structure C

structures.
( )
, .
C.
, ( ), - .
:
<>.<>(< >);
..
mycar.startEngine();

structure C.
.
.

OOP.

.

.
interface
. implementation hiding
data abstraction.

.

2.3

JAVA
java structure C.

:
class <class_name> {
<data_type or class_name>

<variables or objects>;

<returned type> <method_name> (<parameter list>) {


<method body>
}
<data_type or class_name>

<variables or objects>;

<returned type> <method_name> (<parameter list>) {


<method body>
}

Java

...
}
..
class Apple {
int

num_of_vitamins;

//

int countVitamins() {
//
return num_of_vitamins;
}
Vitamins

v1, v2, v3;

Vitamin getVitamin(int num) {


return ....;
}

//
//

}
num_of_vitamins int.
java ( int, float, char ),
. Vitamins v1, v2, v3
Vitamin ( )
.
.

.
.
.


(debugging).
class test {
float add2Accum(float f) {
// Add to accumulator.
return (Accumulator += f);
}
float
Accumulator = 0.0;
// The accumulator.
}
( primitive types) java,
(statements) ,
.

2.4

(inheritance)


. " ".
(instances)
.
. ,
extends :
java :
class A {
int
a;
void add(int x) {
a += x;}
}

Java

class B extends A {
// 'a' 'void add(int x) {...}' .
int
prev;
void sub(int x) {
prev = a;
a -= x;
}
}
a
void add(int x). .

.

' ( ). ..
class B extends A {
int square() {
return a*a;
}
void increaseBy1() {
add(1);
}
}

. :
class B extends A {
a : float;
void add(int x) {

// .
// add(int x).
// overriding.
a = a + ((float) x);
print(a);

}
}
,
, (overriding)
/ / .
override ,
.
.

, (), (subclass)
. (superclass)
. subclassing.
.
.
. ..

class A

class D

class B

class C

Java

superclass D. superclass C,
superclass C! ( ). B, D
subclasses A, C subclass . C
.
overriding
/
.... C
override ' .
- 1

Object compiler
( ). :

class Object (*)

class Socket (*) class InputStream (*)

class mySocket

class A

class D

class B

class C
(*) compiler A, B, C,
D, mySocket .
- 2 ( this super)
- (overrides)
.
subclass
. ..
class A {
void doSomething() {
......
}
}
class B extends A {
void doSomething() {
........
}
}
A
o1;
B
o2;
o1.doSomething();
o2.doSomething();

// "" (overrides)
// doSomething() .

// doSomething() .
// doSomething() .

Java

10

( C)
doSomething() , ,
' .
java .
, , super .
override, ( doSomething()),
:
super.doSomething();
java super this
() . this
:
)

.
class A {
int
a;
void set(int a) {
this.a = a;
}
}
)
.
.
class A {
void make_a_new_object() {
B tmp;
// create a new instance of B and store it in tmp.
// Then give tmp a pointer to you.
tmp.owner(this);
}
}

2.5

(overloading)


, .
class number {
int
a;
void add(int x) {
a += x;
}
void add(float f) {
a += ((int) f);
}
void add(number n) {
a += n.get_a();
}
int get_a() {
return a;
}
}

Java

11

void add(...) (3)


.
(overloading) .
object oriented
. :
aMethod(), aMethod(type1), aMethod(type2), aMethod(type1, type2), aMethod(type2, type1).
. ,
'
, , .
.

2.6

(constructors)


, (. object ).
(constructors) . constructors

. constructors
()
. .
constructor
constructor ( )
.
constructors. JAVA

, :
class A {
int
n;
A() {
// Constructor - 1
n=0;
}
A(int x) {
// Constructor - 2
n = x;
}
}
constructors
. , constructors , void.
( ).
:
A
a;
a = new A();

a = new A(5);

1.
constructor default null constructor
. ()
constructors default constructor .
2.
() constructors.
.
3.
constructor , default
constructor
. constructor
constructor ....

Java

12

4.

constructor
instanciation default constructor
( ) . constructor
super(....); super(...) super
, ( this),
constructor .
( super).
5.
super(...) this(....)
constructors
.

java strings
( ) . string
java String, :
String
str = new String("Hello, I am a new string!");

String
str = "Hello, I am a new string!";

2.7

(Finalization)

C++ Object PASCAL


(destructors) . destructors
. JAVA
.

.
(dangling pointer).
JAVA
(finalization) . . runtime system
java
. (garbage)
. void finalize()
clean-up.
. finalize()
.
- garbage
collection JAVA runtime
system.

2.8

(access specifiers)



.
access specifiers.
access specifiers :
<access specifiers> <type or class>

<variables>;

<access specifiers> <returned type> <method name> (<param list>) {


<body>
}
access specifiers JAVA
, ,
/ . '
:

Java

13

public /
, .
protected - /
.
private /
.
public package.
:
class A {
public int
int
protected
private d;

a;
//
b;
// package,
c;
//
// .

public A() {...}


public void add(int x) {....}
void add(A a) {.....}
protected int convert_A_to_int (A a) { return a.getValue(); }
private void who_am_i() { System.out.println("I am class A!"); }
}
class B extends A {
// I CAN SEE : a, b, c, A() via super(), add(int), add(A),
// convert_A_to_int(A), BUT I CAN'T SEE : d, who_am_i()
}

:
public class A {
.......
}
() ,
command line java interpreter
.
.java, (.. A.java). ,
- :
public static void main(String args[]) {
..... // !
}
main() C.

2.9

(Modifiers)

JAVA
/ . ` :
<access specifiers> <modifiers> <type or class> <variables>;
<access specifiers> <modifiers> <returned type or class> <method name> (<parameter list) {
<body of the method>
}
modifiers final, abstract :
final/abstract class <class name> [extends <class name>] {
......

Java

14

}
modifiers :
final .
.
, final int a = 10; final int a;
a=10; override.
.
synchronized
threadsafe. , (
), .

. : ()
, ( ),
.
abstract -
, {...}
semicolon (;). abstract
abstarct. compile-time error (
new) abstract . '
override abstract .
static /
.
. static
() .
: < >.<static var or method>. : static
static. .
static public static void main(String args[]) ,
.
native native .
C bytecode
. native javah.

2.10

Casting

C JAVA casting
. :
int
a;
short b = 4;
a = (int) b;

a = b;
b = (short) a;
A
a;
B
b;
a = (A) b;
a = b;
b = (B) a;

// short --> int

explicit casting.

// implicit casting
// int --> short

explicit casting ONLY!

// B subclass of A
// B --> A;
// explicit casting is required!


explicit casting
, int (32-bit )
byte (8-bit ).

Java

15

, ( ), explicit
casting
.

2.11


() .
(int, float,short ) C.
int
a;
short b;

. C
(* & ->) .

.
JAVA
.
A
a = new A();
a++;
// !!!

int
a;
a++;
// a int
// .
(
a) , , , (references ref) (handlers)
runtime system. runtime system

garbage collection
.
null
.

2.12

(Polymorfism)


.
.
:
(overriding)
(overloading)
(dynamic method binding)
, :
(Cow, Dog Snake)
(abstract) Animal,
speak().
public class AnimalReference
{

Java

16

public static void main(String[] args)


Animal ref; // set up a reference for an Animal
// make specific objects
Cow aCow = new Cow("Bossy");
Dog aDog = new Dog("Rover");
Snake aSnake = new Snake("Earnie");
// now reference each as an Animal
ref = aCow;
ref.speak();
ref = aDog;
ref.speak();
ref = aSnake;
ref.speak();
}
speak() Animal,
( )
. (dynamic method binding)

2.13

(Interfaces)

(interface)
.
.
nterface .
interfaces
interfaces.
interface abstract :
interface
interfaces

interface Java
.
interface
interfaces :
public interface myinterface extends superinterface1,superinterface2, {
final String One = "One;
final String Tow = Two;
public void method();
}
interfaces I
.
public, static, final public
abstract. access modifiers
private protected.
interfaces .
applet thread
:
public class MyThreadedApplet extends Applet implements Runnable {

Java

17

}
Runnable interface thread
Thread.
threads.
interface.
Runnable interface
public void Method (Runnable mythread,String S, double d) {
...
}
interface
.
interfaces
interface


interface.

2.14

(packages)

K (packages)
directory.
directory .

:
package <packageName>;
packages

import <packageName>.<className>;

1:

Folder 1
A11.java
A12.java
// A11.java
// package Folder1:
package Folder1;
class A11
{ Class Implementation..}
// A12.java
// package Folder1:
package Folder1;
class A12
{ class implementation}
2:

Folder 2
A21.java
A22.java

Java

// A21.java
// package Folder2:
package Folder2;
class A21
{ Class implementation}
// A22.java
// package Folder2
// 11.java
package Folder2;
import Folder1.A11;
class A22
{ Class implementation}

18

Java

19

3.

- -

3.1

JAVA

JAVA C
( bytes) JAVA.

Byte
Short
Int
Long
Float
Double
Char
Boolean

3.2

Byte
Short


(.
)

unicode character
Boolean

8-bit signed, -128..127


16-bit signed
32-bit signed
64-bit signed
32-bit signed
64-bit signed
16-bit
true or false

, literals, ,

JAVA A..Z,
a..,z, 0..9, _, $, ( ) _ $,
(0..9). JAVA.
literals JAVA , , , .
:
Integer literals ( )
324
// decimal
0xABCD
// hexadecimal
032
// octal
2L
// long decimal integer
Float point literals ( )
3.1415 // float
3.1E12
.1e12
2E12
2.0d or 2.0D
//double
2.0f or 2.0F or 2.0
//float
Boolean literals ( )
true, false
// boolean
Character literals ()
continuation
<newline>
new-line
NL (LF)
horrizontal tab
HT
back space
BS
carriage return
CR
form feed
FF
backslash
\
single quote
'
double quote
"
octal bit pattern
0ddd
hex bit pattern
0xdd
unicode char
0xdddd

\
// character literals
\n
\t
\b
\r
\f
\\
\'
\"
\ddd
\xdd
\udddd

Java

20

'\n' , '\23', 'a'


String literals ()
""
\\ the empty string
"\""
"This is a string"
"This is a \
two-line string"
JAVA .
1. /* */ C.
2. // //
3. /** */. /* */
javadoc documentation.
(separators) JAVA :
+ - ! % ^ & * | ~ / > <
( ) { } [ ] ; ? : , . =
(SPACE), HT \t, LF \n
.

3.3
:

+
*
/
%
^

<=
<
>=
>

!=
==


==

&&
||
!

KAI (AND)
H (OR)
OXI (NOT)

Java

21

,
s ( ).
.
true
false.
:

O :

++
--

1
1

++ --
1 .

++a;
a=a+1;
--a;
a=a-1;
++ -- (.
, ++a --a) (. , a++ a--).
++a a .
a++ a .
:
o a 5 :
a = 5;

b = a++;
b 5

b=++a;
b 6. a 6.

+=
-=
*=
/=
%=

a += b; a = a+b;
a -= b; a = a-b;
a *= b; a = a*b;
a /= b; a = a/b;
a %= b; a = a %b;
bits :

Java

&
|
^
!
<<
>>

22

AND bit
OR bit
XOR bit
bit

bits.
&, |, ^ ~ Boole.
>> << .
a 01101000

b = a >> 2;
b 00011010.

++


.
[]
()
-!
~
instanceof
*
/
%
+
<<
>>
>>>
<
>
<=
>=
==
!=
&
^
|
&&
||
?:
=
op=
,

, *
!=.
.
op= :

3.4

+= -= *= /= %= &= |= ^= <<= >>= >>>=

(Strings)

char c=A;
(Strings) . Java
String.
String:
String ntua=National Technical University of Athens;

String ntua = new String("National Technical University of Athens");

Java

23

println()

:
System.out.println(ntua); //

System.out.println(National Technical University of Athens); //
//

print()
:
System.out.print(National);
System.out.print( Technical );
System.out.println( University );
System.out.println( of );
System.out.println( Athens );

String ntuaHMMY = ntua + HMMY Department;
ntuaHMMY :
National Technical University of Athens HMMY Department.
:
s1 s2.

s1.length();
s2=s1.toUpperCase();
s2=s1.toLowerCase();
s2.equals(s1)
int a=s2.indexOf(s1);
>>

3.5

( )
s1
s1
s1
s1 s2
To a s2 s1

C, JAVA
block
,
. ,
( ) C.

Java

24

, , (if - else, for, while, do - while switch),


C if-else, while, do-while
,
boolean . :
while (1) {...}
//
while (true) {....} //
Java.
(control flow):

Java



if-else
switch-case
for
while
do-while

Java
.
(exceptions) (exception handlers)
.

: break, continue return
. .
Java goto.
break continue.
if-else
if ( )
.

( ).
if :
if ()

..
if (x!=0) {
System.out.println("To x 0");
y = 1/x;
}
if else
.
if if if .
if else :

Java

25

if ()
--1
else
--2
..
if (x!=0) {
System.out.println(" x 0");
y=1/x;
}
else {
System.out.println(" x 0");
y=0;
}
switch-case
if

switch-case :
switch () {
case -1:
-1; [break;]

case -:
-; [break;]
[default:
; [break;]]
}
switch-case
.
- .
default .
break
,
( ) ,
break switch-case.
,

( month) (year) :
...
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;

Java

26

break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
}
...
for
for
. for
.
for .
for :
for (; ; )
;
1
10:
...
for (int i=1; i<=10; i++)
System.out.println(i);
...
i ( for loop)
1.
i 10.
i 10.
i 1. i
1, 2, , 10
i. A i 10
, 1
.
while
for
.
while.
H while :
while ()
;
while .
- boolean -

x numbers.
.
found true .
x.

boolean found = false;

Java

27

int i=0;
while (!found && i!=10)
if (numbers[i++] == x)
found = true;

do-while

.
do-while while.
do-while :
do
;
while ();
do-while .
.
H do-while .

,
:
...
int c;
Reader in;
...
do {
c = in.read();
...
} while (c != 1);
...

Java
.
: break, continue return
break switch-case.
break .
while
For.java :
int i;
boolean found = false;
for (i=0; i<10; i++)
if (numbers[i]==x) {
found = true;
break;
}
continue
. for while
do-while .

(true false) .

Java

28

break continue (labeled break labeled


continue)
,

.
return
,
. .
return String
name. getName( )
: return name;
public String getName()
{
...
return name;
}
: return interest;
interest;
public int calculateInterest( )
{
...
return interest;
}

3.6

JAVA :
< > []
<>;

< >
<>[];

int[]
byte
float
A
B[]

nums;
buff[];
matrix[][];
a[];
b;

//

(
).
:
< > = new < > [ <> ];
<> byte, short, int long.

int[]
;
= new int[200];
byte
buff[] = new byte[1024];
A[]
a = new A[4];

Java

29

float
matrix[][];
matrix = new float[30][];
matrix = new float[0][40]; ... matrix = new float[29][40];
:
matrix = new float[30][40];
:
a[2] = 5;
matrix[0][8] = (float) (buff[19] + buff[25]);
indexes 0 -1.
compile-time run-time error.

. :
int[] give_ints() {
int
I[] = new int[3];
I[0] = I[1] = I[2] = 7;
return I;
}

int give_ints() [] {....}


void get_ints(int[] i) {
i[0] = i[1]+i[2];
}

void get_ints(int i[]) { ... }


JAVA .
()
Array. , JAVA
, ( Array),
.
: int a[]; - a.
a[0], ... int
.
length
. :
a.length
//
if (a.length < 1024) {...}
for (int i=0; i<a.length; i++) {
System.out.println(a[i]);
}

Java

30

Java

4.

31

(Exceptions)

JAVA ,
,
(throw=) !
thread .
(exception handlers)
.
runtime system,
. ,
. . ( new)
Exception
. throw
exception. throw
.
. , , , ( ),
exception handler, '
.
.
class MyException extends Exception {
}
class MyClass {
void oops() {
if (/* no error occurred */) {
...
} else { /* error occurred */
throw new MyException();
}
}
}
(exception handler)
try. try
catch. catch ,
( MyException). catch
. :
try {
p.a = 10;
} catch (NullPointerException e) {
println("p was null");
} catch (Exception e) {
println("other error occurred");
} catch (Object obj) {
println("Who threw that object?");
}
catch .
try/catch.
.

. exception handler
. , ,
, ( ), exception handler,
throw
. throw
.

Java

32

try {
f.open();
} catch(Exception e) {
f.close();
throw e;
}
,
.
finally. .
try {
// do something
} finally {
// clean up after it
}
:
try {
// do something
} catch(Object e){
// clean up after it
throw e;
}
// clean up after it
finally try block return,
break, continue throw. :
try {
if (a == 10) {
return;
}
} finally {
print("finally\n");
}
print("after try\n");
"finally" "after
try" a != 10.

Java

33

5. Applets Java
Java Applets Java WWW Browser.
Applet WEB HTML tag.
Browser WEB Applet, Browser
Applet Web Server .
Java Applets Java Browser,
Browser: , ,
interface . Applets
,
Applets :
Applets ,
.
Applets Server Applet
.
Applets
.
Applets
Applet ,
Applet, java.applet :
Public class myClass extends java.applet.Applet{
. . . .
}
Applet Applet
Browser AWT User
Interface , ,
. Applet
, Applet
Applet .

5.1 Applets
Java ,
main(). , main()
. Applets

o Applet (. , , ).
Browser
. Applet Java
. Applet
(
method overriding) Applet .
applet :
1.
public void init(){
...
}
applet
. ,
, font .
2.
public void start(){
...
}

Java

34

init(). start() applet


. applet
HTML
Applet
.
3.
public void stop(){
...
}
stop() Applet start().
stop Applet
. stop() Threads
Applet ( )
.
4.
public void destroy(){
...
}
Applet
( , threads .). Applet
Browser .
Applet .
5.
public void paint(Graphics g){
...
}
Applet . , ,
. Applet
, Browser
, animation
.
Applet -
:
import java.awt.Graphics

5.2 Applets Web


Applet :
import java.awt.Graphics
import java.awt.Font
import java.awt.Color
public class HelloSomeoneApplet extends java.applet.Applet{
Font f = new Font(TimesRoman, Font.Bold, 36);
String myname;
public void init(){
myname = getParameter(name);
if (myname == null)
myname=Laura;
myname = Hello + myname + !;
}
public void paint(Graphics g){
g.setFont(f);
g.setColor(Color.red);
g.drawString(Hello again!, 5,50);

Java

}
}

/classes.

35

HelloAgainApplet.class

o HTML Applet :
<HTML>
<HEAD>
<TITLE>Applet Alignement </TITLE>
</HEAD>
<BODY>
<P>
<APPLET CODE=HelloAgainApplet.class CODEBASE=classes
WIDTH=300 HEIGHT=70
ALIGN= LEFT VSPACE=60 HSPACE 10>
<PARAM NAME=name VALUE=Bonzo>
Hello to whoever you are
</APPLET>
To the left of this paragraph is and applet of a small string in re type, set in 36 points Times bold.
<BR CLEAR = ALL>
<P>
In the next part of this page, we demonstrate how under certain conditions, styrofoam peanuts can be
used as a healthy snack.
</BODY>
</HTML>
To Web Browser :
Netscape: Applet Alignment
0,0
60
50

10

HELLO Bonzo!

To the left of this paragraph


is and applet of a small string
in re type, set in 36 points
Times bold.

60
In the next part of this page, we demonstrate how under certain conditions, styrofoam
peanuts can be used as a healthy snack.

:
Applet ,
string myname name
HTML .
Applet Web tag <APPLET>
BR CLEAR: T </APPLET> tag BR CLEAR

CLEAR (CLEAR=LEFT, CLEAR=RIGHT,
CLEAR=ALL).

Java

36

tags <APPLET>
Applet Web :
CODE: Applet .
CODEBASE: Applet
.
WIDTH HEIGHT:
Applet .
ALIGN: Applet Web.
(LEFT, RIGHT, TOP, TEXTTOP, MIDDLE, ABSMIDDLE, BASELINE, BOTOM,
ABSBOTOM). ALIGN=LEFT Applet
</APPLET>
.
VSPACE HSPACE:
pixels Applet .
PARAM : Applet ,
Name VALUE .

5.3 ,
, Graphics.
,
applet.
(0,0) .
.
0,0

+
5.3.1 Graphics
Graphics
applet .
:
import java.awt.Graphics
:

drawLine(startX, startY, width, height);
drawRect(startX, startY, width, height);
fillRect(startX, startY, width, height);
drawRoundRect(startX, startY, width, height);
fillRoundRect(startX, startY, width, height);
draw3DRect(startX, startY, width, height, boolean value);
fillRect(startX, startY, width, height, boolean value);
drawPolygon(arrayX, arrayY, array length);
fillPolygon(arrayX, arrayY, array length);
drawPolygon(polygon object);
fillPolygon(polygon object);
drawOval(TopCornerX, TopCornerY, width, height);

Java

37

fillOval(TopCornerX, TopCornerY, width, height);


drawArc(TopCornerX, TopCornerY, width, height, arcStart, arcStop);
fillArc(TopCornerX, TopCornerY, width, height, arcStart, arcStop);
-
copyArea(fromStartX, fromStartY, fromWidth, fromHeight, toStartX, toStartY);
clearArea(fromStartX, fromStartY, fromWidth, fromHeight, toStartX, toStartY);


:
setFont(fontObject);
strings :
drawString(aString, atPointX, atPointY);

getFont();

setColor(colorObject);
getColor();
5.3.2 Fonts
Fonts
applet . :
import java.awt.Fonts
Font Font
:
Font f = new Font(TimesRoman, Font.BOLD, 24);
Font.PLAIN, Font.BOLD,
Font.ITALIC ( FontBold + FontItalic).
Font :
getName();
getSize();
getStyle();
isPlain;
isBold;
isItalic();
(
, )
FontMetrics ( API Java Decumentation Sun).
5.3.3 Color
Color
applet . :
import java.awt.Color
Color
Color:
Color c = new Color(redValue, greenValue, blueValue);
, , 0 255.
Color
, Color
(Color.white, Color.black, Color.lightGray, Color.gray, Color.darkGray,
Color.red, Color.green, Color.blue, Colror.yellow, Color.magenta, Color.cyan, Color.pink,
Color.orange).

Java

38

o Background Foreground applet


Applet :
setBackground(colorObject);
setForeground(colorObject);
getBackground();
getForeground();

5.3.4 - -
applet
) ( ), )
( ) )
( ).
)
import java.awt.Graphics;
public class Lamp extends java.applet.Applet{
public void paint (Graphics g){
// the lamp platform
g.fillRect(0,250,290,290);
// the base of the lamp
g.drawLine(125, 250, 125, 160);
g.drawLine(175,250,175,160);
// the lamp shade, top and bottom edges
g.drawArc(85,157,130,50,-65,312);
g.drawArc(85,87,130,50,62,58);
// lamp shade, shides
g.drawLine(85,177,119,89);
g.drawLine(215, 177,181,89);
//dots on the shade
g.fillArc(78,120,40,40,63,-174);
g.fillOval(120,96,40,40);
g.fillArc(173,100,40,40,110,180);
}
}

)
import java.awt.Font;
import java.awt.Graphics;

Java

public class ManyFonts extends java.applet.Applet{


public void paint (Graphics g){
Font f = new Font(TimesRoman, Font.PLAIN, 18);
Font fb = new Font(TimesRoman, Font.BOLD, 18);
Font fi = new Font(TimesRoman, Font.ITALIC, 18);
Font fbi = new Font(TimesRoman, Font.BOLD + Font.ITALIC, 18);
g.setFont(f);
g.drawString(This is a plain font, 10, 25);
g.setFont(fb);
g.drawString(This is a bold font, 10, 50);
g.setFont(fi);
g.drawString(This is an italic font, 10, 75);
g.setFont(fbi);
g.drawString(This is a bold and italic font, 10, 100);
}
}

)
import java.awt.Graphics;
import java.awt.Color;
public class ColorBoxes extends java.applet.Applet{
public void paint (Graphics g){
int rval, gval, bval;
for(int j = 30; j< (size().height -25); j += 30) //rows
for (int I = 5; I < (size().width -25); I += 30){ // columns
rval = (int)Math.floor(Math.random() * 256);
gval = (int)Math.floor(Math.random() * 256);
bval = (int)Math.floor(Math.random() * 256);
g.setColor(new Color(rval,gval,bval));
g.fillRect(I, j, 25, 25);
g.setColor(Color.Black);
g.fillRect(I-1, j-1, 25, 25);
}
}
}

39

Java

40

Java

41

6. Threads
Java
threads . multithreading languages.
process
() .
process
thread . multithreading
process
threads ( lightweight processes)
. processes
process.

6.1 Threads
SimpleThread TwoThreadsTest:
class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
}
}
class TwoThreadsTest {
public static void main (String[] args) {
new SimpleThread("Jamaica").start();
new SimpleThread("Fiji").start();
}
}
simpleThread constructor
string. cunstructor constructors
hread String Thread
.
run. H run
thread thread.
H twoThreads main threads
Jamaica Fiji. H main
thread
start.
To :
0 Jamaica
0 Fiji
1 Fiji
1 Jamaica
2 Jamaica
2 Fiji
3 Fiji

Java

42

3 Jamaica
4 Jamaica
4 Fiji
5 Jamaica
5 Fiji
6 Fiji
6 Jamaica
7 Jamaica
7 Fiji
8 Fiji
9 Fiji
8 Jamaica
DONE! Fiji
9 Jamaica
DONE! Jamaica
. threads,
,
10 . Thread
java.lang
import

6.2

Threads

Thread
run Thread.
Thread
run. (
animation loop
).
run Thread :
Thread (overriding) run
Thread . simpleThread
.
Runnable interface.
Thread -
Runnable interface. To
Threads.

6.3 Threads Applets


Applet Clock
. applet Runnable interface
run Thread .
Thread
(
, scroll ). Java
(
), Clock Thread
Applet. Clock Runnable
interface Threads.
import java.awt.Graphics;
import java.util.Date;
public class Clock extends java.applet.Applet implements Runnable {

Java

43

Thread clockThread = null;


public void start() {
if (clockThread == null) {
clockThread = new Thread(this, "Clock");
clockThread.start();
}
}

public void run() {


// loop terminates when clockThread is set to null in stop()
while (Thread.currentThread() == clockThread) {
repaint();
try {
clockThread.sleep(1000);
} catch (InterruptedException e){
}
}
}
public void paint(Graphics g) {
Date now = new Date();
g.drawString(now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds(), 5, 10);
}
public void stop() {
clockThread = null;
}
}

H start() clockThread null.


Clock Applet
. thread.
:
clockThread = new Thread(this, "Clock");
this Clock Applet,
Runnable interface, Thread .
stop()
clockThread null.
run() Thread .
clockThread.stop()
run() .
H run() Clock Applet.
repaint() paint() .

Java

44

6.4 Threads
H java monitors .
synchnonized monitor.
monitor thread
synchronized . synchronized
thread
synchronized
thread. -synchronized .
synchronized .
thread synchronized
wait().
thread wait monitor
.
thread synchronized , notify(),
thread wait monitor .
thread, , thread
synchronized - monitor .
thread ,
- . notifyAll(),
threads wait monitor .
wait(), notify(), notifyAll() java.lang.Object.
Producer/Consumer . Producer
0 9 (),
CubbyHole, .
, o Producer
0 100
.
Consumer,
CubbyHole ( Producer
) .
threads , get() put()
CubbyHole.
//*******************************
// Class Producer.java
//*******************************
public class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
cubbyhole.put(i);
System.out.println("Producer #" + this.number
+ " put: " + i);
try {
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) { }
}
}
}

Java

//*
// Class Consumer.java
//*
public class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get();
System.out.println("Consumer #" + this.number
+ " got: " + value);
}
}
}
//*******************************
// Class CubbyHole.java
//*******************************
public class CubbyHole {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
} catch (InterruptedException e) { }
}
available = false;
System.out.println("in get");
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) { }
}
contents = value;
available = true;
System.out.println("in gut");
notifyAll();
}
}
//*******************************

45

Java

46

// Class ProducerConsumerTest.java
//*******************************
public class ProducerConsumerTest {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
To ProducerConsumerTest
:
. . .
Consumer #1 got: 3
Producer #1 put: 4
Producer #1 put: 5
Consumer #1 got: 4
. . .

6.5

Threads

To
thread .
stop,suspend resume
(deprecated) .

(flag) thread
.

born
start
ready

t io

ll

y
ify

e
pl
n

no
t

no
tif

co

dispatch
(assign a
processor)

su

ait

iss
ue
I/O

e
sp

s le
ep

or

running
w

nd

waiting

I/O

quantum
expiration
yield
interrupt

sleeping

suspended

sleep interval
expires

re
qu
es
t

blocked

resume
stop

complete

dead

Java

47

Java

47

7. Abstract Windowing Toolkit (AWT)


7.1 GUI
Graphical User Interface-GUI ( )
,
. GUI GUI-components.
GUI-components java.awt (Abstract Windowing
Toolkit) package. Component Container.
Component Component.
Container Container.
GUI-components :
Label
Button
TextField
TextArea

Choice
Checkbox
List
Panel
ScrollPane

.
(event) .
. TextField
.
. TextArea
TextField
.

.
boolean component .
Radio buttons ( ).
.
action event.
container component
.
container component,
Panel,
Scrollbars component
.

GUI-components

java.lang.Object
CheckboxGroup
Component

Label
Button
TextField
TextComponent

FlowLayout
BorderLayout
GridLayout

Choice

TextArea

Checkbox
List
Container
Panel

java.applet.Applet

Window

Frame

ScrollPane

GUI.

Java

48

Component .
Component paint repaint
Applets.

applet ax2+bx+c=0,
.

init applet
GUI components (TextField, Label, Button, Panel ScrollPane).
// EQuation applet
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class eq
//
TextField
Button
Panel
ScrollPane

extends java.applet.Applet {
GUI components
tfA, tfB, tfC, tfD, tfX1, tfX2;
btSolve, btClear;
p;
sp;

public void init() {


// GUI components.
// .
p = new Panel();
sp = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);
tfA = new TextField();
tfB = new TextField();
tfC = new TextField();
tfD = new TextField();
tfX1 = new TextField();
tfX2 = new TextField();
btSolve = new Button("Solve");
btClear = new Button("Clear");
tfD.setEditable(false);

Java
tfX1.setEditable(false);
tfX2.setEditable(false);
}
}

49

Java

50

7.2 GUI
GUIs ( Paint
Windows - GUI , ,
) . , , GUI Java,
Panel components. Panel
Container Applet Panel. Panels
Applets Containers Components, Panel.
Panel .
GUI component hierarchy containment hierarchy.
Panel Components
(layout). Java (Layout Managers)
Component Applet Panel. Layout
Managers :
FlowLayout
BorderLayout
GridLayout
CardLayout

GridBagLayout

default Layout Manager Applets Panels.


Component
Component : , , ,
(North, South, East, West, Center).
Component
( ).
Component . Container
Layout Manager. Container
.
GridLayout Manager.
Component
( ).
Component GridBagLayout Manager
.


component hierarchy
Layout Managers.
init .
// GUI components Panel.
// 1
p.setLayout(new GridLayout(5,4, 5,5));
p.add(new Label(""));
p.add(new Label("EQuation"));
p.add(new Label("Applet"));
p.add(new Label(""));
// 2
p.add(new Label("Factor a"));
p.add(tfA);
p.add(new Label("Determinator D"));
p.add(tfD);
// 3
p.add(new Label("Factor b"));

Java

51

p.add(tfB);
p.add(new Label("Root X1"));
p.add(tfX1);
// 4
p.add(new Label("Factor c"));
p.add(tfC);
p.add(new Label("Root X2"));
p.add(tfX2);
// 5
p.add(new Label(""));
p.add(btSolve);
p.add(btClear);
p.add(new Label(""));
// component hierarchy.
// Panel p ScrollPane sp.
// sp applet.
sp.add(p);
sp.doLayout();
setLayout(new BorderLayout());
add(sp, BorderLayout.CENTER);

applet ( 29).

7.3 GUI (GUI Events)


Java Windows.
GUI event,
AWTEvent. AWTEvent java.awt.event.
java.awt.event.

java.lang.Object

ActionEvent

ContainerEvent

AdjustmentEvent

FocusEvent

ItemEvent

PaintEvent

ComponentEvent

WindowEvent

java.util.EventObject

java.awt.AWTEvent

Key

InputEvent
Class name
Interface name
KeyEvent

MouseEvent

Java

52

event :
) (event listener)
events.
B) (event handler) events
.

event listener ,
event-listener interface java.awt.event.
event-listener interfaces java.awt.event.

java.lang.Object

ActionListener
AdjustmentListener

java.util.EventListener
ComponentListener
ContainerListener
FocusListener
ItemListener
KeyListener
MouseListener
MouseMotionListener
Key
Class name

TextListener

Interface name
WindowListener

event-listener interface event handler . event


handler .
event listener ( ) event
handler event-listener interfaces .
event listener ,
events GUI-Components -
o event , event handler
event.

Java

53


,
(event listeners) Buttons Solve
Clear. init
layout component hierarchy.
class Solve implements ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
double a,b,c,d,x1,x2,sqrtd;
a=(new Double(tfA.getText())).doubleValue();
b=(new Double(tfB.getText())).doubleValue();
c=(new Double(tfC.getText())).doubleValue();
d = b*b-4*a*c;
tfD.setText(Double.toString(d));
if (d>0) {
sqrtd = Math.sqrt(d);
x1 = (-b-sqrtd)/(2d*a);
x2 = (-b+sqrtd)/(2d*a);
tfX1.setText(Double.toString(x1));
tfX2.setText(Double.toString(x2));
} else if (d==0) {
x1 = x2 = -b/(2d*a);
tfX1.setText(Double.toString(x1));
tfX2.setText(Double.toString(x2));
} else {
tfX1.setText("Error");
tfX2.setText("Negative D");
}
} catch (Exception e) {
tfD.setText(e.getMessage());
}
}
}
btSolve.addActionListener(new Solve( ) );
class Clear implements ActionListener() {
public void actionPerformed(ActionEvent ae) {
tfA.setText("");
tfB.setText("");
tfC.setText("");
tfD.setText("");
tfX1.setText("");
tfX2.setText("");
}
}

Java

54

btClear.addActionListener(new Clear( ) );
on the fly
. inline .
components
event
component.
inline - :
someComponent.addSomeEventListener( new SomeEventListener()
{
// -
public void someEventMethod( ) //Overrided
{ Event method implementation here }
} );
inline ,
Buttons Solve Clear :
btSolve.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
double a,b,c,d,x1,x2,sqrtd;
a=(new Double(tfA.getText())).doubleValue();
b=(new Double(tfB.getText())).doubleValue();
c=(new Double(tfC.getText())).doubleValue();
d = b*b-4*a*c;
tfD.setText(Double.toString(d));
if (d>0) {
sqrtd = Math.sqrt(d);
x1 = (-b-sqrtd)/(2d*a);
x2 = (-b+sqrtd)/(2d*a);
tfX1.setText(Double.toString(x1));
tfX2.setText(Double.toString(x2));
} else if (d==0) {
x1 = x2 = -b/(2d*a);
tfX1.setText(Double.toString(x1));
tfX2.setText(Double.toString(x2));
} else {
tfX1.setText("Error");
tfX2.setText("Negative D");
}
} catch (Exception e) {
tfD.setText(e.getMessage());
}
}
});

Java

55

btClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
tfA.setText("");
tfB.setText("");
tfC.setText("");
tfD.setText("");
tfX1.setText("");
tfX2.setText("");
}
});

7.4 Adapter Classes


event listener
interface . ,
interface,
adapter . event listener interface
adapter .
adapter : MouseAdapter interface MouseListener,
MouseMotionAdapter interface MouseMotionListener, MouseMotionAdapter
interface MouseMotionAdapterListener .

7.5 applet EQ
EQ applet
stand-alone
application main( ).
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class eq
TextField
Button
Panel
ScrollPane

extends java.applet.Applet {
tfA, tfB, tfC, tfD, tfX1, tfX2;
btSolve, btClear;
p;
sp;

public void init() {


setBackground(SystemColor.control);
p = new Panel();
sp = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);
tfA = new TextField();
tfB = new TextField();
tfC = new TextField();

Java

56

tfD = new TextField();


tfX1 = new TextField();
tfX2 = new TextField();
btSolve = new Button("Solve");
btClear = new Button("Clear");
tfD.setEditable(false);
tfX1.setEditable(false);
tfX2.setEditable(false);
p.setLayout(new GridLayout(5,4, 5,5));
p.add(new Label(""));
p.add(new Label("EQuation"));
p.add(new Label("Applet"));
p.add(new Label(""));
p.add(new Label("Factor a"));
p.add(tfA);
p.add(new Label("Determinator D"));
p.add(tfD);
p.add(new Label("Factor b"));
p.add(tfB);
p.add(new Label("Root X1"));
p.add(tfX1);
p.add(new Label("Factor c"));
p.add(tfC);
p.add(new Label("Root X2"));
p.add(tfX2);
p.add(new Label(""));
p.add(btSolve);
p.add(btClear);
p.add(new Label(""));
sp.add(p);
sp.doLayout();
setLayout(new BorderLayout());
add(sp, BorderLayout.CENTER);
btSolve.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
double a,b,c,d,x1,x2,sqrtd;
a=(new Double(tfA.getText())).doubleValue();

Java

57

b=(new Double(tfB.getText())).doubleValue();
c=(new Double(tfC.getText())).doubleValue();
d = b*b-4*a*c;
tfD.setText(Double.toString(d));
if (d>0) {
sqrtd = Math.sqrt(d);
x1 = (-b-sqrtd)/(2d*a);
x2 = (-b+sqrtd)/(2d*a);
tfX1.setText(Double.toString(x1));
tfX2.setText(Double.toString(x2));
} else if (d==0) {
x1 = x2 = -b/(2d*a);
tfX1.setText(Double.toString(x1));
tfX2.setText(Double.toString(x2));
} else {
tfX1.setText("Error");
tfX2.setText("Negative D");
}
} catch (Exception e) {
tfD.setText(e.getMessage());
}
}
});
btClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
tfA.setText("");
tfB.setText("");
tfC.setText("");
tfD.setText("");
tfX1.setText("");
tfX2.setText("");
}
});
} //end of init() method
public Insets getInsets() {
Insets
i = super.getInsets();
return new Insets(i.top+10, i.left+10,
i.bottom+10, i.right+10);
}
public void paint(Graphics g) {
Dimension
dim = getSize();
g.setColor(Color.lightGray);

Java
g.draw3DRect(3, 3, dim.width-9, dim.height-9, false);
g.draw3DRect(4, 4, dim.width-11, dim.height-11, true);
}
public static void main(String args[]) {
Frame fr = new Frame("EQ");
eq
eq = new eq();
Button
btClose = new Button("Close");
Panel p2 = new Panel();
eq.init();
eq.start();
p2.setLayout(new FlowLayout(FlowLayout.CENTER));
p2.add(btClose);
fr.setBackground(SystemColor.control);
fr.setLayout(new BorderLayout());
fr.add(eq, BorderLayout.CENTER);
fr.add(p2, BorderLayout.SOUTH);
//

fr.pack();
fr.setSize(300, 150);
fr.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
Frame src = (Frame)we.getSource();
Applet appl=(Applet)src.getComponent(0);
appl.stop();
appl.destroy();
src.setVisible(false);
src.dispose();
System.exit(0);
}
});
btClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
fr.setVisible(true);
}

58

Java

8.

59

Swing (Swing GUIs)

javax.swing
GUI. javax.swing
Abstract Windows Toolkit (AWT). , JButton
, AWT Button ,
.

8.1

Top-Level Swing Containers Swing Components

Swing top-level Swing container.


top-level Swing container Swing
components .
top-level Swing containers: JFrame, JDialog, ( applets) JApplet.
JFrame , JDialog
(
). JApplet applet
Web Browser. top-level Swing containers :

Jframe

JDialog

JApplet
top-level containers, JFrame, Swing components
JComponent. H JComponent
:
java.lang.Object
java.awt.Component
Java.awt.Container
java.swing.JComponent

Java

60

swing Containers Components

Top-Level Containers
Container Swing .

Applet
Frame
Dialog

General-Purpose Containers
Container .

Scroll pane
Panel

Tabbed pane

Split pane

Tool bar

Special-Purpose Containers
Container GUI.

Java

61

Internal frame
Layered pane

Root pane

Basic Controls
Component ,
.

List
Buttons

Combo box

Slider

Menu

Java

Spinner

62

Text field or Formatted text field

Uneditable Information Displays


Component .

Progress bar

Tool tip
Label

Interactive Displays of Highly Formatted Information


Component (
) .

Color chooser

File chooser

Table
Text

Tree

Java

63

Swing
Swing :

JFrame

JPanel

JButton

Swing Components . ,
GUI Swing, JFrame
(layout) . JPanels Jframe.
JPanels layout JFrames. ,
Component.
.

import
import
import
import
import

java.lang.*;
java.util.*;
java.awt.*;
java.awt.event.*;
javax.swing.*;

class SimpleGui1 {
public static void main(String args[]) {
// Let's make a button first.
JButton btn = new JButton("Click Me!");
btn.setMnemonic(KeyEvent.VK_C); // Now you can hit the button with
// Alt-C.
// Let's make the panel with a flow layout.
// Flow layout allows the components to be
// their preferred size.
JPanel pane = new JPanel(new FlowLayout());
pane.add(btn);
// Add the button to the pane.
// Now for the frame
JFrame fr = new JFrame();
fr.setContentPane(pane); // Use our pane as the default pane
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit program
//when frame is closed.
fr.setLocation(200, 200); //
fr.pack();
//
//
fr.setVisible(true);
//

locate Frame at (200, 200).


Frame is ready. Pack it up for
display.
Make it visible.

}
}
:

Java

64

JButton, JPanel, JFrame


( JAVA PI ).
,
, "" .

8.2

- Event Handlers


component (JButton )
(ButtonListener). ,

( ).
AWT
Component. JButton
:
import
import
import
import
import

java.lang.*;
java.util.*;
java.awt.*;
java.awt.event.*;
javax.swing.*;

class SimpleGui1 {
public static void main(String args[]) {
// Let's make a button first.
JButton btn = new JButton("Click Me!");
btn.setMnemonic(KeyEvent.VK_C); // Now you can hit the button with
// Alt-C.
btn.addActionListener(new ButtonListener()); // Allow the button
// to disable itself

// Let's make the panel with a flow layout.


// Flow layout allows the components to be
// their preferred size.
JPanel pane = new JPanel(new FlowLayout());
pane.add(btn);
// Add the button to the pane.
// Now for the frame
JFrame fr = new JFrame();
fr.setContentPane(pane); // Use our pane as the default pane
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit program
//when frame is closed.
fr.setLocation(200, 200); //
fr.pack();
//
//
fr.setVisible(true);
//
}

locate Frame at (200, 200).


Frame is ready. Pack it up for
display.
Make it visible.

Java

65

// Button event handler


static class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
btn.setEnabled(false); // Disable the button
}
}
}
. , ,
:

Swing components (events).


.
Some Events and Their Associated Event Listeners
Act that Results in the Event

Listener Type

User clicks a button, presses Enter while typing


ActionListener
in a text field, or chooses a menu item
User closes a frame (main window)

WindowListener

User presses a mouse button while the cursor is


MouseListener
over a component
User moves the mouse over a component

MouseMotionListener

Component becomes visible

ComponentListener

Component gets the keyboard focus

FocusListener

Table or list selection changes

ListSelectionListener

Any property in a component changes such as


PropertyChangeListener
the text on a label

8.3

Swing Threads

H AWT Swing GUI


Threads. AWT threads (thread safe) swing
.
Threads synchnonized Java
o threads .
AWT
. (deadlocks)
(. buttons, panels, )
.
swing thread-safe.
Swing thread

Java

66

event-dispatching thread.
event handler event handler.
(deadlock), Swing components
, eventdispatching thread.

8.3.1 invokeLater
invokeLater thread event-dispatching
thread .
run Runnable Runable
invokeLater. invokeLater
event-dispatching thread.
invokeLater:
Runnable updateAComponent = new Runnable() {
public void run() { component.doSomething(); }
};
SwingUtilities.invokeLater(updateAComponent);

GUI event-dispatching thread invokeLater.
Swing
GUI event-dispatching thread
invokeLater. invokeLater invokeAndWait

import
import
import
import
import

java.lang.*;
java.util.*;
java.awt.*;
java.awt.event.*;
javax.swing.*;

class SimpleGui1 {
private static JButton btn = null;
public static void createAndShowGUI() {
// Let's make a button first.
btn = new JButton("Click Me!");
btn.setMnemonic(KeyEvent.VK_C); // Now you can hit the button with
// Alt-C.
btn.addActionListener(new ButtonListener()); // Allow the button
// to disable itself

// Let's make the panel with a flow layout.


// Flow layout allows the components to be
// their preferred size.
JPanel pane = new JPanel(new FlowLayout());
pane.add(btn);
// Add the button to the pane.

Java

67

// Now for the frame


JFrame fr = new JFrame();
fr.setContentPane(pane); // Use our pane as the default pane
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit program
//when frame is closed.
fr.setLocation(200, 200); //
fr.pack();
//
//
fr.setVisible(true);
//

locate Frame at (200, 200).


Frame is ready. Pack it up for
display.
Make it visible.

public static void main(String[] args) {


//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

// Button event handler


static class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
btn.setEnabled(false); // Disable the button
}
}
}

Java

68

Java

69

9. Animation Java
9.1 Animation
Java
Java applet , animation.
animation
.
animation.
animation:
1. multi-frame animation.
(frames) (
animation 10-20 frames
).
(cartoons).
2. .
( sprite)
(background). .
sprite frames,
background. ,
, (sprite) (transparent) background
.
format GIF 89 Compuserve.

9. 2 animation loop
animation ,
(animatin loop),
animation. Java
thread.
paint() update() java.awt.Component
, AWT
thread
(event handling) . animation loop
run() thread
animation. paint() frame
( ).
animation loop.
frameNumber, frame
( frame)
delay, msec ( )
frames.
frame animation loop, repaint()
java.awt.Component. paint() (
paint() frame) frame.

public void run() {


while (true) {
// animation frame .
frameNumber++;

Java

70

// .
repaint();
// delay msec.
try {Thread.sleep(delay); } catch (InterruptedException e) {}
}

9.3. animation
Applet multi-frame
animation, animation loop
. ,
Java animation. .

import java.awt.*;
import java.applet.Applet;
// applet Runnable interface
// threads.
public class AnimatorApplet extends Applet implements Runnable {
int frameNumber = -1;
// frames
int delay;

// msec

// Thread animation
Thread animatorThread;
public void init() {
// 100msec frames
delay=100;
}
public void start() {
// Thread animation
if (animatorThread == null) {
animatorThread = new Thread(this);
}
// Thread animation
animatorThread.start();
}
}
public void stop() {
// hread animation
animatorThread = null;
}
// animation loop.
public void run() {
//animation loop

Java

71

while (Thread.currentThread() == animatorThread) {


// frame
frameNumber++;
// frame
repaint();
// msec
try {Thread.sleep(delay) }
catch (InterruptedException e) { break; }
}
}
// paint() frame.
public void paint(Graphics g) {
// string
// frame
g.drawString("Frame " + frameNumber, 0, 30);
// , frame
}
}

9.4.
animation:
Frame i, i frame.
,
. string ( string
- ),
.
flashing flickering
(smooth, flicker free) animation.
screen flickering :
repaint() animation loop, frame,
repaint(), background
paint() . ,
background frame
(refresh rate) .
(
background frame)
( frame , ,
background).

animation
flickering (smooth) animation.
update().
Abstract Windowing Toolkit (AWT) package Java
(Applet, Canvas, Frame) update()

Java

72

. , update() clearRect()
background paint()
.
update() : background
.
animation loop flickering.
background
frame. update()
paint() ( background). ,
update frame, -
frame.
buffer


.
(offscreen) frame o
.
frame , frame
frame .
frame , . ,
frame . Java, buffer
(offImage) Image
createImage() java.awt.Component.
, Graphics (offGraphics)
Image getGraphics().
, update()
. frame
drawImage()
update().
Applet
smooth animation.
:

import java.awt.*;
import java.applet.Applet;
public class ImageSequence extends Applet implements Runnable {
int frameNumber = -1;
int delay;
Thread animatorThread;
boolean frozen = false;
Dimension offDimension;
Image offImage;
Graphics offGraphics;
Image[] images;
public void init() {
String str;
int fps = 10;
// milliseconds frames;
str = getParameter("fps");
try {

Java

if (str != null) {
fps = Integer.parseInt(str);
}
} catch (Exception e) {}
delay = (fps > 0) ? (1000 / fps) : 100;
// .
images = new Image[10];
for (int i = 1; i <= 10; i++) {
//
images[i-1] = getImage(getCodeBase(),
"myimage"+i+".gif");
}
}
public void start() {
if (frozen) {
// .
} else {
// animation!
if (animatorThread == null) {
animatorThread = new Thread(this);
}
animatorThread.start();
}
}
public void stop() {
// animation
animatorThread = null;
//
//
offGraphics = null;
offImage = null;
}
public boolean mouseDown(Event e, int x, int y) {
if (frozen) {
frozen = false;
start();
} else {
frozen = true;
// animating thread.
animatorThread = null;
}
return true;
}
public void run() {
//
// animation thread
//
// .
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

73

Java

//
long startTime = System.currentTimeMillis();
//animation loop.
while (Thread.currentThread() == animatorThread) {
frameNumber++;
repaint();
//
try {
startTime += delay;
Thread.sleep(Math.max(0,
startTime-System.currentTimeMillis()));
} catch (InterruptedException e) {
break;
}
}
}
public void paint(Graphics g) {
update(g);
}
// update()
//
// background .
// backround
// frame.
//
//
public void update(Graphics g) {
Dimension d = size();
//
if ( (offGraphics == null)
|| (d.width != offDimension.width)
|| (d.height != offDimension.height) ) {
offDimension = d;
offImage = createImage(d.width, d.height);
offGraphics = offImage.getGraphics();
}
// frame,
offGraphics.setColor(getBackground());
offGraphics.fillRect(0, 0, d.width, d.height);
offGraphics.setColor(Color.black);
// frame
offGraphics.drawImage(images[frameNumber % 10], 0, 0, this);
//
g.drawImage(offImage, 0, 0, this);
}

74

Java

75

Java

75

10. / - Streams
,
, , , ,
. ( ),
( ) .

10.1
Java,
, , ( file system )
( device ), Streams. stream .
, .
Java streams,
. streams / InputStream
OutputStream, .
streams DataInputStream DataOutputStream
, , -
Java , (
) . ,
- Java. , DataInputStream
DataOutputStream Unicode ( string ),
UTF-8.
streams, ( file
buffers ),
, / ( / ).
BufferedInputStream BufferedOutputStream (
) .
buffered stream, buffer
stream. , ,
flush buffers,
buffer ( file system ). ,
file system,
FileInputStream FileOutputStream ,
.

10.2 System
Java applet ,
import , System.
, /.
System.in, InputStream
stream ( ).
stream
, , modem,
.
stream ,
.
strings, ( integer ) ,
bytes. string :
public class InputTest() {
String str;

Java

76

public static void main(String args[])


{
str = System.in.getln();
}
}

10.3 System
, streams.
,
, standard output,
. monitor, , ,
, . System
System.out OutputStream. To ,
, standard output.
public class InputTest() {
String str;
public static void main(String args[])
{
str = System.in.getln();
System.out.println(str);
}
}
:
applet, .. Netscape Navigator, standard Java
Console Netscape, ,
( command line ).

10.4 DataInputStream

DataInputStream.
Constructor :
public DataInputStream(InputStream in)
data input stream
input stream .
:
in - input stream.
:
read(byte[])
byte.length bytes data input stream,
bytes
readBoolean()
boolean data input stream.
readByte()
8-bit data input stream.

Java

77

readChar()
Unicode data input stream.
readFloat()
float data input stream.
readInt()
32-bit ( integer ) data input stream.
readLine()
data input stream.
readLong()
64-bit ( integer ) data input stream.

10.5 DataOutputStream

DataOutputStream.
Constructor :
public DataOutputStream(OutputStream out)
data output stream output
stream .
:
out - output stream.
:
flush()
, . output
stream. buffer.
size()
bytes data output stream.
writeChar(int)
stream 2-byte ,
byte, .
writeDouble(double)
double long
doubleToLongBits Double long
stream 8-byte , byte,
.
writeInt(int)
( int ) stream bytes,
byte, .

Java

78

11. Java
11.1 Uniform Resource Locator (URL)
( World Wide Web ),
URL, HTML Web.
, :
: URL Uniform Resource Locator
( ) Internet.
( ) URL,
, URLs
. URL
... Internet : http://www.ntua.gr .
URL, , :
( protocol identifier ) , .. http
/ ( resource name ), .. //www.ntua.gr .
To protocol identifier ,
. , http
( hypertext documents ). ftp
, news , file gopher.
Internet. H
,
:
host : .
( filename ) : , host.
( port number ) : (
).
( reference ) : .
, ,
. To java.net URL,
URL .

11.1.1 URL (relative)


URL
URL. specifications URL
HTML .
L JoesHomePage.html.
links , PicturesOfMe.html MyKids.html,
directory JoesHomePage.html. links
PicturesOfMe.html MyKids.html JoesHomePage.html
:
<a href="PicturesOfMe.html">Pictures of Me</a>
<a href="MyKids.html">Pictures of My Kids</a>
URL URL, URL
( JoesHomePage.html). Java,
URL specification URL.

Java

79

, URL gamelan site:


http://www.gamelan.com/pages/Gamelan.game.html
http://www.gamelan.com/pages/Gamelan.net.html
URL
URL: http://www.gamelan.com/pages/ :
URL gamelan = new URL("http://www.gamelan.com/pages/");
URL gamelanGames = new URL(gamelan, "Gamelan.game.html");
URL gamelanNetwork = new URL(gamelan, "Gamelan.net.html");
snippet URL
URL URL ( )
specification URL. :
URL(URL baseURL, String relativeURL)
URL URL.
String resource
. URL ,
() URL URL specification. ,
URL URL specification
URL.

URL (anchors)
.
Gamelan.net.html
BOTTOM .
URL, URL :
URL gamelanNetworkBottom = new URL(gamelanNetwork, "#BOTTOM");

11.1.2 URL
class URL URL .
URL, HTTP
URLs, host, ,
resource name portion URL.
string URL specification,
URL.
network browsing panel
browsing panel , host,
. panel
URL. URL ,
host . URL
Gamelan.net.html site Gamelan:
new URL("http", "www.gamelan.com", "/pages/Gamelan.net.html");
:
new URL("http://www.gamelan.com/pages/Gamelan.net.html");
, host
path . forward
slash . host.

Java

80

URL
:
URL gamelan = new URL("http", "www.gamelan.com", 80,
"pages/Gamelan.net.html");
URL URL:
http://www.gamelan.com:80/pages/Gamelan.net.html
URL
, toString() toExternalForm()
URL, String .

11.1.3 MalformedURLException
URL MalformedURLException
. ,

URL try/catch pair, :
try {
URL myURL = new URL(. . .)
} catch (MalformedURLException e) {
...
// exception handler code here
...
}
URLs '' '' .
URL ,
( )(, host, ).

11.1.4 URL
URL, ()
, :
getProtocol()
String .
getHost()
String host.
getPort()
(integer) (port).
port number URL -1.
getFile()
String filename.
getRef()
URL.
getXXX ,
URL
URL.
URL class, ,
URLs. ,

Java

81

URL
.
URL string
URL:
import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new
URL("http://java.sun.com:80/docs/books/tutorial/intro.html#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("host = " + aURL.getHost());
System.out.println("filename = " + aURL.getFile());
System.out.println("port = " + aURL.getPort());
System.out.println("ref = " + aURL.getRef());
}
}
:
protocol = http
host = java.sun.com
filename = /docs/books/tutorial/intro.html
port = 80
ref = DOWNLOADING

11.1.5 URL
URL, openStream()
stream, .
, openStream() , Java.io.InputStream ,
URL, ,
streams, streams.
, .
,
HTML.
import java.net.*;
import java.io.*;
class OpenStreamTest {
public static void main(String args[]) {
try {
DataInputStream in = new DataInputStream(System.in);
DataInputStream dis;
String inputLine;
String address;
// Get the address from the user.
System.out.print(Give the address : );
address = in.readLine();
URL adr = new URL(address);
dis = new DataInputStream(adr.openStream());
while ((inputLine = dis.readLine()) != null) {
System.out.println(inputLine);
}

Java

82

dis.close();
} catch (MalformedURLException me) {
System.out.println("MalformedURLException: "+ me);
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
}
}
// End of main()
// End of class

, , ,
URL, ( query ),
cgi-script.

11.1.6 URL
URL
openConnection. ,
Java URL .

... :
try {
URL ntua = new URL("http://www.ntua.gr");
ntua.openConnection();
} catch (MalformedURLException e) { // new URL() failed
...
} catch (IOException e) {
// openConnection() failed
...
}
openConnection URLConnection,
, , URL
URLConnection. ,
openConnection .

11.1.7 URLConnection
input stream URL,
(connection) URL input stream ,
.
BufferedReader input stream, .
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);

Java

83

in.close();
}
}
URLConnection
URL
URLConnection .

11.1.8 URLConnection
HTML ,
(server).

, Web browser URL ,
cgi-bin script, , (server) ,
, HTML .
cgi-bin scripts POST
, URL posting
url. Java cgi-scripts
, URL,
. :
URL.
URL.
URLConnection.
(stream) . stream
stream cgi-bin script .
stream .
stream .
Hassan Schroeder, JAVA,
cgi-bin script, backwards site:
http://java.sun.com/cgi-bin/backwards.
, . ,
script , backwards
.
string standard ,
standard . :
string=string_to_reverse, string_to_reverse string
.
import java.io.*;
import java.net.*;
public class Reverse {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: java Reverse string_to_reverse");
System.exit(1);
}
String stringToReverse = URLEncoder.encode(args[0]);
URL url = new URL("http://java.sun.com/cgi-bin/backwards");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());

Java

84

out.println("string=" + stringToReverse);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
.
if (args.length != 1) {
System.err.println("Usage: java Reverse " +
"string_to_reverse");
System.exit(-1);
}
String stringToReverse = URLEncoder.encode(args[0]);

. string cgi-bin
script backwards. .
, string
server. URLEncoder.
, URL, URLConnection
.
URL url = new URL("http://java.sun.com/cgi-bin/backwards");
URLConnection c = url.openConnection();
c.setDoOutput(true);
(stream)
PrintWriter :
PrintWriter out = new PrintWriter(c.getOutputStream());
URL , getOutputStream :
UnknownServiceException. URL ,
(stream) standard URL
(server).
.
, (stream)
.
out.println("string=" + stringToReverse);
out.close();
(stream) println.
, URL
(stream). (stream)
backward script
. Reverse
script string string
.

Java

85

, URL, cgi-bin script


. script ,
, URL. ,
URL .
Reverse :
BufferReader in = new BufferedReader(
new InputStreamReader(c.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
Reverse "Reverse Me",
:
Reverse Me
reversed is:
eM esreveR

Java

86

11.2 Sockets
11.2.1 Client - Server

- ( client - server ). ,
-
, -, .
, :
- .
, , -
.
- , ,
,
. , ,
, ( .. ,
, mail ).
, server
.
, ,
.
, .
, :
{ , -, -, -,
- }
.
- -, , .
- -,
, ,
.
host , 16-bit
, ( port number ) ,
.
, ( half association ), { , , - }, { , -,
- }. socket.
O : Socket , ,
. ,
.
4.1cBSD Unix ( 1982 ), VAX,
Berkeley, socket interface
. C Unix,
, ( .. Winsock
library Microsoft Windows ), ( .. Java ).
socket,
file system. sockets :
T TCP ( Transmission Control Protocol ) socket
( connection-oriented service ).
, ,

Java

87

,
.
UDP (Unreliable Datagram Protocol ) socket
( connectionless service ). To ,
, :
, (
) .
, , TCP sockets
:
. UDP socket .
,
. , TCP socket
( handshake packets )
UDP datagrams.
.
, Java, Socket
TCP sockets, ,
UDP sockets, Datagram.
sockets
java.net .

/
Socket
ServerSocket
DatagramSocket
DatagramPacket
netAddress
URL
URLConnection

TCP -
CP -
UDP ( client & server )
UDP
Internet Protocol (
IP )
Uniform Resource Locator

web.

11.2.2 Client - Server TCP sockets


, (
echo service ). TCP sockets 7,
, , ,
. . , .
,
, ,
, 8205.
O ( client )
client
:
Socket()
getInputStream()
getOutputStream()
read() write()

- server
- socket
/ Java, . streams
- -

Java

88

socket - stream
.. - /
close()
- socket
.
,
.
Socket, , ,
(!) ( constructors ) .
:
Socket s = new Socket(args[0], 8205);
. s, socket
(args[0] - ,
, command line,
).
, streams /
socket , /. ,
, ( ) / Java
streams. , getInputStream()
getOutputStream() Socket, :
DataInputStream sin = new
DataInputStream(s.getInputStream());
DataOutputStream sout = new
DataOutputStream(s.getOutputStream());
streams socket, /
streams. .. :
sout.println(Hello);
// socket
String message = sin.readLine(); //
// socket
socket s,
, , port.
System.out.println(Connected to +
s.getInetAddress() + : + s.getPort());
/, socket ,
, ( file handlers ),
.
...
finally {
try {
if ( s != null) s.close();
} catch(IOException ioe) {
;
}
}
client echo :
// The client program for the echo service
// Written using JDK, ver. 1.1.5

Java

import java.io.*;
import java.net.*;
public class EchoClient
{
public static void echoclient(DataInputStream sin,
DataOutputStream sout) throws IOException
{
DataInputStream in = new DataInputStream(System.in);
PrintStream out = new PrintStream(sout);
String line;
while(true) {
line = "";
// read keyboard input and write to TCP socket
try {
line = in.readLine();
out.println(line);
} catch(IOException e) {
System.out.println(e.getMessage());
}
// read TCP socket and write to terminal...
try {
line = sin.readLine();
System.out.println(line);
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
}

// End of echoclient() function...

public static void main(String[] args)


{
Socket s = null;
try {
// Create the socket to communicate with "echo"
// on the specified host
s = new Socket(args[0], 8205);
// Create streams for reading and writing lines
// of text from and to this socket
DataInputStream sin =
new DataInputStream(s.getInputStream());
DataOutputStream sout =
new DataOutputStream(s.getOutputStream());
// Tell the user that weve connected
System.out.println("Connected to " +
s.getInetAddress() + ":" + s.getPort());
// Use the echo feature...
echoclient(sin, sout);

89

Java

90

} catch(IOException e) {
System.out.println(e);
}

}
}

// Always be sure to close the socket...


finally {
try {
if (s != null)
s.close();
} catch(IOException e) {
System.out.println("Closing socket...");
}
}
// End of main()
// End of class

,
socket streams , try
,
IOException. ,
/ socket.
, close() ,
finally.
( server )
TCP - / port
-,
. port server
-,
. server port socket ,
, . . , socket
listening socket.
, .
, ,
- , . ,
.
EchoClient,
: EchoServer, listening-socket
EchoThread, Thread Java.
EchoServer
, .
server :
ServerSocket() - listening socket
accept()
-
new Thread
- thread

getInputStream()
- socket accept
getOutputStream()
/
Java, . streams
read() write()
- -
socket - stream
.. - /

Java
close()

91

- socket ( listening )
.

ServerSocket java.net
TCP socket, ,
client/server .
,
.
,
. , .
:
ServerSocket serversoc = new ServerSocket(8205);
, server
:
Socket incoming = serversoc.accept();
accept() ,
listening-socket, . .
, accept() Socket ( listening-socket )
.
listening socket ,
( well-known ). ,
EchoThread :
EchoThread et = new EchoThread(incoming);
et.start();
thread socket
accept(), , , streams / :
DataInputStream in =
new DataInputStream(s.getInputStream());
PrintStream out =
new PrintStream(s.getOutputStream());
/ socket ( streams ), /
. , thread socket
accept ( close() ) . listening socket
, EchoServer.
try,
( socket ),
.
echo,
.
// Server program for the echo service. An alternative
// to the standard echo at port 7. We use TCP port 8205.
// Written using JDK 1.1.5, Petros Zerfos @1998
import java.net.*;
import java.io.*;
import java.lang.*;
import java.util.*;
public class EchoServer

Java
{
public static void main(String args[])
{
// initialize the network connection
try {
ServerSocket serversoc = new ServerSocket(8205);
// Now sit in an infinite loop and wait for
// requests...
while (true) {
// accept the message
Socket incoming = serversoc.accept();
// spawn a child to serve the request
EchoThread et = new EchoThread(incoming);
et.start();
}
} catch (IOException e) {
System.out.println("Error : " + e.getMessage());
}
}
}

// End of main
// End of class EchoServer()

class EchoThread extends Thread


{
// The socket we are writing to
Socket s;
// Our constructor
EchoThread(Socket s)
{
this.s = s;
}
// The run method of the thread...
public void run()
{
boolean finished = false;
try {
// Create streams for reading / writing lines of text to the socket
DataInputStream in =
new DataInputStream(s.getInputStream());
PrintStream out =
new PrintStream(s.getOutputStream());
// Print a message:
System.out.println("Client from : " +
s.getInetAddress() + " port " + s.getPort());
// now get the input from the socket...
while(!finished) {
String st = in.readLine();
// Send the same back to client
out.println(st);
// Write it to the screen as well

92

Java

93

System.out.println(st);
// If the input was 'quit' then exit...
if (st.equals("quit")) {
finished = true;
System.out.println("Thread exiting...");
}
}
} catch (IOException e) {
System.out.println("Error : " + e.getMessage());
}
// Always be sure to close the socket...
finally {
try {
if (s != null)
s.close();
} catch(Exception e) {
System.out.println("Error : " +
e.getMessage());
}
}
}
}

// End of run
// End of class EchoThread...

11.2.3 M Socket
, ,
Socket.

Socket(InetAddress, int)
stream ( TCP ) socket port
.
Socket(String, int)
stream ( TCP ) socket port host,
.

close()
socket ( ).
getInetAddress()
host socket
.
getInputStream()
stream socket.
getLocalAddress()
host socket (
).
getLocalPort()
( ) host socket
.
getOutputStream()
stream socket
getPort()
host socket

Java

94

11.2.4 ServerSocket
, ,
ServerSocket.

ServerSocket(int)
server socket
. 0,
( ) .
ServerSocket(int, int)
server socket
,
port, , . , 0
.

accept()
server socket .
close()
server socket.
getInetAddress()
server socket.
getLocalPort()
port server socket .

11.2.5 Datagrams
TCP sockets,
, UDP Datagrams
peer-to-peer, . .
.
, ,
.
, , , , , TCP sockets

( ,
),
datagrams, ( packets )
. , TCP sockets ,
, , ,

, UDP datagrams, , ,
host- . ,
. datagram
:
: Datagram , ( .
) , ,
.

Java

95

,
, , TCP
sockets. , PING,

. , PING
,
. TCP,
.

11.2.6 UDP Datagrams


,
, UDP datagrams. ,
( ),
,
, .
UDP , :
, o TimeClient,
host, . TimeServer
, host.
8505 ,
.
: DatagramSocket,
UDP datagrams DatagramPacket,
.

host
TimeServer.
(.. #java TimeClient 127.0.0.1
127.0.0.1 default
localhost). To
InetAddress, getByName(String),
InetAddress :
InetAddress hostAddress = InetAddress.getByName(args[0]);
datagram socket,
. :
DatagramSocket serversoc = new DatagramSocket();
, port
, datagram socket.
, datagram socket streams
/, / ,
.
. DatagramPacket,
4 : buffer,
bytes ( String array ),
, InetAddress ,
. TimeServer, buffer
, .
DatagramPacket packet;

Java

96

byte[] message = new byte[256];


packet = new DatagramPacket(message, 256, hostaddress, port);
, , send(DatagramPacket) datagram
socket :
serversoc.send(packet);

receive(DatagramPacket) datagram socket.
serversoc.receive(packet);
receive() , datagram
port datagram socket. ,
UDP .
,
, .
, getData() DatagramPacket,
bytes , String .
getInetAddress() getPort()
, . ,
, . DatagramSocket().
TimeClient :
// the TimeClient program in Java,
// using UDP Datagrams... We will use UDP port 8505
// Petros Zerfos @1998
import java.io.*;
import java.net.*;
public class TimeClient {
public static void timeclient(DatagramSocket serversoc,
InetAddress hostaddress, int port) {
// Declare a datagram packet...
DatagramPacket packet;
// Declare a byte array to send as a request and
// receive the answer
byte[] message = new byte[256];
try {
// construct the packet with all the information
// needed
packet = new DatagramPacket(message, 256, hostaddress, port);
System.out.println("Sending the request for the time...");
// since the socket is already open, send the
// request
serversoc.send(packet);
// Now, get the reply
System.out.println("Waiting for reply...");
serversoc.receive(packet);
String mesg = new String(packet.getData(), 0);

Java

97

// Print the server's time


System.out.println("Time at server's location " +
packet.getAddress() + ":" + packet.getPort() + is " + mesg );
} catch(Exception exc) {
System.out.println("Error : " + exc.toString());
}
// End of timeclient()

public static void main(String args[]) {


// We use the command line to get the address of the
// time server
InetAddress hostAddress;
int portnum;
// Declare a datagram socket
DatagramSocket serversoc;
// initialize the network
try {
// Get network info
hostAddress = InetAddress.getByName(args[0]);
portnum = 8505;
serversoc = new DatagramSocket();
timeclient(serversoc, hostAddress, portnum);
// Don't forget to release the resource...
// by closing the datagram socket.
if (serversoc != null) serversoc.close();
} catch (UnknownHostException uhe) {
System.out.println("Unknown host : " +
uhe.toString());
} catch (SocketException exc) {
System.out.println("Error : " + exc);
}
}
}

// End of main()
// End of class

try,
.


server client.

. , ,
,
,
.
datagram packet, 8Bytes. UDP datagrams,
, ,
.

Java

98

, ,
datagram socket, :
DatagramSocket port ( . 8505 ), socket,
. :
// The TimeServer for the time service...
// Using UDP Datagrams and port number 8505
// Petros Zerfos @1998
import java.io.*;
import java.net.*;
import java.util.*;

// For the date functions...

public class TimeServer {


public static void main(String args[]) {
// Our datagram socket for I/O
DatagramSocket s = null;
// Our packet for getting the request and sending the
// reply
DatagramPacket packet = null;
// Create a receive buffer
byte[] buf = new byte[256];
// Create the packet to receive the request
packet = new DatagramPacket(buf, buf.length);
// now create a socket to listen in
try {
s = new DatagramSocket(8505);
} catch(Exception e) {
System.out.println("Error : " + e.toString());
}
// Now sit in an infinite loop and reply to the
// queries...
while (true) {
// sit around and wait for a request
try {
s.receive(packet);
} catch (Exception e) {
System.out.println("Error : " + e.toString());
}
// Get the client's info
InetAddress cl = packet.getAddress();
int port = packet.getPort();
System.out.println("Client from " +
cl.getHostAddress() + ":" + port +
" requested the time.");
// Construct the response and sent it back...
String localtime = new Date().toString();
// Convert the localtime string to an array
// of bytes
localtime.getBytes(0, localtime.length(), buf, 0);
// Construct the packet
try {

Java

99

packet = new DatagramPacket(buf, buf.length, cl, port);


// Send it!
s.send(packet);
} catch (Exception e) {
System.out.println("Error : " + e.toString());
} //End of while
System.out.println("Client served...");
}
}
}

// End of main()
// End of TimeServer class.

11.2.7 M DatagramSocket

DatagramSocket()
datagram socket port,
host.
DatagramSocket(int)
datagram socket
, host.
DatagramSocket(int, InetAddress)
datagram socket .
SocketException ,
.

close()
datagram socket.
getLocalAddress()
Gets the local address to which the socket is bound.
, socket .
getLocalPort()
, socket
.
receive(DatagramPacket)
datagram socket.
send(DatagramPacket)
datagram socket.

11.2.8 M DatagramPacket

DatagramPacket(byte[], int)
DatagramPacket,
. buffer
.
DatagramPacket(byte[], int, InetAddress, int)
datagram packet .
bytes, ,

Java
100
.

getAddress()
, datagram ,
.
getData()
, .
getLength()
, .
getPort()
host,
, host, .

You might also like