You are on page 1of 381

-

, 2006

: . -
-
. -
-
:

,
- - , 2006

............................................................................................................... 13
.......................................................................................................................... 14
..................................................... 14
1. - ....... 17
1.1. - ....................................... 17
1.2. ......................................................................................................... 18
1.3. - ........................................... 19
1.4. OO - ............................................. 20
1.5. - .............................................. 22
1.6. .......................................................................................... 22
1.7. - ........................................................................................................ 23
1.8. - ......................................................................................... 26
2. JAVA NETBEANS .............................................................................................. 29
2.1. JAVA?...................................................................................................... 29
2.2. , JAVA ............................................. 30
2.3. AVA? .................................................................................... 31
Java ................................... 31
Java - ......................................................................... 32
Java ..................................................................................... 33
...................................... 33
Java ................................................................................. 34
2.4. NETBEANS IDE .................................................................................................. 35
NetBeans....................................................................................... 36
NetBeans .............................................................................. 37
Source ..................................................................... 39
Forms Wizards ................................. 39
Classpath................................................................................ 40
Java Source NetBeans............... 40
, , .......... 41
- Pay Calculator.................................................... 41
............................................................................ 46
GUI- .......................................................................................... 47
........................................................................................................ 47
............................................................................... 48
Event Handlers ( ) ................................ 50
.......................................................................... 55
2.5. ........................................................................................................... 55
2.6. ..................................................................................... 55
3. - AVA ....................... 57
3.1. .............................................................................................. 57
3.2. ................................................................................. 59
.............................................................................................................. 59

-
......................................................................................................... 60
........................................................................................... 61
3.3. , .............................................................. 66
......................................................................................................... 66
......................................................................... 68
.............................................................................. 70
......................................................... 71
........................................................................................ 71
- ................................................................................... 73
3.4. ........................................................................................................... 76
3.5. ..................................................................................... 77

4. ............................................... 78
4.1. ..................................................................................................... 79
.......................................................................................... 80
................................................................................ 82
() ........................................................... 83
................................................................... 84
....................................................................................... 85
............................................................................. 85
4.2. ........................................................................................................ 86
.................................................................................. 87
.................................................................. 91
.................................... 94
............................................................................. 97
......................................................................................... 98
4.3. , ....................................................................... 98
.................................................................................................................. 98
....................................................................................... 101
............................................................................................................. 101
.................................................................. 102
4.4. ............................................................ 102
While do-while ............................................................................... 103
for ........................................................................................................ 104
if-else .................................................................................................. 105
switch ................................................................................................. 107
....................................................... 109
............................................................................ 109
break .................................................................................................. 110
continue ............................................................................................. 111
return .................................................................................................. 113
4.5. - ........................................................................... 113
................................................... 114
- ...................................................................... 114
............................................................. 115
............................................................ 116
................................................................... 118
4.6. ......................................................................................................... 118
4.7. ................................................................................... 119

5. ....................................................................................... 120
5.1. .............................................................................. 120
new .................................................................... 120
new?............................................................................................... 122
...................................................... 123
5.2. .................................... 123
................................................................................ 123
.................................................................................. 124
............................................................................. 125
5.3. ................................................................................. 126
.............................................................................................. 128
5.4. ................................................................................. 128
5.5. ...................... 130
......................................... 131
..................................................................................... 132
.................... 133
5.6. ........................... 134
........................................................................... 134
................................................................ 136
5.7. ................................. 136
5.8. ......................................................................................................... 138
5. 9. .................................................................................. 139
6. ..................................................................................... 140
6.1. .................................................................................. 140
6.2. ....................................... 140
....................................................... 141
.......................................................................................................... 141
............................................................................. 143
6.3. .................................................................................... 143
.................................................................................. 143
this........................................................................................... 145
............................. 146
o ..................................................... 147
.............................................................................................. 149
6.4. ..................................................................... 150
................................................................................................ 150
6.5. ................................................... 151
................................ 151
................................... 151
6.6. ......................................................................................................... 154
6.7. ................................................................................... 154
7. ................................................................................................................. 155
7.1. , ..................... 155
7.2. - ................................................................................... 159
................................................................................... 159
................................................................ 160

-
....................................................................... 161
7.3. ........................................................................ 162
....... 163
o .......................................................... 164
.................................................................... 166
7.4. ........................................................................................... 167
7.5. ......................................................................................................... 168
7.6. ................................................................................... 168

8. ....................................................................... 169
8.1. ............................................... 169
8.2. .......................................................................................... 171
..................................................................... 172
.............................................................................................. 172
...................................................................................................... 173
........................................................................................................ 173
..................................................................................................... 173
................................................................................................................ 174
........................................................................................... 174
8.3. ................................................ 175
........................................................................................................... 176
........................................................................... 177
......................................................... 177
8.4. <APPLET> ........................................................................ 178
ALIGN ................................................................................................................. 178
HSPACE VSPACE ........................................................................................ 180
CODE CODEBASE ....................................................................................... 181
8.5. JAVA .................................................................................................... 181
8.6. ................................................... 182
8.7. ......................................................................................................... 187
8.8. ................................................................................... 188
9. , .......................................................................... 190
9.1. GRAPHICS ......................................................................................... 190
GRAPHICS.............................................................. 191
9.2. ............................................................................................ 191
................................................................................................................. 192
................................................................................................ 192
........................................................................................................... 195
................................................................................................. 197
.................................................................................................................... 197
...................................................................... 201
.................................................................................... 202
9.3. ........................................................................................... 203
- ........................................................................... 203
............................................................................ 204
............................................................ 205
9.4. ................................................................................................................. 207
Color .......................................................................... 208

........................................... 209
........................................................................... 209
9.5. ......................................................................................................... 210
9.6. ................................................................................... 211
10. , ............................................ 212
10.1. JAVA.................................................................... 212
.................................................................................... 212
...................... 213
: ...................................................................... 213
................................................................................... 214
10.2. : ............................... 216
.............................................................................................. 217
....................................................... 218
10.3. .................................... 220
............................................................ 220
update()................................................................ 220
. 1: ...................................................... 221
.2: ............................................. 223
10.4. ......................................................................................... 229
....................................................................................... 229
......................................................................................... 230
.................................................................................. 234
.............................................................................. 234
10.5. ................................................................. 234
Neko ................................................................................................ 234
1: ..................................................................... 235
2: .............................................. 235
3: ................................................................... 236
4: .................................................................................... 239
10.6. ............................................................................................ 242
10.7. ..................................... 244
................................................. 245
.............................................................. 246
Checkers - ...................................................................... 246
10.8. ....................................................................................................... 249
10.9. ................................................................................. 249
11. ............................................. 251
11.1. ABSTRACT WINDOWING TOOLKIT .................................................................. 251
11.2. ............................................ 252
................................................. 252
............................................................................................................... 254
............................................................................................................ 255
Check box .......................................................................................................... 256
................................................................................................. 259
.............................................................................................. 261
......................................................................................................... 263
................................................................................................ 265

10

-
(sliders and scrolbars) .......................................... 266
.............................................................................................................. 268
11.3. ....................................................................................................... 270
11.4. ................................................................................. 270

12. ............................... 271


12.1. ......................................................... 271
...................................................................... 271
Flow layout......................................................................................................... 272
.............................................................................................. 273
Border ................................................................................................. 275
12.2. .................................................. 276
12.3. ................................................... 277
.................................................................... 277
................................................................... 279
: ......................................................................... 280
: ........................................................................ 281
: ....................................................... 284
: ................... 286
: ............................................................................ 288
........................................................................................ 290
............................................................................................................. 290
12.4. ....................................................................................................... 291
12.5. ................................................................................. 291
13. ................................................... 293
13.1. ........................................................................... 293
.......................................................................................... 293
Handlevent()-....................................................................................... 294
13.2. ................................................... 294
- ............................................... 294
: .................................................................................................. 296
................................................................................. 299
13.3. .............................................. 300
- ............ 300
- ........................................................... 300
: .................................................................................. 301
13.4. ........................................... 305
....................................................... 306
Default ................................................................................................. 307
: .................................. 308
..................... 311
13.5. EVENT-HANDLER......................................................................... 312
13.6. ...................................... 314
............................................................. 315
....................................................... 317
.......................................................................... 318
...................................................................... 318
(scrollbar)............................................................... 318

11

13.7. ....................................................................................................... 318


13.8. ................................................................................. 319
14. E AWT .................................. 320
14.1. , - ..................................................... 320
.......................................................................................... 320
(frames) ................................................................................................. 320
-............................................................................................... 324
................................................................................................ 324
.............................................................. 327
.................................................................. 328
14.2. ............................................................................ 329
................................................................................................................ 329
- (menu, menu bar) ..................................................... 329
(menu items).................................................................... 330
...................................................................... 330
......................................................................................... 331
awt ........................................................ 332
14.3. : RGB HSB ............................................... 333
.................................. 334
-....................................................................... 336
............................................................................. 338
........................................................................ 339
..................................................................................... 341
14.4. ....................................................................................................... 344
14.5. ................................................................................. 344
15. ....................................... 345
15.1. M ............................................................................................ 345
15.2. ..................... 346
?.................................................... 346
(rotection)............................................................. 347
.......................................................................................... 348
(Private) ........................................................................... 348
(Public) ................................................................................... 350
(Protected) ...................................................................... 350
................................................................... 351
....................................................... 352
..................... 352
- .............. 352
cessor ............................................ 353
Accessor ..................................................................... 354
ccessor ...................................................................... 355
15.3. ................................................................. 355
15.4. , ................................. 357
................................................................................ 358
.................................................................... 358
............................................................................. 358
15.5. ..................................................................... 359

12

-
15.6. ....................................................................................................... 361
15.7. ................................................................................. 362

16. ............................................................................... 363


16.1. .......................... 363
16.2. ?........................................................................................... 364
16.3. ............................................................................ 365
............................................................. 365
import............................................................................................. 365
.................................................................................. 367
CLASSPATH ...................... 367
16.4. .............................................................. 368
.............................................................................. 368
................................................... 369
package ................. 369
........................................................................... 369
16.5. ? ...................................................................................... 371
...................................................... 371
..................................... 373
........................................................................................ 374
16.6. ......................................... 374
implements............................................................................. 374
...................................... 376
................................................................... 376
16.7. .......................................... 377
............................................................................................. 377
............................................................................... 378
.................................................................. 379
: ....................................................... 380
16.8. ....................................................................................................... 381
16.9. ................................................................................. 381
K .................................................................................. 383



- ,
. , ,
.
Sun Microsystems.
- .
, ,
,
(reusability).
, (portability).
Microsoft ,
Visual Studio.
, ,
, , , space shuttle.
, , Solaris (
UNIX), UNIX, Linux, Windows Mac
OS. Netscape
Navigator, (
Internet Explorer, Mozilla Firefox, Opera).
Netscape. ,
JDK 1.2 Linux, J2EE,
,
. -
.
.
,
. -
. -
( ), multithreading (
), streams ( ),
, - , .
, ,
, , .
,
;
(mouse=, browser=), (instance=
, layout=, thread=, override=),
(Abstract Window Toolkit).

, , ,
: www.sun.com/java.

.
, ,
, , -
.

14

- (World Wide Web),


,
. (Web-)
. , Web
,
. Web

Web . ,
Netscape ,

.
Java, Web Java .
, ,
, ..
,
Java .
Web , Java;
Web .
Java Java
Java. Java
Java Web
HTML.
Java
. Java
Java .
, Java
, .
. Java
, , ,
Java Web .
, Java
, .


Java ,
.
Java .
Java:

1 -
- , , ,
.

15

2 Java, NetBeans IDE


. Java
.
3
Java.
4 Java
: , ,
.
5 Java:
, ,
, .
Java .
6 . ,
Java ;
Java (Java - Web
).
7 6.
,
, .

Java
:

8
, ,
. HTML Java
.
9 Java
, , .
10 9,
(threads) .
11 ; Java Abstract
Windowing
, , ,
check box-, .
12 , .. (layout)
.
13
Java .
14
Java: ,
.


Java
:

16

15 Java
,

.
16
, ..
.

1. -
, -
(), . -

, .. , ,
,
,
. , ,
.
-
, .
, OO
, OO
, ,
.
( ) ,
- ( ,
--). , -
, --, ''
- ( -),
.
.

1.1. -
- 70-,
;
- - ;
- () ;
- - ,
: ?;
- , ..
;
- , ;
- ,
- ;
- -
.
,
.
;
- , - : , .
- :
1

18

- -:
1

/ 1- , 2- , 3 , 4 /
( , , )

1.2.

PDP-1 MIT,
. Sketchpad Ivan Sutherland
1963; , , .
Simula 67,
, Ole-Johan Dahl Kristen Nygaard
. (

. -
,
.)
,
. ,
( ), ..
. Simula ,
, .
Smalltalk, Xerox PARC,
. Smalltalk
Simula 67, Smalltalk
, , " ",
. ''. (,
Smalltalk ,
" ", Simula,
""). Simula 67 , Lisp o
Pascal.
-
80-, C++,
C.
, o . GUI
OO- Cocoa Mac OS X,
Objective C, -, C Smalltalk.
OO , , event-driven () ( OO).

19

ETH Zrich, Niklaus Wirth


. Modula-2
, , Oberon , .
Smalltalk, C++. -
, . Ada,
BASIC, Lisp, Fortran, Pascal, .
,
. "" -
, ,
. gap,
, - ,
. Bertrand Meyer Eiffel
.
Java ,
C C++,
,
. ,
. Microsoft .NET
, . ,
-,
, Python Ruby. Java,
- Visual Basic .NET C#, Microsoft
.NET .
, -
. design patterns,
, ( UML).

1.3. -
- (OO) :
- -,
() .
-
, .
- (.. -)
, .
- .
, .. ()
. ()
.
- 2 ,
, .
, .. .
- ..
.
. ( ).

20

(
).
- -.
, - -. -
() - (),
.
( ).
, / .
is-a , . is-a .
-
() ; ., "" the Dog
Dog ,
Canidae ( Dog), Carnivora ( Canidae), .
, .
OO,
. , speak (,,Dog,,) speak
(,,Jackal,,); , speak (,,Dog, Chihuahua,,) speak
(,,Dog,Dalmatian,,).
:
, raiseRuckus() ''
(, ,
, .) speak() , raiseRuckus()
. (,
, . .,

.) -
- , .

1.4. OO -
OO ,
. , OO
,
. , ,
. OO ,
.
, .
, , ,
. OO -
- , SIMULA 67,
, CPU ,
.
-
. -
. ,
- ,
- .

21

- ,
, .
- :

Subject-:
Object-: ,

Subject-:
Object-: ,

OO - .

(.e. ). ,
- , .
(), .
OO ,
OO . ,
OO,
-.

, OO.
(reusability) OO. ,
, , 1950,
-. ,
, .
, ,
, ,
OO-.
OO , ,
OO ,
. OO
, .
,
, , .
OO, .
-
. OO
, . ,
design patterns
.
- - "
", .. .

22

1.5. -
- , C++ Java,
, -
, .e. . -
.
. -

, ,
. , , API
,
- , run-time
. - , Eiffel,
,
, Eiffel run-time,
.e. .

1.6.
-
-. .. ,
.. .
.. ,
,
. (
).

( ). ,

.
.
,
:
- :
B

B
B
B

:
,

23

-
run-time .
. C++:
class IME {
public:
// constructors
// destructors
// operators
// modifiers
// selectors
protected:
// member objects
private:
// friends
};

Class name:
- attributes
- methods

- (class utility) -
( ), ++.
() ,
.
-
( ), .
- ()
(). (
).
- () ,
.
(). ,
. .. ,
.

1.7. -
.
,
() .
- 3 :
- ;
-
;
-
.
(
, ),
. - 3 :

24

-
1.
2.

().

.
3.
.
:
-

,
.

-
.
( ).

.
- - ,
.
-.
.. , ..
. .. ,
,
.
-, ,
.
, ,
. - 2
. .
.
.

.
,
. , .

. ,
. -
,
, .
) :
1. ( ),
2. , .
.

3. (, , )
.

25

4. ( .
) .
5.
:
- ,
- ,
- ,
- .
6.
.
7. .
8. .

9. , :
- ,
8.
- ,
- .
10. :
- , ,
- ,
- .
11. :
- is kind of ,
- is analogous to .
- is part of .

12. ( ) ,
. :
- ?
- ?
13. :
- is part of, - has knowledge of, - depends upon .
14.
.
) :

15.
.
16. , .
17. .
18. :
- kind of ,
- ,

26

- ,
- .
19. , , :
- ,
- ,
- .

20. .
21. .
. .
22. .

23. .
.
24. .
25. .
26. .

1.8. -

.
(Smalltalk, Eifel), ,
(C++, Java).
. ,
. . ,
.
. ++ int, float
( ), .
.
:
. :
-
. .
-
default ,
.
:
- ,
.
,
, .
. ++ :
,
.

27


.
.
. Smalltalk . ,

,
defaults.
.
, ( run time).
.
, ( )
. Smalltalk (
), ++
.
. :
-
,
- , . ,
- , ,
- ,
- .
-
, , .,
.

,
.
.
.
,
.. ,
.
3 :
1.
.
2. default
, .. .
.
3. Template step-by-step .
( ),
template , .

28

.

, .
(top-down).
, ,
:

-

( Self). Meta-,
. .. "
". .
- (C++)
,
( Meta-
, C++). 2 : .
- (Java)
,
Meta-. Meta- ,
( 3 - ).
.
2 ( ), -.
- (Smalltalk)
3- ,
, .. Meta- . Meta-
3- , Meta-,
.. "Meta-Class " 5- : ,
, class , Meta-, Meta-Class .

"class class"- , "new",


"class " ( Smalltalk),
( C++). 3
(, , -).
C:
main()
{
int a, b;
...
funk1();
}
funk1()
{
int c, d;
...
}

C++:
class vozilo
{
int a, b, c, d;
funk1()
{...
}
main()
{
vozilo m;
...
}
}

2. Java NetBeans
- Java
- Web
( ) ( ).
. ,
:
Java, .
Java
.
NetBeans IDE -
. NetBeans.
Java ;
Java Java !

2.1. Java?
Java
, Java
.
. Java
, Java ,
.
, Java
C, C++, Visual Basic, Pascal,
HTML, JavaScript.
, Java Sun
Microsystems, UNIX .
C++, Java ,
,
, Java
( )
Java ( ).
Java World Wide Web,
Netscape Navigator Microsoft Internet Explorer
"Java enabled". Java enabled
Java , , .
Web ,
, .
, ,
, , Web
.
Java,
Java ,
. Java

30


, C C++.

2.2. , Java
Java Sun Microsystems 1991

, ,
.
Java , ,
. Java
Internet,

.
Java Sun
( Oak),
HotJava. HotJava,
World Wide Web 1994 ,
Java,
. Java
- Netscape
HotJava .
Java . Java
, Sun, Java
JavaSoft.
Java, , Java API,
, Sun- Java Developer Kit, JDK.
JDK 1.5. Java
1.0.2 JDK,
. JDK,
Java API 1.1, 1996.
,
.
1.1 - .
Java, Java
. Sun- JDK ,
Java .
, Java ,
Sun Java Workshop, NetBeans, Symantec Caf, Microsoft Visual
J++, Natural Intelligence Roaster; .
Java ? .

Sun Java ,
,
, . Sun
Java Web , Java (

NetBeans

31

Java ), Java
. JDK 1.5, .. J2EE
; JDK 1.1.
Sun (framework) Java Beans,
(component objects)
Java, Microsoft ActiveX (OLE) .

. Java Beans .
Java-
, : Solaris, Windows, MacOS.
Java ( )
.
Java
, Java ..
.

2.3. ava?
, Java
,
Java. , Java
,
. .

Java
(,
),
Java ,
.
(World Wide Web),
,
. Java .
, Java
. Java

, .
Java,
, .

Java ,
.
- C ,
.
, Intel , , Intel

32

- .
, ,
,
. 2.1 :
.
Java. Java
: Java (compiler) Java (interpreter). Java
Java ,
, - (bytecodes). - (bytecodes)
,
.
Java , - (bytecode)
(interpreter), - (bytecodes)
Java ( 2.2). Java -
Java Java runtime.

2.1. .

2.2. Java .

- ? , -
Java-enabled ,
- Java . Java ,
Java .
Java ,
Java , . , Java -
( Windows
Java ).

Java -
, (OOP)
,
.
,
,
.

NetBeans

33

Java C++, ..
;
. ,
Java
, .
Java ,
, ,
. Java,
, ava .
Java .

Java
,
ava ,
, , ,
, - . ,

. , ava
.
Java C C++,
Java,
. Java,
. Java.
. ,
,
, Java .
Java
, , HTML.
,
Java . !
Web , Java
.


. JDK -
, . Notepad,
- . ,
(
NetBeans).
2.1. Java .
1: class HelloWorld {
2:
public static void main (String args[]) {
3:
System.out.println("Hello World!");

34
4:

-
} }

,
HelloWorld.java. . Java
(
) .java.
, javac command, ,
Windows (javac Java
compiler). :
C:\> javac HelloWorld.java

HelloWorld.class,
:
C:\> java HelloWorld

, -
Hello World! !
Java Compiler .java files
.class files, .

Java

. Java Web
, .
,
. , Hello
World , ,
Web
.
Hello World , Web .
Hello World ,
. 2.2 .
2.2. Hello World .
1: import java.awt.Graphics;
2:
3: public class HelloWorldApplet extends java.applet.Applet {
4:
5:
public void paint(Graphics g) {
6:
g.drawString("Hello world!", 5, 25);
7:
}
8:}

Hello World ,
.
HelloWorldApplet,
HelloWorldApplet.java.
HelloWorldApplet. class
. Java ; Web

NetBeans

35

- class HTML-
<APPLET> tag. 2.3
HTML .
2.3. HTML .
1:
2:
3:
4:
5:
6:
7:
8:
9:

<HTML>
<HEAD>
<TITLE>Hello to Everyone!</TITLE>
</HEAD><BODY>
<P>My Java applet says:
<APPLET CODE="HelloWorldApplet.class" WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>

<APPLET> ; .
Width/ Height , Code
. HTML
class , .html ( HTML
- HelloWorldApplet.html).

2.4. NetBeans IDE


(IDE) -
, . , IDE-
. Drag-and-drop
(GUI)
,
.
NetBeans IDE open source Java.
-
, - IDE JDK 1.5.
NetBeans IDE ,
Sun Microsystems.
IDE,
, Java .
GUI
, NetBeans IDE.
, , link Java API,
. -
, .
NetBeans Java , Java 2, Enterprise
Edition (J2EE) Java 2, Micro Edition (J2ME), Java 2,
Standard Edition (J2SE) , . - JDK 1.5
NetBeans IDE. JDK 1.5 NetBeans 4.1
.

36

NetBeans
NetBeans IDE open source ,

. NetBeans 4.1
. NetBeans IDE
Java .
J2SE, ,
:
:
- Java, XML, HTML, CSS, JSP, IDL
- - ,
-
- Pop-up Javadoc
-
- ,
-
-
-
- Goto Goto
-
- JumpList
GUI Builder:
- WYSIWYG Test Form
- -
- Swing AWT

- ,
- AWT/Swing layout , drag-and-drop
- GridBagLayout
- (layout)
- , ,
- JavaBeans, ,

- JavaBean -
JavaBean
- beans- Connection
-
:
- , ,

-
- (View)

NetBeans

37

- SQL DDL
SQL DDL
-
- , . Oracle, IBM DB2, Microsoft SQL Server,
PointBase, Sybase, Informix, Cloudscape, MySQL, .
NetBeans IDE (refactoring),
, , ,
. , Ant .

NetBeans
, NetBeans.org
.
NetBeans.org (
) IDE-.
NetBeans upgrade Internet,
. ,
Update Center
.
NetBeans, 2.3.

Quick Start Guide, .. ,
. , Sample Project
IDE. NetBeans ,
IDE .
: projects, nodes, workspaces.
NetBeans, , (source)
meta-; properties ; Ant build
; ,
, , .
-,
-. - .
NetBeans , :
- source
-
- classpaths ,
- Java
- Ant build (build.xml),
IDE- :
.
File New Project. New Project
2.4.

38

2.3. NetBeans

2.4.

, Category General, Web, Enterprise, Samples.


General . General, Java
Application. ,
. IDE-
, . Finish.
Project ,
. .
- Files tab. ,
, Ant properties
:
- nbproject/build-impl.xml - . IDE , .
- build.xml - build-impl.xml.
.
,
JAR ( J2SE ) WAR files ( ), Javadoc.
NetBeans
, . Files tab,
().
, .
.
.
- ,
, , , bean
.
Runtime tab
. Runtime view
. ,
runtime , . (RMI)
. , , ,
.

NetBeans

39

Files tab. source file


, .. Source Editor.
.
.
.
Main.java source , Source Editor- 2.6.

2.5. Tabs

2.6.

,
. ,
. -
Projects Set Main Project.

Source
Source Editor- .
,
. Tools -> Options -> Editing ->
Editor Settings -> Java Editor -> Fonts and Colors.
, , , .
, .
Esc.
Tools -> Options -> Editing -> Editor Settings -> Java Editor -
Code Completion Instant Substitution.
Source Editor-. ,
. Source Editor- .
View.

Forms Wizards
NetBeans IDE , ,
. Projects ,
, bean .
Add , 2.7 2.8.

40

2.7.

2.8.

Classpath
NetBeans classpath .
classpath:
- Projects , , Properties.
- Project Properties dialog box, Libraries .
- Compile tab dialog box-.
- classpath
. :
- . JAR file WAR file ,
source Javadoc ;
- . JAR ,
source Javadoc .
- JAR file - .

Java Source NetBeans


template-
:
- Java Project - template
Java . Java
IDE , , .
- Java Project Ant Script - template
Java .

NetBeans

41

Ant script , ,
.
Java ,
Ant script-.
1.
2.
3.
4.
5.

6.
7.
8.

File -> New Project (Ctrl-Shift-N).


General -> Java Project With Existing Sources.
Next.
Project Name, .
IDE- .
Browse Project Folder
NetBeans .
- NetBeans .
Set as Main Project box, Next.
Source Packages Folder, Add Folder,
source , src .
() Test Packages Folder, Browse
JUnit .
Finish.

Projects Files.

, ,
, NetBeans IDE,
, , ,
GUI .
2.9.
, :
- Form Editor-
- Source Editor-
- Palette, Inspector, Properties
-
-
- (refactor)
-
, ,
drag-and-drop , .
.

- Pay Calculator
File New Project.
Project . , General Categories
Java Application Projects. Next.

42

2.9. Pay calculator

2.10.

,
. Location
Folder .
Create Main Class box. Finished,
.
GUI, Form Editor-
,
. Java API GUI , .. Swing,
: JFrame, JDialog, JApplet. GUI
.
, . GUI
.
,
.
, ( )
GUI-.
.
File menu, .. New File, Java GUI Forms
Categories. File Types . ,
JFrame. JFrame Form, Next.
JFrame SamplesJFrame, Finish.
, Files tab. NetBeans IDE
, SamplesJFrame. SamplesJFrame
Source Editor .
.
, tab-
Design view,
, Source view, . ,
GUI drag-and-drop .
menu bar, 2.11 2.12.

2.11.

NetBeans

43

2.12.
Design view Form Editor 2.11.
GUI .
JFrame .
Palette .
.
,
IDE- ( 2.13):
Palette - JFC/Swing, AWT, Layout , JavaBeans .
Inspector -
, , .
, , , . -
, . .
Properties -
Inspector, Editor, Projects, Files .
properties box .

2.13. NetBeans
Palette, NetBeans ,
.
Properties , . Source Editor, .
. , ,

44

, . ,
.
, JFrame SamplesJFrame. ,
JFrame, . JTabbedPane
Palette, -.
Inspector .
, JPanel Palette, JTabbedPane.
JTabbedPane.
JPanel, jTabbedPane1[JTabbedPane] Inspector .
Shift key JPanel Palette,
. tab. tab-,
.
Inspector,
Properties. ,
Inspector Properties - Properties
. tab, JPanel
Inspector . ., jTabbedPane1 .
, Properties
Tab Title. (...) ,
. Pay Calculator
OK. Design view tab-.
jPanel2 Inspector, Properties,
Tab Title Images.
, Source
, 2.12. Source Editor- ,
. .
, -
, .

2.14.

NetBeans

45

layout manager JPanel .


layout . jPanel1, Set
Layout Manager to GridBagLayout.
Design view,
Properties box JPanel. , 8
, , .
.
.
. layout
. , GridBagLayout .
GridBagLayout , a
.
, jPanel1 Inspector.
Shift
JLabel,
. JTextField. JButton .
,
. .
, .
GridBagLayout Inspector, Customize. Customizer
.
GridBagLayout Customizer,
. Customizer,
, , .
, .
Customizer .
, Close.
.
, Inspector Rename.
OK.
,

. ,
. Properties
, , :

jLabel1

Hours Worked:

jLabel2

Rate per Hour:

jLabel3

Regular Pay:

jLabel4

Overtime Pay:

jLabel5

Total:

,
Inspector.

46

Properties. , ,
, , ..
. ,
default . ,
.
,
.
Inspector, JTextField , ,
Rename. hoursWorked.
JTextField.


, ,
JLabel .
, overtimepayField, regularpayField, and finalTotal.
,
. ,
, .
,
, , .
, .
:
-
- -
-
- .
NetBeans :
- , .
- a
. ,
source .
- , , -
. , source
.
- getter setter , ..
getter setter .
-
.
-
.

NetBeans

47

GUI-

2.15. Test Form

2.16. Build

,
GUI-. NetBeans preview
Test Form ,
2.15. Test Form,
.
,
GridBagLayout Customizer.
,
. Build ( 2.16) IDE-
Clean and Build Main Project. .
,
Source view, Inspector SamplesJFrame
- Run Run File. Run SamplesJFrame.
.
F9.


( ). ,
. , ,
NetBeans. .. breakpoint.
NetBeans IDE, breakpoint-
, .

. ,
. ,
, JUnit . IDE-

. Breakpoint e source
. breakpoint,

. Source Editor- breakpoint-
.

48

breakpoint-, Java breakpoint-


IDE . , breakpoint , IDE-
,
. breakpoint,
Source Editor- Ctrl-F8.
breakpoint-, :
Method () -
.
Exception (, ) -
; source ,
.
Variable () -
( .,
- ), .
Thread () -
, , .
Class () -
, , .
,
, breakpoint-
. breakpoint-
, .


, GUI .
. ,
.
, ,
, ( ,
). Inspector:
, , .
Design view, Inspector, JFrame.
Properties
. , pop-up box- Pay Calculator. -
. , Inspector, JFrame,
Add From Palette, Swing JMenuBar.
Inspector box, JMenuBar, Add
JMenu. JMenu FileMenu.
FileMenu Add JMenuItem. OpenMenu.
. ,
JMenuBar, Add JMenu, HelpMenu.
Design view, . Test Form
.
GUI- Images ( 2.17),
.

NetBeans

49

Swing , . , , , - ..
. Icon. Swing
Icon : ImageIcon,
GIF, JPEG, PNG. ,
- :
ImageIcon icon = createImageIcon("images/middle.gif","The name of
an image.");
label1 = new JLabel("Image and Text", icon, JLabel.CENTER);
...
label2 = new JLabel(icon);

NetBeans ,
Palette Properties. .
Images, JLabel,
.
Images tab Design view
JPanel Inspector. layout = BorderLayout. Palette,
JLabel, layout-.
. JLabel ,
Direction .
Properties. preferredSize 70, 14,
.
, BorderLayout.
, - .
.
drop-down Select Mode: Icon Editor.
Image Source Types ( 2.18). ,
URL URL Name text:
http://java.sun.com/developer/onlineTraining/new2java/newjava.gif
File Name
text. preview . OK.
Source view ,
, :
jLabel6.setIcon(new javax.swing.JLabel() {
public javax.swing.Icon getIcon() {
try {
return new javax.swing.ImageIcon(
new java.net.URL(
"http://java.sun.com/developer/onlineTraining/new2java/newjava.gif")
);
} catch (java.net.MalformedURLException e) {
}
return null;
}
}.getIcon());

50

jLabel6.setToolTipText("This is a label with an image");

GUI- , .
. Design view
Pay Calculator.

2.17.

2.18. Icon Property

Event Handlers ( )
Java
. ,
, , .
,
, .
. IDE,
:
1.
2.
3.


,
,
.

2.19.
GUI ,
-
.
. -
ActionListener .
, - listener.

NetBeans

51

NetBeans ,
.
, listener .
Design view , .
Events, Action -> actionPerformed(computePayActionPerformed). Source
, ,
listener:
computePay.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
computePayActionPerformed(evt);
}
});

NetBeans :
private void computePayActionPerformed(java.awt.event.ActionEvent
evt) {
// TODO add your handling code here:

,
. , :
-
-
,
-
-
,
String. ,
int double. ,
. ,
( );
. , (
).
: Integer, Double, NumberFormat.
. ,
( ., int, float,
double). - ,
, , ,
String . String
, .
String .
.
. ,
, .
.
,
, :

52

byte - Byte
short - Short
int - Integer
long - Long
char - Character
float - Float
double - Double
boolean - Boolean

, Character,
a String .
, String
:
String myString = "12345";
int myInt = Integer.parseInt(myString);

String myString int - myInt.


.
.
Boolean ,
:
byte - Byte.parseByte(aString)
short - Short.parseShort(aString)
int - Integer.parseInt(aString)
long - Long.parseLong(aString)
float - Float.parseFloat(aString)
double - Double.parseDouble(aString)
boolean - Boolean.valueOf(aString).booleanValue();

: Character ,
charAt:
// The variable e is the character e in the string Hello
String hello = "Hello";
char e = hello.charAt(1);

String ,
NumberFormatException. runtime ,
try-catch . NumberFormat
.
. ,
public class PrintNum {
public static void main(String args[]) {
double amount = 400000.00;
System.out.println("He paid " + amount
+ " for the house.");
}}

NetBeans

53

He paid 400000.0 for the house.


NumberFormat java.text .
,
( ), .
3 :
- getInstance getNumberInstance , . 600,000.
- getCurrencyInstance , . $600,000.00.
- getPercentInstance , . 56%.
, NumberFormat
:
NumberFormat nf = NumberFormat.getCurrencyInstance();

, locale
:
NumberFormat nf =
NumberFormat.getCurrencyInstance(Locale.US);

:
He paid $400,000.00 for the house.

,
:
import java.text.NumberFormat;
import java.util.Locale;

, .
if-, , . .
computePayActionPerformed()-
:
//Gets how many hours worked from the text field, and then parses
it to type int.
int hw = Integer.parseInt(hoursWorked.getText());
//Gets the pay rate entered in the text field, and parses it to
type double.
double rateEntered = Double.parseDouble(rate.getText());
//Creates two variables of type double for later use.
double regularPay = 0;
double overTimePay = 0;
//Simple if statement for calculations
if (hw > 40) {
regularPay = 40 * rateEntered;
overTimePay = (hw - 40) * 1.5 * rateEntered;
} else {
regularPay = hw * rateEntered;

54

overTimePay = 0.0;
}
//Creates a variable of both types of pay combined.
double total = regularPay + overTimePay;
//Creates variables for number formatting
NumberFormat nfRegular =
NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat nfOverTime =
NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat nfTotal =
NumberFormat.getCurrencyInstance(Locale.US);
//Writes the totals in the correct format to the labels
regularpayField.setText(" " + nfRegular.format(regularPay));
overtimepayField.setText(" " + nfOverTime.format(overTimePay));
finalTotal.setText(" " + nfTotal.format(total));
}

.
, . 33.00, .
2.20.
, .
,
. Inspector Project,
ExitItem, , Events, Action -> actionPerformed.
Source Editor, :
// TODO add your handling code here:
System.exit(1);

Clean and Build Project, ,


Exit.
.
,
Inspector -. , Delete.
. yes, . Build and
Clean, . OpenItem
. .

2.20.

NetBeans

55


,
.
Javadoc ,
NetBeans
. Files tab, SamplesJFrame. Build
Menu Generate Javadoc for JavaApplication1 (
). Javadoc .
browser HTML.
SamplesJFrame, .
, ,
Javadoc .

2.5.
Java
. Java , C/C++,
. , Java
World Wide Web Java.
Java Web .
, ,
Web . Java
, -
. ,
Java
Java . Java
.
NetBeans
IDE. NetBeans IDE .
,
Java , . J2EE J2ME.
, NetBeans , NetBeans , . Sun Java Studio Creator Sun Java
Studio Enterprise. IDE- ,
IDE ,
.

2.6.
:
:

HTML, .
Java ?
,
Java HTML. , Java

Java.

56

:
:

JavaScript Java?
.
Java JavaScript
. Java
; . JavaScript
Netscape Java;
. JavaScript HTML.
, Java
Java, Netscape .
?
, ?
Java Sun
Java
:
Java

Java

Java
.
, Java, , Java
Java
( ).
,
.
8," ".
Java
?
!
Java Java :
http://java.sun.com/
Java, JDK,
2, NetBeans,
.

:
:

3. - ava
- (OOP)
,
-
. ,
.
.
- Java
.

.
:
.

.
.

- ,
()
..
.

3.1.
- ,
.. .
-
. -

, .
- ,
.
.
. ,
( , ,
). -
,
. ,
(,
, , ),
( 3.1).

58

3.1.


.
.
() ,
. , ?
. , ()
. ,
.
.


.
.
Java
.
.
( , , ) . (
?
? ?). ,
() -
,
,
. ,


.

- ava

59

,
(), struct typedef.
,
.
Java ,
. , ()
. , Java ,

. , : Java
( )
,
( , , ,
.), . ,
Java- ,
Java
. Java
.



. Java-
Java.

3.2.
Java :
.
(Motorcycle). ,
Java .


, .
(Motorcycle).
:

(Color): , , ,
(Style): , ,
(Make): , ,

60

;
, ,
.
.

.
,
.


.
,
.


.
, .
,
, .
,
.
,
.


;
, .
. ,
(Motorcycle):

- , .. Java
.
,
. Java (
++).

- ava

61



.
,
.

, .
, .
( )
;
. .


, . ,
Motorcycle, ..
Java. Java
(Motorcycle)
.

.
;
. ,
.
? . Java
( ):
class Motorcycle {
}

! . , ,
Java .
- .
:
String make;
String color;
boolean engineState = false;

, : , (make)
(color), (String objects) (string - ,
; String, S,
). ,
(engineState), (boolean variable)

62

; false , true
. boolean b.


boolean ( true or false )


boolean Java true
or false. , booleans .

.
.
, - -
.
:
void startEngine() {
if (engineState == true)
System.out.println("The engine is already on.");
else {
engineState = true;
System.out.println("The engine is now on.");
}
}

startEngine() (
engineState == true) , .
, true ( )
. , startEngine() ,
void . (
;
6 - Java).

, , ,
(
"The startEngine() method").
, .
,
Motorcycle.java (
Java ).
3.1 .
3.1. Motorcycle.java
1: class Motorcycle {
2:
3: String make;
4: String color;

- ava

63

5: boolean engineState = false;


6:
7: void startEngine() {
8:
if (engineState == true)
9:
System.out.println("The engine is already on.");
10:
else {
11:
engineState = true;
12:
System.out.println("The engine is now on.");
13:
}
14: }
15: }

(indentation) Java .
, .
,
. Java
. .
,
startEngine() (.. 14 15). showAtts()

. :
void showAtts() {
System.out.println("This motorcycle is a "
+ color + " " + make);
if (engineState == true)
System.out.println("The engine is on.");
else System.out.println("The engine is off.");
}

showAtts() :
, .
Java .
:


Java . , :
( NetBeans) -
Java ,
javac .
> javac Motorcycle.java
Java, . ?
Java , Java
main(). main()
, Java :

64

In class Motorcycle: void main(String argv[]) is not defined


Exception in thread "main": java.lang.UnknownError

-
, Java
, .. main() .
, . 3.2 main()
.
Motorcycle.java (}),
startEngine() showAtts().
3.2. main() Motorcycle.java.
1: public static void main (String args[]) {
2:
Motorcycle m = new Motorcycle();
3:
m.make = "Yamaha RZ350";
4:
m.color = "yellow";
5:
System.out.println("Calling showAtts...");
6:
m.showAtts();
7:
System.out.println("--------");
8:
System.out.println("Starting engine...");
9:
m.startEngine();
10:
System.out.println("--------");
11:
System.out.println("Calling showAtts...");
12:
m.showAtts();
13:
System.out.println("--------");
14:
System.out.println("Starting engine...");
15:
m.startEngine();
16:}

main()- ,
.
(output):
:
Calling showAtts...
This motorcycle is a yellow Yamaha RZ350
The engine is off.
-------Starting engine...
The engine is now on.
-------Calling showAtts...
This motorcycle is a yellow Yamaha RZ350
The engine is on.
-------Starting engine...
The engine is already on.

- ava

65

main()- ,
, (
).
main() . 2,
Motorcycle m = new Motorcycle();
m.
Java ;
. 3 4
: Yamaha RZ350
( 1980-) . 5 6
showAtts(), . (,
6 ; 5 ).
-

. 7 .
9 startEngine() ,
. 11
. , .
15 , .
, :
.
3.3 ,
:
3.3. Motorcycle.java.
1: class Motorcycle {
2:
3:
String make;
4:
String color;
5:
boolean engineState;
6:
7:
void startEngine() {
8:
if (engineState == true)
9:
System.out.println("The engine is already on.");
10:
else {
11:
engineState = true;
12:
System.out.println("The engine is now on.");
13:
}
14:
}
15:
16:
void showAtts() {
17:
System.out.println("This motorcycle is a "
18:
+ color + " " + make);
19:
if (engineState == true)
20:
System.out.println("The engine is on.");
21:
else System.out.println("The engine is off.");
22:
}
23:

66
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40: }

-
public static void main (String args[]) {
Motorcycle m = new Motorcycle();
m.make = "Yamaha RZ350";
m.color = "yellow";
System.out.println("Calling showAtts...");
m.showAtts();
System.out.println("------");
System.out.println("Starting engine...");
m.startEngine();
System.out.println("------");
System.out.println("Calling showAtts...");
m.showAtts();
System.out.println("------");
System.out.println("Starting engine...");
m.startEngine();
}

3.3. ,
, , ,
Java ,
. ,
. Java
,
.

-

Java .
;

. , - ,

- ( 3.2).
( )
- ( ).

.

- ava

67

3.2
- .. ,
.
,
.
.


-
.
( ) -
( . -
.
Java Object;
. Object ;
Java.

. ,

.
Java
, .
, .
,
.
( ),
.
,
(subclassing).
,
. -

68

;
.



.

? Object,
Java . ,
, Java
Object.
, Object.


,
,
. ,
Java , , :

,
,
. -
.
( )
- -
,
,
.

Java
.
Java .
- .
, .

, .
.
,
, , .,
,
.
.
Object, Java .

- ava

69

. ,
.

, . ? :
?
, ,
,
, ,
.
- - . 3.3
.

3.3.
.
: , , .
-
, ( 3.4).

3.4.
, - ,
. ,
,
, .

70

? ,
.
.

; -
.


?
?
, -

. ,

.
:
,
. , Java
.
,
, ( 3.5).

3.5.
-
(, ) .
, (
) .
, -
, .
(overriding a method).
7 - .

- ava

71


-
(, ) .
( 3.6).

3.6.


Java, ,
. Java
( -).
- , ++,

. .
, ..
,
. Java
, .


: .
(topics)
. 16,
, .
Java
.

, -

72

. Java
, ..

.
( ), .
Java (
), .
,
.
, (
),
, .


, ,

,
.
.
, , !
Java . Java

.

. ,
. ,
:

JDK java.
Java Java
. Java
, input output , ,
window toolkit .
( Sun Netscape
), .
default, Java java.lang
( Java ).
,
, .
,
, (.).
, (Color class), awt (awt
Abstract Windowing Toolkit). wt , , Java
. ,
java.awt.Color.

- ava

73

-
, -
. , ,
.
-,
Java, . -
Applet ( java.applet). -
Applet, window toolkit layout
,
, keypresses
mouse clicks. , Hello World
, Hello string- .
, .
:
public class HelloAgainApplet extends java.applet.Applet {
}

, HelloAgainApplet.
extends java.applet.Applet - Applet . Applet java.applet,

.
public. Public
Java .
public, Java
, public. ( public
).
;
-.
, ,
. ,
Font:
Font f = new Font("TimesRoman", Font.BOLD, 36);

f Font, java.awt.
Font Times Roman font, boldface, 36 points.
Hello World, :
12-point Times Roman. Font,
.
, .
.
,
,
. , .. ,
,

74

.
paint(), .
paint() - .
paint(), . paint():
public void paint(Graphics g) {
g.setFont(f);
g.setColor(Color.red);
g.drawString("Hello again!", 5, 40);
}

paint(). ,
public, . Paint()-
public - public.
public,
public , error .
, paint() :
Graphics. Graphics -
, .
Graphics ,
. paint()-, :


f.

(Color) .
- "Hello Again!" ,
x y - 5 25. .

, .
:
public class HelloAgainApplet extends java.applet.Applet {
Font f = new Font("TimesRoman",Font.BOLD,36);
public void paint(Graphics g) {
g.setFont(f);
g.setColor(Color.red);
g.drawString("Hello again!", 5, 40);
}
}

,
. , (
: HelloAgainApplet.java) .
:
HelloAgainApplet.java:7: Class Graphics not found.

- ava

75

?
, Graphics Font,
(by default).
Java java.lang.
Applet
(java.applet.Applet). ,
.
.
:
,
. ,
,

.
, . :
Graphics, Font Color. java.awt.
. ,
:
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;

public
(*) . ,
awt, :
import java.awt.*;
, , HelloAgainApplet.java
.class . 3.4
.
3.4. HelloAgainApplet.java.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
public class HelloAgainApplet extends java.applet.Applet {
Font f = new Font("TimesRoman",Font.BOLD,36);
public void paint(Graphics g) {
g.setFont(f);
g.setColor(Color.red);
g.drawString("Hello again!", 5, 40);
}
}

76

, HTML <APPLET>
. HTML :
<HTML>
<HEAD>
<TITLE>Another Applet</TITLE>
</HEAD>
<BODY>
<P>My second Java applet says:
<BR><APPLET CODE="HelloAgainApplet.class" WIDTH=200 HEIGHT=50>
</APPLET>
</BODY>
</HTML>

HTML , Java .class file


HTML . HelloAgainApplet.html
Java Java applet viewer. 3.7
("Hello Again!" ).

3.7. HelloAgain.

3.4.
- ,
.
, ,
Java .
- , .
- .
,
:
class: ,
.
.
class method: ,
.
class variable:
.

- ava

77

instance: ; .
instance method: ,

. .
instance variable:
.
interface: ,
.
object: .
,
.
package: . java.lang
.
subclass: ,
. , .
superclass: , .

3.5.
:

:
:

.
,
?
-
(++ - member functions).
-
,
.

- , Java
.
,
.
Java .
,
, . ,
.
(, ? ,
). , ,
,
.
.
.

4.
Java
Java ,
. ,
Java. ,
Java . ,
Java
Java main().
.
:
, ,
,
.
,

.
, .

if-else while, .. ,
.
(arrays) - .


Java C++, C.
.
C C++ ,
( ),
Java.
BasicDemo , 10
:
public class BasicsDemo {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
System.out.println("Sum = " + sum);
}
}

:
Sum = 55

79

,
Java, ,
.
,
Java, ,
.

4.1.
.
: .
,
.
Unicode
.
.
, .
,
:
type name

,
, . ,
, () .

, ..
.
MaxVariablesDemo :
4.1. MaxVariablesDemo
1: public class MaxVariablesDemo {
2:
public static void main(String args[]) {
3:
4:
// integers
5:
byte largestByte = Byte.MAX_VALUE;
6:
short largestShort = Short.MAX_VALUE;
7:
int largestInteger = Integer.MAX_VALUE;
8:
long largestLong = Long.MAX_VALUE;
9:
10:
// real numbers
11:
float largestFloat = Float.MAX_VALUE;
12:
double largestDouble = Double.MAX_VALUE;
13:
14:
// other primitive types
15:
char aChar = 'S';
16:
boolean aBoolean = true;
17:

80

18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:

// display them all


System.out.println("The largest byte value is "
+ largestByte);
System.out.println("The largest short value is "
+ largestShort);
System.out.println("The largest integer value is "
+ largestInteger);
System.out.println("The largest long value is "
+ largestLong);
System.out.println("The largest float value is "
+ largestFloat);
System.out.println("The largest double value is "
+ largestDouble);
if (Character.isUpperCase(aChar)) {
System.out.println("The character " + aChar
+ " is upper case.");
} else {
System.out.println("The character " + aChar
+ " is lower case.");
}
System.out.println("The value of aBoolean is " +
aBoolean);

41:
42: }

:
The
The
The
The
The
The
The
The

largest byte value is 127


largest short value is 32767
largest integer value is 2147483647
largest long value is 9223372036854775807
largest float value is 3.40282e+38
largest double value is 1.79769e+308
character S is upper case.
value of aBoolean is true


, , , ,
. MaxVariablesDemo
:
MAX_VALUE if-else . MAX_VALUE
Java

. if-else .


.

. , MaxVariablesDemo , int

81

largestInteger largestInteger integer (int).


(
).
, , , .
Java :
.
: , boolean ()
. , integer 32 ,
, char 16
Unicode .
value

variableName

4.1. .
4.1
Java , ,
. MaxVariablesDemo
.
4.1. .

byte

Integer byte-

short

integer

int

Integer

long

integer

float





Unicode

(true
false)

8-
integer
16-
integer
32-
integer
64-
integer
32- IEEE 754

64- IEEE 754

16- Unicode

double

char
boolean

8 /1 (8
, 1 )


,

. , Java

. .

82


. , 4 integer ,
:
int anInt = 4;

4 integer . 4.2
.
4.2. .

178
8864L
37.266
37.266D
87.363F
26.77e3
' c'
true
false


int
long
double
double
float
double
char
boolean
boolean

, integer.
integer L l .
L 1.
double. float
f F . Unicode
. boolean true false.
, .
,
( ) ,
( 4.2).
. Java
.
.

4.2. ( ) .



. ,
largestByte , MaxVariablesDemo largestByte.
largestByte,

83

. ,

.
Java
:

. ,
Unicode .
, boolean (true false)
null.
.

. ,
, .


,
.
, ,
, : isVisible. (_)
,
(
).

()
,
. ,

. ,
-
.
.

.
- . ,
. -
. ,
.
.
,
. MaxVariablesDemo,
main - .

84

main
(}).

4.3. : -,
, .

.
.
, ,
. { },
catch. :
if (...) {
int i = 17;
...
}
System.out.println("The value of i = " + i);

// error

,
i . i { }. i
}. ,
if println
if.


-
.
, .
MaxVariablesDemo
.
, :
// integers
byte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;

85

int largestInteger = Integer.MAX_VALUE;


long largestLong = Long.MAX_VALUE;
// real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;
// other primitive types
char aChar = 'S';
boolean aBoolean = true;


. .



final , .
.
, final
:
final int aFinalVar = 0;


.
aFinalVar .
. :
final int blankfinal;
. . .
blankfinal = 0;

,
, . ,
, ,
blankfinal
.



. : final double AVOGADRO = 6.023e23;


, .
Java :
. .
. ,
.

86


,
. :
-, ,
.

, (=).

.

4.2.
, .
. ,
++ 1.
. , =
. ,
.
Java ?:,
if-else .
.
:
operator op

//prefix notation

:
op operator

//postfix notation

,
:
op1 operator op2

//infix notation

;
:
op1 ? op2 : op3

//infix notation

, .
. ,
,
, .
,
: , .
:

87

.
.
.
.
.


Java
. :
+ (), - (), * (), / () % (). 4.3
Java.
4.3. .

op1 + op2

*
/
%

op1
op1
op1
op1

*
/
%

op2
op2
op2
op2

op1 op2;

op2 op1
op1 op2
op1 op2
op1 op2

ArithmeticDemo,
( )
. +
. :
4.2. ArithmeticDemo.
1: public class ArithmeticDemo {
2:
public static void main(String[] args) {
3:
4:
//a few numbers
5:
int i = 37;
6:
int j = 42;
7:
double x = 27.475;
8:
double y = 7.22;
9:
System.out.println("Variable values...");
10:
System.out.println("
i = " + i);
11:
System.out.println("
j = " + j);
12:
System.out.println("
x = " + x);
13:
System.out.println("
y = " + y);
14:
15:
//adding numbers
16:
System.out.println("Adding...");
17:
System.out.println("
i + j = " + (i + j));
18:
System.out.println("
x + y = " + (x + y));
19:
20:
//subtracting numbers

88

21:
System.out.println("Subtracting...");
22:
System.out.println("
i - j = " + (i - j));
23:
System.out.println("
x - y = " + (x - y));
24:
25:
//multiplying numbers
26:
System.out.println("Multiplying...");
27:
System.out.println("
i * j = " + (i * j));
28:
System.out.println("
x * y = " + (x * y));
29:
30:
//dividing numbers
31:
System.out.println("Dividing...");
32:
System.out.println("
i / j = " + (i / j));
33:
System.out.println("
x / y = " + (x / y));
34:
35: //computing the remainder resulting from dividing numbers
36:
System.out.println("Computing the remainder...");
37:
System.out.println("
i % j = " + (i % j));
38:
System.out.println("
x % y = " + (x % y));
39:
40:
//mixing types
41:
System.out.println("Mixing types...");
42:
System.out.println("
j + y = " + (j + y));
43:
System.out.println("
i * x = " + (i * x));
44:
}
45: }

:
Variable values...
i = 37
j = 42
x = 27.475
y = 7.22
Adding...
i + j = 79
x + y = 34.695
Subtracting...
i - j = -5
x - y = 20.255
Multiplying...
i * j = 1554
x * y = 198.37
Dividing...
i / j = 0
x / y = 3.8054
Computing the remainder...
i % j = 37
x % y = 5.815
Mixing types...
j + y = 49.22
i * x = 1016.58

89


, .

. 4.4
, .
.
4.4. .

long
int
double
float


float double (integer
); long.
float double (integer
); long.
double.
float;
double.

+
:
4.5. .

+op

-op

op int byte, short


char.
op

: ++
1 -- 1. ++ --
. ++op/--op
,
. op++/op--,
, .
, SortDemo ++ --:
public class SortDemo {
public static void main(String[] args) {
int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,
2000, 8, 622, 127 };
for (int i = arrayOfInts.length; --i >= 0; ) {
for (int j = 0; j < i; j++) {
if (arrayOfInts[j] > arrayOfInts[j+1]) {
int temp = arrayOfInts[j];
arrayOfInts[j] = arrayOfInts[j+1];
arrayOfInts[j+1] = temp;
}

90

-
}
}
for (int i = 0; i < arrayOfInts.length; i++) {
System.out.print(arrayOfInts[i] + " ");
}
System.out.println();
}

(
) .
arrayOfInts,
.
arrayfInts.length .
: arrayfInts.
length[index], index
. 0, 1.

:
3

12

32

87

127

589

622 1076

2000

,
4.7, 4.10 4.11,
, 4.5. .
SortDemo ,
.
:
for (int i = arrayOfInts.length; --i >= 0; ) {
...
}
for .
, for-
--i 0.
--
i 0.
--,
i -1, , i
, .

++.
,
.

91

,
.

4.6:
4.6. .

++

op++

++

++op

--

op--

--

--op

op 1.
op .
op 1.
op .
op 1.
op .
op 1.
op .



. , != true
. 4.7 :
4.7. .

>

op1 > op2

>=

op1 >= op2

<

op1 < op2

<=

op1 <= op2

==
!=

op1 == op2
op1 != op2

true op1 op2.


true op1
op2.
true op1 op2.
true op1
op2.
true op1 op2.
true op1 op2.

RelationalDemo
.
4.3. RelationalDemo.
1: public class RelationalDemo {
2:
public static void main(String[] args) {
3:
4:
//a few numbers
5:
int i = 37;
6:
int j = 42;
7:
int k = 42;
8:
System.out.println("Variable values...");
9:
System.out.println("
i = " + i);

92

10: System.out.println("
j = " + j);
11: System.out.println("
k = " + k);
12:
13:
//greater than
14: System.out.println("Greater than...");
15: System.out.println("
i > j is " + (i > j));
16: System.out.println("
j > i is " + (j > i));
17: System.out.println("
k > j is " + (k > j));
18:
19:
//greater than or equal to
20: System.out.println("Greater than or equal to...");
21: System.out.println("
i >= j is " + (i >= j));
22: System.out.println("
j >= i is " + (j >= i));
23: System.out.println("
k >= j is " + (k >= j));
24:
25:
//less than
26: System.out.println("Less than...");
27: System.out.println("
i < j is " + (i < j));
28: System.out.println("
j < i is " + (j < i));
29: System.out.println("
k < j is " + (k < j));
30:
31:
//less than or equal to
32: System.out.println("Less than or equal to...");
33: System.out.println("
i <= j is " + (i <= j));
34: System.out.println("
j <= i is " + (j <= i));
35: System.out.println("
k <= j is " + (k <= j));
36:
37:
//equal to
38: System.out.println("Equal to...");
39: System.out.println("
i == j is " + (i == j));
40: System.out.println("
k == j is " + (k == j));
41:
//not equal to
42: System.out.println("Not equal to...");
43: System.out.println("
i != j is " + (i != j));
44: System.out.println("
k != j is " + (k != j));
45:
46:
}
47: }

:
Variable values...
i = 37
j = 42
k = 42
Greater than...
i > j is false
j > i is true
k > j is false
Greater than or equal to...
i >= j is false
j >= i is true
k >= j is true
Less than...
i < j is true

//false
//true
//false

//false
//true
//true

//true
//false
//false

//true
//false
//true

//false
//true
//true
//false

93

j < i is false
k < j is false
Less than or equal to...
i <= j is true
j <= i is false
k <= j is true
Equal to...
i == j is false
k == j is true
Not equal to...
i != j is true
k != j is false


. Java
- -
4.8.
4.8. .

&&
||
!

op1 && op2


op1 || op2
!op

&

op1 & op2

op1 | op2

op1 ^ op2

true op1 op2 true.


true op1 op2 true.
true op1 false.
true op1 op2 boolean
true.
true op1 op2 boolean
op1 op2 true.
true, op1 op2 ..
.

&& (AND) .
&&
true.
.
0 NUM_ENTRIES,
.
0 <= index && index < NUM_ENTRIES

,
. :
(numChars < LIMIT) && (...)
&& true true.
numChars LIMIT, && false,
&&

. , .

94

, stream,
.
boolean, &
&&. , & true
true. , boolean, |
||. |
true true. , & |
.


-
. 4.9
,
Java.
4.9. .

<<

op1 << op2

>>

op1 >> op2

>>>

op1>>> op2

op1
op2;
.
op1
op2; ()
.
op1
op2;
.


.
. ,
13 :
13 >> 1;

13 1101.
110 .. 6. 0
. 4.10 Java
.
, & AND
. AND
1 1.
4.11.

95

4.10. .

&

op1 & op2

op1 | op2

^
~

op1 ^ op2
~op2

AND ;
AND boolean.
OR
; OR
boolean.
OR (XOR).
.

4.11. AND (op1 & op2).


op1
0
0
1
1

op2
0
1
0
1

0
0
0
1

AND : 13 & 12.


12 12 1100,
13 1101.
1101
& 1100

1100

// 13
// 12
// 12

1, AND 1;
0.
, | or , ^
or (XOR) . or
1, 1. 4.12
or :
4.12. OR (op1 | op2).

op1
0
0
1
1


op2
0
1
0
1

0
1
1
1

or , 1;
0. 4.13 or
:

96

-
4.13. EX_OR (op1 | op2).

op1
0
0
1
1


op2
0
1
0
1

0
1
1
0

, (~),
: 1, 0; 0,
1. , ~1011 (11) 0100 (4).
,
boolean . , ,
boolean
: , .
boolean , , flags, .
flags .
, , - .
static
static
static
static

final
final
final
final

int
int
int
int

VISIBLE = 1;
DRAGGABLE = 2;
SELECTABLE = 4;
EDITABLE = 8;

int flags = 0;

,
:
flags = flags | VISIBLE;

, :
if ((flags & VISIBLE) == VISIBLE) {
...
}

4.4. :
1: public class BitwiseDemo {
2:
3:
static final int VISIBLE = 1;
4:
static final int DRAGGABLE = 2;
5:
static final int SELECTABLE = 4;
6:
static final int EDITABLE = 8;
7:
8:
public static void main(String[] args) {
9:
int flags = 0;
10:


11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26: }

97

flags = flags | VISIBLE;


flags = flags | DRAGGABLE;
if ((flags & VISIBLE) == VISIBLE) {
if ((flags & DRAGGABLE) == DRAGGABLE) {
System.out.println("Flags are Visible and Draggable.");
}
}
flags = flags | EDITABLE;
if ((flags & EDITABLE) == EDITABLE) {
System.out.println("Flags are now also Editable.");
}
}

:
Flags are Visible and Draggable.
Flags are now also Editable.



=. MaxVariablesDemo =
:
// integers
byte largestByte =
short largestShort
int largestInteger
long largestLong =

Byte.MAX_VALUE;
= Short.MAX_VALUE;
= Integer.MAX_VALUE;
Long.MAX_VALUE;

// real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;
// other primitive types
char aChar = 'S';
boolean aBoolean = true;

Java ,
,
, .
i = i + 2;

+=
:
i += 2;

98

. 4.14
:
4.14. .

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

op1
op1
op1
op1
op1
op1
op1
op1
op1
op1
op1

op1
op1
op1
op1
op1
op1
op1
op1
op1
op1
op1

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

=
=
=
=
=
=
=
=
=
=
=

op1 + op2
op1 - op2
op1 * op2
op1 / op2
op1 % op2
op1 & op2
op1 | op2
op1 ^ op2
op1 << op2
op1 >> op2
op1>>> op2


Java
4.15:
4.15. O .

?:
[]
.
(params )
(type )
new
instanceof

if-else.
, .
.
.
.
.
.

4.3. ,
,
, .
, -
.
. { },
.

. ,
,
.

99

: ,
.. .
: ,
( )
.
, ,
. MaxVariablesDemo

:
// other primitive types
char aChar = 'S';
boolean aBoolean = true;
// display them all
System.out.println("The largest byte value is " + largestByte);
...
if (Character.isUpperCase(aChar)) {
...
}

. 4.16:
4.16. MaxVariablesDemo .

aChar = 'S'
"The largest byte
value is " +
largestByte
Character.isUpper
Case(aChar)


S
aChar.
The
largest byte value
is largestByte

string.

isUpperCase.


aChar
(S).

The largest
value is 127.

string:
byte


: true.

,
. aChar = S ,
.
, boolean , string
.
Java ,
,
. :
x * y * z

100

, ,
; ,
.
. , ,
:
x + y / 100

//ambiguous


- ( ). :
(x + y) / 100

//unambiguous, recommended


, .
. ,
.
:
x + y / 100
x + (y / 100)

//unambigous, recommended

,
.
.
4.17 Java.
.
, .
.
:
4.17. .



,

AND
OR
OR
AND
OR
if-else

[] . (params ) expr ++ expr -++expr --expr +expr -expr ~ !


new (type )expr
* / %
+ > >>>
<> <= >= instanceof
== !=
&
^
|
&&
||
?:
= += -= *= /= %= &= ^= |= <<= >>=

101

,
. ,
, .
.


, ,
. .
(;):

.
++ --.
.
.

:
aValue = 8933.234;
aValue++;
System.out.println(aValue);
Integer integerObject = new
statement

//assignment statement
//increment statement
//method call statement
Integer(4);
//object creation

, .
:
double aValue = 8933.234;

// declaration statement


. for- if-
.

,
,
. MaxVariablesDemo
, :
if (Character.isUpperCase(aChar)) {
System.out.println("The character " + aChar + " is upper
case.");
} else {
System.out.println("The character " + aChar + " is lower
case.");
}

102


,
( ), .
,
.
,
.
, Java
.
- (;). :
, .
- {
}. ,
, .

4.4.
, .
,
, .
,
, , ..
,
. , if-
System.out.println ,
Character.isUpperCase(aChar):
char c;
...
if (Character.isUpperCase(aChar)) {
System.out.println("The character " + aChar + " is upper
case.");
}

Java
4.18.
:
control flow statement details {
statement(s)
}

, { }
. , ,

.

103

4.18. .


while, do-while, for
if-else, switch-case
try-catch-finally, throw
break, continue, label:, return

While do-while
while , ..
. while :
while (expression) {
statement(s)
}

, while .. expression, boolean


. true, while- while
. while ,
false.
WhileDemo while
,
, g.
4.5. WhileDemo.
1: public class WhileDemo {
2:
public static void main(String[] args) {
3:
4:
String copyFromMe = "Copy this string until you " +
5:
"encounter the letter 'g'.";
6:
StringBuffer copyToMe = new StringBuffer();
7:
8:
int i = 0;
9:
char c = copyFromMe.charAt(i);
10:
11:
while (c != 'g') {
12:
copyToMe.append(c);
13:
c = copyFromMe.charAt(++i);
14:
}
15:
System.out.println(copyToMe);
16:
}
17: }

:
Copy this strin

104

Java while - dowhile. :


do {
statement(s)
} while (expression);

do-while .
,
.
4.6. DoWhileDemo.
1: public class DoWhileDemo {
2:
public static void main(String[] args) {
3:
4:
String copyFromMe = "Copy this string until you " +
5:
"encounter the letter 'g'.";
6:
StringBuffer copyToMe = new StringBuffer();
7:
8:
int i = 0;
9:
char c = copyFromMe.charAt(i);
10:
11:
do {
12:
copyToMe.append(c);
13:
c = copyFromMe.charAt(++i);
14:
} while (c != 'g');
15:
System.out.println(copyToMe);
16:
}
17: }

:
Copy this strin

for
for
. for :
for ( ; ; ) {
...
}

// infinite loop

, for- ,
.
.
4.7. ForDemo.
1: public class ForDemo {

105

2:
public static void main(String[] args) {
3:
int[] arrayOfInts = { 32, 87, 3, 589, 12,
4:
1076, 2000, 8, 622, 127 };
5:
6:
for (int i = 0; i < arrayOfInts.length; i++) {
7:
System.out.print(arrayOfInts[i] + " ");
8:
}
9:
System.out.println();
10:
}
11: }

:
32 87 3 589 12 1076 2000 8 622 127


for .
for-,
. for-
,
. i, j k
for ; for
.

if-else
if
, . ,
, boolean DEBUG.
DEBUG true, , ..
, x. ,
. :
if (DEBUG) {
System.out.println("DEBUG: x = " + x);
}

if: if
. , if-
:
if (expression) {
statement(s)
}

?
else. .
,
OK, .
if, else:

106

. . .
// response is either OK or CANCEL depending
// on the button that the user pressed
. . .
if (response == OK) {
// code to perform OK action
} else {
// code to perform Cancel action
}

else if- false. else-


else if, . if
else if , else .
IfElseDemo
: A - 90% , B - 80% .
4.8. IfElseDemo.
1: public class IfElseDemo {
2:
public static void main(String[] args) {
3:
4:
int testscore = 76;
5:
char grade;
6:
7:
if (testscore >= 90) {
8:
grade = 'A';
9:
} else if (testscore >= 80) {
10:
grade = 'B';
11:
} else if (testscore >= 70) {
12:
grade = 'C';
13:
} else if (testscore >= 60) {
14:
grade = 'D';
15:
} else {
16:
grade = 'F';
17:
}
18:
System.out.println("Grade = " + grade);
19:
}
20: }

:
Grade = C
?: upper isUpperCase true.
lower.
. ?: , if
println .

, .

107

switch
switch
. SwitchDemo
month,
. , month
switch :
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
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;
}
}
}

switch , month
case .
August. , if
. . switch
, if
.
switch ,
case - break. break switch
switch .
break, case .
case
.
4.9. SwitchDemo2.
1: public class SwitchDemo2 {
2:
public static void main(String[] args) {
3:
4:
int month = 2;
5:
int year = 2000;
6:
int numDays = 0;
7:

108
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34: }

-
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;
break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
}
System.out.println("Number of Days = " + numDays);
}

:
Number of Days = 29

, break
switch . break
case, case .
, default switch
case
:
int month = 8;
. . .
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;

109

case 12: System.out.println("December"); break;


default: System.out.println("Hey, that's not a valid month!");
break;
}


Java
.
, . ?

-
. ,
, .
:

try ,
.
catch , try

.
try .
finally , try

try .

:
try {
statement(s)
} catch (exceptiontype name) {
statement(s)
} finally {
statement(s)
}


Java :

break .
continue .
return .

break continue ,
label-. label .
label- (:):

110

statementName: someJavaStatement ;

break
break : label-.
label-. , break label-
switch switch-.
break label- for,
while do-while .
4.10. BreakDemo.
1: public class BreakDemo {
2:
public static void main(String[] args) {
3:
4:
int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,
5:
2000, 8, 622, 127 };
6:
int searchfor = 12;
7:
8:
int i = 0;
9:
boolean foundIt = false;
10:
11:
for ( ; i < arrayOfInts.length; i++) {
12:
if (arrayOfInts[i] == searchfor) {
13:
foundIt = true;
14:
break;
15:
}
16:
}
17:
18:
if (foundIt) {
19:
System.out.println("Found " + searchfor + " at
index " + i);
20:
} else {
21:
System.out.println(searchfor + "not in the array");
22:
}
23:
}
24: }

break , for
. for ..
println .
:
Found 12 at index 4

break label-,
label- break .
BreakWithLabelDemo ,
. for .

111

, break label-
search, for .
4.11. BreakWithLabelDemo.
1: public class BreakWithLabelDemo {
2:
public static void main(String[] args) {
3:
4:
int[][] arrayOfInts = { { 32, 87, 3, 589 },
5:
{ 12, 1076, 2000, 8 },
6:
{ 622, 127, 77, 955 }
7:
};
8:
int searchfor = 12;
9:
10:
int i = 0;
11:
int j = 0;
12:
boolean foundIt = false;
13:
14:
search:
15:
for ( ; i < arrayOfInts.length; i++) {
16:
for (j = 0; j < arrayOfInts[i].length; j++) {
17:
if (arrayOfInts[i][j] == searchfor) {
18:
foundIt = true;
19:
break search;
20:
}
21:
}
22:
}
23:
24:
if (foundIt) {
25:
System.out.println("Found"+searchfor+" at "+i+","+j);
26:
} else {
27:
System.out.println(searchfor + "not in the array");
28:
}
29:
30:
}
31: }

:
Found 12 at 1, 0

. break
label-, label-.
break.

continue
continue for
do-while . label-
, boolean
.. . ,
ContinueDemo, , .

112

p, continue
. p, p P.
4.12. ContinueDemo.
1: public class ContinueDemo {
2:
public static void main(String[] args) {
3:
4:
StringBuffer searchMe = new StringBuffer(
5:
"peter piper picked a peck of pickled peppers");
6:
int max = searchMe.length();
7:
int numPs = 0;
8:
9:
for (int i = 0; i < max; i++) {
10:
//interested only in p's
11:
if (searchMe.charAt(i) != 'p')
12:
continue;
13:
14:
//process p's
15:
numPs++;
16:
searchMe.setCharAt(i, 'P');
17:
}
18:
System.out.println("Found " +numPs+ " p's in the string");
19:
System.out.println(searchMe);
20:
}
21: }

:
Found 9 p's in the string.
Peter PiPer Picked a Peck of Pickled PePPers
continue label-
label-. , ContinueWithLabelDemo,

.
,
.
4.13. ContinueWithLabelDemo.
1: public class ContinueWithLabelDemo {
2:
public static void main(String[] args) {
3:
String searchMe = "Look for a substring in me";
4:
String substring = "sub";
5:
boolean foundIt = false;
6:
7:
int max = searchMe.length() - substring.length();
8:
9:
test:
10:
for (int i = 0; i <= max; i++) {
11:
int n = substring.length();
12:
int j = i;
13:
int k = 0;


14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24: }

113

while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)){
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt? "Found it" :"Didn't find it");
}

:
Found it

return
return.
.
. return : , .
, ( )
return:
return ++count;

4.5. -
4.7, 4.10 4.11,
. Java, ,
.
, . ,
. ,
Java
, .

.
. Java
.
(
), .
, , ,
, , .

114

Java, :
1.
2.
3.

.
- -.
.



, . -
( ),
, ([]).
:
String difficultWords[];
Point hits[];
int temps[];


, . ,
. :
String[] difficultWords;
Point[] hits;
int[] temps;

-
- .
:

new

new
:
String[] names = new String[10];

10 (.. ).
- new,
. .
, . ,
:
int[] temps = new int[99];

- new,
(0 , false boolean, '\0' ,
null ).
.

115

. new
, , :
String[] chiles = {"jalapeno", "anaheim", "serrano",
"habanero", "thai"};


null null (
).
'\0', NULL C.
,
- ( ,
).
. String
chiles .


,
. ,
([]):
myArray[subscript];

myArray ,
. subscript , ,
.
0, C C++. , 10 0
9.
, ,
, (
0, ). C, Java

, (
, C). ,
:
String[] arr = new String[10];
arr[10] = "eggplant";

- .
( - ).
arr 10 , 0,
10 .
runtime ( , )
, Java .

116


?
length , :
int len = arr.length // returns 10

, : 10, 9.
0. ,
, 1
.


,
:
myarray[1] = 15;
sentence[0] = "The";
sentence[10] = sentence[0];

,
( C C++).
, ,
. (
), ;
. int
float, .
, ,
, ,
. ,
, , ,
, .
? ,
Java.
Java . ,
, , .
4.14 .
4.14. .
1: class ArrayTest {
2:
3: String[] firstNames = {"Dennis", "Grace", "Bjarne", "James"};
4:
String[] lastNames = new String[firstNames.length];
5:
6:
void printNames() {
7:
int i = 0;
8:
System.out.println(firstNames[i]
9:
+ " " + lastNames[i]);
10:
i++;
11:
System.out.println(firstNames[i]


12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:}

117

+ " " + lastNames[i]);


i++;
System.out.println(firstNames[i]
+ " " + lastNames[i]);
i++;
System.out.println(firstNames[i]
+ " " + lastNames[i]);
}
public static void main (String args[]) {
ArrayTest a = new ArrayTest();
a.printNames();
System.out.println("----------");
a.lastNames[0] = "Ritchie";
a.lastNames[1] = "Hopper";
a.lastNames[2] = "Stroustrup";
a.lastNames[3] = "Gosling";
a.printNames();
}

:
Dennis null
Grace null
Bjarne null
James null
---------Dennis Ritchie
Grace Hopper
Bjarne Stroustrup
James Gosling

.
, ArrayTest,
String . , firstNames (),
( 3) 4 .
, lastNames (),
4, .
lastNames firstNames -
firstNames.length .
length , .
ArrayTest : printNames() main(). printNames(),
6 - 19,
firstNames lastNames ,
, . ()
(i), 0, Java
0.

118

, main(), . main()
4 :

22 ArrayTest,

.
23 printNames(),
. 4 ;
firstNames , lastNames null.
,
(.., null , 0 ,
false booleans).
25 - 28
lastNames .
, 29 printNames(),
lastNames ,
. 4 .

? .
Dennis Ritchie C, Bjarne Stroustrup C++, Grace Hopper
COBOL, , , James Gosling Java.
4.14 .
,
;
. , .
, , .


, (). Java . , (
., ),
- :
int coords[][] = new int[12][12];
coords[0][0] = 1;
coords[0][1] = 2;

4.6.
, Java
. ,
, .
;
, Java .

119

, (),
; , ,
; , .
,
Java .
, Java : ,
, . ,
, , ..
.
if switch,
, . , for,
while, do ,
, .

4.7.
:
:

:
:

integer
int?
,
, . ..
- overflow. , ,

. (
) ,
. ,
.
?
(int, float, boolean .), .
,
, casting. ( ).
, instanceof,
.
, new,
.. length, Array?
Java .
Java.
Array Java ; Array
, length.
, Array
. , , .

5.
,
o 3. -
, . , ,
, , ,
. ,
, .

:
( )
,

5.1.
, , .
3, - ,
; ,
, .
.
? string literal- (
),
String, . String
. ,
. ;

new.

int char
? , .
,
, .
(
).

new
, new
, :

121

String teamName = new String();


Random randInfo = new Random();
Jabberwock j = new Jabberwock();

; . ,
, ;
,
, .
:
GregorianCalendar date = new GregorianCalendar (64, 6, 6, 7, 30);
Point pt = new Point (0,0);

new,
constructor. (
).
(
, ),
.
,
. Date, java.util,
. 5.1
Date
new.
5.1. CreateDates.java
1: import java.util.Date;
2:
3: class CreateDates {
4:
5:
public static void main(String args[]) {
6:
Date d1, d2, d3;
7:
8:
d1 = new Date();
9:
System.out.println("Date 1: " + d1);
10:
11:
d2 = new Date(71, 7, 1, 7, 30);
12:
System.out.println("Date 2: " + d2);
13:
14:
d3 = new Date("April 3 1993 3:24 PM");
15:
System.out.println("Date 3: " + d3);
16:
}
17: }

,
:
Date 1: Tue Feb 14 09:36:56 PST 2006

Date 2: Sun Aug 01 07:30:00 PDT 1971

122

-
Date 3: Sat Apr 03 15:24:00 PST 1993

, date
new. ( 8) new Date()
, Date (
).
Date - .
: , , , , .
, Date object : Sunday, August 1, 1971, 7:30 a.m.

Java 0.
, 7 Java .
Date , ,
. Date object, ,
Date object ( ). date
; API Date
( java.util) .

new?
new.
,
.
(. constructor).



.
,
,
.
,
. new,
,
.
Date() , new.
,
,
.

123


- ,
new ,
, ?
. ,
.
. .
,
() , ,
. ,
.
.
e
, .

5.2.
,
, .
? !
.
.


,
. :
.


,
, .
, , myCustomer,
orderTotal,
:
myCustomer.orderTotal;

( ),
.
. orderTotal
, -
layaway, :
myCustomer.orderTotal.layaway;

124

,
myCustomer orderTotal,
layaway.



= :
myCustomer.orderTotal.layaway = true;

layaway true ().


5.2 Point. Point java.awt x y
.
5.2. testpoint.java
1: import java.awt.Point;
2:
3: class TestPoint {
4: public static void main(String args[]) {
5:
Point thePoint = new Point(10,10);
6:
7:
System.out.println("X is " + thePoint.x);
8:
System.out.println("Y is " + thePoint.y);
9:
10:
System.out.println("Setting X to 5.");
11:
thePoint.x = 5;
12:
System.out.println("Setting Y to 15.");
13:
thePoint.y = 15;
14:
15:
System.out.println("X is " + thePoint.x);
16:
System.out.println("Y is " + thePoint.y);
17:
18: }
19:}

, :
X is 10

Y is 10
Setting X to 5.
Setting Y to 15.
X is 5
Y is 15

, Point, X Y 10 ( 5).
8 9 ,
. 11 14 5

125

15, . , 16 17 X Y
.


, -
.
. -,
.
, .
- .
, .
- static
. ,
:
class FamilyMember {
static String surname = Igwebuike;
String name;
int age;
}

FamilyMemeber
, - surname ()
: Igwebuike. ,
FamilyMember .

static ()
: .
,
.
- ,
, -.
,
, .
:
FamilyMember dad = new FamilyMember();
System.out.println (Familys surname is: + dad.surname);
System.out.println (Familys surname is: +
FamilyMember.surname);


,

.

126

,
. ,
.

5.3.

-: . ,
,
, :
myCustomer.addToOrder (itemNumber, price, quantity);

,

myCustomer.cancelAllOrders();

, ,
.
talkManager(), cancelAllOrders(),
myCustomer:
myCustomer.cancelAllOrders().talkToManager() ;


-. putOnLayaway,
- Total,
myCustomer:
myCustomer.orderTotal.putOnLayaway (itemNumber, price, quantity);

System.out.print1n(),
, .
System, java.lang ,
, .
System.out PrintStream.
PrintStream ,
, .
PrintStream print1n(), .
5.3 ,
String. ,
.
5.3. checkstring.java
1: class TestString {
2:
3:
public static void main(String args[]) {
4:
String str = "Now is the winter of our discontent";
5:


6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21: }

127

System.out.println("The string is: " + str);


System.out.println("Length of this string: "
+ str.length());
System.out.println("The character at position 5: "
+ str.charAt(5));
System.out.println("The substring from 11 to 17: "
+ str.substring(11, 17));
System.out.println("The index of the character d: "
+ str.indexOf('d'));
System.out.print("The index of the beginning of ");
System.out.println("substring \"winter\": "
+ str.indexOf("winter"));
System.out.println("The string in upper case: "
+ str.toUpperCase());
}

,
:
The string is: In my next life, I will believe in

reincarnation
Length of this string: 48
The character at position 7: e
The substring from 24 to 31: believe
The index of the character x: 8
The index of the beginning of the substring will: 19
The string in upper case: IN MY NEXT LIFE, I WILL
BELIEVE IN REINCARNATION

4 String . (
new, ).

:

5 , 4:
, .
7 strLength(), string .
48 .
9 charAt(),
.
0, 1, 7 .
11 Substring() () ,
,
. Substring(),
,
.
13 indexOf(),
(, x).
x 13 ,
String.

128

15 indexOf() ,
- .
17 toUppercase()
, .


, ,
, .
,
, . ,
String valueOf(),
( , Boolean, .). valueOf()
String, string .
String,
,
, String.
, ,
(). , Math, java.lang
,
Math,
Boolean . , Math.max(),
.
Math , , :
int.maximumPrice = Math.max (firstPrice, secondPrice);

.
,
, . ,
, ,
.
5:
String s, s2;
s = item;
s2 = s.valueOf (5);
s2 = String.valueOf (5);

5.4.
,
.


,
.

129

, , ,
.
. .
, 5.4
.
5.4. referencetest.java
1: import java.awt.Point;
2:
3: class ReferencesTest {
4:
public static void main (String args[]) {
5:
Point pt1, pt2;
6:
pt1 = new Point(100, 100);
7:
pt2 = pt1;
8:
9:
pt1.x = 200;
10:
pt1.y = 200;
11:
System.out.println("Point1: " + pt1.x + ", " + pt1.y);
12:
System.out.println("Point2: " + pt2.x + ", " + pt2.y);
13:
}
14: }

:
Point1: 200, 200

Point2: 200, 200

5: Point
6: new Point pt1
7: pt1 pt2.

9-12 . x y pt1,
200, pt1 pt2, .
pt1 pt2 . ,
. , x y pt2
e, . ,
7 pt2 pt1, pt2,
pt1. pt2 pt1;
5.1. ,
.

5.1

130

pt1 pt2 ,
new Point() 6 7,
, :
pt1 = new Point (100, 100);
pt2 = new Point (100, 100);

,
. .

, ,
C C++. ,
.

5.5.
,
.
, .
,
,
(). int,
, float .
, ,
.

:
. print1n() ,
, , ,
(+).
, String.
:
float gpa = 2.15F;
System.out.print1n
+1.5));

(Honest,

dad,

my

GPA

is

(gpa

,
. ,
. float , .
(cast) .


(Casting)
. ,
.

131

() - .
- () .
,
(int, float
Boolean), (String, Point, ZipFile, ).
:

, int float ,
float double

,

, . .
.



. ,
, . Boolean
,
. ,
,
. .
128 127, int 2.1 2.1 ,
.
byte char int ; int
long, int float, double, . ,
,
. int
float int long float, float double,
.
,
,
. :
(typename) value

, typename ,
short, int, float (, , ). Value
. , , x
y, int:
(int) (x/y);

132

int ,
,
. I 65, (char)
.
65, ASCII , ,
.
,
, , x
int, y,
.


, ,
, :
.
.
,
. ,
,
.
, : Object
Window.
Object, Object . Window
Dialog,
FileDialog Frame.
.
class Window, ,
.
. , ,
.
, . ,
,
. ,
Integer, Number
Integer.
, .
,
, .
,
. ,
:
(classname) object

133

, classname , object -
.
classname; .
VicePresident
() Employee (); VicePresident
Employee, VicePresident
:
Employee emp = new Employee();
VicePresident veep = new VicePresident();
emp = veep; // ne e potrebna konverzija za gornata upotreba
veep = (VicePresident)emp; // mora jasno da se konvertira

, 2D
, 1.2.
Graphics Graphics2D, .
Graphics, screen,
Graphics2D .. screen2D:
Graphics2D screen2D = (Graphics2D) screen;

Graphics2D Graphics, java.awt .


9, , .
,

, .

, ,
.


,
, .
,
.
, java.lang ,
: Integer, Float, boolean .
, ,
, . ,
, ,
, .
,
, new.
Integer 4403:
Integer dataCount = new Integer (4403);

134

,
. , ,
. , int
dataCount, :
int newCount = dataCount.intValue(); // returns 4403

, , String
, . ,
parseInt() Integer. String-
, ,
:
String pennsylvania = 65000;
int penn = Integer.parseInt (pennsylvania);

API . HTML
Sun
Microsystems- web :
http://java.sun.com

Boolean, Byte, Character, Double,


Float, Integer, Long, Short, Void.

5.6.
,
:


,
,


:
, , , . ,
, .
, ,
.
: ==()
!=(). ,
.
, .
,
.

135

String . String
. , ==
, .
, .
String ,
equals(). ,
. 5.5
.
5.5. equalstest.java
1: class EqualsTest {
2: public static void main(String args[]) {
3:
String str1, str2;
4:
str1 = "she sells sea shells by the sea shore.";
5:
str2 = str1;
6:
7:
System.out.println("String1: " + str1);
8:
System.out.println("String2: " + str2);
9:
System.out.println("Same object? " + (str1 == str2));
10:
11:
str2 = new String(str1);
12:
13:
System.out.println("String1: " + str1);
14:
System.out.println("String2: " + str2);
15:
System.out.println("Same object? " + (str1 == str2));
16:
System.out.println("Same value? "+str1.equals(str2));
17:
}
18: }

:
String1: Free the bound periodicals.

String2: Free the bound periodicals.


Same object? true
String1: Free the bound periodicals.
String2: Free the bound periodicals.
Same object? false
Same value? true

( 3-5), (str1 i
str2), str1, str2.
, str1 str2 ,
9, .
, String- str1,
str2 String . ,
str1 str2, . ,
, == ( 15)
( ).

136

equals() - 16, (
).

,
str2, new? -
,
,
string .
.


?
, obj:
String name = obj.getClass().getName();

? getClass() Class,
. Class
( Class ), getName().
, . ,
instanceof, :
, .
, ,
:
swordfish instanceof String // true
Point pt = new Point(10, 10);
pt instanceof String // false

instanceof ;
, instanceof-
, true.

5.7.
, 1.02,
, .
, ( .
) . ,
, ,
, , .
. 5.6
SeeMethods.
5.6. seemethods.java


1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

137

import java.lang.reflect.*;
import java.util.Random;
class SeeMethods {
public static void main(String[] arguments) {
Random rd = new Random();
Class classname = rd.getClass();
Method[] methods = className.getMethods();
for(int i=0; i<methods.length; i++){
System.out.println(Method:+methods[i]);
}
}
}

java.lang.reflect.* ,
, , .
SeeMethods Random 6,
. E
:
1: Method: public final native java.lang.Class java.lang.Object.
getClass
2: Method: public native int java.lang.Object.hashCode()
3: Method: public boolean java.lang.Object.equals (java.lang. Object)
4: Method: public java.lang.String java.lang.Object.toString()
5: Method: public final native void java.lang.Object. notify()
6: Method: public final native void java.lang.Object.notifyAll()
7: Method: public final native void java.lang.Object.wait(long) throws
java.lang.InterruptedException
8: Method: public final void java.lang.Object.wait(long,int) throws
java.lang.InterruptedException
9: Method: public final void java.lang.Object.wait() throws java.lang.
InterruptedException
10: Method: public synchronized void java.util.Random. setSeed (long)
11: Method: public void java.util.Random.nextBytes(byte[])
12: Method: public int java.util.Random.nextInt()
13: Method: public long java.util.Random.nextLong()
14: Method: public double java.util.Random.nextDouble()
15: Method: public synchronized double java.util.Random. nextGaussian()

, SeeMethods
Random,
Random. ,
:
public;
;
;
;
,
.

138

SeeMethods
. 6 SeeMethods.java, ,
.
, browser- ,
.
JavaBeans,
( ),
.
java.lang.reflect :
Field -
Method -
Constructor -

Array -
Modifier - ,
( 15,
).
,
Class, .
,
.
, JavaBeans,
.

5.8.
, ,
.
, .. -
,
, .

- ,
: , ,
. : ,
,
.
, . ,
, .

139


. .
( 6, ).

5. 9.
:


, int boolean.

(byte, short, int, long, float,


double, boolean, char) .
, :
,
. ,
,
. ,
,
- .

? ,
,
,
?

. , , .
, , Node
(), -, Node.
, Node
, .
,
, .

6.
,
.
, ,
. , , ,
.
, ( String, Math
). ,
. :

-

Main() ,

6.1.
,
.
class, ,
:
class Ticker {
// telo na klasata
}

, Object,
.
, extends (),
.
Ticker:
class SportsTicker extends Ticker {
// telo na klasata
}

6.2.
,
, ,
.

. : -,
. .

141


3
, .
.
.
, .
, -
. 6.1
, Jabberwock (),
Reptile ().
6.1. jabberwocky.java
1: class Jabberwock extends Reptile {
2:
String color;
3:
String sex;
4:
boolean hungry;
5:
int age;
6: }

.
, -.
:

color () - ( : , ,
);
sex () - ;
hungry () - boolean ,
, ;
age () - , .

,
.
,
, .


, ,
.
, .

,
.
: , , .

142

1.02,
1.1. ,
, 1.02.
, final
, ,
:
final float pi = 3.141592;
final boolean debug = false;
final int numberOfJenny = 8675309;


, .
, .
, :
final int LEFT = 0;
final int RIGHT = 1;
final int CENTER = 2;

,
alignment, :
int alignment;

, ,
:
this.alignment = CENTER;

, :
switch (this alignment) {
case LEFT:
// ako e levo poramnuvanje
break;
case RIGHT:
// ako e desno poramnuvanje
break;
case CENTER:
// ako e centralno poramnuvanje
break;
}

.
,
:
this.alignment = CENTER;
this.alignment = 2;

143


, -
,
. -
,
.
static -,
:
static int sum;
static final int maxObjects = 10;

6.3.
,
-
,
.
,
.
.


:

,



.

,
, - public private,
throws, .
.
, ,

. , , ,
, .
, .

144

:
returnType methodName (type1 arg1, type2 arg2, type3 arg3 ) {
// telo na metodot
}

ReturnType , .
, , void,
.
, ,
, returnType, .
,
:
int[] makeRange(int lower, int upper) {
// telo na metodot
}

,
, .
,
. , , ,
, , , -
.
void, ,
, .
, return.
6.2 , makeRange() .
makeRange()
. ,
.
6.2. RangeClass.java
1: class RangeClass {
2:
int[] makeRange(int lower, int upper) {
3:
int arr[] = new int[ (upper - lower) + 1 ];
4:
5:
for (int i = 0; i < arr.length; i++) {
6:
arr[i] = lower++;
7:
}
8:
return arr;
9:
}
10:
11:
public static void main(String arg[]) {
12:
int theArray[];
13:
RangeClass theRange = new RangeClass();
14:
15:
theArray = theRange.makeRange(1, 10);
16:
System.out.print("The array: [ ");
17:
for (int i = 0; i < theArray.length; i++) {


18:
19:
20:
21:
22:
23: }

145

System.out.print(theArray[i] + " ");


}
System.out.println("]");

:
The array: [ 1 2 3 4 5 6 7 8 9 10 ]

Main()- makeRange(),
1 10
( 6), for-,
.

this

. -
,
. ,
this, . this,
,
: , ,
. this:
t = this.x;
// x - instancna varijabla za ovoj objekt
this.resetData(this); // povik na metodot resetData, definiran vo
// ovaa klasa, i prosleduvanje na tekovniot objekt
return this;
// se vraka tekovniot objekt

,
this, . , ,
-,
, this
. , ,
:
t=x;
// x - instancna varijabla za ovoj objekt
resetData(this); // povik na metodot resetData, definiran vo ovaa
// klasa

this, ,
.
this ,
.

146

, static,
this.


,
.



.
, .
,
. , ,
. -
,
.
,
(
), , ,
. ,
,
- .
,
.
,
, ( ) ,
.
, 6.3.
6.3. scopetest.java
1: class ScopeTest {
2:
int test = 10;
3:
4:
void printTest () {
5:
int test = 20;
6:
System.out.println("test = " + test);
7:
}
8:
9:
public static void main (String args[]) {
10:
ScopeTest st = new ScopeTest();
11:
st.printTest();
12:
}
13: }

147

test = 20

. ,
test - 10.
, 20.
test printTest() test, printTest()- main() test = 20.
this.test,
-, test, .
,
, .
,
, .
;
,
. ,
;
- ,
, .

.
, .

o
,
, .
, .
,
. , ,
. 6.4 .
6.4. Passbyreference
1: class PassByReference {
2:
int onetoZero(int arg[]) {
3:
int count = 0;
4:
5:
for (int i = 0; i < arg.length; i++) {
6:
if (arg[i] == 1) {
7:
count++;
8:
arg[i] = 0;
9:
}
10:
}
11:
return count;
12:
}
13:
public static void main (String arg[]) {
14
int arr[] = { 1, 3, 4, 5, 1, 1, 7 };

148

15:
16:
17:
18:
19:
20:
21:
22:
23:
24
25:
26:
27:
28:
29:
30:
31:
32: }

PassByReference test = new PassByReference();


int numOnes;
System.out.print("Values of the array: [ ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("]");
numOnes = test.onetoZero(arr);
System.out.println("Number of Ones = " + numOnes);
System.out.print("New values of the array: [ ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("]");
}

:
Values of the array: [ 1 3 4 5 1 1 7 ]

Number of Ones = 3
Number values of the array: [ 0 3 4 5 0 0 7 ]

onetoZero() 2 12,
. onetoZero() :
(1) .
1, 0 .
Main()- PassByReference,
onetoZero(). main() ,
.
14-16 .
; PassbyReference,
test. ,
. 18-22 ;
. 24
, ;
onetoZero(), test
arr. ,
numOnes.
? 25 (
onetoZero() ). 3, .
. -
,
. 27-30

(0).

149


,

. ,
. ,
, ,
. , ,
Math. Math-
, ,
:
float root = Math.sqrt(453.0);
System.out.print (The larger of x and y is + Math.max (x, y));

, static
,
. , max() ,
:
static int max (int arg1, int arg2) {
// telo na metodot
}

, ; ,
Integer, Float Boolean .
,
, - . ,
parseInt() Integer, .
, ,
int ( ).
parseInt():
int count = Integer.parseInt(42);

, 42
parseInt() , 42, count.
static ,
. ,
.

,
.
, ,
.

150

6.4.
, , ,
, .
, ,
. , browser
.
. ,
browser-,
.

.

, , ,
, .
: main() .
, main() .
;
main().
main() :
public static void main (String arguments[]) {
// telo na metodot
}

main()-:
public .
public. public, private
.
static main() .
void main() .
main() .
main()-
, ,
. main() ,
main() .
main(), .
,
main()-.


,
, ,

. .

151

DK,
CLASS-PATH.
,
. ,
main()-. ,
.
main()- ,
.

6.5.
,
. ,
,
.
,
,
.



. Windows UNIX,
, .
Windows Solaris,
.
:
java MyProgram argumentOne 2 three

, :
argumentOne, 2, three.
.
,
. , Java is cool
;
.

main()-.


,
main()
. main():

152

public static void main (String arguments[]) {


// telo na metodot
}

arguments .
.
main()-,
,
. , 6.5
, .
6.5. echoargs.java
1: class EchoArgs {
2:
public static void main(String args[]) {
3:
for (int i = 0; i < args.length; i++) {
4:
System.out.println("Argument " + i + ": " + args[i]);
5:
}
6:
}
7: }

o :
java EchoArgs 1 2 3 jump

EchoArgs
, :
Argument
Argument
Argument
Argument

0:
1:
2:
3:

1
2
3
jump

, :
java EchoArgs "foo bar" zap twaddle 5

:
Argument
Argument
Argument
Argument

0:
1:
2:
3:

foo bar
zap
twaddle
5

;
foo bar,
.
:
, .
, .

153

argv C UNIX.
arg[0], , ..
,
C.
.
, ,
SumAverage,
. 6.6
. ;
.
6.6. sumaverage.java
1: class SumAverage {
2:
public static void main (String args[]) {
3:
int sum = 0;
4:
5:
for (int i = 0; i < args.length; i++) {
6:
sum += args[i];
7:
}
8:
9:
System.out.println("Sum is: " + sum);
10:
System.out.println("Average is: " +
11:
(float)sum / args.length);
12:
}
13: }

, for
, ,
.
:
SumAverage.java:6: Incompatible type for +=.
Can't convert java.lang.String to int.
sum += args[i];

, .
,
, .
Integer , parseInt.
6, , :
sum += Integer.parseInt(arguments[i]) ;

. ,
:
Sum is: 6
Average is: 2

154

6.6.
,
. ,
. ,
. :
- , ,
.
. ,
.

. ,
, this
.
. main()-
.
,
, - .

6.7.
:

:
:

:
:


, 1.02.

1.2?
browser-
. -
browser- .
- origin.
origin ,
a . ,
-?

-.
, this.origin
-, origin,
.
,
, .
,
, ; .
,
,
.

7.
-
. ,

,
.
. ,
,
,
.
, :
1. , ..
, .
2. -
,
.
3. -
-.
4. - ,
.

7.1. ,

. ,
- ,
.
(

) .
, draw() ,
. ,
, .
,
.


,
.
.
,
, ,
( ).

.

156

,
. ,
, ,
. ,
-
.
. 7.1
MyRect, .
MyRect
: x1, y1, x2 y2.

MyRect ? .awt

. MyRect,
.
7.1. MyRect.
1:
2:
3:
4:
5:
6:

Klasa MyRect {
int x1 = 0;
int y1 = 0;
int x2 = 0;
int y2 = 0;
}

. ,
,
main()-. ,
.
MyRect ,
0. buildRect(),
,
,
(
, this
):
MyRect buildRect (int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
return this;
}

157


, , Point-, ?
buildRect(),
Point ( java.awt.Point
, ):
MyRect buildRect (Point topLeft, Point bottomRight) {
x1 = topLeft.x;
y1 = topLeft.y;
x2 = bottomRight.x;
y2 = bottomRight.y;
return this;
}

,
. .
buildRect();
MyRect buildRect (Piont topLeft, int w, int h) {
x1 = topLeft.x;
y1 = topLeft.y;
x2 = (x1 + w);
y2 = (y1 + h);
return this;
}

, printRect()
, main
( ). 7.2.
: buildRect , printRect() main().
7.2. MyRect
1: import java.awt.Point:
2:
3: class MyRect {
4:
int x1 = 0;
5:
int y1 = 0;
6:
int x2 = 0;
7:
int y2 = 0;
8:
9:
MyRect buildRect (int x1, int y1, int x2, int y2) {
10:
this.x1 = x1;
11:
this.y1 = y1;
12:
this.x2 = x2;
13:
this.y2 = y2;
14:
return this;
15:
}
16:
17:
MyRect buildRect (Point topLeft, Point bottomRight) {
18:
x1 = topLeft.x;
19:
y1 = topLeft.y;
20:
x2 = bottomRight.x;
21:
y2 = bottomRight.y;

158
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:

-
return this;
}
MyRect buildRect (Point topLeft, int w, int h) {
x1 = topLeft.x;
y1 = topLeft.y;
x2 = (x1 + w);
y2 = (y1 + h);
return this
}
void printRect () {
System.out.print (MyRect: < + x1 + , + y1);
System.out.print (, + x2 + , + y2 + >);
}
public static void main (String args [] ) {
MyRect rect = new MyRect ();
System.out.println (Calling buildRect
25,25,50,50:);
rect.buildRect (25,25,50,50);
rect.printRect ();
System.out.println (----------);

with

coordinates

System.out.println (Calling buildRect w/points (10,10),


(20,20):);
rect.buildRect(new Point (10,10) new Point (20,20));
rect.printRect();
System.out.println (----------)

47:
48:
49:
50:
51:
System.out.print (Calling buildRect w/1 points (10,10),);
52:
System.out.println (width (50) and height (50):);
53:
54:
rect.buildRect (new Point (10,10), 50,50);
55:
rect.printRect();
56:
System.out.println (----------);
57:
}
58: }

:
Calling buildRect with coordinates 25,25,50,50:
MyRect: <25, 25, 50, 50>
---------Calling buildRect w/point (10,10), (20,20):
MyRect <10, 10, 20, 20>
---------Clling buildRect w/1 point(10,10), width(50) and height (50):
MyRect: <10, 10, 60, 60>
----------

, buildRect()-
.

159

, ,
.

7.2. -
, . -
.
, -
; , -
. ,
new, :
- .
- ,
(0 , null
, false , \0 ).
- - (
).



Java .
-,
, ,
.
.
,
,
,
. ,
,
new .


, .
-
- .
, 7.3 Person.
Person :
Person Person.
7.3. Person.

160

1: class Person {
2:
String name;
3:
int age;
4:
5:
Person (String n, int a) {
6:
name = n;
7:
age = a;
8:
}
9:
10:
void printPerson() {
11:
System.out.print(hi, my name is + name);
12:
System.out.println(. I am + age + years old.);
13:
}
14:
15: public static void main (String args[]) {
16:
Person p;
17:
p = new Person (Laura, 20);
18:
p.printPerson();
19:
System.out.println(----------);
20:
p = new Person (Tommy, 3);
21:
p.printPerson();
22:
System.out.println(----------);
23: }
24: }

:
Hi, my name is Kaura. I am 20 years old.
---------Hi, my name is Tommy. I am 3 years old.
----------

Person : , 5 8
,
new. Person
printPerson() ,
main() .


-
;
.
,
.
Java .
, this,
, , :
this(arg1, arg2, arg3);

this(), .

161


-
,
,
. , buildRect(),
MyRect , ,
.
, buildRect()-
( ),
. 7.4. , MyRect2,
MyRect, , buildRect()-.
MyRect ,
.
7.4. MyRect2 ( ).
1: import java.awt.Point;
2:
3: class MyRect2 {
4:
int x1 = 0;
5:
int y1 = 0;
6:
int x2 = 0;
7:
int y2 = 0;
8:
9:
MyRect2(int x1, int y1, int x2, int y2) {
10:
this.x1 = x1;
11:
this.y1 = y1;
12:
this.x2 = x2;
13:
this.y2 = y2;
14:
}
15:
16:
MyRect2(Point topLeft, Point bottomRight) {
17:
x1 = topLeft.x;
18:
y1 = topLeft.y;
19:
x2 = bottomRight.x;
20:
y2 = bottomRight.y;
21:
}
22:
23:
MyRect2(Point topLeft, int w, int h) {
24:
x1 = topLeft.x;
25:
y1 = topLeft.y;
26:
x2 = (x1 + w);
27:
y2 = (y1 + h);
28:
}
29:
30:
void printRect() {
31:
System.out.print("MyRect: <" + x1 + ", " + y1);
32:
System.out.println(", " + x2 + ", " + y2 + ">");
33:
}
34:

162
35:
36:
37:
38:

-
public static void main(String args[]) {
MyRect2 rect;
System.out.println("Calling MyRect2 with coordinates
25,25 50,50:");
rect = new MyRect2(25, 25, 50,50);
rect.printRect();
System.out.println("----------");

39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55: }

System.out.println("Calling MyRect2 w/points (10,10),


(20,20):");
rect= new MyRect2(new Point(10,10), new Point(20,20));
rect.printRect();
System.out.println("----------");
System.out.print("Calling MyRect2 w/1 point (10,10)");
System.out.println(" width (50) and height (50):");
rect = new MyRect2(new Point(10,10), 50, 50);
rect.printRect();
System.out.println("----------");
}

:
Calling MyRect2 with coordinates 25,25 50,50:
MyRect: <25, 25, 50, 50>
---------Calling MyRect2 w/points (10,10), (20,20):
MyRect: <10, 10, 20, 20>
---------Calling MyRect2 w/1 point (10,10), width (50) and height (50):
MyRect: <10, 10, 60, 60>
----------

7.3.
,
,
,
.
, . ,
,
.
.
, .
, ,
.

163


,
(, )
.
,
. ; 7.5
printMe(),
.
7.5. PrintClass .
1: class PrintClass {
2:
int x = 0;
3:
int y = 1;
4:
5:
void printMe() {
6:
System.out.println("x is " + x + ", y is " + y);
7:
System.out.println("I am an instance of the class " +
8:
this.getClass().getName());
9:
}
10: }

7.6 PrintSubClass
PrintClass.
z.
7.6. PrintSubClass .
1: class PrintSubClass extends PrintClass {
2:
int z = 3;
3:
4:
public static void main(String args[]) {
5:
PrintSubClass obj = new PrintSubClass();
6:
obj.printMe();
7:
}
8: }

:
x is 0, y is 1
I am an instance of the class PrintSubClass

main- PrintSubClass PrintSubClass


printMe() . PrintSubClass ,
PrintSubClass ,
PrintClass. , printMe() PrintClass,
z.
. PrintSubClass2 PrintSubClass,
printMe z. 7.7
.

164

PrintClass :
main()- . PrintClass
PrintSubClass
main()-.
, main()-.
7.7. PrintSubClass2 .
1: class PrintSubClass2 extends PrintClass {
2:
int z = 3;
3:
4:
void printMe() {
5:
System.out.println("x is " + x + ", y is " + y +
6:
", z is " + z);
7:
System.out.println("I am an instance of the class " +
8:
this.getClass().getName());
9:
}
10:
11:
public static void main(String args[]) {
12:
PrintSubClass2 obj = new PrintSubClass2();
13:
obj.printMe();
14:
}
15: }

printMe()-,
printMe , printMe-
PrintClass ( ):
:
x is 0, y is 1, z is 3
I am an instance of the class PrintSubClass2

o
, o
:
- .
- .
;
, .
,
.
.

.
,
super
.

165

void myMethod (String a, String b) {


// tuka nesto raboti
super.myMethod(a, b);
// tuka raboti uste nesto
}

super -.
this, -,
. , 7.8
prientMe() .
7.8. printMe() .
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

// from PrintClass
void printMe() {
System.out.println("x is " + x + ", y is " + y);
System.out.println("I am an instance of the class" +
this.getClass().getName());
}
}

//from PrintSubClass2
void printMe() {
System.out.println("x is " + x + ", y is " + y + ", z
is " + z);
12:
System.out.println("I am an instance of the class " +
13:
this.getClass().getName());
14:
}


, -
:
// from PrintClass
void printMe() {
System.out.println("I am an instance of the class" +
this.getClass().getName());
System.out.println("x is " + x);
System.out.println("y is " + y);
}

, , printMe ,
:
// From PrintSubClass2
void printMe() {
super.printMe();
System.out.println("z is " + z);
}

printMe :
I am an instance of the class PrintSubClass2
x is 0

166

-
y is 1
z is 3


,
.
, . ,
,
-
- .
-,

-.
-,
super.methodname (arguments).

, :
super(arg1, arg2,...);

super():
. super()
, super()
.
this() , super() - (
- .).
-, super() .
.
-
;
. ,

-.
7.9 NamedPoint,
Poin awt . Point
x y Point . NamedPoint
(string ) x, y
.
7.9. NamedPoint .
1: import java.awt.Point;
2: class NamedPoint extends Point {
3:
String name;
4:


5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15: }

167

NamedPoint(int x, int y, String name) {


super(x,y);
this.name = name;
}
public static void main (String arg[]) {
NamedPoint np = new NamedPoint(5, 5, "SmallPoint");
System.out.println("x is " + np.x);
System.out.println("y is " + np.y);
System.out.println("Name is " + np.name);
}

:
x is 5
y is 5
Name is SmallPoint

NamedPoint ( 5 8)
Point x y.
x y,
Point ,
,
.

7.4.
.
,

.
finalize(). Object default
. ,
finalize() :
protected void finalize() throws Throwable {
super.finalize();
}

throws Throwable ot
.
. ,
.

finalize()
. , super.finalize()
, (
, , ).
finalize() ;
. , finalize()

168

. ,
.

- , ,
(
),
.
finalize().

7.5.
, , , , ,

.
,
;

.

7.6.
:

:
int total(int arg1, int arg2, int arg3) {...}
float total(int arg1, int arg2, int arg3) {...}

:
:
O:


. . ?
,
- , .
.
- ?
, (

)?
! ,
, -.
this()
. this()?
.
.
-
.

8.
- World Wide Web
-
, .
, ,
,
Netscape, Internet Explorer, Mozila Firefox . ,
, ,
.
,
. ,
,
.
, :
- ;
- :
;
- -
;
- .

8.1.

, .

. , .
, .
World Wide Web .
HTML .
- ,
(download)
( ). (
class
).
,
: ,
,
.
( ),
(
).

170


.
,
.

.
.
,
,
.
World Wide Web
, -
,
.
(
, ),
.
:
-
, ,
.
- ,
,
.
-
. UNIX .
-
, DDL.

Microsoft Internet Explorer - ;
- appletviewr
JDK
. ,


. .


(
). Sun

.

171

,

.

.


,

, CPU
. Sun Net
;

.

8.2.

- main()- ,
.
,
, ,
.
, Applet. Applet ,
java.applet ,
- . Java Abstract
Windowing Toolkit GUI (
)- : , ,
, , check box- ;
, . Awt
java.awt .


Java Abstract Windowing Toolkit (awt)
GUI- .
awt.
,
- .
- :
public class myClass extends java.applet.Applet {
...

172

- public.
,
, public.
- ,
-,
; ,
(browser-).
, main-
- , -
-.
, ,
.


,
main() . ,
main(), main()
. ,
, main()-.

- :
, , .
, , .
.
,
-. , ;
.
,
: ,
, , .

(
) main() .
,
,
. ,
init() -:
public void init() {
...

173

, .
,
, .
.
: ,
.
, start():
public void start() {
...

}
start() - ,
,
, .

.

.

, stop().
, , ,
.
. stop(),
, - :
public void stop() {
...

.
,
. ,
, ,
.
destroy(),
, ,
. ,
destroy():
public void destroy() {
...

174


destroy() finalize(), ?
, destroy() . finalize()
,
.

, ,
, , .
( ,
,
,
, , ).
paint()- ,
( ). paint() :
public void paint(Graphics g) {
...
}

, , paint()
, .. Graphics.
paint , .
, Graphics ( .awt )
, import
:
import java.awt.Graphics;


,
HelloAgainApplet (
HelloAgain). ,
. ,
. 8.1
.
8.1. Hello Again .
1:
2:
3:
4:
5:
6:
7:
8:
9:

import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
public class HelloAgainApplet extends java.applet.Applet {
Font f = new Font("TimesRoman", Font.BOLD, 36);
public void paint(Graphics g) {


10:
11:
12:
13:
14: }

175

g.setFont(f);
g.setColor(Color.red);
g.drawString("Hello again!", 5, 50);

paint()-,
(, default
paint() ). (
),
, start(), stop(), int() destroy() .
paint() .
Graphics, paint()-,
.. ,
, . 10 11
(,
f, Color ).
12 HelloAgain!,
5, 50. 0- x, y
, y , 50
. 8.1
.

8.1.
,
: main()-.
, main()-.
- (Int(), Start(), Stop(),
Paint() .), .

8.3.
,
class ,
, HTML .
HTML ;
class file .

176


HTML .
HTML online.


, <APPLET> .
<APPLET> HTML
. 8.2
.
8.2. HTML .
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

<HTML>
<HEAD>
<TITLE>This page has an applet on it</TITLE>
</HEAD>
<BODY>
<P>My second Java applet says:
<BR><APPLET CODE="HelloAgainApplet.class" WIDTH=200
HEIGHT=50>
Hello Again!
</APPLET>
</BODY>
</HTML>

- :
1. CODE- class-
, .class-. , class-
HTML .
, CODEBASE
.
2. WIDTH HEIGHT
-
. WIDTH HEIGHT
; ,
,
,
.
3. <APPLET> </APPLET>
<APPLET> (
).
,

177

HTML ,
, -
. , .
, HelloAgain!.
<APPLET> , <IMG>, ,
, <P>
(<H1>, <H2> .).


class- HTML- ,
,
( Internet Explorer Open File
Browse ).
HTML-,
.
,
. JDK,
appletviewer- .
,
. 8.2 HelloAgain Netscape:

8.2. Hello Again


HTML ,
,
World Wide Web,
.
HTML ,
.
;
. ,
,

178

HTML .class ,
.
,
. ( ,
, ).

8.4. <APPLET>
, CODE, WIDTH, HEIGHT,
<APPLET>
. <APPLET> , ,

.

<APPLET> ,
HTML <IMG> .

ALIGN
ALIGN
. : LEFT, RIGHT,
TOP, TEXTTOP, MIDDLE, ABSMIDDLE, BASELINE, BOTTOM, ABSBOTTOM.
ALIGN=LEFT ALIGN=RIGHT,
,
, .
,
(BR) CLEAR-, . CLEAR : CLEAR=LEFT
, CLEAR=RIGHT
CLEAR=ALL
.

Netscape Navigator Windows, ALING


( ;
UNIX MAC- Netscape).
,
, ALIGN.
, HTML
,
:
<P><APPLET CODE="HelloAgainApplet.class" WIDTH=200 HEIGHT=50
ALIGN=LEFT>Hello Again!</APPLET>
To the left of this paragraph is an applet. Its a

179

Simple, unassuming applet, in which a small string is


printed in red type, set in 36 point Times bold.
<BR CLEAR=ALL>
<P> In the next part of the page, we demonstrate how
under certain conditions, styrfoam peanuts can be
used as a healthy snack.

8.3 ,
( default , ).

8.3.
,
. , 7 ALIGN
:
- ALIGN=TEXTTOP
;
- ALIGN=TOP (
, );
- ALIGN=ABSMIDDLE
;
- ALIGN=MIDDLE
;
- ALIGN=BASELINE ;
(ALIGN=BASELINE ALIGN=BOTTOM, ALIGN=BASELINE
);
- ALIGN=ABSBOTTOM

( , );
8.4 , ,
.

180

8.4.

HSPACE VSPACE
HSPACE and VSPACE
. HSPACE
( ). VSPACE
( ). , HTML 50 10:
<P><APPLET CODE="HelloAgainApplet.class" WIDTH=300 HEIGHT=200
ALIGN=LEFT VSPACE=50 HSPACE=10>Hello Again!</APPLET>
To the left of this paragraph is an applet. Its a
simple, unassuming applet, in which a small string is
printed in red type, set in 36 point Times bold.
<BR CLEAR=ALL>
<P>In the next part of the page, we demonstrate how
under certain conditions, styrofoam peanuts can be
used as a healthy snack.

8.5.

8.5.

181

CODE CODEBASE
<APPLET>
CODE CODEBASE. ,
; , .
CODE .class
. CODE <APPLET> , class
HTML- .
class CODE .class
; - ,
. class-
, HTML-,
class . ,
CODEBASE. CODE class ;
CODEBASE ( URL
) . , class-
classes, HTML , CODEBASE
:
<APPLET CODE="myclass.class" CODEBASE="classes"
WIDTH=100 HEIGHT=100></APPLET>

,
URL CODEBASE:
<APPLET CODE="myclass.class"
CODEBASE="http://myserver.com/javaclasses"
WIDTH=100 HEIGHT=100></APPLET>

class ?
URL CODEBASE :
<APPLET CODE="myclass.class"
CODEBASE="http://www.joesserver.com/javaclasses"
WIDTH=100 HEIGHT=100></APPLET>

8.5. Java
, Java
, .. <APPLET>
- . Java
. ,
, .

, . , , ,
-
.
,

182

. Java .
Java ,
. Java ,
.
, .
Java ,
, (

). Java
, Java class ( ). Netscape,
:
<APPLET CODE="MyApplet.class" ARCHIVE="appletstuff.zip" WIDTH=100
HEIGHT=100>
...
</APPLET>

zip . zip
,
. ,
zip ; . ARCHIVE
.
,
Java
.
, Java 1.1
JAR . Java , ,
. ,
,
JDK. JAR
,
( ). JAR
, ,
JDK 1.1 http://java.sun.com/products.

8.6.
Java , main()
, , - Java
Runner.
, .
, , .
? HTML
<APPLET> , -.
, :
- HTML ;
- .

183

- : ,
, ,
. , ,
, color red. ,
, speed 5.
HTML , ,
<PARAM>, , (
) NAME VALUE. <PARAM> <APPLET>
:
<APPLET CODE="MyApplet.class" WIDTH=100 HEIGHT=100>
<PARAM NAME=font VALUE="TimesRoman">
<PARAM NAME=size VALUE="36">
Java applet appears here.</APPLET>

MyApplet: font,
TimesRoman, size 36.
, .
init() ,
getParameter(). ,
, ,
( Java ,
string-). font
HTML , init() :
String theFontName = getParameter("font");

<PARAM>
getParameter(), ,
. , <PARAM NAME="name"> <PARAM
NAME="Name">.
, .
, HTML
, getParameter() null. ,
null Java ,
:
if (theFontName == null)
theFontName = "Courier"

getParameter()
, .
size HTML integer
, theSize, :
int theSize;

184

-
String s = getParameter("size");
if (s == null)
theSize = 12;
else theSize = Integer.parseInt(s);

? ?
. HelloAgain, hello
, "Hello Bill" "Hello Alice".
, HTML .
HelloAgainApplet, MoreHelloAgain (
8.3).
8.3. - More Hello Again.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
public class MoreHelloApplet extends java.applet.Applet {
Font f = new Font("TimesRoman", Font.BOLD, 36);
public void paint(Graphics g) {
g.setFont(f);
g.setColor(Color.red);
g.drawString("Hello Again!", 5, 40);
}
}

,
hello. ,
,
7:
String name;

, HTML
.
init(). paint() (,
, void). ,
null. default, , o
hello "Laura". init()
paint(), 9:
public void init() {
name = getParameter("name");
if (name == null)
name = "Laura"; }

HTML ,
Hello
, .

185

paint() ,
.
, , init().
init() :
name = "Hello " + name + "!";

, , paint()
. drawString()
:
g.drawString("Hello Again!", 5, 40);

, name,
:
g.drawString(name, 5, 40);

8.4 MoreHelloApplet.
class .
8.4. MoreHelloApplet .
1: import java.awt.Graphics;
2: import java.awt.Font;
3: import java.awt.Color;
4:
5: public class MoreHelloApplet extends java.applet.Applet {
6:
7:
Font f = new Font("TimesRoman", Font.BOLD, 36);
8:
String name;
9:
10:
public void init() {
11:
name = getParameter("name");
12:
if (name == null)
13:
name = "Laura";
14:
15:
name = "Hello " + name + "!";
16:
}
17:
18:
public void paint(Graphics g) {
19:
g.setFont(f);
20:
g.setColor(Color.red);
21:
g.drawString(name, 5, 40);
22:
}
23: }

HTML , . 8.5
MoreHelloApplet.
8.5. HTML MoreHelloApplet.
1:
2:

<HTML>
<HEAD>

186
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

-
<TITLE>Hello!</TITLE>
</HEAD>
<BODY>
<P>
<APPLET CODE="MoreHelloApplet.class" WIDTH=200 HEIGHT=50>
<PARAM NAME=name VALUE="Bonzo">
Hello to whoever you are!
</APPLET>
</BODY>
</HTML>

<APPLET>, class
(200, 50). 8
<PARAM>, .
NAME , VALUE "Bonzo".
HTML :

8.6. MoreHello
. MoreHelloApplet,
, Laura.
8.6 HTML name.
8.6. HTML MoreHelloApplet.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

<HTML>
<HEAD>
<TITLE>Hello!</TITLE>
</HEAD>
<BODY>
<P>
<APPLET CODE="MoreHelloApplet.class" WIDTH=200 HEIGHT=50>
Hello to whoever you are!
</APPLET>
</BODY>
</HTML>

187

, , ,
( 8.7).

8.7. MoreHelloApplet .

8.7.
, , Java
. Java ,
,
, ,
.
, :
- Java,
Applet, java.applet. Applet

, ,
-.
.
- ,
: init(), start(), stop(),
destroy(), paint(). ,
, .
.
- class , HTML
, <APPLET>. Java
<APPLET>, .
Java World Wide Web, HTML
, -
.
- ,
,
HTML . HTML
<PARAM> <APPLET> .
<PARAM> : NAME , VALUE

188

. ( init()),
getParameter().

8.8.
:

:
:

,
.

,
?
Java
. ,
Java
,
.
,
, , . ,
Java
. Java , Java
,
. ,
100% , Java .
.
,
, , ,
?
? , ,
, Java ?
Java ,
. , Java
. ,
, .
, Java Java ,
,
.
.
, ,
Java ,
.
,
?
Sun ,
.
,
(
, Sun,

:
:
:

189

Sun ).
HotJava .
, HotJava (
). ?
HTML ,
, .
,
Mozilla Firefox, Internet Explorer, JDK .
<APPLET> .
.
NAME
.

init(), resize()
<APPLET> WIDTH HEIGHT.
, resize()
.
.
resize() init(), ,
,
. , WIDTH () HEIGHT ()
, resize().
HTML
. , null
. ?
( NAME)
getParameter()? ,
, .
, , <PARAM>
<APPLET> ,
.
, stdout ,
, System.out.
println() ?
.
Java, ,
debugging- ( System.out.println()),
(Internet Explorer Java
Options | Advanced).
, System.out.println() ,
-
!

9. ,
,
.
, ,
, .
.
- ..
, ,
. :

Java: Graphics,
;
Java,
, , ;
,

;
Java, Color
( ) .


Java class , java.awt .
, -
, .
,
. - Java API ,
Java Web site-: http://java.sun.com/products.

9.1. Graphics
Java,
, , .
Java
Graphics. Graphics
; paint()- ( )
Graphics . , , ,
. Graphics java.awt
, ( ),
:
import java.awt.Graphics;
public class MyClass extends java.applet.Applet {
}

, 191

Graphics
,
Graphics. ,
, , .
- .
10,10 20,20.
Java (0,0) .
x , y .
; . 9.1

.

9.1. .
,
(0,0) .
, .

9.2.
Graphics
, , , , .

Bitmap , . GIF,
Graphics .
.

192

, drawLine().
drawLine() 4 : x y , x y
. ., MyLine
25,25 75,75. drawLine()
Graphics (
). g:
import java.awt.Graphics;
public class MyLine extends java.applet.Applet {
public void paint(Graphics g) {
g.drawLine(25,25,75,75);
}
}

9.2 MyLine
.

9.2. .

,
:

- ,

, : -
, - .
, drawRect() fillRect().
4 : x y ,
. ., (MyRect) :
, ( 9.3 ):

, 193

9.3. .
import java.awt.Graphics;
public class MyRect extends java.applet.Applet {
public void paint(Graphics g) {
g.drawRect(20,20,60,60);
g.fillRect(120,20,60,60);
}
}

, ,
. drawRoundRect()
fillRoundRect()
,
.
- ;
, - .
- ;

. 9.4 .

9.4. .
paint()- MyRRect :
10 ; - ,
20 ( 9.5 ):

194

9.5. .
import java.awt.Graphics;
public class MyRRect extends java.applet.Applet {
public void paint(Graphics g) {
g.drawRoundRect(20,20,60,60,10,10);
g.fillRoundRect(120,20,60,60,20,20);
}
}

, .
3D,
.
5 - x y ,
.
3D (true) (false).
, :
draw3DRect() fill3DRect(). My3DRect, 3D
- , ( 9.6
):

9.6. .
import java.awt.Graphics;
public class My3DRect extends java.applet.pplet {
public void paint(Graphics g) {
g.draw3DRect(20,20,60,60,true);
g.draw3DRect(120,20,60,60,false);
}
}

, 195

3D 9.6 3D, ?
Java Developer's Kit, 3D
3D , .
3D -.

.
, x y .
,
. ,
( drawPolygon() fillPolygon(),
). -
x y , Polygon.
, drawPolygon() fillPolygon()
:

x
y

x y, .
( 9.7
):

9.7. .
import java.awt.Graphics;
public class MyPoly extends java.pplet.pplet {
public void paint(Graphics g) {
int exes[] = { 39,94,97,142,53,58,26 };
int whys[] = { 33,74,36,70,108,80,106 };
int pts = exes.length;
g.drawPolygon(exes,whys,pts);
}
}

196

Java ;
, - .
, , .
drawPolygon() fillPolygon()
Polygon . Polygon

. Polygon,
, . ,
:
Polygon poly = new Polygon();

- :
int exes[] = { 39,94,97,142,53,58,26 };
int whys[] = { 33,74,36,70,108,80,106 };
int pts = exes.length;
Polygon poly = new Polygon(exes,whys,pts);

,
:
poly.addPoint(20,35);

, -
drawPolygon() fillPolygon(). ,
Polygon . ( 9.8
):

9.8. .
import java.awt.Graphics;
public class MyPoly2 extends java.pplet.pplet {
public void paint(Graphics g) {
int exes[] = { 39,94,97,142,53,58,26 };
int whys[] = { 33,74,36,70,108,80,106 };
int pts = exes.length;
Polygon poly = new Polygon(exes,whys,pts);
g.fillPolygon(poly);
} }

, 197


.
, .
4 : x y ,
. ,
. ,
. , drawOval()
, fillOval() .
- ( 9.9
):

9.9. .
import java.awt.Graphics;
public class MyOval extends java.pplet.pplet {
public void paint(Graphics g) {
g.drawOval(20,20,60,60);
g.fillOval(120,20,100,60);
}
}


Graphics, , .

; , -
. 9.10 .

9.10. .

198

drawArc() 6 : , ,
, . ,
drawArc()- fillArc()-
. ;
, .
,
. ,
;
. ,
; ()
. , C
, 9.11.

9.11. C .
,
. x y ,
. 4
drawArc() fillArc(). 9.12
.

9.12. .
, ,
. 3, 90
12, 180 9 , 270 6 .
. ,

, 199
C 90 ; 90 .
,
( ,
). , ,
180 - 180 .
180 ,
Java. C, 180
, -180. 9.13
.

9.13. .

.

, .
; C C
, 9.14:

9.14. .
import java.awt.Graphics;
public class MyOval extends java.pplet.pplet {
public void paint(Graphics g) {
g.drawArc(20,20,60,60,90,180);
g.fillArc(120,20,60,60,90,180);
}

200

;
.
9.15.

9.15. .
, .
, ,
drawArc() fillArc()
( 9.16).

9.16. .
- .
90 180 ,
. 25 ,
130 ( 9.17).

9.17. .
, . Java
, ( ,
):
import java.awt.Graphics;
public class MyOval extends java.pplet.pplet {
public void paint(Graphics g) {

, 201
g.drawArc(10,20,150,50,25,-130);
g.fillArc(10,80,150,50,25,-130);
}

9.18 .

9.18. .
, Java :
1.
2.
3.
4.

.
,
(
).
.
(
,
).



. , ( ,
). 9.1 lamp;
9.19 .

9.19. Lamp.
9.1. Lamp.

202

1: import java.awt.*;
2:
3: public class Lamp extends java.pplet.pplet {
4:
5:
public void paint(Graphics g) {
6:
// the lamp platform
7:
g.fillRect(0,250,290,290);
8:
9:
// the base of the lamp
10:
g.drawLine(125,250,125,160);
11:
g.drawLine(175,250,175,160);
12:
13:
// the lamp shade, top and bottom edges
14:
g.drawArc(85,157,130,50,-65,312);
15:
g.drawArc(85,87,130,50,62,58);
16:
17:
// lamp shade, sides
18:
g.drawLine(85,177,119,89);
19:
g.drawLine(215,177,181,89);
20:
21:
// dots on the shade
22:
g.fillArc(78,120,40,40,63,-174);
23:
g.fillOval(120,96,40,40);
24:
g.fillArc(173,100,40,40,110,180);
25:
}
26: }


,
, . Graphics
. copyArea()
- . copyArea() 6
: x y ,
, x y .
, 100 , -
100 :
g.copyArea(0,0,100,100,100,0);

, clearRect().
clearRect(), 4 drawRect()
fillRect(),
( ).
, size(),
Dimension . -
:
g.clearRect(0,0,size().width,size().height);

, 203

9.3.
Graphics, ,
Font ( FontMetrics). Font
- , , - FontMetrics
( ,
),
. , .
.

-
,
Font. Font - .. ,
(bold, italic), .
, , "TimesRoman", "Courier", "Helvetica".
Font;
class - , Font.PLAIN, Font.BOLD, Font.ITALIC.
, point size ; ,
. ,
3 Font new :
Font f = new Font("TimesRoman", Font.BOLD, 24);

TimesRoman BOLD, 24 .
Java ,
java.awt.Font .


; , Font.BOLD + Font.ITALIC
bold italic.
,
.
, Java default
font ( Courier).
:
String[] fontslist = this.getToolkit().getFontList();

, .
, , "TimesRoman", "Helvetica", "Courier".

204


font ,
drawChars() drawString(). ,
, setFont().
Graphics
. , Java
. ,
. paint() ,
, "This is a big
font.", 10,100:
public void paint(Graphics g) {
Font f = new Font("TimesRoman", Font.PLAIN, 72);
g.setFont(f);
g.drawString("This is a big font.", 10, 100);
}

;
Hello World Hello Again.
drawString() . x
; y .
drawString() drawChars(),
, . drawChars() 5 :
,
, (
), x y .
, drawString() drawChars().
9.2 ; 9.20
.

9.20. ManyFonts .
9.2. .
1: import java.awt.Font;
2: import java.awt.Graphics;
3:
4: public class ManyFonts extends java.pplet.pplet {
5:
6:
public void paint(Graphics g) {
7:
Font f = new Font("TimesRoman", Font.PLAIN, 18);

, 205
8:
Font fb = new Font("TimesRoman", Font.BOLD, 18);
9:
Font fi = new Font("TimesRoman", Font.ITALIC, 18);
10: Font fbi = new Font("TimesRoman", Font.BOLD + Font.ITALIC,18);
11:
12:
g.setFont(f);
13:
g.drawString("This is a plain font", 10, 25);
14:
g.setFont(fb);
15:
g.drawString("This is a bold font", 10, 50);
16:
g.setFont(fi);
17:
g.drawString("This is an italic font", 10, 75);
18:
g.setFont(fbi);
19:
g.drawString("This is a bold italic font", 10, 100);
20:
}
21:
22: }


Java
, - .,
.
Graphics Font. 9.1
.
9.1. .

getFont()


Graphics

font object

setFont()

getName()

Font

getSize()

Font

(
)

getStyle()

Font


(
: 0 = regular, 1 = bold, 2 =
italic, 3 = bold italic)

isPlain()

Font

true false,
regular

isBold()

Font

true false,
bold

isItalic()

Font

true false,
italic

( .,
), () .

206

FontMetrics :
, , . ,
FontMetrics , getFontMetrics():
Font f = new Font("TimesRoman", Font.BOLD, 36);
FontMetrics fmetrics = getFontMetrics(f);
g.setfont(f);

9.2 .
FontMetrics.
9.2. .


stringWidth(string)

string,
,

charWidth(char)

getAscent()

ascent ,

getDescent()

descent , ..

( p q
)

getLeading()

leading , ..
descent , ascent

getHeight()

,
ascent, descent, leading

, 9.3 Java-

.
; ,
. 9.21 (
).

9.21. .

, 207
9.3. .
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:

import java.awt.Font;
import java.awt.Graphics;
import java.awt.FontMetrics;
public class Centered extends java.pplet.pplet {
public void paint(Graphics g) {
Font f = new Font("TimesRoman", Font.PLAIN, 36);
FontMetrics fm = getFontMetrics(f);
g.setFont(f);
String s = "This is how the world ends.";
int xstart = (size().width - fm.stringWidth(s)) / 2;
int ystart = size().height / 2;
g.drawString(s, xstart, ystart);
}
}

size() 13 14,
Dimension .

width height Dimension,
.
,
;
.
, , 9.21,
. ,
getAscent()
getDescent() FontMetrics.
,
, .

9.4.
,
. Java
Color,
. Java 24-bit ,
, .
0 255. 0,0,0 , 255,255,255 ,
3 . Java,
Java ,
256 . -

208

,
. , Java
, .

Color
,
Color . Color
color , class ,
. ., Color.red Color
(RGB 255, 0, 0), Color.white (RGB values of 255, 255,
and 255), . 9.3
Color.
9.3. .

RGB

Color.white

255,255,255

Color.black

0,0,0

Color.lightGray

192,192,192

Color.gray

128,128,128

Color.darkGray

64,64,64

Color.red

255,0,0

Color.green

0,255,0

Color.blue

0,0,255

Color.yellow

255,255,0

Color.magenta

255,0,255

Color.cyan

0,255,255

Color.pink

255,175,175

Color.orange

255,200,0

Color , .
color , .
:
Color c = new Color(140,140,140);

. ,
, . ,
float - 0.0 1.0:
Color c = new Color(0.55,0.55,0.55);

, 209


color ,
color ,
. setColor(), (
Graphics ) :
g.setColor(Color.green);

, .
,
, , setBackground()
setForeground(). java.awt.Component,
. setBackground()
, (
). , Color :
setBackground(Color.white);

setForeground()
, . setForeground()
-
:
setForeground(Color.black);

setColor(), setForeground() setBackground(),


get ,
, . getColor() (
Graphics), getForeground() ( Applet), getBackground() (
Applet).
:
setForeground(g.getColor());


9.4 ,
, .
,
.
9.4. .
1:
2:
3:
4:
5:
6:
7:
8:

import java.awt.Graphics;
import java.awt.Color;
public class ColorBoxes extends java.pplet.pplet {
public void paint(Graphics g) {
int rval, gval, bval;

210
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21: }

-
for (int j = 30; j < (size().height -25); j += 30)
for (int i = 5; i < (size().width -25); i += 30){
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.drawRect(i-1, j-1, 25, 25);
}
}

for ;
, - .
, ,
. ,
.
paint ,
,
( reload). 9.22 ( -,
).

9.22. .

9.5.
, : ,
, , . , ,
, ,
Color .
(
) .
.

, 211

9.6.
:

:
:

, .
drawLine() drawRect(), .
?
Java Graphics , ;
. ,
1 .
.
2 font - , ,
.
drawString() x y ,
" ."
bold ?
Java .
,
. stringWidth()
, ,
.
Java?
Java 1.0.2 JDK, .
Unicode. 1.1 JDK,
Unicode, .
,
- .
, ?
. -
( Math) .
- Random java.util .
,
, .
- ,
.
Web .

. ?
1.1. , ,
.
(
). ,
, .

10. ,
Java : Hi
there! .
" cool".
Java, Java
- ,
,
, . Java
, Java Abstract Windowing Toolkit (awt).
Java:

. , :

Java- paint() repaint();


,

-
awt
, Java

bitmap GIF JPEG -


, Java,


, ,
.

10.1. Java
Java 2 :
, .
, .
- ;
Java .


paint(), ,
-
, , . , Java
.
, "" ,
Java . ,
Java . .

213

? paint(). paint() ,
.. .
paint() , .. ,
. " ",
( paint(), Color, Font
paint()), repaint(). repaint()
paint() .


Java
( ),
Java ,
repaint(), ( paint())
. , repaint() Java
. repaint()
, .
repaint .
, awt repaint() .
.


start() stop() " Java
"? .
start() stop(), ,
. , ,
start() stop() ,
. ,
start() stop() .
start() .
,
. , start()
, . stop(),
, ,
, .
start(),
stop().

:
,
(threads). ( ..
"multithreading" ),
:
.
. Java,

214

start() ,
run().
.


,
.
. 10.1

, (
10.1).

10.1. .
paint(), repaint(), start(), stop().
. ,
. ,
.
10.1. DigitalClock.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
21:
22:
23:
24:
25:
26:

import java.awt.Graphics;
import java.awt.Font;
import java.util.Date;
public class DigitalClock extends java.pplet.pplet
implements Runnable {
Font theFont = new Font("TimesRoman",Font.BOLD,24);
Date theDate;
Thread runner;
public void start() {
if (runner == null) {
runner = new Thread(this);
runner.start();
}
}
public void stop() {
if (runner != null) {
runner.stop();
runner = null;
}
}
public void run() {
while (true) {

215

27:
theDate = new Date();
28:
repaint();
29:
try { Thread.sleep(1000); }
30:
catch (InterruptedException e) { }
31:
}
32:
}
33:
34:
public void paint(Graphics g) {
35:
g.setFont(theFont);
36:
g.drawString(theDate.toString(),10,50);
37:
}
38: }

,
.
7 8 : theFont theDate,
, .
. start() stop() ;
run() ( 25 32).
, , run(). while
( 26); (true) true,
. A while ,
:

Date (Date java.util


- 3). 27
Date, ,
theDate.
repaint() ( 28).
14 15, , ,
1000 (1 )
. sleep(), Thread,
. sleep(),
, .
sleep() . try
catch Java , .
ry catch .. .

paint() 34 37. paint(),


( theFont),
( toString() ).
paint() theDate,
.
. ,
Date paint().
-

216

Date. ,
. paint()
. ,
, paint()
. paint() -
,
. Font
.

10.2. :
? ?
Java .
, .
,
, , .
, . .
, ; , .
,
, , -
. ; ,
, .
;
- .. .
. ,
, ,
. -
. Multithreading ( ) Java,
, ,
. , ,
.
.
.
, .
, ,
. multithreaded ,
,
.
. Ta, ,
, while() .
, while() Java,
, (),
. , while()-
, Java, . , Java
while(), . Java,

217

( )
, .
, ,
. ,
. :
( . ),
.


. ,

. , ,
. 4
:

- implements Runnable.
.
start()
.
stop() .
run() .

. :
public class MyAppletClass extends java.Applet.Applet {
...
}

:
public class MyppletClass extends java.applet.Applet implements
Runnable {
...
}

? Runnable
. "-
Java,"
- ,
. ,
Runnable ;
, default run().
Runnable, Run()
.
. ; Thread
(Thread java.lang, ):
Thread runner;

218

, start() ,
.
start()-:
public void start() {
if (runner == null) {
runner = new Thread(this);
runner.start();
}
}

start() ,
? run(), :
public void run() {
// what your pplet actually does
}

run(), default run(),


Runnable . run()
, start() paint(),
.
run() :

, ,
.
run(), . run()
. , start()
, stop(),
,
. stop(), start(), :
public void stop() {
if (runner != null) {
runner.stop();
runner = null;
}
}

stop() 2 :
runner null. null
Thread ,
.
, start()
. ! ,
.


DigitalClock,
. 10.2 .

219

10.2. DigitalClock, .
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:

import java.awt.Graphics;
import java.awt.Font;
import java.util.Date;
public class DigitalClock extends java.pplet.pplet
implements Runnable {
Font theFont = new Font("TimesRoman",Font.BOLD,24);
Date theDate;
Thread runner;
public void start() {
if (runner == null) {
runner = new Thread(this);
runner.start();
}
}
public void stop() {
if (runner != null) {
runner.stop();
runner = null;
}
}
public void run() {
while (true) {
theDate = new Date();
repaint();
try { Thread.sleep(1000); }
catch (InterruptedException e) { }
}
}
public void paint(Graphics g) {
g.setFont(theFont);
g.drawString(theDate.toString(),10,50);
}
}

.
5 6;

Runnable. -
Runnable.
10 , .. runner
Thread, - . 12 - 23
start() stop() ,
. ,

220

. ,
run()- 25 32, .
while , repaint(),
sleep()-, .

10.3.

, ,
. ( ,
, - ).
; - Java.
,
, .



. repaint(), paint().
. paint() repaint(),
:
1.
2.
3.

repaint() update().
update() (,
), paint().
paint() .

2, update(), .
,
. .
Java :

update() , ..
.
update() paint(), .

, .
,
. - .
: update().

update()
update().
, update(). default
update() ( Component, awt, Applet. ):

221

public void update(Graphics g) {


g.setColor(getBackground());
g.fillRect(0, 0, width, height);
g.setColor(getForeground());
paint(g);
}

, update() (,
), , paint().
update(), update()
. ,
update(), .

. 1:
.
, . .
ColorSwirl ("All the Swirly Colors"),

. . 10.3
, a 10.2 .

10.2.: ColorSwirl.
10.3. ColorSwirl.
1: import java.awt.Graphics;
2: import java.awt.Color;
3: import java.awt.Font;
4:
5: public class ColorSwirl extends java.pplet.pplet
6:
implements Runnable {
7:
8:
Font f = new Font("TimesRoman",Font.BOLD,48);
9:
Color colors[] = new Color[50];
10:
Thread runThread;
11:
12:
public void start() {
13:
if (runThread == null) {
14:
runThread = new Thread(this);
15:
runThread.start();
16:
}
17:
}
18:
19:
public void stop() {
20:
if (runThread != null) {
21:
runThread.stop();
22:
runThread = null;
23:
}
24:
}

222
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52: }

public void run() {


// initialize the color array
float c = 0;
for (int i = 0; i < colors.length; i++) {
colors[i] =
Color.getHSBColor(c, (float)1.0,(float)1.0);
c += .02;
}
// cycle through the colors
int i = 0;
while (true) {
setForeground(colors[i]);
repaint();
i++;
try { Thread.sleep(50); }
catch (InterruptedException e) { }
if (i == colors.length ) i = 0;
}
}
public void paint(Graphics g) {
g.setFont(f);
g.drawString("All the Swirly Colors", 15, 50);
}

3 :

9 Colors,
50 . ,
run() ( 28 34) color
. ,
; ( for
init() ,
). 50 ;
20, 250 .
color , Color,
.. getHSBColor(), RGB .
getHSBColor() color (hue),
(saturation), (brightness), ,
, . HSB ,
hue, saturation brightness,
, RGB .
, ; .
, ,
repaint().

223

, ( 44),
.
, .
- ,
.
, , . - .
,
: update()
. ,
. update(),
paint(). update()
( paint() - 51):
public void update(Graphics g) {
paint(g);
}

2-3 . ?

.2:
, .
, .
. , .. Checkers, ( ,
) , .
10.4 , 10.3 .

10.3. Checkers.
10.4. Checkers.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

import java.awt.Graphics;
import java.awt.Color;
public class Checkers extends java.pplet.pplet
implements Runnable {
Thread runner;
int xpos;
public void start() {

224
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:

-
if (runner == null) {
runner = new Thread(this);
runner.start();
}
}
public void stop() {
if (runner != null) {
runner.stop();
runner = null;
}
}
public void run() {
setBackground(Color.blue);
while (true) {
for (xpos = 5; xpos <= 105; xpos+=4) {
repaint();
try { Thread.sleep(100); }
catch (InterruptedException e) { }
}
xpos = 5;
}
}
public void paint(Graphics g) {
// Draw background
g.setColor(Color.black);
g.fillRect(0, 0, 100, 100);
g.setColor(Color.white);
g.fillRect(101, 0, 100, 100);
// Draw checker
g.setColor(Color.red);
g.fillOval(xpos, 5, 90, 90);
}
}

: ,
xpos, (
, y , x;
y-). run(), x
, 100 .
,
, .
paint() , (
), .

225

, ColorSwirl, . ( 25,
, ,
.) ,
,
, . ,
;
.
? , ,
,
. ,
.
, . ,
, paint(),
- . , ..
(clipping). ,
graphics,
; ,
.



.
,
. ,
( ,
), x-,
- . ,
Checkers
. ,
. ux1 ux2 (u update), ux1
, ux2 - :
int ux1,ux2;

run()
, ( )
. ,
paint() repaint().

repaint() paint().
( . ), paint()
paint() ,
. ,
paint() ( ), Java ,
paint(), .
Checkers.
repaint(),

226

paint() ,

, .. .
repaint() paint(),
- .
,
. ,
paint(), ,
paint() , .
, ,
( ).
, .
run(), .
.
ux1 ( ) x-
(xpos), ux2 e x-
( 90 ). run():
public void run() {
setBackground(Color.blue);
while (true) {
for (xpos = 5; xpos <= 105; xpos += 4) {
repaint();
try { Thread.sleep(100); }
catch (InterruptedException e) { }
}
xpos = 5;
}
}

, ux2 (
):
ux2 = xpos + 90;

- repaint(), ux1 x
. ,
paint, .
paint ? ux1 paint()
( . 0), run() ,
paint():
if (ux1==0) ux1=xpos;

, .
,
, (
, ). ,
ux2 .
ux2; if :

227

if (xpos == 5) ux2=size().width;
else ux2 = xpos+90;

size() ;
size().width ,
. run() :
public void run() {
setBackground(Color.blue);
while (true) {
for (xpos = 5; xpos <= 105; xpos+=4) {
if (xpos == 5) ux2 = size().width;
else ux2 = xpos + 90;
repaint();
try { Thread.sleep(100); }
catch (InterruptedException e) { }
if (ux1 == 0) ux1 = xpos;
}
xpos = 5;
}
}

run().
,
run(), update().
, clipRect(). clipRect(),
drawRect(), fillRect(), clearRect(), Graphics
4 : x y , .
ux1 ux2. ux1 x ;
ux2 ux1 .
y y- ,
( y = 5 95). ,
update(), paint():
public void update(Graphics g) {
g.clipRect(ux1, 5, ux2 - ux1, 95);
paint(g);
}

,
paint() . paint() ,
. ,
paint().
paint(),
paint(). 0 run(), paint()
ux1 ux2 0, :
ux1 = ux2 = 0;

228

,
(
).
, . .
10.5 Checkers (
Checkers2.java).
10.5. Checkers .
1: import java.awt.Graphics;
2: import java.awt.Color;
3:
4: public class Checkers2 extends java.pplet.pplet implements
Runnable {
5:
6:
Thread runner;
7:
int xpos;
8:
int ux1,ux2;
9:
10:
public void start() {
11:
if (runner == null) {
12:
runner = new Thread(this);
13:
runner.start();
14:
}
15:
}
16:
17:
public void stop() {
18:
if (runner != null) {
19:
runner.stop();
20:
runner = null;
21:
}
22:
}
23:
24:
public void run() {
25:
setBackground(Color.blue);
26:
while (true) {
27:
for (xpos = 5; xpos <= 105; xpos+=4) {
28:
if (xpos == 5) ux2 = size().width;
29:
else ux2 = xpos + 90;
30:
repaint();
31:
try { Thread.sleep(100); }
32:
catch (InterruptedException e) { }
33:
if (ux1 == 0) ux1 = xpos;
34:
}
35:
xpos = 5;
36:
}
37:
}
38:
39:
public void update(Graphics g) {
40:
g.clipRect(ux1, 5, ux2 - ux1, 95);
41:
paint(g);
42:
}
43:
44:
public void paint(Graphics g) {

,
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58: }

229

// Draw background
g.setColor(Color.black);
g.fillRect(0, 0, 100, 100);
g.setColor(Color.white);
g.fillRect(101, 0, 100, 100);
// Draw checker
g.setColor(Color.red);
g.fillOval(xpos, 5, 90, 90);
// reset the drawing area
ux1 = ux2 = 0;
}

10.4.
Java . Image
java.awt, ,
Applet Graphics
,
. ,
Java .


,
Java .
, . Applet
getImage(),
Image. ,
java.awt.Image Java , getImage
URL- .
:
getImage() ( URL)
URL.
getImage() 2 : - URL (URL object)
( ).
( URL URL object),
. , Java ,
URL , ,
Java files. ,
. Applet 2
URL getImage():

getDocumentBase()- URL object


HTML . ., HTML

230

http://www.myserver.com/htmlfiles/javahtml,
getDocumentBase() URL .
getCodeBase(),
- ,
HTML , CODEBASE <APPLET>
.

getDocumentBase() getCodebase(),
HTML , Java
class files. .
URL,
getImage(); getDocumentBase() getCodeBase()
HTML files , Java
. ( , class
. , class files
, ).
getImage, .
getImage() URL (http://www.server.com/
files/sliki.gif). URL ,
Java applet :
Image img = getImage(
new URL("http://www.server.com/files/image.gif"));

getImage, image.gif
HTML :
Image img = getImage(getDocumentBase(), "image.gif")

, image.gif :
Image img = getImage(getCodeBase(), "image.gif")

, .
getImage() image.gif images, Java
:
Image img = getImage(getCodeBase(), "images/image.gif")

getImage() , null. drawImage()


null . null
.

, Java GIF JPEG .


; GIF JPEG.


getImage()
Image. , .

231


, .
getImage(),
Image object.
.
,
, ..
( ).

( ., , ),
ImageObserver.
ImageObserver " ."
.
Graphics ,
drawImage(). drawImage() 4 :
, x y this:
public void paint() {
g.drawImage(img, 10, 10, this);
}

:
, x - y . 10.6
, ladybug.gif
. 10.4. .

10.4. .
10.6. LadyBug.
1: import java.awt.Graphics;
2: import java.awt.Image;
3:

232

4: public class LadyBug extends java.applet.Applet {


5:
6:
Image bugimg;
7:
8:
public void init() {
9:
bugimg = getImage(getCodeBase(),
10:
"images/ladybug.gif");
11:
}
12:
13:
public void paint(Graphics g) {
14:
g.drawImage(bugimg, 10, 10,this);
15:
}
16: }

bugimg
(Ladybug), init(). paint()
.
drawImage() 6 : , x y
, this.
-
.
,
( , , ..
).

,
. Image
: getWidth() getHeight(). ,
ImageObserver,
( ). , this
getWidth() getHeight().
ladybug bugimg,
, pixels:
theWidth = bugimg.getWidth(this);



. getWidth() getHeight()
, -1.

.
10.7 ladybug,
( 10.5 ).

10.5. Lady bug .


10.7. ladybugs, .
1: import java.awt.Graphics;
2: import java.awt.Image;
3:
4: public class LadyBug2 extends java.applet.Applet {
5:
6:
Image bugimg;
7:
8:
public void init() {
9:
bugimg = getImage(getCodeBase(),
10:
"images/ladybug.gif");
11:
}
12:
13:
public void paint(Graphics g) {
14:
int iwidth = bugimg.getWidth(this);
15:
int iheight = bugimg.getHeight(this);
16:
int xpos = 10;
17:
18:
// 25 %
19:
g.drawImage(bugimg, xpos, 10,
20:
iwidth / 4, iheight / 4, this);
21:
22:
// 50 %
23:
xpos += (iwidth / 4) + 10;
24:
g.drawImage(bugimg, xpos , 10,
25:
iwidth / 2, iheight / 2, this);
26:
27:
// 100%
28:
xpos += (iwidth / 2) + 10;
29:
g.drawImage(bugimg, xpos, 10, this);
30:

233

234
31:
32:
33:
34:
35: }

// 150% x, 25% y
g.drawImage(bugimg, 10, iheight + 30,
(int)(iwidth * 1.5), iheight / 4, this);


drawImage():
this, getWidth() getHeight().
?
ImageObserver (..,
ImageObserver).

. .,
, "loading", .. .
Applet, , default
( Component),
this drawImage(),
getWidth(), getHeight().
,
,
.


,
java.awt.image
, bitmap .
, .. .

10.5.

,
.
, paint.
, .
Neko.

Neko
Neko Macintosh, Kenji Gotoh 1989.
"Neko" ","
, , , . Neko
, screensaver. ,

235

, Neko .
Neko, ( ""
), Neko
, , , , ,
.

:
,
. ,
, start stop,
run() . .

1:
Java ,
. Neko 9
( 36), 10.6.

10.6. Neko.
, images.
, ,
.

2:
.
, ,
. Java,
Image, .
( for ),
. Neko,
2 : , ..
nekopics, Image, .. currentimg,
:
Image nekopics[] = new Image[9];
Image currentimg;

9 , Neko 9 .
, .
Neko ,
x y ,
. y (Neko -), x
. :

236

int xpos;
int ypos = 50;


java.util class (HashTable)
hash . , hash
.
,
, .
, . ,
nekopics.
init(). 9 9 ,
getImage() . ,
file (nekosrc, array of strings), a
for . init()
Neko nekopics:
public void init() {
String nekosrc[] = { "right1.gif", "right2.gif",
"stop.gif", "yawn.gif", "scratch1.gif",
"scratch2.gif","sleep1.gif", "sleep2.gif",
"awake.gif" };
for (int i=0; i < nekopics.length; i++) {
nekopics[i] = getImage(getCodeBase(),
"images/" + nekosrc[i]);
}
}

getImage()
( Image) .

3:
, .
run(). , Neko 5 :


, ,
Neko .
, .. (. Neko),
.

237

Neko .
. nekorun(), 2
: x , x . Neko
(y ).
void nekorun(int start, int end) {
...
}

Neko ;
, ( 0 1
), . for-
start end, x-
.
, . ,
, repaint() sleep()
. ,
- . pause(),
- . :
void pause(int time) {
try { Thread.sleep(time); }
catch (InterruptedException e) { }
}

nekorun(). , nekorun()
start end. ,
x , currentimg ,
repaint(), . ? nekorun:
void nekorun(int start, int end) {
for (int i = start; i < end; i+=10) {
xpos = i;
// swap images
if (currentimg == nekopics[0])
currentimg = nekopics[1];
else currentimg = nekopics[0];
repaint();
pause(150);
}
}

10 . 10, 5
8? .
. ,

.

238

repaint(), paint(),
. paint() ; paint()
x - y .
. ,
, ( ).
, currentimg null, drawImage()
:
public void paint(Graphics g) {
if (currentimg != null)
g.drawImage(currentimg, xpos, ypos, this);
}

run(), .
nekorun() ; run()
Neko :
// run from one side of the screen to the middle
nekorun(0, size().width / 2);

Neko .
( 2 3 ),
. ,
repaint(), .
; .
:
// stop and pause
currentimg = nekopics[2];
repaint();
pause(1000);
// yawn
currentimg = nekopics[3];
repaint();
pause(1000);

: Neko .
. (
4 5 ). , ,
.
nekoscratch() : .
, ,
, repaint:
void nekoscratch(int numtimes) {
for (int i = numtimes; i > 0; i--) {
currentimg = nekopics[4];
repaint();

239

pause(150);
currentimg = nekopics[5];
repaint();
pause(150);
}
}

run, nekoscratch() (4):


// scratch four times
nekoscratch(4);

- , Neko . 2
( 6 7 ), . nekosleep()
, , :
void nekosleep(int numtimes) {
for (int i = numtimes; i > 0; i--) {
currentimg = nekopics[6];
repaint();
pause(250);
currentimg = nekopics[7];
repaint();
pause(250);
}
}

nekosleep() run():
// sleep for 5 "turns"
nekosleep(5);

, , Neko .
( 8),
nekorun:
// wake up and run off
currentimg = nekopics[8];
repaint();
pause(500);
nekorun(xpos, size().width + 10);

4:
.
. default (),
.
, run() :
setBackground(Color.white);

? ,
, . ,
, repaint()
. .
, ,

240

.
, .
, 10.8. Neko.
10.8. The final Neko applet.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Color;
public class Neko extends java.applet.Applet
implements Runnable {
Image nekopics[] = new Image[9];
Image currentimg;
Thread runner;
int xpos;
int ypos = 50;
public void init() {
String nekosrc[] = { "right1.gif", "right2.gif",
"stop.gif", "yawn.gif", "scratch1.gif",
"scratch2.gif","sleep1.gif", "sleep2.gif",
"awake.gif" };
for (int i=0; i < nekopics.length; i++) {
nekopics[i] = getImage(getCodeBase(),
"images/" + nekosrc[i]);
}
}
public void start() {
if (runner == null) {
runner = new Thread(this);
runner.start();
}
}
public void stop() {
if (runner != null) {
runner.stop();
runner = null;
}
}
public void run() {
setBackground(Color.white);
// run from one side of the screen to the middle
nekorun(0, size().width / 2);
// stop and pause
currentimg = nekopics[2];
repaint();

,
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:

pause(1000);
// yawn
currentimg = nekopics[3];
repaint();
pause(1000);
// scratch four times
nekoscratch(4);
// sleep for 5 "turns"
nekosleep(5);
// wake up and run off
currentimg = nekopics[8];
repaint();
pause(500);
nekorun(xpos, size().width + 10);
}
void nekorun(int start, int end) {
for (int i = start; i < end; i += 10) {
xpos = i;
// swap images
if (currentimg == nekopics[0])
currentimg = nekopics[1];
else currentimg = nekopics[0];
repaint();
pause(150);
}
}
void nekoscratch(int numtimes) {
for (int i = numtimes; i > 0; i--) {
currentimg = nekopics[4];
repaint();
pause(150);
currentimg = nekopics[5];
repaint();
pause(150);
}
}
void nekosleep(int numtimes) {
for (int i = numtimes; i > 0; i--) {
currentimg = nekopics[6];
repaint();
pause(250);
currentimg = nekopics[7];
repaint();
pause(250);
}
void pause(int time) {
try { Thread.sleep(time); }

241

242

104:
105:
106:
107:
108:
109:
110:
111: }

catch (InterruptedException e) { }
}
public void paint(Graphics g) {
if (currentimg != null)
g.drawImage(currentimg, xpos, ypos, this);
}

10.6.

, . , , ,
Applet awt, Java
.
, Java Sun- AU ,
.. -law . AU ,
. ,
HTML (
), Java .
play(),
Applet . play()
getImage() :

play() , URL object, audio clip


URL.

play() , URL , audio


file. getDocumentBase()
getCodeBase().

, meow.au,
audio. audio, :
play(getCodeBase(), "audio/meow.au");

play() , .
, ;
. ,
, (play );
- . ,
getAudioClip() AudioClip (
java.applet - ),
AudioClip.
.
, :
AudioClip clip = getAudioClip(getCodeBase(),
"audio/loop.au");

243

, play():
clip.play();

, stop():
clip.stop();

, loop():
clip.loop();

getAudioClip() ,
, null.
, play(), stop(), loop() null object
(.. ). ,
; .

.
,
.
stop():
public void stop() {
if (runner != null) {
if (bgsound != null)
bgsound.stop();
runner.stop();
runner = null;
}
}

10.9. 2 : ,
loop.au, . , (beep.au),
5 . ( ,
).
10.9. AudioLoop.
1: import java.awt.Graphics;
2: import java.applet.AudioClip;
3:
4: public class AudioLoop extends java.applet.Applet
5: implements Runnable {
6:
7:
AudioClip bgsound;
8:
AudioClip beep;
9:
Thread runner;
10:
11:
public void start() {
12:
if (runner == null) {
13:
runner = new Thread(this);
14:
runner.start();
15:
}

244
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43: }

-
}
public void stop() {
if (runner != null) {
if (bgsound != null) bgsound.stop();
runner.stop();
runner = null;
}
}
public void init() {
bgsound = getAudioClip(getCodeBase(),"audio/loop.au");
beep = getAudioClip(getCodeBase(), "audio/beep.au");
}
public void run() {
if (bgsound != null) bgsound.loop();
while (runner != null) {
try { Thread.sleep(5000); }
catch (InterruptedException e) { }
if (beep != null) beep.play();
}
}
public void paint(Graphics g) {
g.drawString("Playing Sounds....", 10, 10);
}

. , init()
26 - 29, loop.au the beep.au.
, bgsound
beep null, .
, loop(), stop(), ,
. null
, run()- 32 36.
, bgsound
beep null. , 20,
.
, .

10.7.

. ,
.
, :
.
, (.. offscreen), ,
;
.

245

,
.
(offscreen) ,
. ,
.
. ,
update() ;
.
,
. , ,
.


,
: offscreen , .
: (
Graphics) , drawImage ( drawString),
Image .
4 . ,
offscreen
paint() .
:
Image offscreenImage;
Graphics offscreenGraphics;

, , Image
Graphics ( ,
). createImage()
Image, getGraphics(),
:
offscreenImage = createImage(size().width,
size().height);
offscreenGraphics = offscreenImage.getGraphics();

, ( paint() ), offscreen
. , img 10,10, :
offscreenGraphics.drawImage(img, 10, 10, this);

, paint(), offscreen
, offscreen
buffer- :
g.drawImage(offscreenImage, 0, 0, this);

, update(),
:

246

public void update(Graphics g) {


paint(g);
}

4 :
1.
2.
3.
4.


offscreen buffer-.
.
offscreen buffer,
.
paint() , offscreen buffer-
.


,
,
. awt
; Java garbage collector
. ,
.

dispose(). destroy() (

" "; ,
init(), start(), stop()):
public void destroy() {
offscreenGraphics.dispose();
}

Checkers -

.
- Checkers .
.
, (offscreen)
:
Image offscreenImg;
Graphics offscreenG;

, init offscreen buffer-:


public void init() {
offscreenImg = createImage(size().width, size().height);
offscreenG = offscreenImg.getGraphics();

247

, paint() ,
:
public void paint(Graphics g) {
// Draw background
offscreenG.setColor(Color.black);
offscreenG.fillRect(0, 0, 100, 100);
offscreenG.setColor(Color.white);
offscreenG.fillRect(100, 0, 100, 100);
// Draw checker
offscreenG.setColor(Color.red);
offscreenG.fillOval(xpos, 5, 90, 90);
g.drawImage(offscreenImg, 0, 0, this);
}


update(), ; .
paint(), offscreen
. , destroy(),
offscreenG:
public void destroy() {
offscreenG.dispose();
}

10.10.
(Checkers3.java), .

Checkers

10.10. Checkers, .
1:
2:
3:
4:
5:

import java.awt.Graphics;
import java.awt.Color;
import java.awt.Image;
public class Checkers3 extends java.applet.Applet implements
Runnable {

6:
7:
Thread runner;
8:
int xpos;
9:
int ux1,ux2;
10:
Image offscreenImg;
11:
Graphics offscreenG;
12:
13:
public void init() {
14:offscreenImg=createImage(this.size().width,this.size().height);
15:
offscreenG = offscreenImg.getGraphics();
16:
}
17:
18:
public void start() {
19:
if (runner == null); {

248
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72: }

-
runner = new Thread(this);
runner.start();
}

public void stop() {


if (runner != null) {
runner.stop();
runner = null;
}
}
public void run() {
setBackground(Color.blue);
while (true) {
for (xpos = 5; xpos <= 105; xpos+=4) {
if (xpos == 5) ux2 = size().width;
else ux2 = xpos + 90;
repaint();
try { Thread.sleep(100); }
catch (InterruptedException e) { }
if (ux1 == 0) ux1 = xpos;
}
xpos = 5;
}
}
public void update(Graphics g) {
g.clipRect(ux1, 5, ux2 - ux1, 95);
paint(g);
}
public void paint(Graphics g) {
// Draw background
offscreenG.setColor(Color.black);
offscreenG.fillRect(0,0,100,100);
offscreenG.setColor(Color.white);
offscreenG.fillRect(100,0,100,100);
// Draw checker
offscreenG.setColor(Color.red);
offscreenG.fillOval(xpos,5,90,90);
g.drawImage(offscreenImg,0,0,this);
// reset the drawing area
ux1 = ux2 = 0;
}
public void destroy() {
offscreenG.dispose();
}

249

10.8.
!
.
-start(), stop(), paint(), repaint(), run(), update();
.
bitmap ,
Java. , ,
, .
,
, .

10.9.
:

:
:

:
:

:
:

paint(), repaint(), update(), .?


paint()
?
Java awt .
paint(), , , .
, .
.
, -
.
?
,
, Java .
.
,
, ? ?
.? ?
. , Java
. ,
, .
, . , ?
ColorSwirl 5 6 ,
. ?
.
. upgrad ,
.
, Checkers .
.
, . ,
,

250

-
. ,
.. .
Neko, init().
Java ,
init() , .
run()?
. getImage()
; , Image object ,
.
getImage() ,
. , Java
, , ..
, .

getAudioClip() loop(). , .
, .

, , .
,
:
runner.stop() //stop the thread
bgsound.stop() //also stop the sound
,
?
, .
, .
,
paint(). paint(),
. -
.

11.
Apple- Macintosh Microsoft- Windows
,
(GUI),
. ,
, .
,
.
.
, Abstract Windowing Toolkit,

.
. 1.2,
browser-.

. awt,
,
.
Abstract Windowing Toolkit-,
1.2 .

11.1. Abstract Windowing Toolkit


Abstract Windowing Toolkit, AWT,

.
, AWT ,
.


AWT,
. ,
Netscape, Microsoft browser-,
AWT-
.
browser-.
AWT, :

. ,
, ,
, , .

252

. .
,
, , .
(Layaout managers).
.
,
.

AWT- java.awt.
,
:
import java.awt.* ;

, ,
.
import .
AWT-, ,
. AWT, ,
.

11.2.
,
. ,
.
, - .

11.1. AWT.

, Applet .

253

.
add() .

, add() , Applet. AWT-


, ,
.
Button
. ,
-, :
Button panic = new Button (Panic!);

Button- Panic!.
, ,
add()- .
, panic- Applet-,
:
add (panic);

.
, paint().
, paint()-
repaint()-.
, x y
.
, , .

.
,
, ,
. flow layout,
FlowLayout-.
,
, init().
, 11.1. A Slacker button-
Applet- . paint(), Applet.
11.1. slacker.java.
1: import java.awt.*;
2:
3: public class Slacker extends java.applet.Applet {
4: String note = I am extremely tired;
5: button tired = new Button(note);

254

6:
7: public void init() {
8:
add(tired);
9: }
10: }

, <APPLET> :
<applet code=Slacker.class width=550 height=75>
</applet>

,
Label.

.
drawstring()
, :

,
paint()-.
-,
x y, .
, :
Label(), .
Label (String), -,
.
Label (String, int), - ,
int. -
: Label.RIGHT, Label.LEFT, Label.
CENTER.
setFont().
, (.. ),
.
setText(String)
, . , String,
.
getText() .
11.2
Helvetica Bold .
11.2. Labels.java
1: import java.awt.*;
2:
3: public class Labels extends java.applet.Applet {

255

4:
5: public void init() {
6:
setFont(new Font ("Helvetica", Font.BOLD, 14));
7:
setLayout(new GridLayout(3,1));
8:
add(new Label("aligned left", Label.LEFT));
9:
add(new Label("aligned center", Label.CENTER));
10:
add(new Label("aligned right", Label.RIGHT));
11: }
12: }

<APPLET> :
<applet code=Labels.class height=150 width=175>
</applet>

11.2 appletviewer-.
, ,
.
lligned right Applet ,
alligned center .

11.2. Labels
7 GridLayout-,
.

, flow layout. 7
, .


Button, Slacker.
, . Quit
.
, :

Button(), ,

Button (String), - .

256

Button-,
setLabel(String),
getLabel()-.
11.3
.
11.3. ButtonTest.java
1: import java.awt.*;
2:
3: public class ButtonTest extends java.applet.Applet {
4:
5: public void init() {
6:
add(new Button("Rewind"));
7:
add(new Button("Play"));
8:
add(new Button("Fast Forward"));
9:
add(new Button("Stop"));
10: }
11:}

HTML:
<applet code=ButtonTest.class height=60 width=300>
</applet>

11.3 appletviewer-. A
- . Mo
Applet- 500, 300 .

11.3. ButtonTest

Check box
Check box-
: () .
,
Disable Sound Password Protected
Windows- screen saver.

257

Check box- ,
, .
,
. -,
, .
Checkbox .
e e check box,
:

Checkbox() - check box, .


Checkbox(String) - check box, String-
.

Checkbox,
setState(Boolean), box,
, box . getState()
, check box-.
11.4. check box-,
. ,
.
11.4. checkboxTest.html
1: import java.awt.*;
2:
3: public class CheckboxTest extends java.applet.Applet {
4:
5: public void init() {
6:
setLayout(new FlowLayout(FlowLayout.LEFT));
7:
add(new Checkbox("Shoes"));
8:
add(new Checkbox("Socks"));
9:
add(new Checkbox("Pants"));
10:
add(new Checkbox("Underwear", null, true));
11:
add(new Checkbox("Shirt"));
12: }
13: }

11.4 ,
<APPLET> :
<applet code=CheckboxTest.class height=200 width=150>
</applet>

check box- ,
, CheckboxGroup,
:
CheckboxGroup radio = new CheckboxGroup() ;

CheckboxGroup check box- .


Checkbox-.

258

11.4. CheckboxTest
Checkbox(String, CheckboxGroup, boolean) check box,
- CheckboxGroup. true,
Checkbox- , - false.
setCurrent(Checkbox)
check box . getCurrent(),
check box.

1.2, Checkbox(String, CheckboxGroup, boolean)


, .. Checkbox(String, boolean,
CheckboxGroup). ,
. .
check box-:
CheckboxGroup betterDarrin = new CheckboxGroup() ;
Checkbox r1 = new Checkbox (Dick York, betterDarrin, true) ;
Checkbox r2 = new Checkbox (Dick Sargent, betterDarrin, false);

betterDarrin check box- r1


r2. r1, Dick York.
,
r1 r2.
Radio button- check box-,
. radio button-,
CheckboxGroup:
CheckboxGroup cbg = new CheckboxGroup();

check box- 3
( , , check box
). radio button-, ,
, true , default:

259

add(new Checkbox("Yes", cbg, true);


add(new Checkbox("No", cbg, false);

11.5. CheckboxGroupTest.java
1: import java.awt.*;
2:
3: public class CheckboxGroupTest extends java.applet.Applet {
4:
5: public void init() {
6:
setLayout(new FlowLayout(FlowLayout.LEFT));
7:
CheckboxGroup cbg = new CheckboxGroup();
8:
9:
add(new Checkbox("Red", cbg, false));
10:
add(new Checkbox("Blue", cbg, false));
11:
add(new Checkbox("Yellow", cbg, false));
12:
add(new Checkbox("Green", cbg, true));
13:
add(new Checkbox("Orange", cbg, false));
14:
add(new Checkbox("Purple", cbg, false));
15: }
16:}

<APPLET> , web
, 11.5:
<applet code= CheckboxGroupTest.class height=200 width=150>
</applet>

11.5. CheckboxGroupTest

11.6.


, Choice ,
.
World Wide
Web. 11.6. .

ChoiceTest .

260

Choice-
, :
Choice fruit = new Choice();

addItem(String)-
. :
fruit.addItem (apples);
fruit.addItem (oranges);

addItem(),
.

addItem(String) 1.02.
- add(String),
.
, ,
- add(),
.
11.6 . ChoiceTest
o, .
11.6. ChoiceTest.java
1: import java.awt.*;
2:
3: public class ChoiceTest extends java.applet.Applet {
4:
5: public void init() {
6:
Choice c = new Choice();
7:
8:
c.addItem("Apples");
9:
c.addItem("Oranges");
10:
c.addItem("Strawberries");
11:
c.addItem("Blueberries");
12:
c.addItem("Bananas");
13:
14:
add(c);
15: }
16: }

HTML-,
11.6.
<applet code=ChoiceTest.class height=200 width=150>
</applet>

261

Choice-
:

GetItem()-
, . ,
0, 1
.
CountItems()- .
1.02, getItemCount(),
.
GetSelectedIndex()-
.
GetSelectedItem()-
.
Select(int)- .
Select(String)-
.


,
. -
. TextField.
, :

TextField(), , .
TextField(int),
. ,
TextField (String, int).
TextField(String),
.
TextField(String, int), .
,
, ,
FlowLayout.
.
, 30 :
TextField name = new textField (30) ;


Puddin N. Tane:
TextField name = new TextField(Puddin N. Tane, 30) ;

262

,
, . Enter Password
, .
, setEchoCharacter
(char) TextField. (
setEchoChar(char)). ,
, *.
String .
(#),
:
TextField passkey = new TextField(16) ;
passkey.setEchoCharacter(#) ;

11.7 .
,
.
.
11.7. TextfieldTest.java
1: import java.awt.*;
2:
3: public class TextfieldTest extends java.applet.Applet {
4:
5: public void init(){
6: add(new Label("Enter your Name"));
7: add(new TextField("your name here", 45));
8: add(new Label("Enter your phone number"));
9: add(new TextField(12));
10: add(new Label("Enter your password"));
11: TextField t = new TextField(20);
12: t.setEchoCharacter('*');
13: add(t);
14: }
15:}

<APPLET> :
<applet code=Textfieldtest.class width=350 height=125>
</applet>

,
,
. ,
applet-,
11.7. (
, ).

263

11.7. xtfieldTest
textField
:
getText() .
setText() .
setEditable (boolean) .
False , True
( default).
isEditable()
(true) (false).


, TextArea ,
,
.
,
.
,
:

TextArea(), .
TextArea(int, int),
( ),
( ).
TextArea(String),
.
TextArea(String, int, int),
, ( )
( ).
11.8 ,
.

264

11.8. TextAreaTest.java
1: import java.awt.*;
2:
3: public class TextAreaTest extends java.applet.Applet {
4:
5: public void init() {
6: String str = "Once upon a midnight dreary, while I pondered,
weak and 7: weary,\n" +
8: "Over many a quaint and curious volume of forgotten lore,\n" +
9: "While I nodded, nearly napping, suddenly there came a
tapping,\n" +
10: "As of some one gently rapping, rapping at my chamber door.\n"
+
11: "\"'Tis some visitor,\" I muttered, \"tapping at my chamber
door-\n" +
12: "Only this, and nothing more.\"\n\n";
13: // more text deleted for space
14:
15:
add(new TextArea(str,10,50));
16: }
17: }

TextAreaTest HTML-:
<applet code= TextAreaTest.class height=250 width=450>
</applet>

appletviewer, 11.8.

11.8. TextAreaTest
-, , TextComponent,
,
. , ,
setText(), getText(), setEditable() isEditable() , ,
:

265

InsertText(String, int)-, -
, . 0
. 1.02
insert(String, int).
ReplaceText(String, int, int)-,
, , -.
1.02,
replace(String, int).


, List,
, :

,
.
(popup) . ,
,
.
,
.

List,
. List :

List() - ,
.
List (int, boolean) -
, .
,
(true) (false).
List, addItem(),
. (: , 1.2 -
add(String)).
, :
List lackeys = new List() ;
lackeys.addItem (Rosencrantz) ;
lackeys.addItem (Guidenstern) ;

,
, add()-. 11.9
.
11.9. ListsTest.java
1: import java.awt.*;
2:
3: public class ListsTest extends java.applet.Applet {
4:

266

5: public void init() {


6:
List lst = new List(5, true);
7:
8:
lst.addItem("Hamlet");
9:
lst.addItem("Claudius");
10:
lst.addItem("Gertrude");
11:
lst.addItem("Polonius");
12:
lst.addItem("Horatio");
13:
lst.addItem("Laertes");
14:
lst.addItem("Ophelia");
15:
16:
add(lst);
17: }
18: }

11.9; -:
<applet code=ListsTest.class height=150 width=200>
</applet>

11.9. ListsTest

: getItem(int), countItems(), getSelectedIndex(),
getSelectedItem(), select(int) . CountItems()
1.2: getItemCount().
scrolling ,
:

getSelectedIndexes()-, ,
.
getSelectedItems()-,
.

(sliders and scrolbars)


(sliders)
.

267

,
. ,
, Scrollbar .
,
.
, :

Scrollbar(),
0.
Scrollbar(int),
= 0 . -
, : Scrollbar.
HORIZONTAL Scrollbar.VERTICAL.

, , :
Scrollbar (int, int, int, int, int). :

Scrollbar.HORIZONTAL Scrollbar.VERTICAL.
, ,
.
scrollbar box-.
0, default ( ) .
.
.

11.10 scrollbar. O
GridLayout setLayout(),
.
.
11.10. scrollbar.java
1: import java.awt.*;
2:
3: public class SliderTest extends java.applet.Applet {
4: Label l;
5:
6: public void init() {
7:
setLayout(new GridLayout(1,2));
8:
l = new Label("0", Label.CENTER);
9:
add(l);
10:
add(new Scrollbar(Scrollbar.HORIZONTAL,0,0,1,100));
11: }
12:
13: public Insets insets() {
14:
return new Insets(15,15,15,15);
15: }
16:
17: public boolean handleEvent(Event evt) {
18:
if (evt.target instanceof Scrollbar) {
19:
int v = ((Scrollbar)evt.target).getValue();
20:
l.setText(String.valueOf(v));

268

21:
repaint();
22:
return true;
23:
} else return false;
24: }
25: }

, Applet
, (scrollbar box-)
. 11.10 :
<applet code=Scrollbar.class height=20 width=500>
</applet>

Scrollbar- ,
:

getValue()
(scrollbar).
setValue (int) .

11.10. Scrollbar

,
, .
, ,
.
, Canvas.
, paint()-.
canvas , ,
Canvas- .
Crosshair, 11.11.
Applet ,
,
.
11.11. crosshair.java

269

1: import java.awt.*;
2:
3: public class Crosshair extends java.applet.Applet {
4: GridLayout g1 = new GridLayout(1,1);
5: MyCanvas can=new MyCanvas();
6:
7: public void init() {
8:
setLayout(g1);
9:
add(can);
10: }
11:
12: }
13:
14: class MyCanvas extends java.awt.Canvas{
15: public void paint(Graphics g){
16: int x=size().width/2;
17: int y= size().height/2;
18: g.setColor(Color.black);
19: g.drawline(x-10,y,x-2,y);
20: g.drawline(x+10,y,x+2,y);
21: g.drawline(x,y-10,x,y-2);
22: g.drawline(x,y+10,x,y+2);
23: }
24: }

Crosshair .
<APPLET> :
<applet code=Crosshair.class height=100 width=100>
</applet>

11.11 . , Crosshair, .
, 14-24, MyCanvas ,
Canvas:
Crosshair- :

4 GridLayout ,
8.
5 MyCanvas can,
Canvas 14-24.
9 can Applet-.
, canvas- , .
MyCanvas, ..
. :

16 17 Applet-.
, .
size().width size().height
, 2 -

270

. ,
getSize().width getSize().height.
18 .
Graphics-,
. Graphics- paint(),
.
19-22 x, y ,
. 8
2 .

11.3.
,
-
Abstract Windowing Toolkit-.
, , .

. Applet ,
add()- .
.

:
- -
.
- .

11.4.
:
:

Abstract Windowing Toolkit-,


1.02?
, ,
1.2 1.5. , browser-
1.02, , 1.02
. Sun ,
, ,
- .


, ,
. Abstract Windowing Toolkit?

, Abstract Windowing Toolkit-
. , AWT-
, .
, .

12.

, :
.
,
. ,
Abstract Windowing Toolkit-,
(layout managers).
-
, .
,
, .
,
, .
.

12.1.
,
Abstarct windowing toolkit-,
.
,
, . ,
. ,
, .
Microsoft Visual Basic,
x,y .
,
. Abstract
windowing toolkit,
, .



. FlowLayout
.
AWT : FlowLayout, GridLayout,
BorderLayout, CardLayout GridBagLayout.
, :
FlowLayout flo = new FlowLayout() ;

,
setLayout()- .

272

.
, float layout.

setLayout(),
Applet :
public class Starter extends java.applet.Applet
FlowLayout 1m = new FlowLayout() ;

public void init() {


setLayout (1m) ;
}
}

,
. ,
FlowLayout, , .
,
.

Flow layout
FlowLayout .

, , .
default, ,
FlowLayout() .
,
FloatLayout.LEFT FlowLayout.
RIGHT, :
FlowLayout righty = new FlowLayout (FlowLayout.RIGHT);

FlowLayout.CENTER
.
12.1
flow-. FlowLayout()
FlowLayout.LEFT - ,
.
12.1. FlowLayoutTest.java
1: import java.awt.*;
2:
3: public class FlowLayoutTest extends java.applet.Applet {
4:
5: public void init() {
6:
setLayout(new FlowLayout());
7:
add(new Button("One"));


8:
add(new
9:
add(new
10:
add(new
11:
add(new
12:
add(new
13: }
14: }

273

Button("Two"));
Button("Three"));
Button("Four"));
Button("Five"));
Button("Six"));

12.1 appletviewer-,
<APPLET> :
<applet code=FlowLayoutTest.class height=120 width=220>
</applet>

12.1.
FlowLayoutTest , flow-
. ,

FlowLayout()-.
FlowLayout (int, int, int) ,
:

, FlowLayout.CENTER, FlowLayout.LEFT
FlowLayout.RIGHT.
, .
, .

flow-
, 30 , 10:
FlowLayout flo = new FlowLayout (FlowLayout.CENTER, 30, 10);



. ,
.
,
, .

274

() GridLayout .
GridLayout
. 10
3 :
GridLayout

gr = new

GridLayout (10, 3) ;

flow-,
.
10 , 3 ,
5 , 8 :
GridLayout g2r = new GridLayout(10, 3, 5, 8);

Default 0 ,
, .
12.2 3 , 2 ,
10 , 30 .
12.2. GridLayoutTest.java
1: import java.awt.*;
2:
3: public class GridLayoutTest extends java.applet.Applet {
4:
5: public void init() {
6:
setLayout(new GridLayout(3, 3, 10, 30));
7:
add(new Button("One"));
8:
add(new Button("Two"));
9:
add(new Button("Three"));
10:
add(new Button("Four"));
11:
add(new Button("Five"));
12:
add(new Button("Six"));
13: }
14: }

12.2 <APPLET> :
<applet code= GridLayoutTest.class height=160 width=160>
</applet>

12.2. 3x2

275

12.2,
.
flow- .
,
. GridLayoutTest- appletviewer
,
Applet .

Border
Border , BorderLayout ,
: , , , .
12.3, .

12.3. border
border ,
.
,
.
Border BorderLayout() BorderLayout(int, int) . border .
,
.
,
add()- :
add (String, component)


. -
. 5 : North,
South, East, West, Center.
quitButton :
add (North, quitButton) ;

276

12.3 12.3.
12.3. borderTest.java
1: import java.awt.*;
2:
3: public class BorderTest extends java.applet.Applet {
4:
5: public void init() {
6:
setLayout(new BorderLayout());
7:
add("North", new Button("One"));
8:
add("East", new Button("Two"));
9:
add("South", new Button("Three"));
10:
add("West", new Button("Four"));
11:
add("Center", new Button("Five"));
12:
add(new Button("Six"));
13: }
14: }

<APPLET> :
<applet code=BorderTest.class height=120 width=120>
</applet>

12.2.
, Abstract Windowing Toolkit
. ,
:
! ! !
,
.
, .. Applet ,
.
,
Panel. ,
.
:
,
.
.
Panel,
:
Panel pane = new Panel() ;

277

setLayout()- .
setLayout()-
Applet Panel Container ,

. border a
Panel- pane ():
BorderLayout bo = new BorderLayout() ;
pane.setLayout(bo) ;

add() ,
, . .
dialogue,
pane ():
pane.add(dialogue) ;

12.3.
flow, grid border
Abstract Windowing Toolkit-
: ,
,
.


,
,
.
card ().
HyperCard Macintosh,
System Properties Windows 95/98/2000/XP,
.
,
. ,
, .
CardLayout,
:
CardLayout

cc = new CardLayout() ;

setLayout() ,
:

278

setLayout(cc) ;


, add()-
.
add (String, container).
.
, ,
.
add()-
. .
, ..
, : Card 1, Card 2, Card 3, .
options,
Options Card:
add (Options Card, options) ;

,
Applet-, show()
, . show()
:
, .
, this
.
.
show() cc:
cc.show (this, Fact Card);

this, ,
Fact Card . ,
. ,
.
,
. ,
,
.
, card layout
:
setLayout(new CardLayout());
//add the cards
Panel one = new Panel()
add("first", one);
Panel two = new Panel()
add("second", two);

279

Panel three = new Panel()


add("third", three);
// move around
show(this, "second");
show(this, "third");
previous(this);
first(this);

//go to the card named "second"


//go to the card named "third"
//go back to the second card
//got to the first card


, AWT,
,
() .
:
.

.

.
, GridBagLayout
, , GridBagConstraints. GridBagLayout
GridBagConstraints

, , . ,
, .
,
:
1. GridBagLayout
,
;
2. GridBagConstraints;
3. ;
4.
;
5. .

. (
; ).
// postavuvanje layout
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
setLayout(gridbag);
// definiranje ogranicuvanja za kopceto
Button b = new Button("Save");
constraints.gridx = 0;

280

constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.weightx = 30;
constraints.weighty = 30;
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.CENTER;
// pridruzuvanje na ogranicuvanjata na layout, dodavanje kopce
gridbag.setConstraints(b, constraints);
add(b);

,
.
, ,
.

:

.
-
. ,
.
12.4 .
12.5 .
,
.
,
.
. , :
x y ( ,
). 12.5,
,
.

12.4.

281

12.5. ,
x y ;
. ,
. 0,0.
1,0. ,
0,1, 1,1, .
; ,
. 12.6 .

12.6. ,

:

.
. ,

.
( )
. ,
.

,
.
buildConstraints() : GridBagConstraints-
, GridBagConstraints: gridx,
gridy, gridwidth, gridheight, weightx, weighty. ,
;
:
void buildConstraints(GridBagConstraints gbc, int gx, int gy,
int gw, int gh, int wx, int wy) {

282

-
gbc.gridx = gx;
gbc.gridy = gy;
gbc.gridwidth = gw;
gbc.gridheight = gh;
gbc.weightx = wx;
gbc.weighty = wy;

init() , ,
. ,
GridBagLayout, , (
GridBagConstraints):
public void init() {
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
setLayout(gridbag);
constraints.fill = GridBagConstraints.BOTH;
}

: , constraints.fill,
( ) .
, .. .
; .
. (
,
,
). ,
.
init()-, setLayout:
// Name label
buildConstraints(constraints, 0, 0, 1, 1, 100, 100);
Button label1 = new Button("Name:");
gridbag.setConstraints(label1, constraints);
add(label1);

, ,
, .

GridBagConstraints, ,
.
:
buildConstraints()?


,
, ,

gridx gridy.
.
?

283

. -
,
. ,
gridx gridy ( buildConstraints() 0 0,
).
gridwidth gridheight.
; ,
: gridwidth gridheight .
, 1.
weightx weighty.
,
. , ,
100. .
,
setConstraints()-, gridBagLayout
: ( ), .
, .
,
GridBagConstraints
.
, buildConstraints(). , buildConstraints() .
, - .
1,0 ( , );
, ( ) 100:
buildConstraints(constraints, 1, 0, 1, 1, 100, 100);

, ,
; .
password 0,1 ( , ), -
password 1,1 ( , ):
buildConstraints(constraints, 0, 1, 1, 1, 100, 100);
buildConstraints(constraints, 1, 1, 1, 1, 100, 100);

, ,
.
, .. (0,2). ,
gridwidth gridheight , 1,
. Gridweight 2 ( ), gridheight 1
( ):
buildConstraints(constraints, 0, 2, 2, 1, 100, 100);

284


.
,
. 12.7 .
, .
, ,
, ,
( ,
).

12.7. ,

:

. ,
( ) -.

- .
weightx weighty.
widthx widthy,
, 0
. ,
weightx weighty , 100.

, weightx weighty ;
.
, ,
.

, 100, .

285

, 0?
, 0, .
, ,
0.
buildConstraints(),
:
buildConstraints(constraints, 0, 0, 1, 1, 100, 100); //name
buildConstraints(constraints, 1,0,1, 1, 100, 100); //name text
buildConstraints(constraints, 0,1,1, 1, 100, 100); //password
buildConstraints(constraints,1,1,1,1, 100, 100); //password text
buildConstraints(constraints, 0, 2, 2, 1, 100, 100); //OK button

buildConstraints,
, 0. x ( ),
.
12.5 ( ),
.
,
10, 90 . ( ; ).
.
- ,
, .
- -
-:
buildConstraints(constraints, 0, 0, 1, 1, 10, 100); //name
buildConstraints(constraints, 1, 0, 1, 1, 90, 100); //name text

, password
-?
-, .
, , 0.
buildConstraints(constraints, 0, 1, 1, 1, 0, 100); //password
buildConstraints(constraints, 1, 1, 1, 1, 0, 100); //password text
buildConstraints(constraints, 0, 2, 2, 1, 0, 100); //OK button

, 0, .
, . 0
; 0
.
weightx 100,
weighty . .
, 20 , ( 40 ). x-,

286

(
), weightx = 0.
buildConstarints() :
buildConstraints(constraints,
buildConstraints(constraints,
buildConstraints(constraints,
buildConstraints(constraints,
buildConstraints(constraints,

0,
1,
0,
1,
0,

0,
0,
1,
1,
2,

1,
1,
1,
1,
2,

1,
1,
1,
1,
1,

10, 40); //name


90, 0); //name text
0, 40); //password
0, 0); //password text
0, 20); //OK button

12.8. ,
,
.
,
.

:
,
.
, . , . 12.9
,
.

12.9. ,

287

, . ,
.
, .
: fill anchor.
Fill
( , ). Fill
, -
GridBagConstraints-:

GridBagConstraints.BOTH,
;
GridBagConstraints.NONE,
;

GridBagConstraints.HORIZONTAL,
;
GridBagConstraints.VERTICAL,
.

.
; ,

.
default, fill NONE.
?
, init()-:
constraints.fill = GridBagConstraints.BOTH;

. ,
fill, .

, anchor.
, AWT-,
. anchor
() GridBagConstraints.CENTER,
, ,
:
GridBagConstraints.NORTH, GridBagConstraints.NORTHEAST,
GridBagConstraints.EAST, GridBagConstraints.SOUTHEAST,
GridBagConstraints.SOUTH, GridBagConstraints.SOUTHWEST,
GridBagConstraints.WEST, GridBagConstraints.NORTHWEST.

288

Default anchor- GridBagConstraints.CENTER.


:
GridBagConstraints .
GridBagConstraints() ( ),
init()-.
.
default- ( ).
, GridBagConstraints
,
. , fill anchor
,
.
, fill anchor
:

fill EAST (
).
(
, ).
fill .
.

:

, .

.

, .
12.4
. ,
,
.
12.4. GridBagTestFinal.java
1: import java.awt.*;
2:
3: public class GridBagTestFinal extends java.applet.Applet {
4:
5: void buildConstraints(GridBagConstraints gbc, int gx, int gy,
6:
int gw, int gh,
7:
int wx, int wy) {
8:
gbc.gridx = gx;
9:
gbc.gridy = gy;
10:
gbc.gridwidth = gw;
11:
gbc.gridheight = gh;


12:
gbc.weightx = wx;
13:
gbc.weighty = wy;
14: }
15:
16: public void init() {
17:
GridBagLayout gridbag = new GridBagLayout();
18: GridBagConstraints constraints = new GridBagConstraints();
19:
setLayout(gridbag);
20:
21:
// Name label
22:
buildConstraints(constraints, 0, 0, 1, 1, 10, 40);
23:
constraints.fill = GridBagConstraints.NONE;
24:
constraints.anchor = GridBagConstraints.EAST;
25:
Label label1 = new Label("Name:", Label.LEFT);
26:
gridbag.setConstraints(label1, constraints);
27:
add(label1);
28:
29:
// Name text field
30:
buildConstraints(constraints, 1, 0, 1, 1, 90, 0);
31:
constraints.fill = GridBagConstraints.HORIZONTAL;
32:
TextField tfname = new TextField();
33:
gridbag.setConstraints(tfname, constraints);
34:
add(tfname);
35:
36:
// password label
37:
buildConstraints(constraints, 0, 1, 1, 1, 0, 40);
38:
constraints.fill = GridBagConstraints.NONE;
39:
constraints.anchor = GridBagConstraints.EAST;
40:
Label label2 = new Label("Password:", Label.LEFT);
41:
gridbag.setConstraints(label2, constraints);
42:
add(label2);
43:
44:
// password text field
45:
buildConstraints(constraints, 1, 1, 1, 1, 0, 0);
46:
constraints.fill = GridBagConstraints.HORIZONTAL;
47:
TextField tfpass = new TextField();
48:
tfpass.setEchoCharacter('*');
49:
gridbag.setConstraints(tfpass, constraints);
50:
add(tfpass);
51:
52:
// OK Button
53:
buildConstraints(constraints, 0, 2, 2, 1, 0, 20);
54:
constraints.fill = GridBagConstraints.NONE;
55:
constraints.anchor = GridBagConstraints.CENTER;
56:
Button okb = new Button("OK");
57:
gridbag.setConstraints(okb, constraints);
58:
add(okb);
59: }
60: }

, <APPLET> :
<applet code= GridBagTestFinal.class height=180 width=240>
</applet>

289

290

, setEchoCharacter()
48, ,
1.02. setEchoChar(),
1.2 ( ) .


,
: ipadx ipady.
padding (
). default,
(
). Ipadx , ipady,
.

,
( ipadx ipady
),
. , ,
. Insets
, ,
.
. ,
insets()- 1.02, getInsets() 1.2.
. insets() getInsets()-,
Insets , Insets- , , ,
. insets() Insets. : 10
30 . 12.10
.
public Insets insets() {
return new Insets(10, 30, 10, 30);
}

291

12.10. 10 , 30

12.4.

.

.
.
Abstract Windowing Toolkit-,

.
,

:
. , :
, !

12.5.
:

;
(
). ,
.
,
x, y .
?

, . AWT
, ,

292

-

, , , .

, ,
,
, .
, ,
.
,
.
? null ,
reshape()- ,
:
setLayout (null) ;
Button myButton = new Button (OK);
myButton.reshape (10, 10, 30, 15);

reshape() Component.
:
:

AWT - peer.
peer (nobl) , API
. peer-?
Peers AWT. ,
AWT , Window
,
WindowPeer,
X Window,
Macintosh Macintosh, Windows 95. nobl
,
.
(AWT ),
(nobl ),
,
, .

13.
,
, , .

.
,
. (vents)
Java Windows
.
, :
, .
1.2,
web browser, .

13.1.
,
, .
Windows , , ,
paint(), init() start(), . ,
,
.


,
.
, , , .

. ,
, . ,
,
, .
:

. ( ),
( )
( );
.
(
);
. ,
( );
. ,
scrollbar-, .

294

Handlevent()-

1.02 1.2. ,
, ,
.
.
1.02,
,
handleEvent(). Component,
java.applet.Applet, .
handleEvent()-, ,
,
. mouseDown(), mouseUp()
keyDown().
,
. ,
mouseDown(), .
, .

13.2.

.
.

, ,
, .
,
.

-
, :
, ,
, .
.
;

.
:
public boolean mousedown(Event evt, int x, int y) {
// ...
}

295

mouseDown() ( mouseUp(), ), :
x y ,
.
evt () Event.
Event.
, .
, .
X y - , x y -
mouseDown(), ,
. ,
,
, .
x y - Event ;
, .

:
public boolean mouseDown(Event evt, int x, int y) {
System.out.println("Mouse down at " + x + "," + y);
return true;

,
,
(standard output device).

System.out.println()
. Appletviewer-
, appletviewer . Netscape Navigator
, (Java Console)
Window/ Java Console. Microsoft
Internet Explorer .

.
,
, (
void), .
event-handler- ( ),
(true, false),
, ..
. :
, false, Windows .

296

, ,
true.
mouseUp(),
.
, mouseUp()- .
mouseDown() :
public boolean mouseUp(Event evt, int x, int y) {
// ....
}

:

. Spots () ,
. ,
. 10 . 13.1
Spots.

13.1 Spots
,
:
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Event;
public class Spots extends java.applet.Applet {
final int MAXSPOTS = 10;
int xspots[] = new int[MAXSPOTS];
int yspots[] = new int[MAXSPOTS];
int currspots = 0;
}

Abstract Windowing Toolkit - : Graphics, Color


Event. , Event,
.

297
Spots : MAXSPOTS,
,
x y - ,
(integer) .

Event implements Runnable


. ,
run(). ? ,
; .
, .
init()-
:
public void init() {
setBackground(Color.white);
}

init(), paint()
, . paint()
, paint(),
.
init(), .
mouseDown(),
:
public boolean mouseDown(Event evt, int x, int y) {
if (currspots < MAXSPOTS) {
addspot(x,y);
return true;
}
else {
System.out.println("Too many spots.");
return false;
}
}

, mouseDown()
10 . , addspot() (
) true ( ).
, false. addspot() ?
, ,
currspots repaint():
void addspot(int x, int y) {
xspots[currspots] = x;
yspots[currspots] = y;
currspots++;
repaint();

298

,
- . repaint()
, .
, ,
. paint() - :
public void paint(Graphics g) {
g.setColor(Color.blue);
for (int i = 0; i < currspots; i++) {
g.fillOval(xspots[i] -10, yspots[i] - 10, 20, 20);
}
}

paint(),
xspots yspots (, ,
;
).
.
.
mouseDown() mouseUp(),
. 13.1 Spots.
13.1. Spots.java
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:

import java.awt.Graphics;
import java.awt.Color;
import java.awt.Event;
public class Spots extends java.applet.Applet {
final int MAXSPOTS = 10;
int xspots[] = new int[MAXSPOTS];
int yspots[] = new int[MAXSPOTS];
int currspots = 0;
public void init() {
setBackground(Color.white);
}
public boolean mouseDown(Event evt, int x, int y) {
if (currspots < MAXSPOTS) {
addspot(x,y);
return true;
}
else {
System.out.println("Too many spots.");
return false;
}
}

299
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
20);
38:
39:
40: }

void addspot(int x,int y) {


xspots[currspots] = x;
yspots[currspots] = y;
currspots++;
repaint();
}
public void paint(Graphics g) {
g.setColor(Color.blue);
for (int i = 0; i < currspots; i++) {
g.fillOval(xspots[i] - 10, yspots[i] - 10, 20,
}
}

HTML:
<applet code=Spots.class height=250 width=250>
</applet>


,
?
? Java Event
clickCount, ,
(. cosecutive mouse clicks),
.
,
mouseDown() :
public boolean mouseDown(Event evt, int x, int y) {
switch (evt.clickCount) {
case 1: // single-click
case 2: // double-click
case 3: // triple-click
....
}
}

, ,
mouseDown()
. :
public boolean mouseDown(Event evt, int x, int y) {
system.out.prntln(Broj na klikot: + evt.clickCount);
return false;
}

, ,
:

300

Broj na klikot: 1
Broj na klikot: 2
Broj na klikot: 3

,
. ,
mouseDown() .

13.3.
, -
.
, . AWT
: -
,
- .
: ,
/ ,
, .
, mouseDown() mouseUp(),
.

-
- ,
mouseDrag() mouseMove().
mouseMove() ,
(
,
, ,
). mouseDrag() :
public boolean mouseDrag(Event evt, int x, int y) {
...
}

mouseMove() mouseDrag(), x y , .

-
mouseEnter() mouseExit()
, .
mouseEnter() mouseExit()
. : , x y -

301
, .
mouseEnter() mouseExit():
public boolean mouseEnter(Event evt, int x, int y) {
...
}
public boolean mouseExit(Event evt, int x, int y) {
...
}

:

. 13.2
.

13.2.
( ),
.
,
, init():
import
import
import
import

java.awt.Graphics;
java.awt.Color;
java.awt.Event;
java.awt.Point;

public class Lines extends java.applet.Applet {


final int MAXLINES = 10;
Point starts[] = new Point[MAXLINES]; // starting points
Point ends[] = new Point[MAXLINES];
// ending points
Point anchor;
// start of current line
Point currentpoint; // current end of line
int currline = 0; // number of lines
public void init() {
setBackground(Color.white);
}

302

.
, ,
, - (Points). Points x y
, . ,
Point (java.awt.Point)
:
starts, .
ends, .
anchor,
.
currentpoint,
.
currline, (
, MAXLINES
.).
, init()
.
: mouseDown(),
(. anchor-) ; mouseDrag() -
; MouseUp() - .
.
.
mouseDown(), (
):
public boolean mouseDown(Event evt, int x, int y) {
if (currline < MAXLINES) {
anchor = new Point(x,y);
return true;
}
else {
System.out.println("Too many lines.");
return false;
}
}

,
. ,
- (anchor),
. mouseDrag(),
,
( ,
). ,
. mouseDrag()
:

303

public boolean mouseDrag(Event evt, int x, int y) {


if (currline < MAXLINES) {
currentpoint = new Point(x,y);
repaint();
return true;
}
else return false;
}

,
. mouseUp(),
addline(),
( ):
public boolean mouseUp(Event evt, int x, int y) {
if (currline < MAXLINES) {
addline(x,y);
return true;
}
else return false;
}

addline(),
, :
void addline(int x,int y) {
starts[currline] = anchor;
ends[currline] = new Point(x,y);
currline++;
currentpoint = null;
anchor = null;
repaint();
}

currentpoint anchor null,


.
null, paint(),
.
Paint starts
ends, ( anchor
currentpoint, ). ,
. paint()- Lines ():
public void paint(Graphics g) {
// crtanje na postoeckite linii
for (int i = 0; i < currline; i++) {
g.drawLine(starts[i].x, starts[i].y,
ends[i].x, ends[i].y);
}

304

-
// crtanje na tekovnata linija
g.setColor(Color.blue);
if (currentpoint != null)
g.drawLine(anchor.x, anchor.y,
currentpoint.x, currentpoint.y);

K paint()-,
currentpoint null. ,
, .
currentpoint ( currentpoint null addline()),
. ; 68
web browser. 13.2
Lines,
.
13.2. Lines.java
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:

import
import
import
import

java.awt.Graphics;
java.awt.Color;
java.awt.Event;
java.awt.Point;

public class Lines extends java.applet.Applet {


final int MAXLINES = 10;
Point starts[] = new Point[MAXLINES]; // startni tocki
Point ends[] = new Point[MAXLINES];
// krajni tocki
Point anchor;
// start na tekovna linija
Point currentpoint; // kraj na tekovna linija
int currline = 0; // broj na linii
public void init() {
setBackground(Color.white);
}
public boolean mouseDown(Event evt, int x, int y) {
if (currline < MAXLINES) {
anchor = new Point(x,y);
return true;
}
else {
System.out.println("Too many lines.");
return false;
}
}
public boolean mouseUp(Event evt, int x, int y) {
if (currline < MAXLINES) {
addline(x,y);
return true;
}
else return false;
}

305
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60: }

public boolean mouseDrag(Event evt, int x, int y) {


if (currline < MAXLINES) {
currentpoint = new Point(x,y);
repaint();
return true;
}
else return false;
}
void addline(int x,int y) {
starts[currline] = anchor;
ends[currline] = new Point(x,y);
currline++;
currentpoint = null;
anchor = null;
repaint();
}
public void paint(Graphics g) {
// Draw existing lines
for (int i = 0; i < currline; i++) {
g.drawLine(starts[i].x, starts[i].y,
ends[i].x, ends[i].y);
}
// draw current line
g.setColor(Color.blue);
if (currentpoint != null)
g.drawLine(anchor.x,anchor.y,
currentpoint.x,currentpoint.y);
}

HTML:
<applet code=Lines.class height=250 width=250>
</applet>

13.4.

. ,
-
, .
,
; ,
.
, .
, .
- ,

306

. ,
. , (containers),
.
,
requestFocus() - .
Button. quit:
quit.requestFocus();

,
requestFocus().


, keyDown():
public boolean keyDown(Event evt, int key) {
...
}

, ( keyDown()
), Unicode -
. , ,
, return . ( ),
:
currentchar = (char)key;

keyDown(),
: Unicode , (
ASCII ):
public boolean keyDown(Event evt, int key) {
System.out.println("ASCII value: " + key);
System.out.println("Character: " + (char)key);
return true;
}

,
. o o ,
keyUp():
public booklean keyUp(Event evt, int key)
...
}

307

Default
Event
,
. ,
, keyDown() ,
(
, ). ,
,
:
if (key == Event.UP) {
...
}

,
, switch .
13.1: Event:

Class-

Event.HOME

The Home key

Event.END

The End key

Event.PGUP

The Page Up key

Event.PGDN

The Page Down


key

Event.UP

The up arrow

Event.DOWN

The down arrow

Event.LEFT

The left arrow

Event.RIGHT

The right arrow

Event.f1

The f1 key

Event.f2

The f2 key

Event.f3

The f3 key

Event.f4

The f4 key

Event.f5

The f5 key

Event.f6

The f6 key

Event.f7

The f7 key

Event.f8

The f8 key

Event.f9

The f9 key

Event.f10

The f10 key

Event.f11

The f11 key

Event.f12

The f12 key

308

13.1 ,
Event, .

:
.
.
,
. ,
. 13.3
.

13.3. (Keys)
.
: init(), keyDown() paint().
, x y
, .
:
import
import
import
import

java.awt.Graphics;
java.awt.Event;
java.awt.Font;
java.awt.Color;

public class Keys extends java.applet.Applet {


char currkey;
int currx;
int curry;
}

, init() . init()
: , ( 36
Helvetica bold) (
, ).
public void init() {
currx = (size().width / 2) - 8;
curry = (size().height / 2) - 16;
setBackground(Color.white);
setFont(new Font("Helvetica", Font.BOLD, 36));
requestFocus();

309
}

init()- -,
. ,
, .. , .


, requestFocus()
.
Netscape Navigator Microsoft Internet Explorer. JDK
1.2 appletviewer-, requestFocus() ,
.

. , requestFocus(),
focus .
,
keyDown():
public boolean keyDown(Event evt, int key) {
switch (key) {
case Event.DOWN:
curry += 5;
break;
case Event.UP:
curry -= 5;
break;
case Event.LEFT:
currx -= 5;
break;
case Event.RIGHT:
currx += 5;
break;
default:
currkey = (char)key;
}
repaint();
return true;
}

keyDown()- switch,
. ,
. (. ),
( switch ).
repaint() true.
paint() ;
. ,
, ,
. currkey 0,
currkey :

310

public void paint(Graphics g) {


if (currkey != 0) {
g.drawString(String.valueOf(currkey), currx,curry);
}
}

13.3. Tasteri.java
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:

import
import
import
import

java.awt.Graphics;
java.awt.Event;
java.awt.Font;
java.awt.Color;

public class Tasteri extends java.applet.Applet {


char currkey;
int currx;
int curry;
public void init() {
currx = (size().width / 2) -8; // default
curry = (size().height / 2) -16;
setBackground(Color.white);
setFont(new Font("Helvetica",Font.BOLD,36));
}
public boolean keyDown(Event evt, int key) {
switch (key) {
case Event.DOWN:
curry += 5;
break;
case Event.UP:
curry -= 5;
break;
case Event.LEFT:
currx -= 5;
break;
case Event.RIGHT:
currx += 5;
break;
default:
currkey = (char)key;
}
repaint();
return true;
}
public void paint(Graphics g) {
if (currkey != 0) {
g.drawString(String.valueOf(currkey), currx,curry);
}
}
}

311

HTML:
<applet code=Tasteri.class height=100 width=100>
</applet>


Shift, Control (CTRL) Meta (
). , ,
,
.
; , Shift
Shift . :

, -
.

UNIX ;
ALT PC Command (apple) Macintosh .
Event
( ): shiftDown(), metaDown()
controlDown(). (Boolean)
.
event handle :
public boolean mouseDown(Event evt, int x, int y ) {
if (evt.shiftDown())
// handle shift-click
else // handle regular click
}

,
, ( ,
). default, (
), .
, ,
, Meta Control (CTRL), .
.
,
. ,
. if-
, :
public boolean mouseDown(Event evt, int x, int y ) {
if (evt.metaDown())
// handle a right-click
else if (evt.controlDown())

312

-
// handle a middle-click
else // handle a regular click


, ,
( ) ,
.
, ,
, .
, CTRL +
Windows, Control Macintosh,
; -
Command (apple), Macintosh,
(
).

,
, .
,

.

13.5. event-handler
Default
, event handler ,
handleEvent(). handleEvent()-, Abstract Windowing Toolkit-
,
, .
handleEvent()-,
. ,
( . scroll ,
), default event-handler ,
,
handleEvent() .
handleEvent() :
public boolean handleEvent(Event evt) {
...
}

id Event,
handleEvent(). (id)
(integer), event,
, handleEvent().
, switch

313
. , handleEvent()
:
public boolean handleEvent(Event evt) {
switch (evt.id) {
case Event.MOUSE_DOWN:
System.out.println("MouseDown: " +
evt.x + "," + evt.y);
return true;
case Event.MOUSE_UP:
System.out.println("MouseUp: " +
evt.x + "," + evt.y);
return true;
case Event.MOUSE_MOVE:
System.out.println("MouseMove: " +
evt.x + "," + evt.y);
return true;
case Event.MOUSE_DRAG:
System.out.println("MouseDrag: " +
evt.x + "," + evt.y);
return true;
default:
return false;
}
}

Event.KEY_PRESS, (
keyDown() ).
Event.KEY_RELEASE, .
Event.KEY_ACTION Event.KEY_ACTION_RELEASE,
( , ,
Page Up, Page Down Home) .

Event.MOUSE_DOWN ,
( mouseDown() ).
Event.MOUSE_UP ,
( mouseUp() ).
Event.MOUSE_MOVE , (
mouseMove() ).
Event.MOUSE_DRAG ,
( mouseDrag() ).
Event.MOUSE_ENTER ,
( ).
mouseEnter() -.
Event.MOUSE_EXIT , .
mouseExit() -.

314

, handleEvent() , default
event handle ,
handleEvent() - .
. ,
, ,
super.handleEvent(). handleEvent(),
. :
public boolean handleEvent(Event evt) {
if (evt.id == Event.MOUSE_DOWN) {
// process the mouse down
return true;
} else {
return super.handleEvent(evt);
}
}

, ,
handleEvent() .
; ,
false ( true false ).
, true.
-, true false,
.

13.6.
Event handle ,
,
. ,
, ,
. ,
.
,
; .

:

(. action events).
,
( ).
, (check box)
, , (. menu item)
, Return Enter .
- (. list select / deselect
events). (check box),

315
(choice menu item) ,
.
- (. got focus, lost focus).
,
, ..
. :
, ,
.
, .


,
,
.
,
action() , :
public boolean action(Event evt, Object arg) {
//...
}

action()
. , action()
, .
( , arg),
.
,
. :
, ,

. 13.2
.
13.2.

(button)
(check box)
(radio button)
(choice menu)
(text field)


string
boolean
boolean
string
string


true
true

action(), ,
(
,
). Event
action(), target,

316

. instanceof
, ,
:
public boolean action (Event evt, Object arg){
if (evt.target instanceof TextField)
return handleText(evt.target);
else if (evt.target instanceof Choice)
return handleChoice(arg);
//...
return false;
}

, action() TextField,
; if, ,
(handleText() handleChoice() ), ,
. ( handleText() handleChoice()
AWT ; ,
. ,
action()- ).
, action() . ,
true, action() , false,
( ).
handleText() , handleChoice(),
true false; false (,
true ).

.
Button.
: (labels)
, ,
. (
).
public boolean action (Event evt, Object arg){
if (evt.target instanceof Button){
String labl=(String) arg;
if(labl.equals(OK))
//upravuva so OK kopcinjata;
else if(labl.equals(Cancel))
//upravuva so Cancel kopcinjata;
//...
else if(labl.equals(Browse))
//upravuva so Browse kopcinjata;
//...
}


, , getLabel()
action(),

317
. (,
;
).

(check box) (radio button).


true,
(false).
,
(. checked).
, (. selected, deselected),
,
( ).


,
,
.
:
(LIST_SELECT), (LIST_DESELECT),
.
,
gotFocus() lostFocus();
action(). :
public boolean gotFocus (Event evt, Object arg){
//...
}
public boolean lostFocus (Event evt, Object arg){
//...
}

,
.
handleEvent(), :
public boolean handleEvent (Event evt){
if (evt.id== Event.LIST_SELECT)
handleSelect(Event);
else if (evt.id== Event.LIST_DESELECT)
handleDeselect(Event);
else return super.handleEvent(evt);
}

, Event.LIST_SELECT Event.LIST_DESELECT
,
,
(handleSelect() handleDeselect()), .
super.handleEvent() ;

318


handleEvent()-.


.
gotFocus() lostFocus()-
:
public boolean gotFocus (Event evt, Object arg){
//...
}


( . scrolling
list), : ,
, ,
, ,
. action(),
.
, ,
handleEvent() LIST_SELECT
LIST_DESELECT.

(scrollbar)
,
( . scrollbar).
. handleEvent()
. 13.3
.
13.3. .

SCROLL_ABSOLUTEG
SCROLL_LINE_DOWNG
SCROLL_LINE_UPG
SCROLL_PAGE_DOWNG
SCROLL_PAGE_UPG


scrollbar-


scrollbar-
scrollbar-

13.7.

. ,

319
,
.
Abstarct Windowing Toolkit-
,
.

13.8.
:
:

Spots, ,
.
?
, .
addspot() , MAXSPOTS.
,
( System.arraycopy()),
x y .
, Vector. Vector,
java.util,
, ++.
Vector .
integers Integer objects, .
Vector
. .
,
AWT- 1.02.
(
),
, . C++
. Smalltallk-
perform. ?
1.02;
action() ,
. ,
.

(event-handle) 1.02.
,
.

14. e awt
Abstract Windowing Toolkit-.
,
. ,
, AWT.

, :
:


.
, -.
.
AWT .

14.1. , -
, AWT

browser-, , .
, , .


AWT -,
: Window. Window ()
Container, awt-
. Window
, . ,
: Frame Dialog.
Frame ,

( ). .
Dialog Frame . FileDialog,
Dialog, -
(
).
- ,
Frame Dialog.

(frames)
(Frame) , ,
, , ,

awt

321

. ,
:

New Frame(), .
New Frame(String), .

(. frames) , ,
browser- ; ,
, , .
,

.
Window,
Container, ( Component),
AWT
. (Containers), ,
, add(). Default
BorderLayout. ,
:
win = new Frame("My Cool Window");
win.setLayout(new BorderLayout(10, 20));
win.add("North", new Button("Start"));
win.add("Center", new Button("Move"));

, resize(),
. ,
100 200 :
win.resize(100, 200);

,
,
. ,
, .
pack(),
resize(). pack() ,
,
,
. .

.
win = new Frame("My Other Cool Window");
win.setLayout(new FlowLayout()));
win.add("North", new Button("OK"));
win.add("Center", new Button("Cancel"));
win.pack();

322

, . show(),
.
hide() :
win.show();

, browser-
browser-
.
Netscape : Unsigned Java Applet
Window ( ).
, ,
browser-. ( Frame ,
).
,
.
.
14.1 14.2 pop-up
(pop-up window frame). :
.
, BaseFrame,
: A popup window.
,
.
14.1. PopUpWindow.java
1: import java.awt.*;
2:
3: public class PopupWindow extends java.applet.Applet {
4:
Frame window;
5:
6:
public void init() {
7:
add(new Button("Open Window"));
8:
add(new Button("Close Window"));
9:
10:
window = new BaseFrame("A Popup Window");
11:
window.resize(150,150);
12:
window.show();
13:
}
14:
15:
public boolean action(Event evt, Object arg) {
16:
if (evt.target instanceof Button) {
17:
String label = (String)arg;
18:
if (label.equals("Open Window")) {
19:
if (!window.isShowing())
20:
window.show();
21:
}
22:
else if (label.equals("Close Window")) {
23:
if (window.isShowing())
24:
window.hide();
25:
}

awt
26:
27:
28:
29:
30: }

323

return true;
}
else return false;

14.2. baseframe1.v
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:

import java.awt.*;
class BaseFrame1 extends Frame {
String message = "This is a Window";
Label 1;
BaseFrame1(String title) {
super(title);
setLayout(new BorderLayout());
l=new Label(message, Label.CENTER);
l.setFont(new Font("Helvetica", Font.PLAIN, 12));
add(Center, 1);
}
public Insets getInsets() {
return new Insets(20,0,25,0);
}
}

, HTML:
<applet code=PopUpWindow.class height=200 width=200>
</applet>

: PopUpWindow ,
pop-up . init()
, .. 7-15, 14.1,
;
.
.
action() 17-30, 14.1, ,
. , (Open
Window); ( 20-22 14.1)
( 20-25).
Pop-up BaseFrame1.
: BorderLayout
.
, init(). ,
, .
(. constructor ) BaseFrame1,
( 8) ()

324

BaseFrame1.
, ,
. ;
.

-
- ,
. -
,
.

- , ..
(
- ). -
(non resizable) (modal)
. (a
, ).
, ..
-, .
.
-
. AWT -: Dialog,
, FileDialog, -
.

-
- , ,
. -,
:

Dialog (Frame, Boolean), -


, (true), (false)
.
Dialog (Frame, String, Boolean), -
, (true), (false) .

-, , ,
,
, .
, ,
show(), hide().

awt

325

, pop-up .
, BaseFrame2. ,
Set Text, TextDialog
.

.
,
BaseFrame1.v, PopUpWindow.Java PopUpDialog.Java.
.
, BaseFrame2. ,
BaseFrame1,
BaseFrame2 BaseFrame2(String ). ,
,
:
TextDialog d1;

- BaseFrame2, ( TextDialog ),
d1 ; (Resize)
. e
, Set
Text.
dl = new TextDialog(this, "Enter Text", true);
dl.resize(150,100);

Set Text ,
BorderLayout South (
).
Button b=new Button(Set Text);
add(South, b);

TextDialog SetText BaseFrame2,


event-handle :
public boolean action(Event evt, Object arg){
if (evt.target instanceof Button) {
d1.show();
return true;
} else
return false;
}

TextDialog- d1,
. Set Text.
pop-up ,
. PopupWindowDialog.
, PopupWindow

326

PopupWindowDialog. , BaseFrame2,
BaseFrame1, :
window = new BaseFrame2(Pop-up window);

TextDialog,
14.3.
14.3. TextDialog.java
1: import java.awt.*;
2:
3: class TextDialog extends Dialog {
4: TextField tf;
5: BaseFrame3 theFrame;
6:
7: TextDialog(Frame parent, String title, boolean modal) {
8:
super(parent, title, modal);
9:
10:
theFrame = (BaseFrame3)parent;
11:
setLayout(new BorderLayout(10,10));
12:
setBackground(Color.white);
13:
tf = new TextField(theFrame.message,20);
14:
add("Center", tf);
15:
add("South", new Button("OK"));
16:
resize(150,75);
17: }
18:
19: public Insets insets() {
20:
return new Insets(30,10,10,10);
21: }
22:
23: public boolean action(Event evt, Object arg) {
24:
String label = (String)arg;
25:
if (evt.target instanceof Button) {
26:
if (label == "OK") {
27:
hide();
28:
theFrame.message = tf.getText();
29:
theFrame.repaint();
30:
}
31:
}
32:
else return false;
33:
return true;
34: }
35: }

o . ,
,
, (event
handler).
, BaseFrame2.
TextDialog

awt

327

Dialog. TextTialog
BaseFrame2,
Frame.
,

8 10 14.3. 8
8 10 14.3. 8
,
10, , Frame ,
BaseFrame2. TextDialog,
: . getInsets()
, action(),
. action() : 28
, 29, - (parent frame).
!
.
, ,
.


.
, Frame,
.
- .
, Dialog,
. -, -
( browser-
), .
- getParent(),
AWT . getParent() ,
. , AWT .
.
getParent(),
Frame. -, :
Object anchorpoint = getParent()
while (! (anchorpoint instanceof Frame))
anchorpoint = ((Component)anchorpoint).getParent();

anchorpoint,
.
anchorpoint ,
object.
while, getParent(),
, Frame .
getParent ,

328

Component,
anchorpoint Component, getParent().
, anchorpoint
Frame ( ).
Dialog ,
anchorpoint - Frame:
TextDialog dl = new TextDialog((Frame)anchorpoint,
"Enter Text", true);


FileDialog - /
(File Open/Save dialog box),
(file system). FileDialog ,
,
(Open File), (Save File).

- FileDialog, browser. ,
browser- .
FileDialog .
:

FileDialog(Frame,String),
, .
.
FileDialg(Frame,String,int)
,
.
( ;
, , ). :
FileDialog.LOAD FileDialog.SAVE.

FileDialog, , show():
FileDialog fd = new FileDialog(this, "FileDialog");
fd.show();


,
getDirectory() getFile().
.
(stream handling) (file
handling), .

awt

329

14.2.

AWT: . ( ,
).

: , ,
, , () .
,
,
, .
handleEvent(),
14.1, switch
id.
14.1.
WINDOW_DESTROY


lose box Close menu item

WINDOW_EXPOSE

WINDOW_ICONIFY

WINDOW_DEICONIFY
WINDOW_MOVED


AWT: (menus). (menu bar)
. ,
(shortcut). AWT ,
MenuBar MenuItem.

- (menu, menu bar)

- (menu bar)
. -
- (
, -).
- ,
MenuBar:
MenuBar mbar = new MenuBar();

330

- default ,
setMenuBar() ( Frame):
window.setMenuBar(mbar);

(File, Edit, .) -,
, -, add().
- , .
Menu myMenu = new Menu("File");
mbar.add(myMenu);

(Help),
. ,
setHelpMenu(). ,
.
Menu helpmenu = new Menu("Help");
mbar.add(helpmenu);
mbar.setHelpMenu(helpmenu);

,
disable() ( enable(),
):
myMenu.disable();

(menu items)
:
MenuItem, .
CheckBoxItem, .
, .
, ,
.


,
MenuItem.
MenuItem, ,
add():
Menu myMenu = new Menu("Tools");
myMenu.add(new MenuItem("Info"));
myMenu.add(new MenuItem("Colors"));

- ,
() Menu, .
:

awt

331

Menu submenu = new Menu("Sizes");


myMenu.add(submenu);
submenu.add(new MenuItem("Small"));
submenu.add(new MenuItem("Medium"));
submenu.add(new MenuItem("Large"));

CheckBoxMenuItem
,
. ( , ;
).
,
:
CheckboxMenuItem coords =
new CheckboxMenuItem("Show Coordinates");
myMenu.add(coords);

, (
),
.
(). ,
, myMenu:
MenuItem msep = new MenuItem("-");
myMenu.add(msep);

(disabled)
disable(), (enabled),
enabled(). .
MenuItem item = new MenuItem("Fill");
myMenu.addItem(item);
item.disable();


,
,
.
action(), .
, CheckBoxMenuItem :
(list select), (list deselect),
handleEvent().
, ,
,
, CheckBoxMenuItem
MenuItem. ,
. , Show Coordinates-
CheckBoxMenuItem, Fill regular- :

332

public boolean action(Event evt, Object arg) {


if (evt.target instanceof MenuItem) {
String label = (String)arg;
if (label.equals("Show Coordinates")) toggleCoords();
else if (label.equals("Fill")) fillcurrentArea();
return true;
}
else return false;
}

awt
.
,
. AWT - , ,
, , , , ..
, , .
?
.
Frame. (threads) ( ,
), Runnable:
class MyAWTApplication extends Frame implements Runnable {
// ....
}


main() Frame, AWT
, ,
AWT .
AWT ,
- , init():
, , ,
. , ,
.
:
import java.awt.*;
class MyawtApplication extends Frame implements Runnable {
MyawtApplication(String title) {
super(title);
setLayout(new FlowLayout());
add(new Button("OK"));
add(new Button("Reset"));
add(new Button("Cancel"));
}

awt

333

public static void main(String args[]) {


MyawtApplications app = new MyawtApplication("Hi! I'm applicat.");
app.resize(300,300);
app.show();
}
}


, .
(
java.applet.Applet, URL,
).
:
,
, System.exit(0),
.
public void windowClosing(WindowEvent e) {
win.hide();
win.destroy();
System.exit();
}

14.3. : rgb hsb


,
, ,
, .
14.1 , :
ColorTest RGB (Red, Green, Blue
, , ), HSB (Hue, Saturation, Brightness ,
) .

14.1. A ColorTest
ColorTest :
. RGB
; HSB .

334

, ,
.
:

ColorTest, Applet.
.
ColorControls, Panel.

. ,
RGB- HSB-,
.
,
. .



AWT , .
, ,
-.
, ,
,
. , ,
( ).
14.2 ColorTest ,
.

14.2. ColorTest -
.
. , RGB - , HSB .
, ColorTest -
Applet. , AWT. ( ,
).
import java.awt.*;
public class ColorTest extends java.applet.Applet {
...
}

awt

335

:
.
, .
,
, -
. ColorControls,
.

, .
, Canvas
, ColorControls :
ColorControls RGBcontrols, HSBcontrols;
Canvas swatch;

init(),
.
:
1.
2.
3.

.
flow , (grid layout)
, .
:
Canvas -.
.

1 . ,
10 :
setLayout(new GridLayout(1, 3, 5, 15));

2 Canvas.
Canvas. Canvas
:
swatch = new Canvas();
swatch.setBackground(Color.black);

,
ColorControls. ,
. ,
, .
RGBcontrols = new ColorControls(...)
HSBcontrols = new ColorControls(...);

3 -, :
add(swatch);
add(RGBcontrols);
add(HSBcontrols);

336

, (10
):
public Insets insets() {
return new Insets(10, 10, 10, 10);
}

? ,
Init , getInsets()
ColorTest.
ColorControls,
.

-
ColorControls
- RGB HSB-
. ColorControls Applet,
; .
Panel:
import java.awt.*
class ColorControls extends Panel {
...
}

ColorControls ,
.
- .
, -
. ,
;
ColorTest:
ColorTest applet;

applet ,
- .
:
TextField tfield1, tfield2, tfield3;

.
, init() ; ,
-.
init():
, -, .
ColorControls ,
RGB HSB .
: ,

awt

337

.
ColorTest.
ColorControls.
:
ColorControls(ColorTest parent,
String l1, String l2, String l3) {
}

, parent
applet:
applet = parent;

.
,
, (
), ( ).
10 :
setLayout(new GridLayout(3,2,10,10));

.
( 0),
:
tfield1 = new TextField("0");
tfield2 = new TextField("0");
tfield3 = new TextField("0");

,
:
add(new Label(l1, Label.RIGHT));
add(tfield1);
add(new Label(l2, Label.RIGHT));
add(tfield2);
add(new Label(l3, Label.RIGHT));
add(tfield3);

ColorControls.
? !

. , ColorTest,
getInsets():
public Insets insets() {
return new Insets(10, 10, 0, 0);
}

. 98
, : ColorText
,
ColorControls.

338

ColorControls ,
: ColorTest ().
init() ColorTest.
ColorControls . .

: ColorTest .
this ColorTest
:
RGBcontrols = new ColorControls(this, "Red", "Green", "Blue");
HSBcontrols = new ColorControls(this, "Hue", "Saturation",
"Brightness");

0 ( 0)
. , RGB
HSB 0, .
,
ColorControls ,
.
.


,
,
.
-. , , ,
.
ColorTest (),
.
, .
, action(),
ColorControls:
public boolean action(Event evt, Object arg) {
if (evt.target instanceof TextField) {
applet.update(this);
return true;
}
else return false;
}

action() ,
- ( - ,
; ). ,
update(), ColorTest ,
.

awt

339

,

.


:
-. update()
ColorTest. update() :
ColorControls, . (
action() ColorControls).

update() update()?
. , ,
. update()
ColorControls,
update(). , update()
. , .
update() .
, .
, e
;
RGBcontrols HSBcontrols:
void update(ColorControls controlPanel) {
if (controlPanel == RGBcontrols) { //RGB has changed, update HSB
...
} else { // HSB has changed, update RGB
...
}
}

update().
RGB -. , RGB
, Color
HSB.
, . ,
-
getText() TextField, ColorControls.

, ,
, (value1, value2, value3).
(
):
int value1 = Integer.parseInt(controlPanel.tfield1.getText());

340

int value2 = Integer.parseInt(controlPanel.tfield2.getText());


int value3 = Integer.parseInt(controlPanel.tfield3.getText());

,
, Color:
Color c;

, - RGB-
, if- update().
Color HSB- .
. RGB ,
Color, :
c = new Color(value1, value2, value3);

. ,
, 0 255 -.
,
.
RGB- HSB.
RGB-, HSB, . Color
RGBtoHSB(), .
. RGBtoHSB(), :

RGBtoHSB() HSB-,
.
HSB- 0,0
1,0. HSB-
, , (0
360), - 0 100.
;
. RGBtoHSB() RGB .

(floats), (HSB),
RGBtoHSB(). ( ,
(float) ,
RGBtoHSB()):
float[] HSB = Color.RGBtoHSB(value1, value2, value3, (new
float[3]));

(float) 0,0 1,0


0 100 ( ) (0 - 360) ,
, :
HSB[0] *= 360;
HSB[1] *= 100;
HSB[2] *= 100;

awt

341

.
-. ,
float,
(integer), .
HSBcontrols.tfield1.setText(String.valueOf((int)HSB[0]));
HSBcontrols.tfield2.setText(String.valueOf((int)HSB[1]));
HSBcontrols.tfield3.setText(String.valueOf((int)HSB[2]));

. RGB-,
- HSB . else
ifelse, , .
RGB- HSB-
. Color, getHSBColor()
Color HSB-. Color,
RGB-. ,
getHSBColor Color.
c, :
c = Color.getHSBColor((float)value1 / 360,
(float)value2 / 100, (float)value3 / 100);

Color, ; RGB- ,
Color. getRed(), getGreen(),
getBlue() Color, :
RGBcontrols.tfield1.setText(String.valueOf(c.getRed()));
RGBcontrols.tfield2.setText(String.valueOf(c.getGreen()));
RGBcontrols.tfield3.setText(String.valueOf(c.getBlue()));

, - RGB HSB,
,
. Color c,
setBackground .
setBackground ,
repaint():
swatch.setBackground(c);
swatch.repaint();

! . ColorTest ColorControls,
HTML ColorTest, .


14.4
ColorTest, 14.5
ColorControls. ,
.
- . Init()
ColorTest.

342

14.4. ColorTest.java
1: import java.awt.*;
2:
3: public class ColorTest extends java.applet.Applet {
4: ColorControls RGBcontrols, HSBcontrols;
5: Canvas swatch;
6:
7: public void init() {
8:
setLayout(new GridLayout(1,3,5,15));
9:
10:
// The color swatch
11:
swatch = new Canvas();
12:
swatch.setBackground(Color.black);
13:
14:
// the subpanels for the controls
15:
RGBcontrols = new ColorControls(this, "Red", "Green",
"Blue");
16:
HSBcontrols = new ColorControls(this, "Hue", "Saturation",
"Brightness");
17:
18:
//add it all to the layout
19:
add(swatch);
20:
add(RGBcontrols);
21:
add(HSBcontrols);
22: }
23:
24: public Insets insets() {
25:
return new Insets(10,10,10,10);
26: }
27:
28: void update(ColorControls controlPanel) {
29:
Color c;
30:
// get string values from text fields, convert to ints
31: int value1 = Integer.parseInt(controlPanel.tfield1.getText());
32: int value2 = Integer.parseInt(controlPanel.tfield2.getText());
33: int value3 = Integer.parseInt(controlPanel.tfield3.getText());
34:
35: if (controlPanel == RGBcontrols) {//RGB has changed,update HSB
36:
c = new Color(value1, value2, value3);
37:
38:
// convert RGB values to HSB values
39: float[] HSB = Color.RGBtoHSB(value1, value2, value3, (new
float[3]));
40:
HSB[0] *= 360;
41:
HSB[1] *= 100;
42:
HSB[2] *= 100;
43:
44:
// reset HSB fields
45:
HSBcontrols.tfield1.setText(String.valueOf((int)HSB[0]));
46:
HSBcontrols.tfield2.setText(String.valueOf((int)HSB[1]));
47:
HSBcontrols.tfield3.setText(String.valueOf((int)HSB[2]));
48:
49:
} else { // HSB has changed, update RGB

awt

343

50:
c = Color.getHSBColor((float)value1 / 360,
51:
(float)value2 / 100, (float)value3 / 100);
52:
53:
// reset RGB fields
54:
RGBcontrols.tfield1.setText(String.valueOf(c.getRed()));
55:
RGBcontrols.tfield2.setText(String.valueOf(c.getGreen()));
56:
RGBcontrols.tfield3.setText(String.valueOf(c.getBlue()));
57:
}
58:
59:
//update swatch
60:
swatch.setBackground(c);
61: swatch.repaint();
62: }
63: }

14.5. ColorControls.java
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:

import java.awt.*;
class ColorControls extends Panel {
TextField tfield1, tfield2, tfield3;
ColorTest applet;
ColorControls(ColorTest parent,
String l1, String l2, String l3) {
// get hook to outer applet parent
applet = parent;
//do layouts
setLayout(new GridLayout(3,2,10,10));
tfield1 = new TextField("0");
tfield2 = new TextField("0");
tfield3 = new TextField("0");
add(new Label(l1, Label.RIGHT));
add(tfield1);
add(new Label(l2, Label.RIGHT));
add(tfield2);
add(new Label(l3, Label.RIGHT));
add(tfield3);
}
public Insets insets() {
return new Insets(10,10,0,0);
}
public boolean action(Event evt, Object arg) {
if (evt.target instanceof TextField) {
applet.update(this);
return true;
} else return false;
}
}

344

, ColorTest
HTML:
<applet code=ColorTest.class width=475 height=100>
</applet>

14.4.

, Abstract windowing toolkit-
.
, , AWT Java 1.2 .
,
- . ,
AWT ?
, : !

14.5.
:
:

:
:



. ?
AWT
, , .
,
main(),
,
init() start() . ,
, 99
, .
, main(),
,
.
,
?! ,
?
WINDOW-CLOSE,
1.02. ,
hide(), ,
destroy(), .
,
System.exit ().

15.
, ,
,
. A , ,
.
.
,
,
, ,
.

:
.
,
.

: accessor .
aa Class .
, -
.
,
.

15.1. M

.

.
, .
.
, ,
, , ..
.

( ) , .

,

.

346

, :
public, protected private;
static
;
M abstract ;
M final
, ;
synchronized volatile
;
native,
.

, ,
. ,
, ,
:
public class MyApplet extends Java.applet.Applet { ... }
private boolean engineState;
static final double pi = 3.141559265
protected static final int MAXNUMELEMENTS = 128;
public static void main(String args[]) { ...}


. .
:
<access> static abstract synchronized volatile final native

, <access> public, protected,


private, ( ).
;
. - ,
.
( , ),
,
.

15.2.
,
,
.

?

? , ,

347

.

.
. ,
,
.
.

. ,
,
. ,
. ,
,
.
.
.
, ,
.
.
, (
) .
,
( ).
,
, ..
,
. encapsulation ()
- .
Encapsulation ()
,
.
;
.
,
.
,
,
.

(rotection)

: public, private, protected package (
,
). ,

348

.
,
.



: package protection ( ). C,
,
. ;
.
, ,
"- "
,
.
,
, .
, .

.
, .. default ,
.

; , default
.

,
. , , default
.

, .

(Private)
default ,
,
. private,

. ,
,

349

. ,
, . ,
-.

. ,
private :
class Writer {
private boolean writersBlock = true;
private String mood;
private int income = 0;
private void getIdea(Inspiration in) {
. . .
}
Book createBook(int numDays, long numPages) {
...
}
}

, Writer (
writersBlock, mood, income getIdea()) private.
Writer class createBook() .
createBook()
Writer ;
,
.

- ,
o. -

.
, ..
.
,
,
.
, ,
, ,
. -

. -
, ,
,
.
"
ccessor ."

350

(Public)

, .
,
- ,
, .. .

.
.
,

.
,
.
default .

. .
.
,
,
. , .
; public
private.

(Protected)

-,
. - -
, :

- ""
.
-
.
-
, .

-,
,
(protected).
, -,
-
.

351


, - .


C++, -
. protected ,

.
?
,
, e -
. , -,
, o
. , AudioPlayer,
. AudioPlayer
openSpeaker(), -
. openSpeaker()
AudioPlayer ,
. AudioPlayer :
class AudioPlayer {
private boolean openSpeaker(Speaker sp_ {
// implementation details
}
}

AudioPlayer -.
StereoAudioPlayer - AudioPlayer?
openSpeaker()
.
( ),
- e protected.


Java JDK 1.0.1, private protected

- . 1.0.2,
.


,
. 15.1,
,
() () .

352

15.1.

Public Protected

Package

private


;
.
- ,
.

( ). ,
:

public ,
public - (
).
protected ,
protected public -.
private.
private
.
( ),
private -.


-
, private. ,
- ,
? . . ,

,
. .

-
,
. ,
:

353

class Circle {
int x, y, radius;
Circle(int x, int y, int radius) {
...
}
void draw() {
...
}
}

: x y
. , draw()
. , ?
, .
. ?
.
.
.
draw() .
.

- -
. , ,

,
.

cessor
private,
?
(
), .
accessor , mutator ( )
getters setters.
Accessor methods
.
,
(
),
, , .
,
.
, , ,
,
- read only, ( ), ,
read-only .

354


- .

.

Accessor
accessor
.
accessor ; . ,
Circle : x, y,
radius. getRadius()
, setRadius()
(
):
class Circle {
private int x, y radius;
public int getRadius() {
return radius;
}
public int setRadius(int value) {
radius = value;
draw();
doOtherStuff();
return radius;
}
....
}

Circle, accessor
set get
.
accessor , .
, ,
setRadius() getRadius(), :
theCircle.getRadius(); //get the value
theCircle.setRadius(4); //set the value (and redraw, etc)

accessor
.
; ,
. accessor
( "set" "get" ),
:

,
.
,
.

355

.
,
.

ccessor

, accessor ,

. , accessor
; .
,
accessor .

, .
accessor ,
accessor -

. ;
accessors-,
, accessor ,
. ,
,
.

15.3.
,
.
, .

static C C++. static



, static .
static, .
, static
. static
:
public class Circle {
public static float pi = 3.14159265F;
public float area(float r) {

356

-
return

pi * r * r;

} }


, .
,

. :
float circumference = 2 * Circle.pi * getRadius();
float randomNumer = Math.random();

, ,
(private), ..
accessor .
15.1 CountInstances
.
15.1. CountInstances, .
1: public class CountInstances {
2:
private static int
numInstances = 0;
3:
4:
protected static int getNumInstances() {
5:
return numInstances;
6:
}
7:
8:
private static void addInstance() {
9:
numInstances++;
10:
}
11:
12:
CountInstances() {
13:
CountInstances.addInstance();
14:
}
15:
16:
public static void main(String args[]) {
17:
System.out.println("Starting with " +
18:
CountInstances.getNumInstances() + " instances");
19:
for (int i = 0; i < 10; ++i)
20:
new CountInstances();
21:
System.out.println("Created " +
22:
CountInstances.getNumInstances() + " instances");
23:
}
24: }
Started with 0 instances
Creates 10 instances

, . 2
private (

357

numInstances). ( static),

, .
private accessor

.
numInstances 0 .
,
, .

,
. 4 - 6, get

(getNumInstances()). ,
. getNumInstances()
protected, public,
- ;
.
accessor .

; .
accessor , addInstance()
8 10, numInstances 1. 12 14
. ,
,
addInstance() . , main()
. main()- 10 CountInstances ,
,
numInstances (.. 10).

15.4. ,
,
final ,
.
. , final ,
:

final ,
-.
, final
.
, final
-.

( final ) , .

358


, final
. final private
public:
public final class
. . .
}

AFinalClass {

final :

.
,
, final.
. final ,
( -) ,
.

final .
- java.lang.System, java.net.InetAddress, java.net.
Socket ( 14, final Java
1.1). final
java.lang.String. String- ,
.
, final ,
,
. ,
( ).



. .
, final
:
public class AnotherFinalClass {
public static final int aConstantInt
= 123;
public final String aConstantString = "Hello world!";
}

( ,
while for ) final.


;

-.

359

public class ClassWithFinalMethod {


public final void noOneGetsToDoThisButMe() {
. . .
}
}

final .
,
, . ,
,
. ,
. final,
,
- .
final ,
final
.
.
accessor ( ),
accessor final .
- ,
.

final .
final, . final
-
.
, ,
.

Private final,
final . final (
) , ;
final. final
final , .

15.5.
,
, -
. , ,
.
;
,
-. (abstract classes),

360

abstract. ,
Fruit public
abstract:
public abstract class Fruit {
...
}

( ,
),
,
. ,
. ;
-
. ,
;
, ,
-.

-. .
, . -
,
.
,
.
:
; .
abstract ,
, static final. ,
. ;
,
.
; ,
.
,
.
15.2 . ,
MyFirstAbstractClass, .
, subclassesImplementMe(), . , doSomething(),
. AConcreteSubclass,
- MyFirstAbstractClass.
subclassesImplementMe(),

MyFirstAbstractClass.

361

,

15.2. : , .
1: public abstract class MyFirstAbstractClass {
2:
int anInstanceVariable;
3:
4: public abstract int subclassesImplementMe(); //no definition
5:
6:
public void doSomething() {
7:
. . .
// a normal method
8:
}
9:}
10:
11:public class AConcreteSubClass extends MyFirstAbstractClass {
12:
public int subclassesImplementMe() {
13:
. . .
// we *must* implement this method here
14:
}
15:}

:
Object a = new MyFirstAbstractClass();// illegal, is abstract
Object c = new AConcreteSubClass(); // OK, a concrete subclass

, ,

( ).
,
.

15.6.


: public, package, protected, private.

private, accessor
. ,
.

, final , ,
.. .
, abstract ,
,
. ,
, .

362

15.7.
:
:

:
:

:
:

:
:

:
:

?
,
. ,
, -,
, .
(
, accessor ).
accessor
?
. -
, ;
accessor final,
.
class (static)
?
. static (class) default - final. -
non-final ? !
,
.
, private abstract
final abstract .
?
, , .
, abstract , abstract
-,
private final.
transient ?
.
ransient
( 1.0.2 1.1);

( ).
, byvalue, future,
generic, , .

. . ?
. , ,
.
- .

16.


.
;

.
,
. :

,
;
;
;
;
;
.

16.1.
,
:

?
?
, , ,
. Bill Joy, Sun Microsystems,
, C, a
Smalltalk.
, ( Smalltalk), .

-
, .
: ,
,
.
,
, ,

.
,
.
, ..
. .

364

16.2. ?
, ,
.
, . ?
,
. , ,
.
, ,

.
:

.

,
.
.
,
,
.
.
,
,
. .
. ,
,

.

,
, ,
. ,
.
. java; io,
net, util, awt.
image.

,
. , Sun Microsystems,
, sun.
Netscape
netscape. java,

.
.

365

16.3.
.
import
(java.awt.Color, ), .
,
.
,
:

java.lang
( , System Date),
. java.lang
.
,
,
( , java.awt.Font).
,
.
,
.

?
- ,
(default) .
.


,
: .
:
java.awt.Font f = new java.awt.Font()

,
. , ,
,
, .

import
, import,
.
:
import java.util.Vector;

366

(*)
:
import java.awt.*

, ,
- public,
.
" ."
(*)
DOS
. ,
classes/java/awt/*,
.class image peer. import
java.awt.* ,
image and peer.
,
. ,
( , L* L). ,
. import
, (
, ).
, ,
?
. o ,
;
.
, . imports,
.


import #include
C, . C
#include.

. import ;
( )
, , .
.

367


,
,
. ,
: .
.
( ):
import joesclasses.*;
import eleanorsclasses.*;

Name. ,
Name .
Name
Name :
Name myName = new Name("Susan");

;
. ,
, Name
:
joesclasses.Name myName = new joesclasses.Name("Susan");

CLASSPATH

,
. ,
. ,
. :
CLASSPATH .
, .
, java.applet.Applet
applet , java
(java/applet/Applet.class, ).
,
CLASSPATH . 2,
JDK, CLASSPATH
. CLASSPATH java/lib

JDK ,
,
.
,

368

. "cannot load class"


CLASSPATH .

Macintosh JDK, CLASSPATH ;



. , ,
.

.

16.4.
,
, ,
. .
.


.
.
, (
graphics or hardware_interfaces).
, ,
( ) ,
.
Sun
. , Sun ,
com.sun.java java.
fooblitzky.eng.nonsense.edu,
edu.nonsense.eng.fooblitzky (
).
.
, .
,
. ,
. ,
, String class, java.lang.String,
.
.

369



.
(mypackage), .
,
. edu.nonsense.eng.fooblitzky,
edu nonsense ,
eng nonsense, fooblitzky eng.
fooblitzky .

package

package . package "
", :
package myclasses;
package edu.nonsense.eng.fooblitzky;
package java.awt;

package, ,
import.
, package ,
default
. ,
,
.


protection
, .
,
: package public. default,
,
, - .
;
.
, :
class TheHiddenClass extends AnotherHiddenClass {
...
}

,
public
:

370

public class TheVisibleClass {


...
}

public
. import
(), .

. ?
:
,

. ,
public,
.
16.1 .
, .
16.1. LinkedList.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

package

collections;

public class LinkedList {


private Node root;

public void add(Object o) {


root = new Node(o, root);
}
. . .

class Node {
// not public
private Object contents;
private Node
next;
Node(Object o, Node n) {
contents = o;
next
= n;
}
. . .
}

.
11, " awt,"
:
, public,
.
, .class
. -- ,
, .

371

LinkedList (
add()) .
LinkedList
. Node, public
collections
.

Node , LinkedList
.
,
, . LinkedList,
Node ,
LinkedList .

,
.
, ,
, ,
() .
.

16.5. ?
,
,
. , ,
,
. : ,

.


- ,
.
,
, -
/ /.
, .
,
,

. .
"- ,"

372

, Vehicle,
16.1.

16.1. Vechicle

BritishScooter BritishMotorcycle, Scooter Motorcycle.

scooter motorcycle British (


leakOil() electricalSystemFailure())
, ,
.
British ,
motorcycles scooters.
(
-
), ?
.
Animal Mammal Bird .

.
. , ?
, ?
Platypus.
,
.
.

.

BritishScooter BritishMotorcycle
(BritishThing)
, British.

, .

.
,
.

373

? ,
Objective-C,
, . ,
, ,
.
.
,
, . ,

.

. ,
java.lang.Runnable, java.util.
Enumeration, java.util.Observable, java.awt.image.ImageConsumer, java.awt.image.
ImageProducer. ; ,
. ,
, API .



- ,
, .
, ,
.
,
,
. (
) -
. ,
.
,
.
,
,
, .
, .. .
, .

,
, .
? ?
. ,
,
.
( ),
, .

374

. ;
.
,
,
.
, .
,
.

.

.
, , .


, ,
. ,
, . ,
.class . ,
, .
,
.
.
.
: new

16.6.
(
), ( ).
:
. .

implements
, implements
. 10 ,
Runnable -:
// java.applet.Applet is the superclass
public class Neko extends java.applet.Applet
implements Runnable { // but it also has Runnable behavior
...
}

375


,
.
, -
. ,
. (
-
,
).
, -
( )
.
,
implements .
- Orange ().
Fruit () ,
Fruitlike, Fruits.
, ,
. ( ,
):
interface Fruitlike {
void decay();
void squish();
. . .
}
class Fruit implements Fruitlike {
private Color myColor;
private int
daysTilIRot;
. . .
}
interface Spherelike {
void toss();
void rotate();
. . .
}
class Orange extends Fruit implements Spherelike {
. . . // toss()ing may squish() me (unique to me)
}

Orange implements Fruitlike,


Fruit, !
Orange (,
, Sphere), Orange
:
class Sphere implements Spherelike {
// extends Object
private float radius;
. . .
}
class Orange extends Sphere implements Fruitlike {
. . . // users of Orange never need know about the change!

376


- ,
,
.
, :
public class Neko extends java.applet.Applet
implements Runnable, Eatable, Sortable, Observable {
...
}


-
? :

,

.
,
; ,
.
, ,
(,
,
). ,
.
,
.


,
. ,
:
Runnable aRunnableObject = new MyAnimationClass()

,

- ,
.
. , aRunnableObject
Runnable,
aRunnableObject.run().
aRunnableObject run()
, (
) . -

377

, "stub" (
, ) .
, ,
. ,
Orange, Fruitlike (
, Fruit) Spherelike.
Orange :
Orange anOrange = new Orange();
Fruit
aFruit
= (Fruit)anOrange;
Fruitlike
aFruitlike = (Fruitlike)anOrange;
Spherelike aSpherelike = (Spherelike)anOrange;
aFruit.decay();
// fruits decay
aFruitlike.squish();
// and squish
aFruitlike.toss();
// things that are fruitlike do not toss
aSpherelike.toss();
// but things that are spherelike do
anOrange.decay();
// oranges can do it all
anOrange.squish();
anOrange.toss();
anOrange.rotate();


. ,
,
( ),
. , ,

.
,
.

16.7.
,
. ;
,
.


, :
public interface Growable {
...
}

, interface
class. .
;
,
, .

378

private
protected. , Growable
public abstract (growIt()),
(growItBigger()).
public interface Growable {
public abstract void growIt(); //explicity public and abstract
void growItBigger();
// effectively public and
abstract
}

,
. , ;
.
, ,
public, static, final ( ).
,
public, static, final,
. Growable
:
public interface Growable {
public static final int increment = 10;
long maxnum = 1000000; // becomes public static and final
public abstract void growIt(); //explicitly public and abstract
void growItBigger(); // effectively public and abstract
}

, .
, public
public abstract, public. -
.
, ,
package .
,
.


:
,
? !
,
, .
,
.
, Fruitlike, (
) decay() squish().

379

germinateSeeds(), : .
? Fruit,
Fruitlike ( Fruitlike),
. Fruitlike
:
public interface Fruitlike {
public abstract germinate(Fruitlike self) {
...
}
}

, ,
Fruitlike :
public class Orange extends Fruit {
public germinate(Fruitlike self) {
Orange theOrange = (Orange)self;
...
}
}


, .
, -
.
, extends
:
public interface Fruitlike extends Foodlike {
...
}

,
Object; .

. , , ,
-. ,
(
extends ),
.
BusyInterface, :
public interface BusyInterface extends Runnable, Growable,
Fruitlike, Observable {
...}

,
,
;
.

380

:
, ,

( java.util ). 16.2 .
16.2. , , .
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:

package

collections;

public class LinkedList {


private Node root;
. . .
public Enumeration enumerate() {
return new LinkedListEnumerator(root);
}
}
class Node {
private Object
private Node

contents;
next;

. . .
public Object contents() {
return contents;
}
public Node
next() {
return next;
}
}
class LinkedListEnumerator implements Enumeration {
private Node currentNode;
LinkedListEnumerator(Node
currentNode = root;
}

root) {

public boolean hasMoreElements() {


return currentNode != null;
}
public Object
nextElement() {
Object anObject = currentNode.contents();
currentNode = currentNode.next();
return anObject;
}
}

381

collections.LinkedList aLinkedList = createLinkedList();


java.util.Enumeration e = aLinkedList.enumerate();
while (e.hasMoreElements()) {
Object anObject = e.nextElement();
// do something useful with anObject
}

Enumeration e, ,
. (LinkedListEnumerator),
.
, LinkedList
(
java.util. Enumeration)
( ). .
, ,
. ,
, ,
.
.

16.8.

.
, ,
-
. ,
, .
,
,

.
.
,
LinkedList, ,
.
.

16.9.
:

import some.package.B*
B?
, (*) .
importing * ?

, :

382

:
:

:
:

:
:

-

, .
( ,
). ,
, ,
* import
.

?
,
. ,
,
,
,
. -
,
. ,
,
, .
bstract
, -?
, . ,
,
. -
. abstract
, -abstract
. ,
.
callbacks.
?
, , . Callbacks
( window systems)

( ,
.). -
,
. Callbacks
,

. , -
, .

383

K
[1] An Introduction to Object-oriented programming, Timothy Budd,
Addison Wesley, 2001.
[2] Object-oriented Modeling and Design, James Rumbaugh, Michael
Blaha, Prentice Hall, 1990.
[3] Teach Yourself Java 1.2 in 21 days, Laura Lemay & Rogers
Cadenhead, Sams Publishing, 1998.
[4] Core Java, Cay Horstman & Gary Cornell, Prentice Hall, 2002.
[5] Java Tutorial- A Short course on the basics, 3-rd Ed. Mary Campione,
Kathy Walrath, Alison Huml, Addison Wesley, 2000.
[6] Java official Web site: www.sun.com/java
[7] Wikipedia - the Free encyclopedia: www.wikipedia.org

You might also like