Вы находитесь на странице: 1из 703

.

3-

-
-
2011
681.3.068
32.973.26-018.1
77

. .
77 Java NetBeans. 3- ., .
. .: -, 2011. 704 .: . + DVD
ISBN 978-5-9775-0671-7
, -
- .
Java, --
, . -
NetBeans,
Java (ME, SE EE). -
.
Java -
. .
DVD
NetBeans 6.9.1. DVD JDK 6u22
NetBeans 6.5 Windows Linux.
Java-

681.3.068
32.973.26-018.1

:

.
.




.

02429 24.07.00. 30.12.10.


70 1001/16. . . . . 56,76.
1500 .
"-", 190005, -, ., 29.
-
77.99.60.953..005770.05.09 26.05.2009 .
.

" ""
199034, -, 9 , 12

ISBN 978-5-9775-0671-7 . ., 2011


, "-", 2011

............................................................................. 11
.......................................................................................................................... 13
1. Java .......................................................... 17
1.1. Java .
................................................................................................................. 17
1.2. Java-, -, JIT-. ,
Java ..................................................................................................... 22
1.3. Java. .
...................................................................................................... 28
Java ............................................................................................................... 29
................................................. 29
Java ............................................................... 31
1.4. . Unicode. ............. 32
...................................................................................... 32
..................... 32
Unicode............................................ 32
..................................................................................... 33
................................................................................. 34
1.5. . . ...................... 35
1.6. - . ............. 38
1.7. . ....................................................... 43
1.8. . . . ...................................... 47
1.9. Java .............................................................................................. 51
1.10. Java, .NET, ASP, PHP ...................................................................................... 55
1.11. NetBeans, Eclipse, JDeveloper, JBuilder, IntelliJ IDEA ....................... 59
NetBeans 6.5............................................................................................................................ 61
Eclipse 3.4.1 (Ganimede) ........................................................................................................ 63
JDeveloper 11 .......................................................................................................................... 65
JBuilder 2008 .......................................................................................................................... 67
IntelliJ IDEA 7.0.4 .................................................................................................................. 69
.............................................................................. 70
................................................................................................................. 70
4

......................................................................................................................... 73
........................................................................................................................................... 74

2. NetBeans 6.5 ........................................................................................ 75


2.1. JDK 6 .................................................................................................................... 75
2.2. NetBeans 6.5 .............................................................................................. 79
2.3. NetBeans Java ......................................................... 87
2.4. . Jar- ......................................... 92
2.5. NetBeans ................................................................................................. 96
2.6. NetBeans Java ............................. 100
2.7. .................................................................................................... 105
2.8. ........................................................................................................ 110
2.9. Look and Feel .................................................. 116
2.10. ............................................................................................................... 119
2.11. .......................................................................... 121
2.12. ..................................................................................................... 129
2.13. Java ....................................................................... 130
2.14. swing awt .................................................................... 139
2.15. (Layout) (Anchor) ........................................................ 144
2.16. Desktop Application ...................................................................... 145
............................................................................................................... 147
....................................................................................................................... 148
......................................................................................................................................... 148

3. .......... 150
3.1. () ................................................................................................... 150
3.2. , , ................................................................................ 151
3.3. ................................. 155
3.4. Math ...................................................................................... 156
3.5.
.................................................................................................... 160
3.6. . (boxing) (unboxing) ................................. 162
3.7. ......................................................................................................... 164
............................................................................................................... 165
....................................................................................................................... 167
......................................................................................................................................... 167

4. Java................................................................. 169
4.1. ............................................................................... 169
....................................................... 169
................................................... 171
. .............. 172
................................................. 173
.................................................................................. 174
. ...... 174
................................................................................. 174
.............................................................................. 175

............................................................................................................. 177

................................................................................................. 178
5


................................................................................................. 178
................. 179
4.2. .................................................................................................. 180
4.3. ................................................................. 183
................................................................................................................... 183
.................................................................................................. 183
........................................................... 185
IEEE 754 .................... 186
............................................................................................................... 190
....................................................................................................................... 191
......................................................................................................................................... 191

5. ..................................................................... 193
5.1. ............................................................................................................. 193
5.2. if .......................................................................................................... 194
5.3. switch....................................................................................................... 198
5.4. ...?... : ... ............................................................................................ 199
5.5. ++ -- ...................................................................... 200
5.6. for............................................................................................................... 200
5.7. ........................................... 202
5.8.
............................................................................................................ 205
5.9. ,
................................................................... 210
5.10. while ............................................................... 215
5.11. do...while ........................................................ 217
5.12. continue, break, return, System.exit ............................................ 217
............................................................................................................... 221
....................................................................................................................... 222
......................................................................................................................................... 222

6. .................... 223
6.1. ............................................................................................ 223
6.2. . . ............................ 231
6.3. .
. this ....................................................................................................... 235
6.4. .
......................................................................................................... 238
6.5. . . ........................... 245
6.6. . super ............................ 250
6.7. . ................................. 252
6.8. Object ........................................................................................................... 254
6.9. . super this. ............... 256
6.10. finalize.
...................................................................................... 260
6.11. ........................................................................................................... 261
6.12.
. ......................................................... 263
6

............................................................................................................... 267
....................................................................................................................... 268
......................................................................................................................................... 269

7. UML-. .
................................................................................................................. 271
7.1. UML- .................................................................................................................. 271
7.2. UML- ................................................................ 279
7.3. UML-...................................................... 282
7.4. (Forward engineering) UML-
.......................................................................................................................... 286
7.5. (Reverse engineering) UML-
....................................................................................................... 293
7.6. ......................................................................................................................... 298
............................................. 301
............................................................................. 303
.................... 303
................................... 304
.................................................. 304
............................................................... 305
............................................................................................................... 306
....................................................................................................................... 306
......................................................................................................................................... 307

8. .................................................................... 308
8.1. ................................................................................................................................ 308
8.2. , , ........................................................................................... 314
8.3. . for-each .................................. 318
8.4. Java. . String, StringBuffer
StringBuilder ......................................................................................................................... 319
8.5. - (enum) ................................................................................................. 333
8.6. . GregorianCalendar ................................................... 335
8.7. ............................... 338
- ........................................................ 338
..................................................................................................... 339
, ........................................................................ 341
8.8. ................................................................................................. 345
............................................................................... 345
................................................................................ 348
throw....................................... 351
, .
throws ........................................................................................ 352
8.9. ............................................................................................... 355
File .......................................... 356
................................................... 359
/ ........................................................................................ 364
............................................................................................................... 372
....................................................................................................................... 373
......................................................................................................................................... 374
7

9. ....................................................................... 375
9.1. . ................................... 375
9.2. . ..................... 378
9.3. ......................................................................................... 380
9.4. ....................... 383
............................................................................................................... 385
....................................................................................................................... 385
......................................................................................................................................... 385

10. ....... 387


10.1. (threads) ............................................................... 387
10.2. .................................. 388
10.3. ......................................................................... 389
............................................................................................. 389
............................................................................................ 391
10.4. Thread Runnable Callable.
......................................................................................................................... 392
10.5. , Thread ....................................................................... 394
10.6.
.............................................................................................................................. 396
........................ 396
................................................................................ 398
........................... 406
10.7. Lock Condition .............................................. 408
Lock.................................................................................................................. 408
Condition ......................................................................................................... 412
............................................................................................................... 414
....................................................................................................................... 415
......................................................................................................................................... 416

11. ................................................ 417


11.1. HTML ..................................................................................... 417
WWW HTML .......................................................................................... 417
............................................................................................................ 419
, ......................................... 425
11.2. .............................................................................................................................. 427
............................................................................................................. 427
. @Override ..................................................................... 429
......................................................................................... 434
HTML-, CSS JavaScript .......................................... 437
11.3. ............................................................................................................................. 442
...................................... 444
.......................................... 451
11.4. JSP Java Server Pages ................................................................................ 456
11.5. JSTL JSP Standard Tag Library ................................................................. 460
............................................................................................................... 462
....................................................................................................................... 463
......................................................................................................................................... 464
8

12. ................................................................................... 465


12.1. .................................................................................................. 465
12.2. (static) ................................................... 466
12.3. (inner) ................................................................................................ 468
12.4. (local) .................................................................................................. 471
12.5. (anonimous) .............................................. 471
12.6. (anonimous) (listeners) ................................. 472
............................................................................................................... 475
....................................................................................................................... 477
......................................................................................................................................... 477

13. DesktopApplication .... 478


13.1. DesktopApplication ........................................................... 478
13.2. DesktopApplication ........................................................................ 480
13.3. DesktopApplicationView ................................................................ 482
13.4. .
................................................................................................ 486
13.5. @Action ................................................................................ 491
13.6. -. TaskMonitor, Task
propertyChange............................................................................................ 493
13.7. Task. ............... 500
13.8. .................................................................................................. 505
13.9. ........................... 510
13.10. lipboard .......................................... 511
............................. 511
. StringSelection ................... 514
.
ImageSelection .................................................................................................................... 515
13.11. ...................................................... 519
............................................................................................................... 523
....................................................................................................................... 524
......................................................................................................................................... 525

14. ......................................... 526


14.1. Java Micro Edition. . ..................... 526
14.2. ........................................................... 527
14.3. ......................................................... 533
14.4. Hello, World! ............................................................................... 538
14.5. "-" ............................................................................ 547
14.6. - .............................................................................................. 556
14.7. , TableItem,
. .............................................................. 563
14.8. "-" ........................................... 571
14.9. ....................................... 573
14.10. ,
NetBeans .............................................................................................................................. 574
............................................................................................................... 577
....................................................................................................................... 578
......................................................................................................................................... 578
9

15. ........................................................ 579


15.1. JavaBeans ............................................................................. 579
15.2. NetBeans 6.5 ............................................................................... 580
15.3. NetBeans 6.5 ......................... 584
15.4. ......................................................................... 588
15.5. ........................................................................ 590
............................................................................................................... 593
....................................................................................................................... 594
......................................................................................................................................... 595

16. - C/C++ Pack ...................... 596


16.1. . -
(native) .................................................................................................................. 596
16.2. JNI (Java Native Interface) Java C/C++.
Java C++ ........................................................................................ 597
16.3. C/C++ Pack. C++, C .......................... 603
16.4. C++ C......................................................................................... 612
16.5. native- ........................................................................ 616
. Java native- .................................. 617
. h- C++, .... 617
. C++ ,
jnipackage_JniMultiply.h ........................................................ 619
. C++ (DLL) ............. 620
. DLL NetBeans ........................................... 621
. DLL ........................................... 621
............................................................................................................... 625
....................................................................................................................... 626
......................................................................................................................................... 626

17. , ...................... 627


17.1. NetBeans ............................................................................ 627
17.2. ..................................................................... 631
17.3. .............................................. 638
17.4. " " ........................................ 642
17.5. .......................................................................................... 656
17.6. .............................................................................. 664
17.7. " ". .................................. 670
17.8. .................................... 678
17.9. ......................................................... 681
............................................................................................................... 687
....................................................................................................................... 688
......................................................................................................................................... 688

.................................................................................................................. 689
. DVD .......................................................... 691
................................................................................................................... 698
...................................................................................................................................... 698
.......................................................................................................................... 698

.............................................................................................. 699
10

, ,
Java NetBeans. -, -
Java. -, NetBeans 6.7, 6.8 6.9.
-, Open JDK (. http://www.openjdk.org/),
Java -
Sun Microsystems. , ,
Oracle, ,
Sun Microsystems.
-
Java . -
, -
, - ,
. -
,
, Java NetBeans.
DVD , (,
Java JDK 6u11 NetBeans 6.5),
, . , DVD
:
JDK 6u22 NetBeans 6.9.1 Windows Linux. -
JDK 6u22.
NetBeans 6.5, NetBeans 6.9.1, NetBeans 6.5 -
, NetBeans 6.9.1 -
.
, . . (, ,
).
-
v.v.monahov@mail.ru. ,
(. http://barsic.spbu.ru/
www/comlan/java_vm.html).
,
-
12


Java NetBeans -
-
Java, C, C++, Fortran, PHP, JavaScript, Ruby, Groovy .
NetBeans
, , -
Java NetBeans.
, Java,

, -
, .
, 2008 , -
. -
, , C C++ Java.
NetBeans 6.5 (
6.0), . ,
, NetBeans
Java-,
Java ,
NetBeans JUnit 4.
, NetBeans 6.5,
NetBeans 6.9. -
JDK , JDK 6u11 -
JDK 6u22, . . -
.
, Java , -
, JDK 5 ( JDK 1.5), -
.
-
Java (JDK 6), ,
Java .
Java -
SDK (Software Development Kit)
Java ( Java-). ,
14

SDK, , . . ,
, 20 . 2006
Sun Microsystems
.
NetBeans
( NetBeans), (packs)
(Beans ). : Java
, , Java Beans
" Java".
NetBeans
Java . -
, Delphi,

, ,
.
NetBeans 6.5
, . -
Java C/C++,
NetBeans 6.5 -
. Sun Microsystems, Java -
NetBeans, Java, -
NetBeans Java Scripting (
Java- , Java -
) -
. -
NetBeans Java- Java.
NetBeans 6.5 6.9 ( DVD)
, Java. ,
"C/C++ Pack", NetBeans
Java, C C++, NetBeans
C/C++. Java-
. - (native)
, native- Java, -
, C/C++.
NetBeans DVD -
http://netbeans.org/. -
, NetBeans -
, . -
, ,

NetBeans.
? NetBeans -
. -
Sun Microsystems,
,
.
, .
15

Java , . - -
Java .
NetBeans 6.5, 2008 , -
6.0, 2007 . -
Java NetBeans.
Java JDK 6 NetBeans 6.5.
, , NetBeans 6.5 6.9
JDK 6u11 JDK 6u22.
Java ,
MS Windows, Solaris, Linux, Mac OS .
Sun Microsystems -

, -
native-, .
16
1


Java

1.1. Java .

Java Sun
Microsystems -
. 1995 .
Java "-", C C++
. 1995 ,
2006 Java -
, C C++, -
. , Java,
.
C, C++, JavaScript Java?
? , ?
, -
-
.
.
, -
, , .
(. . -
), . . .
, , -
- (. . -
source code).
(. . ), -
,
- . -
( -
).
, - , -
() (, . . ). -
18 1

( . translation "", "-


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

( ) -
.
. , -
, , . .
, -
. -
, .
1956 Fortran
(. . ).
,
. -, , , -
, . -,
, .
, , -
" " , -
/ -
, , , . . -
, ,
,
, -
. Fortran -
.
( -
, ), -
, -
. -
,
. ,
, (-
driver "").
, -
. ,
.
, -
- -
, .
Java 19

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

,
. -
. -
, . ,
,
. ,

, . .
.
C 1972 Bell Laboratories
UNIX. -
, -
- -
,
. , C -
, .
-
, -
. -
,
. C ,
. . . -
- (
" ") -. C
-. .
C , -
.
-
. . -
? , -
, -
!
, Fortran,
. , -
, .
Pascal, -
1974 . -
. Pascal, -
20 1

. -
. , -
Pascal, P-
(P Pascal), -
. , -
. , (. . )
. -
.
Pascal -
C, . .

. P- -
Java.
1967
1972 , -
. -
. -
.
1982 C ,
"C ". 1983
C++. : " C
" ", -
, " ( : C "++").
C++ C
" C", - -
. ,
, ++
( "-", "-"). C++
. -
. , ,
,
, -
. , C C++
: ) , ;
) . -
, -
,
.
1995 , -
: Java, Sun, JavaScript,
Netscape Communication,
Netscape Navigator.
Java , -
-
Java 21

, .
( -
). Java -
Java-, Java. -
Java C,
C++, Java C, , -
. C
C++, . . -
. , C/C++ , -
, . ,
true (), ,
! Java
.
JavaScript -
HTML-, HTML,
. HTML,
WWW-, 11.
, JavaScript Java.
"script" . "Java" JavaScript
Netscape Communication. JavaScript C-,
Java, . -
WWW-. HTML XML , -
, -
. JavaScript -
. , JavaScript,
() . -
JavaScript
: .
JavaScript , C/C++, Java.
Java, JavaScript C++ - -
, C- . ,
( ) -
.
, .
:
Java ;
JavaScript HTML-;
C++ .
2000 Microsoft .NET ( "-
", DotNet " NET"). -
Java . ,
-
, . .NET
22 1

, ,
. .NET Java- C# ( " ").
, C# Java -
, "", , -
, .
, Java C# .
Java C- ,
, -
C C++. ,
,
- ,
,
. -
, -
. ,

. -
, Java .NET. -
, , , Java
.

1.2. Java-, -,
JIT-. ,
Java
"" -
- . -
, .
, . -
, , -
.
""
(application). ""
" ". , -
-
.
,
. , , -
, -
: , -
, CD-, DVD-, - -
.
. , MS Windows
Linux, .
Java 23

,
, ,
. , Java,
Java-, -
, Java-.
- ,
Java.
, Java, (
)
java. () -
class. -,
Java- -
.
- - , -
. Java-. -
: , -
Java-,
, , ,
Java.
, JIT-
(Just-In-Time), " ", " ". - -
( ) Java- ,
-
. -
. -
.
JIT- .
,
JIT- -
"" .
, -
.
(
). Sun -
HotSpot JIT- -, -
. -
.
Java - - -
,
. , ,
, Java- (Java
Virtual Machine JVM),
(native code - ).
Java- .
Java- Java ,
( Sun) Java Java-.
24 1


. Java, , -
Java-, . -
, Java-.
. -
main.
Java , -
. JIT- -
, , C C++. , JIT-
,
C/C++ (
, ). JIT- " ",
.
Java -
(native code - ). ,
GNU GCJ (http://gcc.gnu.org/java/). ,
Sun Java- -
, ,
, - .
, Java, /
, , C/C++, -
(slot , -
).
Java- - ( , -
JIT- JIT- ), -
(, , -
), -
, , (garbage
collection).
Java .
(application) .
(applet) -
, WWW- .
(midlet) -
, .
,
Java.
(servlet) -
, WWW . -
JSP (Java Server Pages Java) -
WWW-
.
(Enterprise application)
.
Java 25

(Java Class Library , NetBeans Module -


NetBeans) -
Java.
Java : -

. -
WWW , - WWW-, -
, . -
WWW. ,
-
, ,
.
Java, . -
-
, JSP
javax.servlet. , HTTP-
, . . , .
HTTP (HyperText Transport Protocol) WWW-
.
JSP () HTML-
XML-, -
. -
,
.
JSP , JSP -
, , -
Java- (, GlassFish
, -
WWW). , GlassFish,
Sun Application Server,
NetBeans 6.5.

Java 11.
Sun Microsystems Java , -
WWW- -
. Java
, JSP , -
. .
Java- (Java Runtime
Environment JRE).
Java- :
JRE Java Development Kit (JDK)
Java. SDK
Software Development Kit ( );
JRE -, Java
plugin.
26 1

JDK Sun http://


java.sun.com/.
, -
JRE. ,
. MS Internet Explorer
http://www.java.com/.
Java- ( -
JDK Sun).
Java- ( JDK -
). , , , -
Java, ( ).
JDK Java ( ,
, Java-) . , -
JDK 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6
1.7. ,
, -
(, 1.4.1_01 1.5.0_04).
Java 1.0 1.1 Java 1. Java, c 1.2,
Java 2. JDK, . . Java
JDK 1.5 Java
JDK -
, . , Java JDK 1.5,
Java JDK 1.4 ( Java
JDK 1.3 1.2). , JDK 1.5 Sun -
"Java 2" -
j2, JDK
"1". JDK 5 JDK 6,
JDK 1.5 JDK 1.6.
- jdk1.5 jdk1.6.
JDK -
.
Java :
Java Platform, Micro Edition (Java ME) http://java.sun.com/javame/
" " (. . ,
, , -
, -). J2ME. -
JDK, (Sun Java Wireless Toolkit for
CLDC, Sun Java Toolkit for CDC, NetBeans 6.5, -
). Java
Java-: -
KVM
CVM.
Java Platform, Standard Edition (Java SE) http://
java.sun.com/javase/ " " (. . , -
).
Java 27

J2SE. JDK. Java


Java- JVM (Java Virtual Machine).
Java Platform, Enterprise Edition (Java EE) http://
java.sun.com/javaee/ .
J2EE. Java SE, -
Java EE Java SE JVM.
SDK Sun Java System
Application Server ( Java), -
, Java.
- , Java
Java SE, Java- (JRE
Java Runtime Environment). , Java 6 update 7 ( 7)
JDK jdk1.6.0_07, jre1.6.0_07.
jre1.6.0_07 bin lib.
Java 6 update 10, jre jre6 -
JRE -
.
, Java 6 update 10 Java, -
Java 6 update 7 ( 8 9 ) , -
Java 5 Java 6.
Java 7.
jre6 . bin ,
Java-
. lib , -
.
JDK. , Java 1.6 update 11
jdk1.6.0_11 :
bin ;
demo ;
include C Java -
Java- -
JNI (Java Native Interface) JVMDI (Java Virtual Machine Debugging Interface) -
;
jre , Java-;
lib
bin;
sample .
jdk1.6.0_11 src.zip
Java.
, JRE, JDK -
JDK, . , -
,
28 1

Java- ( , ,
. .).
, JDK
,
Sun, . . 1.1
.

1.1.

javac ,
Java
java -

appletviewer .

jdb , Java
javadoc ,
/**
jar Java- jar
javah C/C++ Java
C/C++ JNI
javap
extcheck jar
native2ascii ,
,
Unicode

, WWW (-
) RMI (Remote
Methods Invocation). rmic, rmiregistry, rmid. -
keytool, jarsigner, policytool -
.
, JDK -
,
NetBeans. JDK
JRE.

1.3. Java.

.
Java -
http://java.sun.com/docs/books/jls/index.html ( -
).
Java 29

Java
Java , ,
. ( ASCII),
( Unicode, UTF-16), -
,
( ).
(. . ) -
, . ,
-
.

,
Java .
ASCII:
ABCD...XYZ ();
abcd...xyz .
ASCII:
_ ;
$ .
:
... ();
... .
:
0 1 2 3 4 5 6 7 8 9

( , ASCII):
( ) { } [ ] ; , .



Java ( -
) . -
ASCII, Unicode .
(, 137).
-, (), -
( ). Java -
, ( true false), (, 'a', 'b',
'1', '2'), (, " - "). -
null.
30 1

0x 0X
( 0, X), -
. :
0x10 1016 = 16;
0x2F 2F16 = 47 . .
.
, C/C++, Java
, 0 (. . 010 108 = 8).
-
,
.
int. -
L ( l, , -
), long, ,
int.
,
.

. ,
, . , -
, -
8 .
" "
( ), .
, -
. ,
.
,
. 10 ( 0 9),
. 10 , . .
, - ,
10 (. . 52 = 510 + 2;
137 = 1102 + 3101 + 7, . .).
,
. . ,
. -
.
. , -
, , -
, . .
, 10, 16 , 10, 16. -
,
( 9) : A, B, C, D, E, F:
0 1 2 3 4 5 6 7 8 9 A B C D E F
: A = 10, B = 11, C = 12, D = 13, E = 14, F = 15.
Java 31

, 0 9
, 9 . 10 15
A F,
. 16 -
10. , -
, -
. 10, 16.
(
).
, -
,
0 9, A F. -
, .

0x10 = 1016 = 16;


0x100 = 10016 = 1616 = 256;
0x1000 = 100016 = (16)3 = 4096;
0x20 = 2016 = 216 = 32;
0x21 = 2116 = 216 + 1 = 33;
0xF = F16 = 15;
0x1F = 1F16 = 116 + 15 = 31;
0x2F = 2F16 = 216 + 15 = 47;
0xFF = FF16 = 1516 + 15 = 255;
4.

Java
. 1.2 (keywords), -
. ,
( , . .).

1.2. Java

abstract assert boolean break byte


case catch char class const
continue default do double else
enum extends final finally float
for goto if implements import
instanceof int interface long native
new package private protected public
return short static strictfp super
switch synchronized this throw throws
transient try void volatile while
32 1

false, null true. -



, , -
.
.

1.4. .
Unicode.

,
(, , -
).
, .

. 1.3 , Java
. ,
( ,
).

1.3.


\b
\f
\n
\r
\t
\
\"
\\
\u Unicode

Java, C++ . Java -


, (\a, \v)
(\?).

Unicode
. ,
\u,
Java 33

UTF-16
UTF-8, :
\u0030 \u0039 ISO-LATIN 0 9;
\u0024 $;
\u0041 \u005a A Z;
\u0061 \u007a a z.


. 1.4 (. .
, ).

1.4.


+

*
/
%
=
~ ( )
? ( )
"? :"
: "? :".

^ XOR ( )
& AND ( )
| OR ( )
! NOT ()
>
<
{ ,
} ,
, ;

. ;
, , ,
( , -

34 1

1.4 ()


) , -

[ ,
] ,
; ,
' ( )
"
\ (backslash)

()
()
@ a ("")
#





. 1.5 ,
, -
.

1.5.


++ ( 1);
x++ x = x + 1
-- ( 1);
x-- x = x 1
&& AND ( )
|| OR ( )
<<
>>>
>>
Java 35

1.5 ()


==
!=
+= y += x y = y + x
-= y = x y = y x
*= y *= x y = y * x
/= y /= x y = y / x
%= y %= x y = y % x
|= y |= x y = y | x
^= y ^= x y = y ^ x
>>= y >>= x y = y >> x
>>>= y >>>= x y = y >>> x
<<= y <<= x y = y << x
/*
/** ,

*/ ( /* /**)
//

1.5. . .

, - -
. ,
(
), . -
,
. -, -
.
Java -. ,
, ( ) . ,
i1 I1 . ,
C/C++, , -
Pascal, .
Java ( ). ,
NetBeans .
36 1

, -
. - ,
, ,
. ,
.
( , , ), -
.
Java :
int ;
float ;
boolean ;
Object () Java;
. .
(),
.
a1 b1, MyType1, :
MyType1 a1,b1;

MyType1 .
j int:
int j;

.
, int , MyType1 .
,
.

.
i1 i2:

int i1=5;
int i2=-78;

int i1=5,i2=-78;

, "=" Java -
, ,
. , ,
, , . , b = a
, () b -
() a. -
:
x = x + 1
Java 37

. , , -
x, 1 ( -
x), x,
.
:
= ;
= ;
1 = 2;

. .
:
i1 = i2 + 5 * i1;

(primitive types) (, , ) -
, ,
.
, ( -
) , , . .
. ,
. , -
, .
,
C/C++/Pascal, -
.
, ,
null. ,
, null.
.
, null. -
, , .
Java . -
:
byte, short, int, long, char;
float, double;
(, ) boolean;
Java .
Java :
( ),
: int, float, boolean . .;
() ,
, ,
(, Object, Float, Boolean, Collection, Runnable). ,
(, JButton, JTextField,
JFormattedTextField, MyType . .). , float Float, boolean
Boolean Java ;
38 1

, ,
(, i, j, object1). ,
: myVariable, jButton2, jTextField2.getText() . .;
(. . 1.8)
, : mypackage, desktopapplication1,
org.jdesktop.swingworker ..;
( ),
"_", :
Double.MIN_VALUE, Double.MAX_VALUE, JOptionPane.INFORMATION_MESSAGE, MY_CHARS_COUNT . .;

"_"
.

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

1.6. -
.
- () -
, :
;
;
.
Java 39

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

- . -

.
-
, -
.


, , -
.
.
.
.
" " (. .
).
-
, ,
40 1

, . , -
, . , ,
(class members).
, , -
, . , , -
, .
("" ,
) , .
, ,
( ), .
, , -
. .
. .
-
.
Java . -
class, ,
( ) .
, . Java
, (. . -
).
, :
, .
, obj1 Circle ("") :
Circle obj1;

. -
, -
: , ( ),
, .
, -
null. ,
null. , , -
.
,
. .
Java , -
. new "",
, . ,
obj1 = new Circle();

, Circle (), (
) obj1. obj1
. new
.
Java 41

.
:
Circle obj1 = new Circle();

, , .
, . -
, ,
x, y r. Circle
, x, -
y, r. obj1 -
:
Circle obj1 = new Circle(130,120,50);

, - -
x = 130, y = 120 r = 50.
,
, -
. ,
Circle.
, . ,
,
. Circle,
-. obj1
, ,
, , -
. Java , ,
. :
Circle circle = new Circle(130,120,50);

,
, -
.
:
Circle circle1 = new Circle(130,120,50);
Circle circle2 = new Circle(130,120,50);

-
: , ,
. , obj1, -
x, :
obj1.x = 5;

show, ,
, :
obj1.show();

. -
. , ,
42 1

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

.( ).

,
. -
, . ,
.
, , -
, , 6,
.

static "".
" ", ,
, .
( ) -
.
static. , ,
, .
:
.

..
, . , . .
, ,
. .
, . . .
, Java. C++ .
, .

. , .
" ".
, . . ,
, , -
. . ,
, , -
, .
show(), -
.
, .
, , ,
, -
Java 43

. Java "", -
, . ,
, "" ,
.
.
, .
, , . . . -
. , ,
, -
. , -
-
.

1.7. .

, , . -
. -
, -
, . -
,
, -
. .
, . -
, . , -
,
.

, . . -
.
.
Java : -
,
, . Java
C++, . C++ -
, . ,
, , . . -
.
, , -
.
, ",
". .
null, -
, .
. Java -
null ( ).
44 1

-
, .
(Run-time error). -
Java () -
null :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.

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

. 1.1.

, -.
, . -
null ( " ", ==0), ""
, null. , Java
==, =, .

. "",
( ),
( ).
"" , " " ( -
) , . .
, , ,
-
.
new, , -
, ,
, -
. ,
"" .
. , circle1
Circle ( null).
" " null (. 1.2).

circle1 = new Circle(x1, y1, r1);

--
x1, y1 r1 ( - ,
) (. 1.3).
Java 45

. 1.2. circle1

. 1.3. circle1 Circle

, .
circle1 1, circle1 -
, . ,
,
circle1.
,
, .
circle2 Circle, :
circle2 = circle1;

,
.
(. 1.4):
Circle circle1 = new Circle(x1, y1, r1);
Circle circle2 = new Circle(x2, y2, r2);
Circle circle3;

. 1.4. ( )
46 1

:
circle3 = circle2;

, . 1.5.

. 1.5.
( circle3=circle2)

( circle2, circle3) -
2 (. . 2).
, , , .
, circle2.x x2, , circle3.x. ,
circle2.x, circle3.x
x 2.
, :
circle1 = circle2;

(. 1.6) , circle1
.

. 1.6.
( circle1=circle2)
Java 47

2 , -
: circle1,
circle2 circle3. 1 -
, , -
. , -
.
. Java -
, , " " (garbage
collection), . -
Java- .
Java, , C/C++ Object Pascal, -
, -
.
,
, . -
, , .
, -
, , . .
( , . . , ,
).

1.8. . .
.
() -
. . ""
"". "", ,
.
Java
,
.
Java -
.
.
, . (public)
, . -
, Java -
, (package).
(namespaces), .
- . -
( ,
, 256). -
, , , ,
.
48 1

, -
, , :
package _;

, ,
.
, ,
default.
. ,
pkg1, pkg2,
pkg3, , MyClass1 pkg3, -
:
package pkg1.pkg2.pkg3;
class MyClass1 {
....
}

. -
.
-
. -
-:
MS Windows pkg1\pkg2\pkg3\
UNIX Linux pkg1/pkg2/pkg3/
Mac OS pkg1:pkg2:pkg3:
NetBeans .
(packages) Java (packs) NetBeans.
NetBeans,
Java.
, , -
public:
public class MyClass2 {
....
}

.
public , MyClass1, -
, . ,
(). C++ -
"" friend, Java , -
default, "
".
.java
.
Java 49

(public) -
, , -
. , MyClass2 :
pkg1.pkg2.pkg3.MyClass2

, .
:
pkg1.pkg2.pkg3.MyClass2 myObject;

, Java
, ,
( )
. , ( !)
, .
. ,
javax.swing.JMenuItem

, :
javax swing ,
JMenuItem .
, -
. import.
MyClass2 pkg3,
(, mypack1), (,
MyClass3)
import pkg1.pkg2.pkg3.MyClass2;

MyClass3 MyClass2 ,
: pkg1.pkg2.pkg3. :
MyClass2 myObject;

, , -
, .
, import
*.
:
import pkg1.pkg2.pkg3.*;

, , -
. . ,

import pkg1.*;

import pkg1.pkg2.*;

MyClass2 , pkg1
pkg2 , pkg3.
50 1

: Java, -
java.lang, .
, g, java.awt.Graphics, -
:
:
java.awt.Graphics g;

Graphics java.awt
:
import java.awt.Graphics;
...
Graphics g;

( Graphics)
java.awt -
:
import java.awt.*;
...
Graphics g;

,
. , PI sin,
cos . java.lang.Math.
sin x
, y ,
x
Java ,
:
y=Math.sin(Math.PI*x)/(Math.PI*x);

java.lang ,
java.lang.Math.PI java.lang.Math.sin. PI
sin , -
:
final double PI=Math.PI;

:
double sin(double x){
return Math.sin(x);
}

sin,
. Java
, .
JDK 5, Java
.
:
import static java.lang.Math.PI;
import static java.lang.Math.sin;
Java 51

:
import static java.lang.Math.*;
:
y = sin(PI * x) / (PI * x);
Java java javax. -
.
. , -
, , .
-
, ,
. , . .
. , -
-
. -
.
Java ,
( , , . . "-
" ). ,
WWW-, .
, phys.spbu.ru (-
http://www.phys.spbu.ru/), -
ru.spbu.phys. -
(computational physics)
ru.spbu.phys.cph, . . cph.
(mathematical
physics) ru.spbu.phys.mph,
. . mph.
ru, fr
. .
, - (-
, JDK), , ,
, , . .
. -
, ,
.

1.9. Java
-
, . , "
", -
.

(" "), " ", ,
52 1

, (), . ,
,
"" " " . -
. ( )
, , . -
, !
-
.
, , -
. Java -
.
JDK 1.6 : java, javax, org com.sun. ,
, .
. 1.6 java.

1.6. java

,
java.applet
java.awt
(Abstract Window Toolkit
)
java.beans JavaBeans

java.io /

java.lang Java.

java.lang.reflect , -
, -
. reflection ""

java.lang.Math , ,

java.math ,

java.net ,
(sockets)

java.nio , -
java.io. , -
() -
, channels ( , )
charset ( ). charset
Unicode
, -

java.rmi
Java 53

1.6 ()

,
java.security , -
, ( ,
, . .)

java.sql SQL-

java.text , -
, , , ,
. ,

java.util (
).
(, ),

java.util.jar jar- ( Java)

java.util.zip zip-

javax, ,
Java 2, . 1.7.

1.7. javax

javax.accessibility
, . ., -
, -

javax.activity
javax.crypto -
javax.imageio (/)
javax.management (MBean Manage-
ment Bean)
javax.naming
javax.net ,
(sockets). java.net
javax.print
javax.rmi .
java.rmi
javax.security , -
. java.security
javax.sound
54 1

1.7 ()


javax.sql SQL- .
java.sql
javax.swing Java 2
javax.transaction
javax.xml XML-

org (. 1.8) ,
.

1.8. org


org.ietf GSS (Kerberos v5)
org.omg Java CORBA, -

org.w3c XML-
DOM
org.xml XML-

com.sun (. 1.9) Sun Microsystems -


javax.

1.9. com.sun


com.sun.accessibility javax.accessibility
com.sun.beans java.beans
com.sun.corba -
CORBA (Common Object Request Broker Architecture)
com.sun.crypto javax.crypto
com.sun.image
com.sun.imageio javax.imageio
com.sun.java (. . 2.9), -
WWW-
com.sun.java_cup JavaCup
com.sun.jlex
com.sun.jmx javax.management
com.sun.jndi
com.sun.management javax.management
Java 55

1.9 ()


com.sun.media
com.sun.naming javax.naming
com.sun.net javax.net
com.sun.org Apache,
CORBA
com.sun.rmi javax.rmi

org.jdesktop, JDK,
NetBeans. ,
. ,
java.beans, javax.swing, org.jdesktop.swingworker,
NetBeans. , org.jdesktop
application, Desktop Application
(. 13), beansbinding, -
(binding) Java Beans (. 15).

1.10. Java, .NET, ASP, PHP


Java 1995 - -
.
C C++ . -
Java Java, ,
, . 1998 -
Java Beans, Java
, -
Microsoft Visual Basic Borland Delphi. , Java -
.
2000 Microsoft ,
.NET, Java: -
, ( -
),
- , JIT- .
.NET .
-, .NET -
. ,
,
, .NET Common Language
Environment Common Language Runtime
. -
.NET C#,
Java, ,
56 1

. , Turbo Pascal -
Delphi ( Object Pascal), Borland Ltd
Microsoft, C# .NET, Java -
, Delphi.
-, Java -
, .NET -
MS Windows. .NET
.NET Framework,
.
.NET ( Java) . ,
.NET (. . Common
Language Environment), - .
, ,
.NET
.NET.
, . -
. , - -
.NET Framework , -

- . , -
.NET Framework,
MS Windows ( Windows XP)
. , -
.
-
.
, .NET ISO (International
Standard Organization ) 2004 , -
, .
Mono .NET Linux,
.NET -

Java . -
, ,
. Java
J.NET .NET, . . -
.
, J.NET Java , ,
, . -
.
J.NET
Java.
, Java Sun, .NET-
Java.NET . Microsoft
Java Visual J++, Borland J-Builder.
Java 57

Java .
, .NET -, Microsoft,
, Java
.NET. NetBeans, Java Scripting
Open Source ( ).
NetBeans , -
Java Beans, . -
NetBeans
Java, NetBeans,
. , NetBeans
. ,
C/C++ Pack
C C++. (Packs), -
JavaScript, Ruby, Groovy, PHP, JavaFX .

NetBeans.
Java, JDK 6,
Java Scripting (. http://
java.sun.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html).
(API, application programming
interface), javax.script, -
Java-. -
, -
Java-.
(. https://scripting.dev.java.net/),
. , NetBeans
( -
).
NetBeans (NetBeans Platform)
NetBeans . ,
Java.

. NetBeans, NetBeans -
http://www.netbeans.org/downloads/zip.html.
NetBeans
.
. -
, .
, , . .
, ,
Schliemann (http://www.netbeans.org/community/magazine/html/03/schliemann/).
(Open Source), -
, .
. (freeware
) -
58 1

, , -

. -
, , ,
-
.
NetBeans 6.5 GNU General
Public License Version 2 with Classpath Exception ("GPLv2 with Classpath Exception")
Common Development and Distribution License ("CDDL"), -
, .
GNU GPL , -
, , ,
. , -
, , -
.
CDDL (" ")
Sun Microsystems Mozilla Public License (MPL) 1.1.
-
, -,
.
-
NetBeans -
Java,
, NetBeans
-
, NetBeans ( Java)
.
.NET
( Swing ). , ,
JDK. -
.NET.
-
JDK. ( java) JDK
, javax. , -
NetBeans (Web & Java EE, UML Pack .) -
(packages).

(Enterprise Software), . . , -
. , ,
. , , -
. (
, ) -
.

"". Java, -
Java 59

, Java. -
11 Java.
, .
,
C/C++. , Java,
, , -
. C/++ Java
native () Java (. 16) " -
" .
C/C++, Java C/C++.
ASP (Active Server Pages) Microsoft.
Java- JSP, 11,
Windows, .
PHP -
ASP JSP, ,
ASP JSP . PHP
Open Source , JSP. PHP5 -
, -
. PHP-
, -
. PHP- -
. , -
. , NetBeans 6.5 -
PHP-.
, , Java -
, ,

Java, .

1.11. NetBeans, Eclipse,


JDeveloper, JBuilder, IntelliJ IDEA
-
(Integrated Development Environment IDE) Java
(. 1.10).

1.10. Java


NetBeans 6.5 Sun, .
netbeans.org
http://www.netbeans.org/.
248 .

Java
60 1

1.10 ()

JDeveloper 11 Oracle ,
Oracle Java EE,

Java.
http://oss.oracle.com/jdeveloper.html. -
656

Eclipse 3.4.1 IBM, .


Eclipse Foundation http://www.eclipse.org/.
86 ( "Eclipse IDE
for Java Developers") 163 ( "Eclipse IDE
for Java EE Developers"). ()

JBuilder 2008 Borland, (JBuilder 2008


CodeGear Turbo) (JBuilder 2008 Professional
JBuilder 2008 Enterprise).

http://www.codegear.com/.
1,8 ,

IntelliJ JetBrain . -
IDEA 7.0.4 .
http://www.jetbrains.com/idea/.
88

, .
,

. , -
Java.
, -
, ,
(. 2).
IDE , -
(. 17).

( -
, . . .
7).
(Vesrion Control
Systems VCS, , , Revision Control Systems, Source Control
Systems Source Code Management SCM). -
, ,
. , -

.
Java 61

(NetBeans, JDeveloper, IntelliJ IDEA) -


,
(. 17).
, -
-
. , , , ,
, Eclipse, . .
. , , -
,
Eclipse, -
. , , JBuilder -
. " "
, .
, -
(-
) , .

NetBeans 6.5
NetBeans (" ") .
. .
-
.
, ,
NetBeans, .
NetBeans ,
, .

(GUI)
(Java ME, . 14).

( -
, ,
. 2,
JDK ).
(deploy)
, .
Java, C,C++, Ruby, Groovy, JavaScript, JavaFX, JRuby, Rails,
Grails, HTML, CSS, XML, XHTML, JSP, EJB, AJAX, Hibernate, JPA,
Spring, Web Services, Struts.
JUnit (. 17).
UML-. Eclipse ( -
) JBuilder.
. IDE, , -
(285 , 315 -
62 1

. 1.7. NetBeans

. 1.8. GUI NetBeans


Java 63

).
( 512 ) -
( Celeron 1000). IntelliJ
Idea JBuilder. .
. 1.7 NetBeans
DesktopApplication (. 2 13). . 1.8 -
NetBeans .
Eclipse 3.4.1 (Ganimede)
Eclipse ("") .
NetBeans
, NetBeans. NetBeans 6.5
JDeveloper 11, , , . -
. .
Java.
Java
.
() MyEclipse, BEA Workshop,
IBM Rational Application Developer, Borland JBuilder ( CodeGear
JBuilder) . ,
,
.
. -
.
Eclipse -
. Software Updates (-
), Help.
Eclipse, ! ,
Eclipse , -
, JDeveloper, JBuilder.
Eclipse -
C++ ( NetBeans 6.5
C++, , , -
. 16).
Eclipse Ganimede
.
. -
JDK,
src.zip JDK, .
.
""
( ,
, . .).
, -

.
64 1

Java, C, C++, Ruby, Groovy, JavaScript, JRuby, Rails,


Grails, Flex, XSL, HTML, CSS, XML, XHTML, JSP, EJB, AJAX, GWT,
Hibernate, JPA, Spring, Web Services, Struts.
JUnit JBuilder.
. (260 -
, 335 -
) NetBeans.
. GUI, -
( GUI -
NetBeans). UML- -
. ,
( Eclipse ).
. -
, -
.
JDK.
NetBeans, IntelliJ Idea.
. 1.9 Eclipse .
: Eclipse -
,
, NetBeans JDeveloper. -
, Java-, -
.

. 1.9. Eclipse
Java 65

JDeveloper 11
JDeveloper ("Java-") , -
Oracle Java EE. -
Oracle,
-
Java.
-
(GUI), . -
, .
(deploy) , -
, .
( ). -
JDK ,
JDK ( src.zip JDK). -

.
JUnit. UML-
.
. , , NetBeans (360
, 410
). NetBeans
. .
JDK. -
,
(, "Program Files") .
,
, -
, . JDeveloper
WebLogic, .
(, JDK) -
.
Windows XP SP2 JDeveloper
( java-),
. XP SP3 (
JDK: JDK 6 update3
). Java ME. -
( , , UML- , . .)
(Undo).
(, XYLayout . . 2.15). -
.
,
.
. 1.10 , JDeveloper -
( , -
66 1

, Java EE,
Java).
. 1.11 JDeveloper ,
. 1.12 GUI.

. 1.10. JDeveloper

. 1.11. JDeveloper
Java 67

. 1.12. JDeveloper

, ,
, UML-, JDeveloper
, , ,
. , , Oracle
, -
NetBeans, .
: JDeveloper NetBeans
Java
Java SE Java EE. Java ME
NetBeans.

JBuilder 2008
(JBuilder 2008 Turbo)
(JBuilder 2008 Professional JBuilder 2008 Enterprise).
. ,
(
). .
Eclipse Eclipse .
Eclipse, . , -
, - -
( )
68 1

. 1.13. JBuilder

. 1.14. JBuilder
Java 69

AspectJ Java, -
GUI ( ), UML-
( ).
. , , NetBeans (350 -
, -
450 ).
(1,8 ). , ( -
, "Program Files"). -
GUI. : jar- -
,
.
, . -
NetBeans, IntelliJ Idea.
. 1.13 JBuilder ,
. 1.14 GUI.
: JBuilder
NetBeans, .

IntelliJ IDEA 7.0.4


. , , -
, -
(Java ME). , -
Java,
Java-. , -
,
600 ,
( , , , , -
, , , , , -
, -
). , -
, .
Java, Ruby, Groovy, JavaScript, JRuby, Rails, Grails, Flex, XSL, HTML, CSS, XML,
XHTML, JSP, EJB, AJAX, GWT, Hibernate, JPA, Spring, Web Services, Struts.
.
JBuilder Eclipse.
.
. , , NetBeans (300 -
, -
450 ). -
" -
" .
" ", . -
, . . Idea -
.
Idea . -
70 1

, ,
IntelliJ IDEA, -
. , -
.
UML-.
JDK. :
jar- ,
. NetBeans.
: IntelliJ IDEA
Java,
NetBeans. -
IntelliJ IDEA .


NetBeans 6.5 -
Java. -
Eclipse, -
IDE, IntelliJ IDEA
JBuilder. JDeveloper, -
11 ,
Java EE. IntelliJ IDEA
NetBeans 6.5 .


Java , .
( ASCII), -
( Unicode),
, .
-
. -
0x 0X, .
Java , JavaScript -
HTML-, C++ -
. Java , -
, - C- .
Java , -
(-). - -, . .

Java- (JVM).
JIT- (Just-In-Time) - -
, . . " ", " ".
-
.
Java 71

Java:
(application) ;
(applet) -
, WWW- ;
(midlet) -
, ;
(servlet) -
, WWW ;
(Enterprise application) -
;
(Java Class Library , NetBeans Module
NetBeans) -
Java.
Java 1.0 1.1 Java 1. Java, c 1.2, -
Java 2.
Java ( Java-)
SDK (Software Development Kit)
. SDK:
Java ME Java Micro Edition, -
" ";
Java SE Java Standard Edition, -
;
Java EE Java Enterprise Edition, -
.
Java -. Java
Unicode.
, -
, .
"\",
.
Unicode "\u", -
,
\u1234.
Java
.
. -
.
, , . . -
,
, . -
Java .
72 1

, -
. ,
.
Java . -
, . -
( -) . null -
, .
- :
, , .
, . ,
. , -
. , .
, , .
. , , .
.
, .
, .
. .
-
, .
. -
.
.
, , -
public. -
. java
. public
, ,
. , .
java javax, .
, java.
javax. .
-
, import pkg1.pkg2.; import
pkg1.pkg2.*;.
,
:
import static java.lang.Math.PI;
import static java.lang.Math.sin;

:
import static java.lang.Math.*;
Java 73

main, -
public static void main(String[] args). -
, , -
.
NetBeans 6.5 -
Java ,
Eclipse ( -
), IntelliJ IDEA JBuilder.
JDeveloper, 11
, -
Java EE.
IntelliJ IDEA NetBeans 6.5
.


Java JavaScript, , JavaScript -
Java. . -
Java JavaScript AJAX
(Asynchronous JavaScript and XML JavaScript XML). -
.
, Java -
(JRE).
(applications) (applets).
0x... -
O.
, Java -
.
, ,
( , Pascal
Fortran).
: , -
. . , . . ,
, , -
.
. .
, .
, -
null.
.
.
74 1

16- 0, 1, 8, 15, 16, 255, 256.


, :
i1, i_1, 1i, i&1, i1234567891011, IJKLMN.

, -
:
myObject, MyObject, myobject, Myobject, my object, my_object, $myobject
2

NetBeans 6.5

NetBeans (Integrated Development


Environment, IDE), . . ( ), -

.
.

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

.

2.1. JDK 6
, -
, Windows,
NetBeans . , Linux -
, linux (. -
).
, , -
. NetBeans 6.5 -
353 . ( Windows XP SP3 1,5
) 176 ,
177 (
). 7 ,
Java- ( java.exe).
1000 , ,
,
. , ,
76 2

512 ,
NetBeans 6.5. , -
, .

Pentium 4 (1,6 ) Celeron (2,4 ) .
- NetBeans 6.5.
NetBeans 6.5 Windows -
netbeans-6.5-ml-windows.exe.
JDK. -
JDK (5 6) , . 2.1.

. 2.1. , ,
JDK

Exit Installer ( )
jdk-6u11-windows-i586-p.exe.
JDK 5 JDK 6 , -
6 5- . -
JDK 6 , JDK 5,
6 , -
( , ),
Java-, Java-
. , JDK 6 update 10,
JDK -
, . -
JDK JRE -
. Java -
.
JDK 6 . ,
MS Windows Windows 2000 SP4 ( 4) ,
XP SP2, Vista. JDK (,
XP SP1) , -
,
( Sun). -
NetBeans, JDeveloper 11, XP SP3
NetBeans 6.5 77

JDK 6 (update 7 ). JDK jdk1.6 -


jdk-6u11-windows-i586-p.exe.
,
, , Sun (. 2.2).

. 2.2.

JDK 1.6u11 (JDK 6 11). -


- JDK,
. -
, NetBeans 6.5, -
.

Accept > ()
JDK. Decline () -
. , Sun -
JDK Java- , -
JDK, ,
"AS IS" (
), - Sun -
.
Accept > -
JDK (. 2.3). .
300 + 46 + 49 + 173 + 25 = 593 . ,
, Public JRE (
Java 173 ). - JDK -
( Change... ) -
.
78 2

. 2.3. JDK

Next > (, ) . -
( 23 -
), (. 2.4),
JRE 6. , JRE, -
, JRE, JDK
.

. 2.4. ,
JRE
NetBeans 6.5 79

. 2.5. JDK

Next > . , 34 -
, . 2.5, -
.
Finish ().

2.2. NetBeans 6.5


, NetBeans IDE netbeans-6.5-
ml-windows.exe. , IDE " ".
,
(. 2.6).

. 2.6. ,

, 23 ,
(. 2.7),
Customize...,
(. 2.8).
80 2

, .
(runtime) -
, -
.

. 2.7. ,

. 2.8.
NetBeans 6.5 81

(
, ,
).
Base IDE. 70,8 . ( .)
NetBeans .
.
Java SE. 63,9 . (
Java.) Java. , , -
,
( Matisse).
NetBeans Java.
.
Common Web Components. 5,2 . (, -
Java Web, PHP, Ruby on Rails, Grails.
JavaScript).
.
Java Web and EE. 110,1 . ( WWW-
Java, () , -
J2EE 1.4 Java EE 5.) , JSP (Java
Server Pages), , Spring ( ""
Java EE JDBC, ORM,
JTA, Servlets/Jsp, JMX .), Struts ("" WWW-
), Java Persistence API ( Java Persistence -
Java), Enterprise Java Beans ( Java Beans), JAX-WS
(- JAX. JAX Java API for XML-
Based Remote Procedure Calls
XML ), RESTful (-, -
-
URI), Java Server Faces ( Java), Groovy, Grails.
-
.
.
Java (. 11).
Java ME. 100,0 . ( -
Java Micro Edition .)
, - -
.
.
Java -
(. 14).
Ruby. 38,3 . (
Ruby () Ruby on Rails.)
82 2

JRuby, ( ) Rails, , -
, " ", Ruby.
.
C/C++. 13,4 . ( C C++.)
, , , -
, . -
- (native) 16.
PHP. 4,7 . ( NetBeans PHP.)
.
SOA. 23,7 . ( SOA
(Service Oriented Architecture) , -
.) BPEL, -
, ,
, , .
, GlassFish Open ESB 2.0.
, .
Runtimes ( ):
GlassFish v2 UR2. 84,8 . ( -
Java.) Java EE 5. -
.

Java EE 5 - .
Sun Java System Application
Server PE 9 Sun TopLink persistence Oracle.

(. . 11.3 11.4). -
, .
GlassFish v3 Prelude. 36,8 . -
GlassFish. 2 ,
, .
. , -
-
.
Apache Tomcat 6.0.18. 10,4 . ( -
.) JSP
(JavaServer Pages).
. , -
(
) GlassFish, -
.
Open ESB v2. 12,2 . ( Enterprise
Service Bus (ESB ), Java
NetBeans 6.5 83

Business Integration (JBI Java- ).) Open ESB


,
, SOA.
.
564 .
OK NetBeans.
Next >.
. -
I accept the terms in the license agreement (
). NetBeans -
.
Next >.
, ,
NetBeans , JDK,
NetBeans (. 2.9).

. 2.9. , NetBeans

Next > -
GlassFish (. 2.10).
, , ,
.
.
Next > -
Glassfish-v3-prelude. Next >. -
Apache Tomcat 6.0.
Next >.
. Install
() . ,
, -
Setup Complete ( ) . 2.11.
84 2

. 2.10. GlassFish

. 2.11. NetBeans 6.5

,
NetBeans, ,
NetBeans GlassFish, -
Finish () -
. -
() Finish, -
. NetBeans,
/ NetBeans 6.5/NetBeans IDE.
NetBeans 6.5 85


, NetBeans,
Customize . , -
-
.
-
NetBeans Tools/Plugins (/
).
NetBeans / ( Open
ESB, ) -
, Uninstall
Program Files\ NetBeans 6.5.
, (,
Kaspersky Antivirus ) -

( nbi-cleaner, ).
, "" -
.
-
(-, ).
NetBeans 6.5 (welcome page, start page)
(. 2.12). , -
, Show On Startup (-
).
. ,
(
), JDK, -
jdk-6-doc.zip -.
(, C:\Program
Files\Java), (IDE) NetBeans
Tools/Java Platforms.
(. 2.13),
Javadoc, Add ZIP/Folder... (
-
, "" ).
(
Add ZIP/Folder) JDK .
NetBeans: Help () -
Javadoc References/Java Platform SE 6,
Help/Javadoc Index Search (<Shift>+<F1>) (. 2.14).
- , -
<Shift>+<F1> .

, ,
(HTML-) ,
.
86 2

. 2.12. NetBeans 6.5

. 2.13. JDK
NetBeans 6.5 87

. 2.14. Javadoc Index Search

2.3. NetBeans
Java
NetBeans Java. -
(IDE) NetBeans, File/New Project..., -
(. 2.15) Categories ()
Java, Projects () Java
Application Next >.
(. 2.16), -
.
Finish.
, .
. 2.17 , -
NetBeans.
, rtl
JDK, .
.
Projects . -
JavaApplication1. -
.
( -
).
88 2

. 2.15. . 1

. 2.16. . 2

() .
(Source Source code )
(,
Design () ).
Main.java Navigator
.
NetBeans 6.5 89

. 2.17.

,
, .
, Java
( 2.1).

2.1.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package javaapplication1;

/**
*
* @author User
*/
public class Main {

/**
* @param args the command line arguments
*/
90 2

public static void main(String[] args) {


// TODO code application logic here
}

/* ... */,
, (template) .
, javaapplication1.
/** ... */, -
. -
@author
javadoc.
,
, -
-
, , -
. . User
. -
( " ").
Java JDK 5 -
, @, ,
, .
. 2.13, 9.1, 11.2, 11.4, 13.5
17.4.
main,
:
public static void main(String[] args) {
}

(. . 1.6) -
Main. ,
main.
main , -
. args -
, String[]. , -
. String "", -
, .
main .
Java ,
, , -
. ,
, (default) , -
, .
NetBeans 6.5 91

, -
. -
. Java , -
.
, (-
), .
, . . (,
).
Java, C/C++, -
, - . -
-, , C/C++/Java -
- void (, -
), main.
NetBeans .
- , . -
"!". main
:
// TODO code application logic here
( ).

,
, -
.
:
System.out.println("!");

System () out (). , -


. println .
/ , -
. -
( -
). , -
, (
, ). -
Java .
,
,
/. NetBeans -
(Graphics Users Interface, GUI)
. ,
.
NetBeans -
(. 2.18).
, ,
out ().
92 2

Main() , , -
, , .

. 2.18.

Main() Main. ,
.

-
<Enter>.
. ,
Java \n, -
<Enter> .
, NetBeans
C:\Documents and Settings\User\ \NetBeansProjects, -
. -
, . -
NetBeans. , -
(
) File/Open Recent Project (/
).

2.4.
. Jar-
compile
() build (). compile -
, -
. build .
Run/
Build Main Project ( <F11>, -
).
.
Run/Clean and Build Main Project ( <Shift>+<F11>
)
NetBeans 6.5 93

( build dist), -
.
Run/Generate Javadoc (JavaApplication1)
. ,
/** ... */,
HTML-.
Run/Complile "Main.java" ( <F9>)
( Main.java, -
Main).
,
Run/Run Main Project ( -
<F6>, ).
( ), -
<F6>.
( -
)
(. 2.19).

. 2.19.

System.out.print System.out.println.
System.out.print System.out.println , println
, print
.
:
System.out.println("!");
System.out.println("!");

:
!
!

System.out.print("!");
System.out.print("!");

:
!!


NetBeans , :
94 2

java -jar "C:\Documents and Settings\User


\ \NetBeansProjects\JavaApplication1\dist\JavaApplication1.jar"

, , , -
.
class, -
.
,
.
(deployment) , Java -
jar ( Java Archive
Java).
, ,
, .
, -
, , (
).

/... ( Far, Windows Commander, Midnight Commander
. .). -
. , , ,
.
Far (http://www.farmanager.com/)
: ,
( <Ctrl>+<O>).
, . . Unicode Far .
, main
, 2.2 ( 02_04_console -
-).

2.2.

public static void main(String[] args) {


System.out.println("!");
try {
System.in.read();
} catch (Exception e) {
}
}

System.in.read().
try-catch . 8.6.
jar -
Java-. -
jar- NetBeans
Run/Build Main Project ( ) (
<F11>).
NetBeans 6.5 95

jar- . ,
( -
),
, -
. -
, .
jar-, :
1. ( Set as Main Project -
,
).
2. Run/Set Project Configuration/Customize... (/
/ ) NetBeans,
Projects
Properties ().
3. Build/Packaging ()
Compress JAR File (. 2.20).

. 2.20. jar-

(, -
).
(, ) -
Run/Clean and Build Main Project ( -
) ( <Shift>+<F11>
). -
, ,
, -
.
96 2

2.5. NetBeans
, NetBeans. Projects (. 2.21) -
: Source Packages ( ), Test
Packages ( ), Libraries () Test Libraries (
). ,
/ ,
/. .

. 2.21. Projects

NetBeans -
. NetBeans
, . -
( ).
,
jar (Java Archive Java). ,
, jar ( JavaApplication1.jar). NetBeans -
, -
,
,
.
NetBeans
,
.
NetBeans .
,
Projects () ( ) -
JavaApplication1/SourcePackages/javaapplication1/.
.
Main.java,

Open.
. Welcome (-
, ). ,
NetBeans 6.5 97


( ). -
.
, .
. . -
(, -
). (Main Project)
Run/Run Main Project.
- , -
-
Set Main Project. - , -
Close Project.
, . 2.17,
,
. , ,
,
Start Page Main.java. , -
. 2.22.

. 2.22.
98 2

. -
, Projects . 2.23.

. 2.23. Projects

Projects Projects,
, . 2.22.
,
.
NetBeans.
. Windows XP
C:\Documents and Settings\\.
( 2.3).
,
. , -
, -
.

2.3.

build
classes
javaapplication1
NetBeans 6.5 99

Main.class
... .class
META-INF
dist
javadoc
lib
JavaApplication1.jar
README.TXT
nbproject
src
javaapplication1
Main.java
... .java
... .form
META-INF
test
build.xml
manifest.mf

, :
build , class;
dist , -
( JAR- ,
HTML- javadoc);
nbproject ;
src . , -
(), .
, . .
XML-, form;
test , -
.
,
.
2.4 README.TXT, dist (
, jar, ).

2.4. README.TXT dist

===============================

===============================
Java, ,
(IDE) jar-, classpath
, dist/lib.
(MANIFEST.MF).

, dist
:
java -jar "JavaApplication1.jar"
100 2

, dist ( lib)
zip-.

* jar-, classpath , ,
lib .
* classpath , classpath
dist.
* , classpath, classpath,
classpath .
* Java,
Projects Properties. Run
Main Class. ,
Main-Class .

2.6. NetBeans Java



, () ,
, , -
. .
, -
, RAD-.
RAD Rapid Application Development ( -
).
NetBeans -
, - -
(Object-Oriented Design, OOD).
NetBeans RAD-
(Graphics Users Interface,
GUI). Java, , ,

. -
.
, -
, ,
Java.
-, ,
.
, , ,
. -
.
-, - -
, , -
, , , . : -
,
, .
NetBeans 6.5 101

NetBeans 6.5 GUI- Desktop Application, -


. -
02_06_ GUI_example -.
-
NetBeansProjects. :
C:\Documents and Settings\User\ \NetBeansProjects.
NetBeans ( )
( ).
Close () (. 2.24).

. 2.24.

(, ),
-
, Close 3 Projects.
.
File/Open Project ( , -
<Shift>+<Ctrl>+<O>).
02_06_GUI_example ( , -
), Open Project (
), Project Folder (. 2.25).
102 2

. 2.25.

Open as Main Project ( ), -


. ,
Open Project
Open as Main Project .
, 2.5.

2.5.

/*
* GUI_application.java
*
*/

package examples;

/**
*
* @author
*/

import javax.swing.*;

public class GUI_application extends javax.swing.JFrame {


/**
* Creates new form GUI_application
*/
public GUI_application() {
initComponents();
}
NetBeans 6.5 103

/** This method is called from within the constructor to


* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
+Generated Code

private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt)


{
System.exit(0);
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI_application().setVisible(true);
}
});
}

// Variables declaration do not modify


private javax.swing.JMenuItem aboutMenuItem;
private javax.swing.JMenuItem contentsMenuItem;
private javax.swing.JMenuItem copyMenuItem;
private javax.swing.JMenuItem cutMenuItem;
private javax.swing.JMenuItem deleteMenuItem;
private javax.swing.JMenu editMenu;
private javax.swing.JMenuItem exitMenuItem;
private javax.swing.JMenu fileMenu;
private javax.swing.JMenu helpMenu;
private javax.swing.JMenuBar menuBar;
private javax.swing.JMenuItem openMenuItem;
private javax.swing.JMenuItem pasteMenuItem;
private javax.swing.JMenuItem saveAsMenuItem;
private javax.swing.JMenuItem saveMenuItem;
// End of variables declaration
}

. examples, -
, . GUI_application
, :
public class GUI_application extends javax.swing.JFrame

, GUI_application,
JFrame, swing, javax.
extends "" (- -
-).
104 2

GUI_application() -
initComponents(),
+Generated Code.
, , .
, .
(private) , :
private void exitMenuItemActionPerformed

public static void main(String[] args)

.
Java- .
.
-
( 9), ( 10) (-
12). .
- . -
-
.
Run/Run Main Project (
<F6>, ) , -
. 2.26 2.27. , -
, , -
.

. 2.26. . 2.27.


exitMenuItemActionPerformed. -
, -
( ). -
exitMenuItemActionPerformed :
System.exit(0);
NetBeans 6.5 105

main
. ,
(
"" ).

2.7.
Design () .
(
Source ( )) (
Design), . 2.28.

. ,
, Palette ()
Properties () .

. 2.28.

,
- . , -
. -
. , " ".
, -
. NetBeans 6.5
Swing -
:
Swing Containers () , -
;
106 2

Swing Controls ( ) -
: , , . .;
Swing Menus () (popup)
;
Swing Windows () (
, );
AWT AWT,
Java;
Beans , -
;
Java Persistence , -
" " (-
, ).
, JButton ( Java
Button). Swing Controls (-
Swing), , Button
.

, . -
, . -
, , . -
(Properties) (Events)
Properties. (
Properties), Events.
, ,
.
,
. , ,
. jButton1, jButton2
. .
, .
.
-, Properties, text -
<Enter> .
-, label.
-, (. . -
), Edit Text ( ) .
, Properties
text label,
(
) (. 2.29).
NetBeans -
, ,
NetBeans 6.5 107

. 2.29.

NetBeans 6.5 (,
JLabel JTextArea).
JButton, JTextField -
,
, .
13,
(Desktop Applications). ,
( !) . -
, .
OK .
(
). -
.
, 02_07_
GUI_example1 -.

. HTML-,
. 11.1, HTML. ,
HTML, HTML- -
Swing. <html>,
HTML- . , HTML-,
, , -
.


HTML ,
. .
108 2

(. 2.30):
"<html><p align=center>OK</p> "

, . 2.31.
( Java -
toolTip, Microsoft hint).
: " "
, toolTipText.
HTML- -
,
. HTML
: <html> -
, HTML-, <br> ,
.

. 2.30.

. 2.31. HTML-

, , ,
(event handler) .
, -
Events/Action/actionPerformed (. 2.32).
Events "", Action "", actionPerformed "
".
NetBeans 6.5 109

. 2.32.

, -
:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

.
. -
(Design), Inspector
(. 2.33). jButton1 [JButton] (
). -
. -
, .
jButton1ActionPerformed -
, :
private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}

,
:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
110 2

. 2.33.


, .
02_07_ GUI_example2
-.
,
- (, ). -
:
javax.swing.JOptionPane.showMessageDialog(null," ");

javax.swing , javax.swing
.

2.8.
( , , )
.
. -
: , . ,
,
. <Enter> -
,
<Esc>.
"..." -
-
, .
,
.
-
, -
Properties.
NetBeans 6.5 111

.
.

checkbox . ,
false, true.
. 2.1 JButton , -
( ).

2.1. ,


Properties ()
action javax.swing.Action,
actionEvent. NetBeans 6.5
ActionPerformed -
Action ( . 13)
background
font
foreground
icon ( , ),
.
Icon (. . 2.11, 13.313.4 13.7)
mnemonic - (, -
q -
<Alt>+<q>)
text ()
toolTipText , -

Other Properties ( )
UIClassID , ,
Look and Fill (. . 2.9)
actionCommand , - -
, ,
(. 13). -

alignmentX
alignmentY
autoscrolls , ,
,

baselineResizeBehavior (. . 3.8), , -

( -
)
border
112 2

2.1 ()


borderPainted
buttonGroup
ButtonGroup.
ToggleButton RadioButton
componentPopupMenu , -

contentAreaFilled ,
( ,
)
defaultCapable , :
<Enter> -
(
)
disabledIcon ,
, (disabled) (. .
enabled false)
disabledSelectedIcon ,
, (disabled)
(. . enabled false)
displayedMnemonicIndex -,
(. . char)
doubleBuffered
(
true). -
,
. -
,

enabled , . -
. -

(. .
)
focusCycledRoot , -
.
,
. .
nextFocusableComponent
focusTraversalPolicy -
() -
. ,
:
ContainerOrderFocusTraversalPolicy
DefaultFocusTraversalPolicy
; SortingFocusTraversalPolicy
-;
LayoutFocusTraversalPolicy -
. . -
nextFocusableComponent
NetBeans 6.5 113

2.1 ()


focusTraversalPolicyProvider , ,
focusTraversalPolicy -

focusPainted
. -
,
focusable , . -
-
-
hideActionText , -
, (. 13).
false ( ),
, (
actionCommand). -

horizontalAlignment / , -
.
:
CENTER ( );
LEADING (, );
LEFT ( );
RIGHT ( );
TRAILING (" ").
LEADING
LEFT, RIGHT TRAILING
horizontalTextPosition ,
.
:
CENTER ( );
LEADING, LEFT ( );
RIGHT, TRAILING ( )
verticalAlignment / , -
.
:
CENTER ( );
TOP ( );
BOTTOM ( )
verticalTextPosition ,
.
:
CENTER ( );
TOP ( );
BOTTOM ( )
iconTextGap () ( ) -
, ( ), ,

114 2

2.1 ()


inheritsPopupMenu . true
( ), -

(),
inputVerifier javax.swing.InputVerifier, -

insets - , , -
, -

label , Text, -
(
java.awt.Label).
maximumSize , -
.
, resizable
true
minimumSize ( ,
).
, resizable
true
model -
. - -
, NetBeans
-

multiclickThreshold ( )

name . ,
Java-
nextFocusableComponent ,
<Tab> . -
,
.
LookAndFeel . . 2.9. System Windows
, Metal
opaque . , -
, ( -
Windows 2000).


paintingForPrint . true
( ), -
print
( print)
preferredSize (
)
NetBeans 6.5 115

2.1 ()


pressedIcon ,
, (
)
requestFocusEnabled , -
.

rolloverEnabled ,

rolloverIcon ,

rolloverSelectedIcon ,
. -


selected . true (-
), .
,
(JCheckBox),
(JToggleButton), ,
selectedIcon ,

verifyInputWhenFocusTarget , -

. inputVerifier,

, Layout ( ), -
. 2.15. , -
-, . -
, (Free Design).
, , -
, Properties .
, ,
, (. 2.2).

2.2.


defaultCloseOperation ,
. HIDE ( ,
). EXIT_ON_CLOSE ( -
), DO_NOTHING ( ), DISPOSE
( )
title
116 2

2.2 ()


Other Properties ( )
alwaysOnTop ,

alwaysOnTopSupported , , , -

alwaysOnTop
bounds
. ( -
), , -
[0,0]. [1,0],
[0,1].
,
200 100 , [0,0,199,99].
bounds ,
, minimumSize
maximumSize
cursor -
. , Crosshair Cursor
.
.
Hand Cursor ( ), -
, ,
Wait Cursor
locationByPlatform , -
true ( false),
, .
, -
. , Windows

,
sizable ( )

state : ( 1) -
( 0 , 1)

2.9.
Look and Feel

.
, -
Java - ( Metal). -
02_09_LookAndFeel1 - (. 2.34).
, , ,
.
NetBeans 6.5 117

- (. .
, ) (. 2.35),
,
initComponents (Users Interface,
UI), 2.6, 02_9_LookAndFeel2 -.

. 2.34. . 2.35.
-
-
, Windows XP

2.6.

import javax.swing.*;
import java.awt.*;

...

public GUI_application() {

try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception e){}

initComponents();

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();


Dimension frameSize = getSize();
setLocation(new Point( (screenSize.width-frameSize.width)/2,
(screenSize.height-frameSize.width)/2 )
);
}

, initComponents(), -
. , ,
true locationByPlatform.
- -
Motif (. 2.36), Solaris (
02_09_LookAndFeel3 -).
118 2

:
UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()
:
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");

. 2.36.
-
. 2.37. - Metal
Motif

. 2.38. Windows XP

. 2.39. Motif
NetBeans 6.5 119


.
-, - -
GUI . -
, , -
( 02_09_LookAndFeel4 02_09_LookAndFeel6 -)
(. 2.372.39).

2.10.
( ,
-
), . -

( NetBeans).
.
. ,
.
,
( ). ,
. NetBeans -
, .
, -
. -
.
NetBeans .
,
, -
NetBeans.
-
. Projects -
,
Copy. (. 2.40), -
( -
_1, _2
. .). , -
( , -
- .
Projects,
(. . ,
). . ,
,
Close.
? , -
. -
120 2

, . ,
, , .
,
. !

. 2.40.

,
, .
, , ( ) ,
.
: " !", -
, , . , -
, - .
, .
,
. , -
, .
-
. -
. NetBeans
,
. , , -
NetBeans (
Versioning) CVS, SVN ( , Subversion) Mercurial ( -
, , Mozilla, OpenJDK NetBeans).
. -
. -
. , -
, , ,
. ?
Window () (. 2.41).
, , -
Window/Properties,
<Ctrl>+<Shift>+<7>. ,
Window/Palette, <Ctrl>+
+<Shift>+<8>.
NetBeans 6.5 121

. 2.41. Window ( )

2.11.

,
. ,
. NetBeans 6.5
, RAD- Delphi Visual Basic.
, .
(, 2_11_GUI_example1),
. - -
(item) , . -
.
.
.
,
<Enter>.
-
.
-
.
, .
: "" "File", "" "Edit", ""
"Help" (. 2.42). ,
, Preview Design
( Design
, ).
122 2

. 2.42.

shortcut (
). .
-.
(Hot Keys, NetBeans , Accelerators)
, -
-
.
<F1>, <F2> . .,
<Ctrl>, <Alt>
<Shift>.

(Hot Keys) (Accelerator


Keys) .
, -
<Alt>.
.

/ -
<Ctrl>+<S>,
, , -
.
,
shortcut. (. 2.43), -
.

. 2.43.
NetBeans 6.5 123

Key Stroke ( ) S ( -
SCAN- -
). Virtual Key ( ) -
VK_S. Ctrl
OK.
, .
( -
) - -
mnemonic .
, -
. ,
,
<Alt> .
MS Windows - <Alt>
. <Alt> ,
, ,
. <> <>
, , ...,
(. 2.44). <> <>
, <> <> .
, , ,
.
-
.
(Inspector ) -
.
. , . 2.45 2.46
Inspector ( Navigator , -
).

. 2.44.

JFrame ( Java Frame , ,


Java).
-
. JFrame, -
menuBar1 JMenuBar fileMemu1 JMenu (. 2.45).
124 2

. 2.45. . 2.46.

, ,
: openMenuItem1, saveMenuItem1, saveAsMenuItem1, exitMenuItem1
(. 2.46). openMenuItem1 -
,
. Text Open .
saveMenuItem1, . .
.
NetBeans 6.5 , -
. - (
, ), (
) <Delete>.
Delete.

<Delete> Delete .
-
.
, - (
),
Undo ( ) (. 2.47). -
, <Ctrl>+<Z>.

. 2.47. ( )
NetBeans 6.5 125

Undo Redo ( -
) <Ctrl>+<Y>.
.
. -, -
(menuBar) Add Menu ( )
(. 2.48).
.
Add From
Palette ( ),
(Menu), (Menu Item),
(Separator) (. 2.49).
:
Menu Item ;
Menu Item/CheckBox (
);
Menu Item/RadioButton (-
).

. 2.48. . 2.49.

,
. ,

Insert.
. 2.50 2.51 -
.
, CheckBox -
RadioButton,
( ,
).
, (...) icon Properties.
(. 2.52) -
, ,
. -
126 2

, -
.
.

. 2.50. . 2.51.


,
buttonGroup. Button Group -
Swing Controls.

. 2.52.

Menu Item/RadioButton Properties


buttonGroup buttonGroup1,
selected ( ,
).
.
. 2.53 2.54 ,
.
NetBeans 6.5 127

. 2.53. . 2.54.

,
.
,
( ). , -
,
.
Inspector -
. , . 2.55
jSeparator2 jCheckBoxMenuItem2 jRadioButtonMenuItem1.

. 2.55. jSeparator2 Inspector

, .
. (Palette)
Swing Menus ( Swing) ,

.
, ""
.
(Inspector) , -
128 2

, Add From Palette/Menu Item. -


, -
menuBar1, Add From
Palette/Menu ( /).
, -
, (Inspector). -
, (, ,
).
02_11_GUI_example3 , . -
, , .
, , -
- .
. .
NetBeans 6.5. (
Design) ( Palette )
JPopupMenu .
Add From
Palette/Swing Menus/Popup Menu.
,
Other Components jPopupMenu1[JPopupMenu].
, , jPopupMenu1 -
.

Add From Palette /Menu Item (. 2.56).

. 2.56.

jPopupMenu1 jMenuItem4[JMenuItem], -
text .
" ".

( Inspector,
, jMenuItem4
NetBeans 6.5 129

Inspector, Events/Action/ActionPerformed).
:
System.exit(0);

, ,
. jPopupMenu1
JButton1,
componentPopupMenu ,
. <none>,
, jPopupMenu1. .
, , -
.
.

2.12.
.

New/Java Class... (. 2.57).

. 2.57. . 1

Java (. 2.58).
Class Name ( ) ,
. Figure.
, , -
(
).
-
NetBeans (File/New File.../ , -
Java, Java Class/Next>). .
130 2

Finish ()
(. 2.59). , NetBeans
, 6.5 .
. ,
:
private int x=0;
private int y=0;

02_12_GUI_example2 ,
. java_gui_example, ,
Figure, , .

. 2.58. . 2

. 2.59.

2.13. Java
-
. Java ,

NetBeans 6.5 131

. /** -
*/ ,
/* */.
.
:
/**
* Creates new form GUI_application
*/


HTML- javadoc, JDK.
NetBeans -
: Run/Generate Javadoc (...) ( -
). -
HTML- (. . 11.1) ,
, . .
:
( );
;
(. 9);
- ( ,
, );
;
.
-
, , , -,
. ,
, public protected.
-
2.7.

2.7.

/**
* Java <br>
* - Months Spring ,
* .
* , .
* @see enumApplication.Months - Months
* @see enumApplication.Spring
* @see enumApplication#m1
* @version 0.2 .
* NetBeans 5.5, NetBeans 6.0, 6.1, 6.5
* @author
*/
132 2

public class enumApplication extends javax.swing.JFrame {


int i=1;
/**
* Spring 3 :
* march,apr,may.
* <ul>
* <li>march
* <li>apr
* <li>may
* </ul>
*
* Months,
* , .
*/
public enum Spring {march,apr,may}

/**
* Months 12 : <br>
* jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec <br>
* (, . .)
*/
public enum Months {jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec}
Spring spr1= Spring.apr, spr2;

/**
*,
*/
public Months m1,m2=Months.mar,m3;

HTML-
( , @ ).
, HTML-,
.
,
<br>, HTML.
HTML, :
<ul> <li>, , . .
,
javadoc
. , HTML-
*,
( ).
HTML 11.
HTML
. , -
, :
http://barsic.spbu.ru/www/comlan/html_r.html.
NetBeans 6.5 133

( ).
@see ()
. (, . .).
:
@see ;
@see . -, ;
@see #
; -
. ,
.
@version () . .
:
@version .

@author () . .
:
@author ( ).

, , -
, . .
@since ( ) JDK, (
) .
:
@since .

@param ( parameter ()) .


/** @param ... */ -
.
:
@param .

@return () .
:
@return .

@throws ( ) ,
.
:
@throws .

@deprecated () , -
.
(warning) , -
, .
134 2

:
@deprecated .


.
NetBeans 6.5 -
, ,
. -
, 2.8, Functions1

Tools/Analyze Javadoc (. 2.60).

2.8.

public int a;
public int f1(int x) {
return 2 * x;
}

public float f2(float x,float y) {


return x+y;
}

. 2.60.

, Output, -
Analyzer () . 2.61.
Functions1.java, -
,
(-, "!").
Fix Selected ( ),
NetBeans 6.5 135

. 2.61, , -
a, f1 f2 (-
2.9).

. 2.61. Analyzer

2.9.

/**
*
*/
public int a;

/**
*
* @param x
* @return
*/
public int f1(int x) {
return 2 * x;
}

/**
*
* @param x
* @param y
* @return
*/
public float f2(float x, float y) {
return x + y;
}

.
-
: Run/Generate Javadoc for " ". -

( HTML-). , -
, 2.7 ,
. 2.622.64.
136 2

02_13_EnumExample\dist\javadoc
index.html. -
, .

. 2.62.

. 2.63. java_enum_pkg
NetBeans 6.5 137

. 2.64. enumApplication

, (summary)
. -
-
. , 23
.
, . -
-
,
.
-
Properties NetBeans Run/Set
Main Project Configuration/Customize , -
, Categories
() Documenting () . 2.65.
Browser Window Title ( ) ,
( , -
) HTML- . -
(public)
(protected) .
private ( ) -
( Include Private and Package Private Members).
, -
. , , Clean and Build Project -
138 2

, , -
.

. 2.65.

, ,
, -
. , Source/Show Documentation (
<Shift>+<Ctrl>+<Space>) -
, (. 2.66).

. 2.66. ,
NetBeans 6.5 139

(-
) " "
, . , pckg1., -
, AdditionalClass (-
, ,
, (. 2.67)).

. 2.67. ""

2.14.
swing awt
, . -
.
-, , NetBeans -
: Swing (
swing), AWT ( awt), Beans Java
Persistence.
Swing -
Java. . 2.3 Swing , -
,
.

2.3. Swing


Swing Controls ( )
1 JLabel
2 JButton /
140 2

2.3 ()

3 JToggleButton .
, -
.
ButtonGroup,
, buttonGroup

4 JCheckBox

5 JRadioButton .
. -
ButtonGroup

6 ButtonGroup JToggleButton
JradioButton

7 JComboBox
8 JList
9 JTextField

10 JTextArea -

11 JScrollBar . -
- ,

12 JSlider . ,
-

13 JProgressBar . ,

14 JFormattedTextField

15 JPasswordField

16 JSpinner /

17 JSeparator .

18 JTextPane .
,
, JTextArea

19 JEditorPane

20 JTree ,
, -

21 JTable . -

NetBeans 6.5 141

2.3 ()

Swing Menus ( )
1 JMenuBar -
JMenu ( ),

2 JMenu (
JMenuItem, JCheckBoxMenuItem JradioButtonMenuItem)

3 JMenuItem . JMenu
JPopupMenu

4 JCheckBoxMenuItem CheckBox
. -
JMenu JPopupMenu

5 JRadioButtonMenuItem (
). -
JMenu JPopupMenu

6 JPopupMenu -
,
componentPopupMenu.
: JMenuItem, JCheckBoxMenuItem
JRadioButtonMenuItem

7 JSeparator . -
( )

Swing Containers ()
1 JPanel ,
.
. -
layout () FlowLayout
( ).
JLayeredPane

2 JTabbedPane
.
,
. -
, ,
, Add From
Palette ( )

3 JSplitPane , ,
, -
,
4 JScrollPane
5 JToolBar .
JToggleButton,

6 JDesktopPane .

142 2

2.3 ()

7 JInternalFrame .
( -
). -

8 JLayeredPane

Swing Windows (, )

1 JDialog .
jDialog1.setVisible (true)

2 JFrame .
jFrame1.setVisible (true)

3 JColorChooser -

4 JFileChooser -
.
- (JDialog, JFrame) -

5 JOptionPane
.
. :
:
javax.swing.JOptionPane.showMessageDialog(null,
" ");
JOptionPane.showMessageDialog(null,"!", "
", JOptionPane.INFORMATION_MESSAGE);
:
int option=javax.swing.JOptionPane.showConfirmDialog(
null,"?");
:
String input=javax.swing.JOptionPane.showInputDialog(
null," :");
, -
,
javax.swing.JOptionPane.NO_OPTION, CANCEL_OPTION,
CLOSED_OPTION, OK_OPTION, YES_OPTION
null.
, .
null, -
( ).
,
(-
, .)
NetBeans 6.5 143

2.3 ()


AWT ( AWT)
113 Label, Button, .
TextField, TextArea, , -
CheckBox, Choice, Java, Java-
List, ScrollBar,
ScrollPane, Panel,
Canvas, MenuBar,
PopupMenu
Beans (, )
1 Coose Bean . ,
Beans. ,
,
15
Java Persistence ( Java Persistence)
1 EntityManager . Java
Persistence (entities) ,

" " (, )
2 Query Java Persistence
3 Query Result Java Persistence ( List)

. -
Java System.out.println ( ).
. -
.

:
JOptionPane.showMessageDialog(null,"!"," ",
JOptionPane.INFORMATION_MESSAGE);

(error), -
:
JOptionPane.ERROR_MESSAGE,

(warning):
JOptionPane.WARNING_MESSAGE ,
:
JOptionPane.QUESTION_MESSAGE.

, , -
:
JOptionPane.PLAIN_MESSAGE.
( 02_14_OptionPane.)
144 2

AWT (Abstract Window Toolkit -


) Swing,
awt Java. AWT -
, Swing,
( ).
AWT, Swing, -
Canvas ( ). -
, , :
java.awt.Graphics g=canvas1.getGraphics();
g.drawLine(10,10,100,100);

Swing ,
:
java.awt.Graphics g=jPanel1.getGraphics();
g.drawLine(10,10,100,100);
g=jButton3.getGraphics();
g.drawLine(10,10,100,100);

2.15. (Layout)
(Anchor)
,
(GUI),
Layout . Java ,
.

(anchors)
( ),
. -

.
,
AbsoluteLayout. NetBeans
Set Layout (. 2.68). Free Design
( ). AbsoluteLayout, -
x y -
.
,
Free Design .
,
(, ), Anchor. -
(. 2.69) (Left
, Right , Top , Bottom ).
,
.
NetBeans 6.5 145

. 2.69.
. 2.68.

,
, Properties Layout -
Horisontal Resizable (" ").

, minimumSize maximumSize.
, , -
, Vertical
Resizable (" ").
, AbsoluteLayout Free Design -
. , AbsoluteLayout -
.
Free Design. -
: -
,
. , -
, , -
.

2.16.
Desktop Application
, NetBeans 6.5 GUI-, -
Desktop Application ( , ).
File/New
Project..., Java, -
Java Desktop Application Next > (. 2.70).
(. 2.71), Basic Application (
) Finish.
146 2

. 2.70. Desktop Application. 1

. 2.71. Desktop Application. 2


NetBeans 6.5 147


() (. 2.72). , . 2.73.
,
.
13, -
.
,
. 13.

. 2.72. Desktop Application.


. 2.73. Desktop Application



(GUI) Design. ,
Swing.
148 2

, -
-
. -
<F1>, <F2> . ., <Ctrl>,
<Alt> <Shift>.
, . -
. -
, -
- .
Java
/** HTML */.
, @. javadoc -
HTML-
.
-
:
JOptionPane.showMessageDialog(null," ", " ",
JOptionPane.INFORMATION_MESSAGE).


(Layout).

() (Anchors). -
,
.
Free Design ( ) -
. .
-
Desktop Application.


JRadioButton JToggleButton -
ButtonGroup.

NetBeans Java Application.


swing. main JOptionPane - -
(, " !").
( -
) OK, , -
,
.
NetBeans 6.5 149

, .
x,
, y , . ,
x y.
x ( -
). , -
.
3

3.1. ()
boolean true false.
:
boolean a;
boolean b;

:
a = true;
b = a;

(. 3.1 3.2)
(. 3.3).

3.1.

&& and ( ) a&&b

|| or ( ) a||b

^ xor ( ) a^b

! not ( ) !a

true false, :
a = true, b = true, a && b true;
a = false b = false, a && b false.

. (true) 1,
(false) 0. . 3.2
a b.
151

, ,
. 0 1, Java
.

3.2.


a 0 0 1 1
b 0 1 0 1
a&&b 0 0 0 1
a||b 0 1 1 1
a^b 0 1 1 0
!a 1 1 0 0

Java -
: . 3.2 , a false,
a&&b false b. , b
, . , a
true, a||b true b.
(. 3.3).
boolean, a b , -
a b, .

3.3.


== a==b
!= a!=b
> a>b
< a<b
>= a>=b
<= a<=b
instanceof obj instanceof MyClass
(. . 6.12 9.3)

3.2. , ,
. 3.4 , Java.
long,
int, -
L, 600000000000000L.
152 3

l, , (
).
, int,
int long.

3.4.

byte 1 -128..127 (8-


)

short 2 -215..215-1 =
-32768.. 32767 (16- )

char 2 \u0000..\uFFFF=0.. 65535 ( 16-


)

int 4 -231..231-1 = (32- )


-2.147483648109..
2.147483647109

long 8 -263..263-1 =
-9.223372036854781018.. (64- )
9.223372036854781018

Java C C++ (-
), . -
,
. . C C++ int short int Java -
, . long C C++
int Java. long Java C
C++ , long long,
int64, _int64 __int64. GNU g++ long long, int
long.

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

3.1.

int i,j,k;
int j1;
byte i1,i2=-5;
short i3=-15600;
long m1=1,m2,m3=-100;

, i, j, k, j1, i1, m2 -
, . . . -

,
:
Variable might not have been initialized
( , , ).

i1 ,
5. :
byte i1=0,i2=-5;

( 3.2).

3.2.

i=5;
j=i*i + 1
m1=j
m2=255;
m1=m1 + m2*2;

char Java, C/C++, ,


. , -
, -
Unicode, Unicode (
):
char c1='a';
char c2='\u0061';
char c3=97;


97, a.
,
.
ASCII ,
. Unicode
, Unicode ASCII ( 3.3).
154 3

3.3. Unicode ASCII

'A' 65, '9' 57;


'B' 66; ':' 58;
'Z' 90; ';' 59;
'a' 97; '<' 60;
'z' 122; '=' 61;
'0' 48; '>' 62
'1' 49;
. .
,
, . -
,
, .
,
1 = 'a' * 'a' + 1000 / 'b'

, .
.
,
public final:
public final int MAX1=255;
public final int MILLENIUM=1000;

, .

.
,
( ).
:
-
. ,
, -
26 ( ). -
, (,
), .
, -
26, -
. , , -
26 (
), , : "_"
( ) . -
27, 26 ( , ). -
155

-
, .
.
CHARS_COUNT = 26, 27 :
CHARS_COUNT + 1,
CHARS_COUNT
(. . , -
, ).

3.3.

. 3.5 .
,
. .
i j ,
v .

3.5.


+ i+j i j
byte, short char,
i-j

* i*j
/ i/j -
-
,
% i%j


= - v=i i,

v
++ v++ v++ v=v+1
( 1) ++v v=v+1
++v

. . 5.5
-- v-- v-- v=v-1
( 1) --v v=v-1
--v

. . 5.5
+= v+=i v+=i v=v+i
156 3

3.5 ()

-= v-=i v-=i v=v-i

*= v*=i v*=i v=v*i

/= v/=i v/=i v=v/i

%= v%=i v%=i v=v%i

Integer Long, -
:
Integer.parseInt()
Long.parseLong()

, jTextField1
jTextField2, :
int n=Integer.parseInt(jTextField1.getText());
long n1=Long.parseLong(jTextField2.getText());

Integer.signum() Long.signum() (. . 1
, 0 0, 1 ).
, Integer Long -
.
Integer Long (wrappers),
.

3.4. Math
. 3.6 Java,
. 3.7 .
java.lang.Math = 3,14... (Math.PI) e = 2,71... (Math.E),
(. 3.8).

3.6.


float 4 1.510-45..3.41038 , 78
.
(32 )
real*4 IEEE754
double 8 510 -324 308
..1.710 , 1516
.
(64 )
real*8 IEEE754
157

3.7.


+ x+y , x y -
, -
x-y

* x*y
/ x/y . -
, x y
,

% x%y
x y. , x
y ,

= v=x x,

v
++ v++ v=v+1
( 1) ++v
-- v-- v=v-1
( 1) --v
+= v+=x v=v+x
-= v-=x v=v-x
*= v*=x v=v*x
/= v/=x v=v/x
%= v%=x v=v%x

3.8. , Math



sin(x) sin(x)
cos(x) cos(x)
tan(x) tg(x)
asin(x) arcsin(x)
acos(x) arccos(x)
atan(x) arctg(x)
atan2(y, x) , x,y,
( -
)
158 3

3.8 ()


toRadians(angdeg) angdeg / 180.0 PI;

toDegrees(angrad) angrad 180.0 / PI;

, ,

exp(x) ex

expm1(x) ex 1. x, 0, ,
exp(x) 1

log(x) ln(x)

log10(x) log10(x)

log1p(x) ln(1 + x). x, 0, ,


log(1 + x)

sqrt(x) x

cbrt(x) 3
x

hypot(x,y)
x2 y 2

pow(x, y) xy x y

ex e x
sinh(x) sh(x)=
2

ex e x
cosh(x) ch(x)=
2

ex e x
tanh(x) th(x)=
ex e x

, , ,

abs(m), abs(x) . int, long, float


double. ,

signum(a), signum(x) . float double.


,

min(m,n), min(x,y) . .
: int, long, float, double. ,

max(m,n), max(x,y) . .
: int, long, float, double. ,

ceil(x) x , x

floor(x) x , x
159

3.8 ()


round(a) x . float double.
long, double, int float. ,
round(x)
(int)floor(x + 0.5)

rint(x) x

ulp(a), ulp(x)
(
). float double.
,

random() 0,0 1,0.


: 0 <= Math.random() < 1

IEEEremainder(x,y) x y, . . :
x y * n, n

. 3.8 x, y, angdeg, angrad double, a float, -


m, n long int. -
double, .

( ),
Math.
, Math.PI Math.sin(x). java.lang
. ,
Math Java ,
. . . jdk 1.5,
:
import static java.lang.Math.*;

Math :
public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;

static , , final
( -).
-
Float Double, -
Float Double:
Float.parseFloat()
Double.parseDouble()

, jTextField1
jTextField2, :
160 3

float f1= Float.parseFloat(jTextField1.getText());


double d1= Double.parseDouble(jTextField2.getText());

Math java.math,
BigDecimal, BigInteger, MathContext, RoundingMode.
BigDecimal
( ).
BigInteger .
MathContext RoundingMode ,
BigDecimal BigInteger.

3.5.


Java- -
int long.
(+, , *, /, %)
.
, byte, short char, -
: byte, short
char int, -
. long,
long, -
.
Java
( ) -
float double.
. double, float,
double, float -
double.
, , -
,
.
. : -
, . -
, ,
.
:
possible loss of precision ( ).

, .
161

, :
double d=1.5;

d float :
(float)d

, f float,
double :
(double)f

, . .
, , -
, ,
.
,
,
. , double
float, . , -
:
double d=1.5;
float f=(float)d;

3.4 .

3.4.

byte byte0 = 1; //-128..127


short short0 = 1;//-32768.. 32767
char char0 = 1;//0.. 65535
int int0 = 1; //-2.147483648E9.. 2.147483647E9
long long0 = 1;//-9.223E18.. 9.223E18
float float0 = 1;// (1.4E-45..3.402E38)
double double0 = 1;// (4.9E-324..1.797E308 )
short0 = byte0;
byte0 = (byte)short0;
char0 = (char)short0;
int0 = short0;
int0 = char0;
char0 = (char)int0;
short0 = (short)int0;
long0 = byte0;
byte0 = (byte)long0;
long0 = char0;
long0 = int0;
int0 = (int)long0;
float0 = byte0;
float0 = int0;
float0 = (float)double0;
double0 = float0;
162 3

3.6. .
(boxing) (unboxing)
, , -
. , Java
, Java Object,
.
Java ,
. . . (class wrappers).
, , ,
. - int char,
Integer Character.
. 3.9.

3.9.


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

Character , -
char .

, -
. (-
box) (boxing),
(unboxing).
("" ) -
,
Value() (, byteValue() Byte).

, . .
, -
. ,
, -
. 3.5
.
163

3.5.

Integer obj1 = 10; //


int i1 = obj1*2; //
Byte b = 1; //
obj1 = i1/10; //
b = 2; //

, /
-
,
.
-
.
, / (
JDK) -
. ,
, .
, -
. , , -
:
Byte.MIN_VALUE
Byte.MAX_VALUE
Float.MIN_VALUE
Float.MAX_VALUE
Double.MIN_VALUE
Double.MAX_VALUE

. .
, . . , -
, -
. , -
:
Byte.parseByte()
Short.parseShort()
Integer.parseInt()
Long.parseLong()
Float.parseFloat()
Double.parseDouble()

, , , ,
:
Byte.valueOf()
Short.valueOf()
Integer.valueOf()
Long.valueOf ()
Float.valueOf ()
Double.valueOf ()
164 3

:
int n1=Integer.MAX_VALUE;
double d1= Double.MIN_VALUE;

,
double d2= Double.parseDouble(jTextField1.getText());

, :
double d2= Double.valueOf(jTextField1.getText());

, valueOf
Double.
, . .
, .
double, -
, d2 .
, ,
.
, , -
,
(
). ,
.
, (
).

3.7.
. ,
, :
,
, . , ,
a*b/c+d ((a*b)/c)+d
.
,
,
(. . , ).
(a+b)*c : a+b,
c.
, Java ,
. -
, , , -

( ). -
,
165

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

3.10.


1 ( ) [ ] .

2 ++ ~ ! +
++
3 new ()

4 * / %
5 +
6 >> >>> <<
7 > >= < <= instanceof
8 == !=
9 &

10 - ^

11 |

12 &&

13 ||

14 ? :
15 = = ( +=, =, *=, /=
. .)


boolean true false.
&& (), || (), ^ ( ), ! () -
. Java
.
a b ,
a b, .
166 3

, -
==.
Java byte, short, int, long -
char, .
char , .
long, -
int,
L.
-
. ,
public final.
Java float double
(, ).
, PI (Math.PI) E (Math.E ) -
Math, java.lang.
Math :
import static java.lang.Math.*;
Math.
Math .

int long. byte, short char -
int,
. long, -
long, -
.
Java
float double.
double, float, double,
float double.
, , -
,
.
Java , . . . -
(class wrappers).
, , , -
. int char, -
Integer Character.
, -
. (-
box) (boxing), -

(unboxing). -
.
167

. , -

, :
Integer.MIN_VALUE, Integer.MAX_VALUE, Float.MIN_VALUE, Float.MAX_VALUE, Double.MIN_VALUE,
Double.MAX_VALUE . .
Java 15 . -
, ,
.


,
a==b a=b. -
: if(a==b){...} if(a=b){...}.
Java , -
. a b if(a=b){...} , a
b, -
. , , .
, Basic, -
a^b , . . ab. Java
Math.pow(a,b).
java.lang.Math java.math.
, , byte, short
char int, -
.
, int.
, ,
.
,
.


. -
.

.

. , , , -
, sin. , ,
. double.
sin ,
.
168 3


.
, JButton -
. -
,
. -
, -
.
:
if(jRadioButton1.isSelected())
1;
if(jRadioButton2.isSelected())
2;
if(jRadioButton3.isSelected())
3;
4

Java

.
,
, ,
.

4.1.
-
, -
. -
-
.



,
.
.
, 2006
, , :
2006 = 2 103 + 0 102 + 0 101 + 6 100,
. . 10. ( -
) . -
.
,
( ), ( ) (
) . ()
:
0, 1 ;
0, 1, 2, 3, 4, 5, 6, 7 ;
170 4

0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ;
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, B, C, D, E, F .
, ,
, A, B, C, D, E, F.
, ,
, :
9510 ;
27F16 ;
67528 ;
10001112 .
,
.
:
(V 5, X 10, L 50,
C 100, M 1000);
, (III 3, XX 20);
(IV 4, VI 6,
IX 9).

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

.
, -
1. 1
1, 2 11, 3 111, 4 1111, . . -
( ?),
. , -
.
2
( -
).
, (0 -
) (1 ). -
BInary digiT (
).
-
, .
Java 171

.
28 = 256 .
8 (8- )
(byte). , -
, -
.
,
(). -
16-, . . 16- () .
16- (,
MS-DOS). -
32- (Windows 95 /98 /NT /ME /2000 /XP, Linux, MacOS), . .
32- .
32-, 64- ( 64- ).
,

, /,
- .



, . . -
. , 5 :
5 = 1 22 + 0 21 + 1 20 = 1012
.
:
6 = 1 22 + 1 21 + 0 20 = 1102
2 = 102
4 = 1002
8 = 10002
9 = 10012
. .
,
2 = 102:
153 = 1 102 + 5 101 + 3 100
, , 10 ,
:
2 = 210
10 = 1010
. .
172 4

0 1. -
.
(. . 102 = 2)
. (. . 1002 = 4)
. .
102
() , 1002 ,
. .
n (
2n) ( 2n).
-
. ,
(0 1), ( 0 9) .
, , 1 9, -
1 1:
12 + 12 = 102
( 1 + 1 = 2).
:
102 + 102 = 1002
. .
:
01102 11002 1112
+ + +
10112 00102 0012
100012 11102 10002

:
1012
112
101
+
101
11112


. , .

.

,
0. -
1. .
01102.
Java 173

.
n
n2 = n :
1. n n1 n n1,
n , (. . 1 0, 0 1).
2. n1 n2 = n1 + 1 (. . n1
).
, . -
, (1) 11112, 8-
111111112. (2) : 11102 111111102 . .
, , -
.


, 1 1,
. 1.
n = 110, n2 = 110.
1: n = 110 = 00012 n1 = 11102;
2: n2 = 11102 + 1 = 11112.
, 110 = 11112.
:
n2 + n = 100002.
, , -
, :
n2 + n = 00002 = 0.
:
n = 210 = 00102 n1 = 11012; n2 = 11102;
n = 310 = 00112 n1 = 11002; n2 = 11012;
n = 410 = 01002 n1 = 10112; n2 = 11002.
, n2 + n = 0.
, 310 210 ( 11102, )?
00112
+
11102
100012

,
, :
00112 + 11102 = 00012
(. . 310 + (210) = 110, ).
174 4


(1) + (1) = 11112 + 11112 = 111102 11102 (-
, ).
:
(1) + (1) = 11102 = 2

, -
.
,
( )
( ) -
.

.

, ()
, -
. , -
, , .


:
a = 310 = 00112;
b = 210 = 00102;
a + b = 01012 = 510;
. . .
:
a = 610 = 01102;
b = 510 = 01012.
a + b = 10112 = 510.
,
,
! -
.
, . -
810 + 810 .
810 = 10002,
810 + 810 = 10002 + 10002 = 100002.
0.
Java 175

:
810 + 910 = 110 . .


,
, , -
, . . 0 1.
, -
.
:
1102 1012 = 1102 1002 + 1102 12 = 110002 + 1102 = 111102.
, , -
11102 = 210 < 0.
,
( !). -
,
.
, .
byte:
m=10, n=10, k=10

:
mn, mk nk
128 127.
mn + mk ( mnk).

, byte,
. , Java
int. ,
, Java
byte, : (byte)(m*n), (byte)(m*k) . .

:
short m=10,n=10,k=10;

(short)(m*n*k).
m=n=k=100 m*n*k 106,
short ( 32 768 32 767).
m*n, m*k n*k ( 4*m*n ). -
int .
m=n=k=2000 ( !) m*n*k
, (
m*n 50 000).
176 4

long -
( ). , -
( long) ! -
100 ( , -
50 , 25 4.

. long).
.
, -
, -
. , -
, , ,
long (. . m, n k double, , -
, ).
, , :
m*n*k (double)m*(double)n*k.
1.0*m*n*k, . .
double int ( double long) double.

1.0*m double.
(1.0*m)*n ( n
double, double).
,
(1.0*m)*n k.

04_1_integerCalc , , -
. . -
,
. ( ), -
m*n*k, 1.0. -
,
1.0*m*n*k, , -
, 1.0E10 1.410065408E9. -
((1.0*m)*n)*k.
-
, -
:
1.0*m*n*k=1.0E10,

m*n*k*1.0=1.410065408E9.
.
,
, , -
Java 177

. , , -
long double. -
-
, -
.
:
byte i=127, j=1, k;
k=(byte)(i+j);
System.out.println(k);

(128).

byte i=127,j=1,k;
System.out.println(i+j);

+128.
, byte -
int.



( ,
. .), -
. -
-
.
. -
, -
16 (1610 = 1016).
10 : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
16- 16 . , -
: A, B, C,
D, E, F:
1010 = A = A16
1110 = B
1210 = C
1310 = D
1410 = E
1510 = F
, :
FF16 = 15 161 + 15 160 = 255.
178 4

Java, 16- , ,
0x:
0xFF FF16, 0x10 1016, . . 1610.
N :
:
N = An 10n + ... + A2 102 + A1 101 + A0 100 (An = 09);
:
N = Bn 2n + ... + B2 22 + B1 21 + B0 20 (Bn = 0 1);
:
N = Cn 16n + ... + C2 162 + C1 161 + C0 160 (Cn = 0F).

(, -
Bn An;
An Bn).



.
N :
N = Bn 2n + ... + B2 22 + B1 21 + B0 20 (Bn = 0 1)
. -
. -
N.
.
010111102 :
010111102 = 0 27 + 1 26 + 0 25 + 1 24 + 1 23 + 1 22 + 1 21 + 0 20 =
= 0 + 64 + 0 + 16 + 8 + 4 + 2 + 0 = 9410



N10 :
N = Bn 2n + ... + B2 22 + B1 21 + B0 20 (Bn = 0 1).
:
1. N 2 .
2. ( ) B0
20.
3. 2 , .
B1 N.
Java 179

4. , 0,
Bn.
, 34510 (. 4.1).

4.1. 345

Bi
345 / 2 172 1 B0
172 / 2 86 0 B1
86 / 2 43 0 B2
43 / 2 21 1 B3
21 / 2 10 1 B4
10 / 2 5 0 B5
5/2 2 1 B6
2/2 1 0 B7
1/2 0 1 B8

34510 = 1010110012.



N :
N = Bn 2n + ... + B2 22 + B1 21 + B0 20 (Bi = 0 1);
N = Hn 16n + ... + H2 162 + H1 161 + H0 160 (Hi = 0F16, F16 =1510).
, 16 = 24. .
0 F16 (. . 0
1510). 24 = 16 ( -
). , -
-
( ) :
00002 = 016 10102 = A16
00012 = 116 10112 = B16
00102 = 216 11002 = C16
00112 = 316 11012 = D16
01002 = 416 11102 = E16
01012 = 516 11112 = F16
01102 = 616
01112 = 716
10002 = 816
10012 = 916
180 4

, 10110101112 :
10110101112 = 0010 1101 01112 = 2D716.

4.2.
,
, 0 1 .
k-
k- . . 4.2 Java.

4.2.


~ ( , ~i
)
^ XOR ( ) i^j
& AND ( ) i&j
| OR ( ) i|j
<< m<<n
>>> m>>>n
>> m>>n

&= y&=x y=y&x m&=n
|= y|=x y=y|x m|=n
^= y^=x y=y^x m^=n
>>= y>>=x y= y>>x m>>=n
>>>= y>>>=x y= y>>>x m>>>=n
<<= y<<=x y= y<<x m<<=n

(, -
). ,
byte.
a 1 m a|m (-
, , OR) (. 4.3).
a = a323 + a222 + a121 + a020, ai -
(. . 0, 1).

4.3. OR

a a3 a2 a1 a0
m 0 1 0 1
a|m a3 1 a1 1
Java 181

. 4.3 , a
. , OR
1 ( -
1, 0).
a 0 m a&m (-
AND) (. 4.4).

4.4. AND

a a3 a2 a1 a0
m 0 1 0 1
a&m 0 a2 0 a0

. 4.4 , a
0. AND
0 ( -
0, 1).
( , ) a (
m ) a^m ( -
XOR) (. 4.5).
. 4.5 , , m , a -
: 1 0, 0 1.
.

4.5. XOR

a 1 1 0 0
m 0 1 0 1
a^m 1 0 0 1

XOR XOR
(. 4.6).

4.6. XOR

a^m 1 0 0 1
m 0 1 0 1
(a^m)^m 1 1 0 0

. 4.6 , , -
a.
, (a ^ m) ^ m = a, . . -
.
182 4

XOR -
. XOR -
.
XOR graphics.setXORMode ().
, , .
~a.
<<, >> >>> ,
, .
.
n m<<n -
m 2n. ( ),
, . , (
), , ,
.
n m>>n m>>>n -
m 2n. m -
>> >>> .
m. -
, . ,
, , -
int long, . . 32-
64- .
m = 1. m = 11112.
m << 1 m = 111102, -
, m = 11102 = 2 (. . -
m 2n).
.
>>
, . , -
m 2n ,
.
m>>>n, ,
. -
2n.
, .
, .
, , -
, float Float.intBitsToFloat ( )
double Double.intBitsToDouble ( ). ,
Float.intBitsToFloat(0x7F7FFFFF) float.
Java 183

4.3.

Java,
, floating point ( -
).
, , , , .
, , -
.


01012 :
01012 = 0 23 + 1 22 + 0 21 + 1 20.
:
11.01012 = 1 21 + 1 20 + 0 21 + 1 22 + 0 23 + 1 24.
, n (
) (102)n = 2n. (. .
) 2n.



(floating point), .
x :
x = s m 2p.
s , m ,
p .
10- , :

1 4 5

. 0, , 1
. , ,
m, 1 <= m < 2.
.
, 1.01012, 10.1012 0.101012 ,
1.01012. ,
, , (. .
101012).
( ) ,
. 1.01012, 10.1012 0.101012 -
0, 1 1 .
184 4

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

Java BigInteger BigDecimal,


, -
,
long double. .
( , , ,
) -
. -
, -
. ,
, .

:
2n, n,
n . 2n -
n , .
, , .
.
11.0112 0.110112 .
1.10112, 1, . . 11.0112 = 1.10112 (102)1.
1.10112, 1, . . 0.110112 = 1.10112 (102)-1.
1, 2 ,
. . 2:
0.110112 = 0.0110112 (102)1.
(,
5 ), 0.01102 (102)1, -
:
Java 185

1.10112 (102)1 + 0.0110112 (102)1 =


(1.10112 + 0.0110112) (102)1
(1.10112 + 0.01102) (102)1 =
10.00012 (102)1 1.00002 (102)2
1.00001112 (102)2.
, , -
. , , -
, .
, , -
.



-
(plain text) 1.5 1014.
, 10 -
E ( Exponent ).
:
1.5 1014 1.5E14,
0.31 107 0.31E7.
E , . -

e, -
.
3e2 3e2, 3 102, -
.
double (-
, 1.5, 17E2, 0.0). float,
f ( float):
1.5f, 17E2f, 0.0f .
float
:
Float.MIN_VALUE 2149;
Float.MAX_VALUE (2223)2127 22127.
double :
Double.MIN_VALUE 21074;
Double.MAX_VALUE (2252)21023 221023.
186 4

IEEE 754

?
IEEE 754 ( IEC 60559:1989), -
.
, : real*4, real*8
real*10. 4, 8 10 . Java real*4 -
float, real*8 double. real*10 -
Pascal, Java .
r s, m 2pd:
r = s m 2pd.
p . .
d ( ) .
pmax,
. :
d = (pmax+1)/2-1.
real*4: pmax = 255, d = 127.
real*8: pmax = 2047, d = 1023.
real*10: pmax = 32767, d = 16383.
,
1 <= m < 2. . -
, 1. 2 -
(. . -
2).
IEEE 754
1 pmax 1 . -
.
, .
.
pmax ,
.
.
. 4.7 -
.
:
s ;
p ;
m .

. 4.7 ;
.
Java 187

4.7.

1 2 3 4 5 ... 10
real*4 sppp pmmm mmmm mmmm ...
pppp mmmm mmmm mmmm
real*8 sppp pppp mmmm ... mmmm
pppp mmmm mmmm mmmm
real*10 sppp pppp 1mmm ... mmmm mmmm mmmm
pppp pppp mmmm mmmm mmmm mmmm

0, , 1 .
real*4 (float) real*8 (double)
, , ,
23 52 ( ), 24 53 .
real*10 ,
64 .
real*4 8 , real*8 11 ,
real*10 15 .
. 4.8
IEEE 754.

4.8. IEEE 754



IEEE 754 Java
real*4 float 23+ 1 8 127
real*8 double 52+ 1 11 1023
real*10 - 64 15 16383

-
?

( ), . . m = 1 p = 1. , -
21 d.
-
, . . m 2 p = pmax 1.
, :
2 2Pmax 1 d = 2Pmax d
1 pmax 1
:
real*4 2.350989E38 3.402824E38;
real*8 2.225074E308 1.797693E308;
real*10 3.362103E4932 1.189731E4932.
188 4

pmax, , -
.
, ,
1 ( 0), 1 0.
.
( ).
:
(1-___) 21 d,
. .
.
2n, n
.
0 -
21 d n.
, :
real*4 1.401298E45 2.350989E38;
real*8 4.940656E324 2.225074E308;
real*10 3.6451995E4951 3.362103E4932.
, -
. .
IEEE 754 +0 0. +0
0 / .
, p = pmax, . .
. -
, :
Inf (Infinity );
NaN (Not a Number );
Ind (Indeterminate ).
. -
, 1 0 Inf, 0 0 Ind. -
NaN ,
, . .
Inf . IEEE 754 -
. , +Inf,
, Inf.
Ind , ,
, (, ), -
. NaN.
NaN
(Signaling NaN) (Quiet NaN).
( 0) ( 1).
Java 189

,
IEEE 754. , Java
, . :
Float.NEGATIVE_INFINITY,
Float.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY,
Double.POSITIVE_INFINITY.

Ind NaN, Float.NaN


Double.NaN .
,
. 4.9.

4.9.

s
p () m ()
()
NaN 1 11..11 11..11
( ) :
10..01
Indeterminate () 1 11..11 10..00
Signaling NaN 1 11..11 01..11
( , ) :
00..01
Infinity 1 11..11 00..00
( )
1 11..10 11..11
: :
00..01 00..00
1 00..00 11..11
:
00..01
0 1 00..00 00..00
+0 0 00..00 00..00
0 00..00 00..01
:
11..11
0 00..01 00..00
: :
11..10 11..11
+Infinity 0 11..11 00..00
( )
190 4

4.9 ()

s
p () m ()
()
Signaling +NaN 0 11..11 00..01
( , )
:
01..11
Quiet + NaN 0 11..11 10..00
( )
:
11..11

, ,
int, float, float
int. -
- .
long double:
Float.intBitsToFloat( int)
Double.longBitsToDouble( long)
Float.floatToIntBits( float)
Double.doubleToLongBits( double)

:
Float.intBitsToFloat(0x7F7FFFFF) , Float.MAX_VALUE,
Float.intBitsToFloat(0x7F800000) Float.POSITIVE_INFINITY,
Float.intBitsToFloat(0xFF800000) Float.NEGATIVE_INFINITY.
Float.intBitsToFloat 0x7F800001
0x7FFFFFFF 0xFF800001 0xFFFFFFFF, Float.NaN.
,
(, int float double long). -
, -
, , , .
(, int
double).
, , .
.


.
,
, -
, ( )
, .
Java 191

AND ( &) ,
0, .
OR ( |) ,
1, .
XOR ( ^) ,
1 ( , ),
. XOR ,
graphics.setXORMode ().
~a.
<<, >> >>> , -
, . m<<n
m*2n, m>>n -
m 2n , -
.
double (-
: 1.5, 17E2, 0.0). float,
f ( float): 1.5f, 17E2f, 0.0f.
, -
.
.
-
. -
,
, . -
,
.


, -
-
, -
. -
.
.
-
, .

,

, JButton . ,
192 4

,
,
.
-
. .

. ,
.
, .
, -
.
,
1 + x float f, -
1 + y double d.
x float y double
.
jLabel1 f 1, jLabel2 d 1.
jLabel3 (f 1) / x + 2, jLabel4
(d 1) / y + 2.
x y, 1E3 1E18.
.
* - -
. ,
f1(x) f2(x),
ex 1 x 1 1 1 2
f 1( x) a( x) b( x) , a( x) 2
, b( x) , f 2(x)
x x .
x x2 2 6 24
f2(x) f1(x) , f1(x) f2(x)
.
f1(x) f2(x) x.
float,
double.
x .
:
f1_double(x), a_double(x), b_double(x), f1_float(x), a_float(x), b_float(x),
:
f1_float(x) f2_float(x) f1_double(x) f2_double(x).
x, 1E8 0.1,
.
5

5.1.
Java -
, , -
.
-
{}.
-
.
, , ,
12 ( ):

{

}

( )
, ( -
), :
{

}

NetBeans,
. -
, Tools/Options,
Editor/Indentation, -
Add New Line Before Brace.
Java ( C/C++) (;) .
194 5

5.2. if
if : if if... else.
- if "", else " ". , -
: "......" "...... ...".
:
if()
1;

true, 1. -
false, .
:
if()
1;
else
2;

if false, 2.
. -
if !

if(a<b)
a=a+1;
else if(a==b)
a=a+1;
else{
a=a+1;
b=b+1;
}

: -
if, ,
.
, if , ,
else ,
. :
if()
1;
2;
else
3;

.
195

, .
, , :
if(){
1;
2;
}else
3;

:
if()
1;
else
2;
3;

!
else -
3
.
,
, , 3 else:
if()
1;
else
2;
3;

3 else, -
:
if()
1;
else{
2;
3;
}


if(1) if(2) 1 else 2;

else if, :
if(1)
if(2)
1;
else
2;

, if else ,
.
196 5

if(1)
if(2)
1;
else
2;

. , -
( , ), , 2 -
, 1==false, . . , if,
. , -
Java.
.

if(1){
if(2)
1;
}else
2;

, Format (
) Source
<Alt>+<Shift>+<F>.
, -
, , -
, .

.
, :
if()
1;
2;

:
if(){
1;
2;
}


, .
Format , -
, -
Java, .
197

, -
, - -
.
, -
Java,
. , , Java -
, . NetBeans -
, if. , 6.5
1; -
<Enter> , -
2; :
if()
1;
2;

-
, , . -
, Format ( <Alt>+<Shift>+<F>) -
.
else
.

if(i==0)
i++;
else
i--;

if(i==0){
i++;
} else{
i--;
}

, ( else)
.
, Java C,
= ==.
, b1 b2,
if(b1==b2)
i=1;
else
i=2;
198 5

:
if(b1=b2)
i=1;
else
i=2;

( -
) . 05_2_if_switch DVD.
, C Java -
, . -
b1=b2 , b2.
, , . , ,
b1.
= == Java ,
C/C++,
. = == ,
, . .
, . Java
.

5.3. switch
if . -
5.1.

5.1. switch

switch(){
case 1: 1;
...
case N: N;
default: ;
}

, , ,
, .
(byte, short, char, int)
(. . 3.6), -.
, long .
: , -
, -
. , -
, -
, case (
), ,
case ( case) default
199

. 05_2_if_switch DVD.
break. Java C.
default ,
. 5.2 switch.

5.2. switch

switch(i/j){
case 1:
i=0;
break;
case 2:
i=2;
break;
case 10:
i=3;
j=j/10;
break;
default:
i=4;
}

, switch:
case, -
, Java;

break. , "" ,
, , -
. . -
, break
( default). -
, " break".

5.4. ...?... : ...


C.
:
?1:2

, -
? :, .
true, 1, -
2.
, j , i+1 i<5 i+2 -
. :
j=i<5?i+1:i+2
200 5

,
. -
? : (
). , - -
:
j=(i<5)?(i+1):(i+2).

5.5. ++
--
++ (), -
(). : (
, ) (
, ).
x x++ ++x x 1,
x-- --x x 1.
: -
, ,
.
, j=i++ j=++i (.
05_5_consol_example DVD). i=0, -
0, . . i 1 .
1, . . , -
. -
i 1.

5.6. for
:
for( ; ;
)
;

-
, for. -
, .
.
, -
, , .
-
, for.
( ) -
. .
201

:
for(int i=1,j=5; i+j<100; i++,j=i+2*j){
...
}

for , -
; ( ) .
for , -
1, ,
. ,
.
, 1 100.
result ( 5.3).

5.3.

int result=0;
for(int i=1; i<=100; i++){
result=result+i;
}

( ) -
:
1. result, -
. -
0.
2. . i
1. -
.
3. . . i
100.
4. 1<=100, true, .
result 0, i 1,
result=result+i result=1. ,
result 1.
5. (. . i++, -
i 1). i 2.
6. . . -
2<=100 true, -
, .
7. , 101.
101<=100 false, -
. result=result+i, -
, result=result+100.
202 5

55 1234, -
i 55, 1234
100. 5.4 .

5.4.

double x=1;
for(i=1;i<=n;i++){
x=x*i;
}

, -
:
: result+=i; result=result+i;

: x*=i; x=x*i;
, -
( ).
Java JDK 5 for, -
for-each ( ). -
( , ). -
. 8.3.

5.7.

(
for) . -
.
s , f(x), -
a b ( ). n -
, h = (b a) / n.
, a, b, n f(x) .
j -
. -
.
, -
5.5.

5.5. -

double s=0;
double h=(b-a)/n;
203

for(double x=a; x<b; x=x+h){


s=s+f(x)*h;
}

, . -
n a b , -
, b. ,
, -
. ?
x = b h, x < b
, .
x = b. x < b,
, x == b (. . ).

. x -
b, .
, , x < b true,
a, b n ,
.
, n
"" , , "-
". , -
, -
.
. -
. ,
, .
j f(a + j * h). -
0, 1 . .
n1.
5.6 .

5.6.

double s=0;
double h=(b-a)/n;
for(int j=0; j<=n-1; j++){
s=s+f(a+j*h)*h;
}

-
05_7_integral, DVD. -
0 1 , ,
. 1. -
204 5

-
, . -
10 . -
,
. , 1
-
.
.
f(x) = x2, a = 0, b = 1 (. 5.1).
, -
n = 10, n = 13, n = 102, n = 103,
n = 1001.

5.1.

n s s

8 0.2734375 0.2734375

9 0.2798353909465021 0.279835390946502
10 0.3849999999999999 0.2850000000000001

11 0.28925619834710753 0.28925619834710750
12 0.29282407407407407 0.292824074074074

13 0.3727810650887573 0.2958579881656805

... ... ...

100 0.32835000000000036 0.32835000000000014

101 0.32839917655131895 0.3283991765513185

102 0.33825131359733385 0.3284473920287069

103 0.3382034121971908 0.3284946743331133


... ... ...

1000 0.33283350000000095 0.33283350000000034


1001 0.3338330001666631 0.33283399916766554

1002 0.3328344973393309 0.33283449733932

, n -
( ). -
-
- . . 5.1 n, -
a b.
, n = 10 a = 0 b ,
. 5.2.
205

5.2.
b

b s s
1.00000 0.3849999999999999 0.2850000000000001
1.00001 0.28500855008550036 0.28500855008550036
1.00002 0.2850171003420023 0.2850171003420022
1.00003 0.38503465103951023 0.28502565076950764
1.00004 0.2850342013680182 0.2850342013680184
1.00005 0.2850427521375357 0.2850427521375357

.
. -
j
. -
, (a +h / 2 a).

5.7. ,

double s=0;
h=(b-a)/n;
for(double x=a+h/2; x<b; x=x+h){
s=s+f(x)*h;
}

( 5.7) ,
x, x < b, -
b ( h / 2).

,
. , -
.
, -
.
- -
.
, -
. . 17.4.

5.8.

.
. -
, ,
, .
206 5

, -

( ).
, 5.8.

5.8.

double s=0;
double h=(b-a)/n;
for(double x=a+h/2; x<b; x=x+h){
s=s+f(x);
}
s=s*h;

f(x) ( f(x) * h),


( ).
t,
:
(n 1) t.
n -
.
( )
,
. -
. " "
( ) , -
, ,
. ,

.
""
Java ,
Java -
Java-

.
05_8_effectiveCalc
(
Java).
( f
fnc):
(optimisedIntegral) , ;
(integral) h;
(slowIntegral) (b a) / n
, h;
207

(inlineIntegralX) x,
. ,

, -
.
. 5.3 -
, (, -
), , -
MiddleRectangles ( 5.9).

5.9.

public static double optimisedIntegral(double a,double b,double n,Fnc fnc) {


double r=0, h=(b-a)/n, a1=a+h/2;
for(int i=0;i<n;i++)
r+=fnc.f(a1+i*h);
return r*h;
}
public static double integral(double a,double b,double n,Fnc fnc) {
double r=0, h=(b-a)/n;
for(int i=0;i<n;i++)
r=r+fnc.f(a+i*h+h/2)*h;
return r;
}
public static double slowIntegral(double a,double b,double n,Fnc fnc) {
double r=0;
for(int i=0;i<n;i++)
r=r+fnc.f( a+i*(b-a)/n+(b-a)/n/2 )*(b-a)/n;
return r;
}
public static double inlineIntegralX(double a,double b, double n) {
double r=0, h=(b-a)/n;
for(int i=0;i<n;i++)
r=r+(a+i*h+h/2)*h;
return r;
}

:
long t0=System.currentTimeMillis();
result=MiddleRectangles.slowIntegral(a,b,n,fnc);
long t=System.currentTimeMillis()-t0;

System.currentTimeMillis() (
1 1970 ).
t0 . -
, -
:
System.currentTimeMillis() t0.
208 5

. 5.3 f(x) ( -
Intel Core 2 Duo 1,73 -
Windows XP SP2) 100 -
( ).

5.3. double

,
f(x) -
Delphi C++

1 1,5 1,5 6,0 0,8 0,5
x 1,5 1,5 6.0 0,8 0,5
x 1,4 1,4 6.0 0,8 0,5
()
x*x 1,5 1,5 6,0 1,1 0,6
1/x 2,3 2,3 7,7 2,3 2,1
sqrt(x) 3,8 3,8 9,3 4,2 4,0
sin(x) 13 13 19 7,9 6,2
cos(x) 13 13 19 7,9 5,7
tan(x) 26 26 32 8,9 12,4
pow(x,0.5) 109 109 115 19 60
pow(x,2) 6,1 6,1 12,9 10 5,8
pow(x,2.0) 6,1 6,1 12,9 10 5,8
pow(x,2.5) 60 60 64 19 36
x*x*sqrt(x) 4,7 3,9 9,3 4,0 3,9

: -
Java -
.
,
. -
- .
, Fortran, C/C++ Object Pascal (Delphi,
Lazarus). , , Java
- NetBeans,
- Java- ( JDK 6).
, -
( ).
,
( ). -
. ,
209

, . . 17.517.7 ,
" " (hot spots) , -
.
. 5.3 , , ""
, .
.
pow -
, ,
:
x*x, x*x*x, 1/x,sqrt(x) . .
, sqrt(x) 30 ,
pow(x,0.5).
, x*x* sqrt(x) 15 , pow(x,2.5).
pow(x,2.5) x*x* sqrt(x),
. , , -
!
( ) pow -
, (,
tan),
sqrt. , . -
, ,
.
, s=s+f(x) s+=f(x) s=s*h s*=h
, -
.
, :
object1.myObjField1.myObjField2.myObjField3.x+=5;

, :
object1.myObjField1.myObjField2.myObjField3.x=
object1.myObjField1.myObjField2.myObjField3.x+5;


.
, , Java ( -
), . ,
. 5.3
Object Pascal
( Delphi) C++ ( g++ GNU, -
-O3).
Object Pascal ,
Java Delphi (,
1/x). Java
(,
210 5

sqrt x2 pow(x,2) Java power(x,2) Delphi).


pow (0.5 2.5) Java
. ,
,
Java- .
C++ , , C++, -
, Delphi, -
. Fortran ( f77, -
Cygwin MGW, : -
C++ gfortran GNU,
ifortran Intel Fortran Sun Studio Sun Microsystems).
Fortran C++ -
23 . C++,
Fortran. , sqrt(x)
Java , C++!
C++ -
( ), -
30%. C++
Fortran Java , -
. -
, C++ Fortran Java
-
JDK. JIT-, Java-
, Java
.
, Java
1,12 ,
, .
-
.

5.9.
,

( -
) .
05_9_effectiveCalc,
.
, 100 -
, (. 5.4).
f -
fnc, -
( 5.10).
211

5.4.

- - C++
- - - C++
- (long
Delphi (long long

(int) long
int
(long) (long) (int) Java)
(long) Java)
1 0.4 0,4 1,6 0,12 0,07 0,06 0,23
i 0,4 0,4 1,6 0,15* 0,12* 0,1* 0,24
i*i 0,7 0,7 1,6 0,23* 0,17* 0,1* 0,62
i/3 3,4 3,4 5,6 2,1* 2,0* 0,27* 2,1
i & 0xAF 0,6 0,6 1,7 0,24* 0,15* 0,07* 0,24
i | 0xAF 0,6 0,6 1,7 0,22* 0,15* 0,07* 0,25
i ^ 0xAF 0,6 0,6 1,7 0,22* 0,15* 0,07* 0,24
i<<3 0,6 0,6 1,7 0,21* 0,15* 0,06* 0,24
i*8 0,7 0,7 1,7 0,21* 0,15* 0,06* 0,24
i>>3 0,6 0,6 1,7 0,21* 0,15* 0,07* 0,29
i/8 3,4 3,4 5,6 2,1* 0,18* 0,11* 0,33

* , .

5.10.

public static long slowSum(long i1,long i2,Fnc fnc) {

long r=0;
for(long i=i1; i<=i2; i++)
r=r+fnc.f(i);
return r;
}

-
, -
+= ( 5.11).

5.11.

public static long fastSum_1(long i1,long i2) {


long r=0;
for(long i=i1;i<=i2;i++)
r+=1;
return r;
}
212 5

public static long fastSum_i(long i1,long i2) {


long r=0;
for(long i=i1;i<=i2;i++)
r+=i;
return r;
}
public static long fastSum_and(long i1,long i2) {
long r=0;
for(long i=i1;i<=i2;i++)
r+=i&0xAF;
return r;
}
public static long fastSum_shl(long i1,long i2) {
long r=0;
for(long i=i1;i<=i2;i++)
r+=i<<3;
return r;
}
public static long usualSum_1(long i1,long i2) {
long r=0;
for(long i=i1;i<=i2;i++)
r=r+1;
return r;
}
public static long usualSum_i(long i1,long i2) {
long r=0;
for(long i=i1;i<=i2;i++)
r= r+i; // i+r;- !
return r;
}
public static long usualSum_i_3(long i1,long i2) {
long r=0;
for(long i=i1;i<=i2;i++)
r=r+i/3;
return r;
}
public static long usualSum_and(long i1,long i2) {
long r=0;
for(long i=i1;i<=i2;i++)
r=r+(i&0xAF);
return r;
}
public static long usualSum_or(long i1,long i2) {
long r=0;
for(long i=i1;i<=i2;i++)
r=r+(i|0xAF);
return r;
}
213

public static long usualSum_xor(long i1,long i2) {


long r=0;
for(long i=i1;i<=i2;i++)
r=r+(i^0xAF);
return r;
}
public static long usualSum_shl(long i1,long i2) {
long r=0;
for(long i=i1;i<=i2;i++)
r=r+(i<<3);
return r;
}
public static long usualSum_shr(long i1,long i2) {
long r=0;
for(long i=i1;i<=i2;i++)
r=r+(i>>3);
return r;
}

. 5.4,
-
long, int.
,
. .
, usualSum_i (. 5.11) -
( 5.12), 23 (
05_9_effectiveCalc) 0,7 ,
0,4 . , r=i+r
r+=i Java- JRE 6, NetBeans (
JDK ).

5.12. r+=i r=i+r

public static long usualSum_i(long i1,long i2) {


long r=0;
for(long i=i1;i<=i2;i++)
r=i+r;//r+=i;
return r;
}

, ,
Java JDK ( , ),
. JRE 6
, -
JIT- .
-
.
214 5

, 64- long -
23 , 32- int. -
-
, ,
. . . ,
, , long.
,
, , int.
,
long . -
10.
, int, -
. long , int, -

.
. 5.4 , ,
Java, - , ,
Delphi ( ), C/C++.
Java -
C/C++ 1,52 , 10 . -
Java ,
, -
, . ,
C/C++ , ,
Java , -
.

, -
. -
(, ) C C++
Java native- (-
, -
). , , ,
, Java:
, ( -
), . -
native- 16.

.
-, .
: & (), | (), ^ ( ) -
:
r=r+(i&0xAF);
r=r+(i|0xAF);
r=r+(i^0xAF);
215

,
, .
,
r=r+i&0xAF;
r+i, -
r.
:
r=(r+i)& 0xAF;

, , -
. Java,
.
-, . 5.4 , -
( -
). , -
.
, Delphi C++ 8
, Java, 3 , Java.
, Delphi C++
2 1 , 4
2 , 8 3 . .
Java . ,

, ,
, :
r=r+ r= +r r+=,
r=r* r= *r r*=,

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

5.10. while

while :
while()
;

true, ,
. false, ,
.
216 5

while for , -
. for -
, ( -
). for while . -
for, .

while

i=1;
x=0;
while(i<=n){
x+=i;// x=x+i;
i*=2;// i=2*i;
}

while , -
- .
, for .
, double float -
(- ). -
- ,
, . -
( 5.13).

5.13. while

double a=...;
double b=...;
double dx=...;
double x=a;
while(x<=b){
...
x=x+dx;
}

, ,
a b .
, a=0, b=10, dx=0.1 ,
x=0, x=0.1, ..., x=9.9.
x=10 , ( -
!). -
. dx - -
0.1, x -
. x=10 . x -
, - . , -
, . . 100, 101 ( ).
217

5.11. do...while

do...while :
do
;
while();

false, .
, .

do...while

int i=0;
double x=1;
do{
i++; // i=i+1;
x*=i; // x=x*i;
}
while(i<n);

do...while
/ float double, -
, for while.
( -
) :
do{
...
}
while(true);

5.12.
continue, break, return, System.exit
-

. goto.
Java
continue, break, return, System.exit:
continue
( ) ;
continue _
( ) , ;
218 5

break ;
break _ , ;
return ( )
;
return ( )
;
System.exit(n) n. n -
. n=0, ,
. n
, , -
.
continue break:
( )
. , .
,
(for, while, do), . -
break _ .
5.14 continue .

5.14. continue

for(int i=1;i<=10;i++){
if(i==(i/2)*2){
continue;
}
System.out.println("i="+i);
}

i, i==(i/2)*2 (. . -
i).
5.15 continue .

5.15. continue

for(int i=1;i<=20;i++){
for(int j=1;j<=20;j++){
if(i*j==(i*j/2)*2){
continue;
}
System.out.println("i="+i+" j="+j+ " 1.0/(i*j-20)="+ (1.0/(i*j-20)));
}
}

5.16 , i, j 1.0/(i*j-20)
i j 1 19 (. .
i j).
219

5.16.

i=1 j=1 1.0/(i*j-20)=-0.05263157894736842


i=1 j=3 1.0/(i*j-20)=-0.058823529411764705
i=1 j=5 1.0/(i*j-20)=-0.06666666666666667
i=1 j=7 1.0/(i*j-20)=-0.07692307692307693
i=1 j=9 1.0/(i*j-20)=-0.09090909090909091
i=1 j=11 1.0/(i*j-20)=-0.1111111111111111
i=1 j=13 1.0/(i*j-20)=-0.14285714285714285
i=1 j=15 1.0/(i*j-20)=-0.2
i=1 j=17 1.0/(i*j-20)=-0.3333333333333333
i=1 j=19 1.0/(i*j-20)=-1.0
i=3 j=1 1.0/(i*j-20)=-0.058823529411764705
i=3 j=3 1.0/(i*j-20)=-0.09090909090909091
i=3 j=5 1.0/(i*j-20)=-0.2
i=3 j=7 1.0/(i*j-20)=1.0
...
i=19 j=9 1.0/(i*j-20)=0.006622516556291391
i=19 j=11 1.0/(i*j-20)=0.005291005291005291
i=19 j=13 1.0/(i*j-20)=0.004405286343612335
i=19 j=15 1.0/(i*j-20)=0.0037735849056603774
i=19 j=17 1.0/(i*j-20)=0.0033003300330033004
i=19 j=19 1.0/(i*j-20)=0.002932551319648094

5.17 continue label1.

5.17. continue

label1:
for(int i=1;i<=20;i++){
for(int j=1;j<=20;j++){
if(i*j==(i*j/2)*2){
continue label1;
}
System.out.println("i=" + i + " j=" + j + " 1.0/(i*j-20)=" +
(1.0/(i*j-20)) );
}
}

, i*j==(i*j/2)*2
( j), j
i . (-
5.18).

5.18.

i=1 j=1 1.0/(i*j-20)=-0.05263157894736842


i=3 j=1 1.0/(i*j-20)=-0.058823529411764705
i=5 j=1 1.0/(i*j-20)=-0.06666666666666667
i=7 j=1 1.0/(i*j-20)=-0.07692307692307693
i=9 j=1 1.0/(i*j-20)=-0.09090909090909091
220 5

i=11 j=1 1.0/(i*j-20)=-0.1111111111111111


i=13 j=1 1.0/(i*j-20)=-0.14285714285714285
i=15 j=1 1.0/(i*j-20)=-0.2
i=17 j=1 1.0/(i*j-20)=-0.3333333333333333
i=19 j=1 1.0/(i*j-20)=-1.0

5.19 break .

5.19. break

for(int i=1;i<=10;i++){
if( i+6== i*i ){
break;
}
System.out.println("i="+i);
}

i+6== i*i (. . -
i, 1 2).
break :
for(int i=1;i<=20;i++){
for(int j=1;j<=20;j++){
if(i*j==(i*j/2)*2){
break;
}
System.out.println("i="+i+" j="+j+ " 1.0/(i*j-20)="+
(1.0/(i*j-20)) );
}
}

i j , i
j, i*j==(i*j/2)*2,
i, j 1.0/(i*j-20) j i
. ( i) , -
i j. , continue
.
5.20 break label_for1.

5.20. break

label_for1:
for(int i=1;i<=20;i++){
for(int j=1;j<=20;j++){
if(i*j==(i*j/2)*2){
break label_for1;
}
System.out.println("i="+i+" j="+j+ " 1.0/(i*j-20)="+
(1.0/(i*j-20)) );
}
}
221

i j , -
i j, i*j==(i*j/2)*2, , -
, ( ).
i=1, j=1.


Java :
if;
switch;
...?... : ...;
++ --.
Java :
for ;
while ;
do...while ;
for each .
continue break,
return, System.exit.
.
,
.
,
, .
,
.
, -
.
,
, Java, 1,52 -
, , -
.
-
.
+=, *= . . -
Java-.
-
. -
, ,
.
222 5

64- long 23
, 32- int.

.
, , x 2n -
x>>n, Java
.
x 2n , x<<n.
.
Java
C/C++. C/C++
.


" break" switch.
.
,
.
.
, .
, , ,
,
.

,
for, while,
do...while , JRadioButton .
,
f(x) = ax2 + bx + c, x, x1 x2, a, b, c, x1 x2
.
-
- (for, while do...while) , -
JCheckBox.
(- a, b, c, x1, x2).
, , -
.
,
JButton
continue, break, return, System.exit ,
JToggleButton .
6



1 -
. .
.
, -
,
. -
, .

6.1.
. -
, . -
(ancestor),
(descendants). , , , -
. .
, , .
, , (
), . Java -
Object (. . ). , -
, - ,
, , .
.
, .
, -
.
" ". -
, , -
. -
, , ,
. .
,
- .
224 6

, , Figure (), show()


( ) hide() ( ). figure -
, - Figure.
Figure show() hide(), figure.show()
figure.hide() , -
. , ,
.
( )
.
.

.
, , , -
(. 6.1). Figure, Dot
(), Triangle () Square (). Dot Circle
(), Circle Ellipse (). , , Square -
Rectangle ().
,
. Generalization (, -
). ,
Specialization (). -
.

. 6.1. ,

- (superclass), -
(subclass). -
: , ,
( -
) .
-
. "-
" "".
, -
(general) ( ). , -
, . -
225

, ( -)
, . -
Figure. x y -
.
Dot () Figure x y,
Figure (. . Dot ). Dot
Circle (), x y, Figure,
.
Circle , . r. , -
,
, , setSize ( ).
Ellipse , Circle,
r2 (
), .
( )
. -
(aspect ratio), k.
r k. , k, -
stretch (). , -
scale r k,
.

. , ,
. , "" .
Ellipse .
Square x y, ,
( a). Triangle , -
, ,
, . .
, , -
, , , -
, . -
,
, , ,
. ,
. .
-
: " A1 A2 , A2
A1, A2 A1". -
.
,
, : "-
226 6

Circle Ellipse ( ), Dot -


Circle ( ), Ellipse , Circle,
Circle , Dot. Ellipse
Circle, Circle Dot". -
, ,
.
. -
,
, . , -
. ,
.
-
-. ,
, -
. , -
,
.
- -
, : -
(
, ). , -
aspectRatio ( setAspectRatio( -
)), -
.
,
setSize ( ), .
Ellipse-Circle-Dot
Ellipse Circle Dot, :
setAspectRatio ,
. , -
. .
, setSize , .
,
.
, , -
aspectRatio , -
( , Ellipse). Circle
-
Ellipse. , Circle
Ellipse.
, -
. , -
, -
227

, ,
.

.

A1 A2 , A2
( ) A1 -
A1, A2 A1. , -
, A2 , A1
.

, , (-
extended) . -
/ . -
, , , -
, .
,
. , -
(, ). , ,
, -
, - ( ,
private (, )).
- , -
- (B A), . -
" B A -
( ), -
".
.
. ,
Figure, . ,
.
-. , . 6.2.

. 6.2.

: Figure -
(. 6.3).
228 6

. 6.3.

, . ?
,
. ,
,
, -

( , ).
-
. ,
. 6.1, .
/ .
,
-,
, .
, , , -
,
( , ). ,
, ( -
), , -
, .
,

.
. ,
Figure, -
,
, Dot, -
Circle Ellipse.

. ,
. .

. Ellipse ,
Circle, , , Dot, -
,
( !) -
.
229

, Dot Circle Ellipse


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

,
. -
!
. -
-
. ( 1), , -
,
. -
, - ( 2),
. , . ,
, . -
. ,
,
- . ,
, -
! ,
, -
.
: 2
1 1,
1. , ,
. 1 2
. , 2 -
, 2, -
2. 2 1,
2 2. ,
, -
.
. ,
( , -
), . ScalableFigure (-
) StretchableFigure ( ). Dot
, . , -
. Circle Square ,
. Rectangle, Ellipse Triangle
230 6

, .
. 6.4.

. 6.4.

-
.
, ,
. Figure, ScalableFigure
StretchableFigure -
, ( )
, . show hide
.
, , . .
( ), ,
, . -
, (-
).
:
1. (, ,
) , .
2. (
. 9).
3. , -
. ( -,
-, - . .). , -
, -
.
4. , "" ("and"). ,
readAndShowSpeed, calculateIntegralAndWriteToFile . .
readSpeed ShowSpeed;
calculateIntegral writeToFile, . .
5. -
, .
231

,
-
. , Figure
Figure figure, Dot Dot dot, ScalableFigure -
scalableFigure . . figure.show()
" ", -
, figure.
dot.show() " ", scalableFigure.show() "-
" . . ,
, - . , -
Dot. dot.show() -
" ", dot
! Figure Dot Circle Ellipse
circle, , circle.show() " -
", . ,
.
-
. , , Figure Dot
Circle Ellipse, , Figure
AbstractDot AbstractCircle AbstractEllipse, . -
Dot AbstractDot, Circle AbstractCircle Ellipse AbstractEllipse.
, . -
abstractDot, , abstractCircle, -
, . -
, -
.
abstract .
Abstract -
, . ,
AbstractFigure, .
abstractFigure.show() . -
!
. ,
, : -
abstract. AbstractFigure
figure, AbstractName name . .
, , -
. , -
,
.

6.2. . .

,
, . Java
.
232 6

(. . ) :
( ){

}

, , -
. , -
, .
:
( )

.
, :
(private, protected, public). ,
( );
(static). , -
, ;
(final).
, , -;
(native , DLL,
C C++; abstract , ;
strictfp , -
Java). , -
, ;
(synchronized) . 10.
(transient
, , , -
(, ) . . -
; volatile ,
(. 10),
, , -
, -
);
(abstract , . .
; strictfp , -
-
Java).
, . Java,
, , -
. , (. . ),
void. -
return.
:
return;
233

:
return ;
, -
.
return ,
if...else switch...case ,
.
- - return, -
missing return statement (
return).
,
,
.
:
1 1, 2 2, ..., N N
, .
, -
. , -
(. . , ,
). -
.
.
. ,
( ), .
( )
, .
-
. , MyMath mult1
, ( 6.1).

6.1.

double mult1(double x, double y){


x++;
y++;
return x*y;
}

6.2 .

6.2.

double a,b,c;
...
MyMath obj1=new MyMath();// MyMath
...
c=obj1.mult1(a+0.5,b);
234 6

, , -
, . -
,
. ,
,
.
x y mult1, a+0.5
b . -
, , -
,
(. . x , -
a+0.5, y ,
b). ,
.

(. . , -
. .). -
, , -
, -
. , mult1 double
int float.
float, int ,
double .
- y ,
y++, , b? , !
y,
b. b -
.
,
? , ! Java , -
, ( -
). Java -
.
, . . -
, , , . ,
, - , -
. .
final. , -
, ( 6.3).

6.3. , final

double mult1(double x, final double y){


x++;
return x*y;
}
235

6.4 .

6.4. , final

double mult1(double x, final double y){


x++;
y++;
return x*y;
}

6.3. .
.
this
, -
. ,
, , -
. :
,
, ,
;
-
, , -
, -
. , -
.
, , , -
, -
! , -
. Java ,
.
( )
() , -
private, protected, public.
, .
private ( ),
.
private- (. . ,
private, ).
, ( -
, ).
( C++) .
protected ,
, , - (
).
236 6

public ,
. ,
, .

6.5.

6.5.

class Vis1 {
private int x=10,y=10;
int p1=1;
protected int p2=1;
public int p3=1;
}

, 6.5, x, y, p1, p2, p3, x y


private, p1 , p2 protected, p3 public. -
, -
.
, -
. , -
. -
,
( ).
, ( ),

. ,
, .
:
,
.
( 6.6), 1 n.

6.6. i r sum1

double sum1(int n){


int i;
double r=0;
for(i=1;i<=n;i++){
r+=i;
}
return r;
}

:
c=obj1.sum1(1000);
237

i r obj1.sum1(1000).
, -
i r.
.
,
,
.
(garbage collector).
- , -
, .
. -
:
. ;
. {...},
. -
;
for. -
.
.
this () (
C++), . -
,
this .
, x show(), :
this.x , x,
this.show() , show().
( ) -
, this. -
, this ,
(, ,
).
this (. . -
static), .
, , -
. :
( ) -
.

set. ,
, . (
) this. ,
238 6

x x, -
:
void setX(double x){
this.x=x
}

( )
.
. this;
( )
for - , -
{...}, . Java
. -
, this;
(, -
) for - , -
{...}, -
. Java .
, (is already defined);
,
. Java -
, . . -
.

6.4. .


-
, . . , -
, , . -
, ,
, .
, ( -
, - -
).
Location ( 6.7).
,
m1, .
, 6.8.

6.7. Location

public class Location {


public int x=0,y=0;
239

public Location (int x, int y) {


this.x=x;
this.y=y;
}
}

6.8. Location

Location locat1=new Location(10,20);

public static void m1(Location obj){


obj.x++;
obj.y++;
}

locat1 Location, x y -
10 20. m1 x y -
, obj.
. -
x y ,
locat1, m1 ( 6.9).

6.9.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {


System.out.println("locat1.x="+locat1.x);
System.out.println("locat1.y="+locat1.y);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
m1(locat1);
System.out.println(" m1(locat1)";
}

, m1(locat1) locat1.x
locat1.y.
,
-
. m1 ( 6.10).

6.10.

public static void m1(Location obj){


obj.x++;
obj.y++;
obj=new Location(4,4);
obj.x++;
obj.y++;
}
240 6

, ()
,
obj, , -
. x y , locat1, -
? -
!
obj=new Location(4,4); , obj
. -
obj.x++ obj.y++ , -
, .
, -
. " " ", -
" , -
. ,
, obj.x++ -
, . " x obj",
, - ! " x
, obj", , -
.
( ) , -
,
. Java ,
, , . -
, , -
, (. . Java
). Java .
,
.
, .
, s3 -
, s1 s2:
void strAdd1(String s1,s2,s3){
s3=s1+s2;
}

Java , .
, -
s3. .

obj1.strAdd1(t1,t2,t3);

t3 .
, Java String , -
s1+s2
. s3=s1+s2
s3 . , ,
241

t3
-. , , strAdd1
,
.
: -
. , -
( ,
). ,
, -
name+count. , , ,
( -
), ,
.
, 6.11.

6.11.

String componentName="myComponent";
int count=0;
public void calcName1(String name) {
count++;
name+=count;
System.out.println(" ="+name);
}

, -
:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
calcName1(componentName);
System.out.println("componentName="+componentName);
}

, ,
componentName "myComponent1", -
"myComponent2" . . myComponent , -
calcName1 , . -
?
, -
,
. -
-
, name.
componentName
- "myComponent".
? .
-, -,
, -,
String ( 6.12).
242 6

6.12.

public String calcName2(String name) {


count++;
name+=count;
return name;
}

, -
:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
componentName=calcName2(componentName);
System.out.println("componentName="+componentName);
}

, ,
.
.
-, ,
. count
( , -
).
-, (wrapper), -
. , -
. , , -
-.
,
. , -
,
, , . -

.
-, StringBuffer StringBuilder.
,
, -
. 6.13 .

6.13. StringBuffer

public void calcName3(StringBuffer name) {


count++;
name.append(count);
System.out.println(" ="+name);
}
StringBuffer sbComponentName=new StringBuffer();
{
sbComponentName.append("myComponent");
}
243

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt){


calcName3(sbComponentName);
System.out.println("sbComponentName="+sbComponentName);
}

componentName sbComponentName
StringBuffer. - -
, -
, sbComponentName -
:
{
sbComponentName.append("myComponent");
}

. 6.9.
.
String , ,
StringBuffer, , .

,
StringBuffer StringBuilder , String.
toStringBuffer() .
StringBuffer sb.append().

append insert
. , ,
toString, Arrays.toString()
(. . 8.1).
,
int[] a=new int[]{10,11,12};
System.out.println("a="+a);

- , a a.toString(),
:
a=[I@15fea60

, .
, toString , -
. -
( I int), -
@, - ( ).
- - ,
- . -
. Java - ,
- . - -
Java-, -
.
244 6

/ .
, :
void m1(Double d){
d++;
}

, d , d -
-
, String.
double, ++,
Double, -
d.
:
public void proc1(Double d1,Double d2,Double d3){
d3=d1+sin(d2);
}

, , d3, -
d3=d1+sin(d2), , . . -
.
,
, -
.
( 6.14).

6.14. , double

public class UsableDouble{


Double value=0;
UsableDouble(Double value){
this.value=value;
}
}

UsableDouble d -
.
.
,
, , ,
.
, -
, Java
, -
, , , Java- C#.
245

6.5. . .


, ,
/ .
(ancestors),
(descendants) . - -
, -, (inheritance)
.
C++ Java "" "" -
(superclasses) (subclasses). , -
, "" -
.
- ,
class , extends
(), - (
). , ,
Object. - , .
Java extends , , -
, , (
, ).
.
, ,
. ,
, - -.
-. ,
, .
:
public , () .
,
;
abstract , , , . . -
(). ,
- ;
final , , (final), . . -
.
, - :
class extends {
;
, ,
}

, (interfaces).
9.
246 6


. , Figure -
, Dot , Circle Dot (. . ). -
, .
Figure . -
, . . , , -
. show () hide () -
. , ,
.
6.15.

6.15. Figure

public abstract class Figure { //


int x=0;
int y=0;
java.awt.Color color;
java.awt.Graphics graphics;
java.awt.Color bgColor;
public abstract void show(); //
public abstract void hide(); //

public void moveTo(int x, int y){


hide();
this.x= x;
this.y= y;
show();
}
}

x y , color .
java.awt. graphics ,
. java.awt.
x, y color,
, . -
bgColor ( "background color") -
. hide,
. ,
. , , -
. ,
FilledCircle ,
XOR ( ), -
setXORMode.
(. . 6.9).
moveTo , , -
show hide. -
. 6.7, .
247

, Figure Dot (). Dot


Object Figure (), Figure -
. , Dot
(), Figure . Dot -
(extends) Figure (
, show hide,
). Figure java.awt
. Dot ,
. . . 6.16 -
.

6.16. Dot Figure

package java_gui_example;

import java.awt.*;
/**
* @author ..
*/
public class Dot extends Figure{

/** Dot */
public Dot(Graphics graphics,Color bgColor) {
this.graphics=graphics;
this.bgColor=bgColor;
}

public void show(){


Color oldC=graphics.getColor();
graphics.setColor(Color.BLACK);
graphics.drawLine(x,y,x,y);
graphics.setColor(oldC);
}
public void hide(){
Color oldC=graphics.getColor();
graphics.setColor(bgColor);
graphics.drawLine(x,y,x,y);
graphics.setColor(oldC);
}
}

, Dot x, y, graphics moveTo -


Figure. show hide (override)
, ,
.
Dot (Graphics graphics, Color bgColor)
Dot . show hide
graphics. show oldC
248 6

.
( java.awt. Color.BLACK). , (-
), -
. , -
, - .
(shared) .
-
, ,
.
override () "".
, . . -
(hiding). , -
, (, , ).
,
.
.
-
. , -
, . 8.6.
, ,
. , ,
, (overloading) . -
. 6.11.
, , ,
.
-
. ( - )
( background). dot,
:
Dot dot=new Dot(jPanel1.getGraphics(),jPanel1.getBackground());

- dot
show hide:
dot.show();
dot.hide();

/ jTextField1 jTextField2.
moveTo, -
, :
int newX=Integer.parseInt(jTextField1.getText());
int newY=Integer.parseInt(jTextField2.getText());
dot.moveTo(newX,newY);

,
.
ScalableFigure ( ),
Figure. ( 6.17).
249

6.17. ScalableFigure Figure

package java_gui_example;
public abstract class ScalableFigure extends Figure{
int size;

public void setSize(int size) {


hide();
this.size=size;
show();
}
public int getSize() {
return size;
}

ScalableFigure -
, . . .
show hide.
size () setSize ( ) getSize (-
), . -
, ,
size , . -
, size, (
). , -
, , ,
, . . - ScalableFigure. -
, , . 6.7 6.12.
Circle (), ScalableFigure ( 6.18).

6.18. Circle ScalableFigure

package java_gui_example;
import java.awt.*;

public class Circle extends ScalableFigure {

Circle(Graphics g,Color bgColor, int r){ //


graphics=g;
this.bgColor=bgColor;
size=r;
}

public void show(){


Color oldC=graphics.getColor();
graphics.setColor(Color.BLACK);
graphics.drawOval(x,y,size,size);
graphics.setColor(oldC);
}
250 6

public void hide(){


Color oldC=graphics.getColor();
graphics.setColor(bgColor);
graphics.drawOval(x,y,size,size);
graphics.setColor(oldC);
}
}

Circle -
size, ScalableFigure. , -
.
, show hide,
, , .
, Circle ScalableFigure -
, .
, Circle ScalableFigure,
Figure.
x, y, color, bgColor, graphics moveTo Circle Figure.
ScalableFigure size setSize.
, , .
, , ,
. " circle
Figure". , , "
circle - Figure".
, , ,
.
Circle () ScalableFigure, ScalableFigure
() Circle (. . ScalableFigure
Circle , Circle ScalableFigure ).
Figure ScalableFigure, Circle. Circle -
ScalableFigure, Figure.
Java Object, Object
Figure, ScalableFigure, Circle.
Figure.

6.6. .
super
, -
.
, private (, ), , -
- . . ,
, Password1 ,
password (), -
251

, . public,
.
protected -
, Password2,
Password1, , :
public String getPass(){
return password;
}

private,
password !
, private- , .
6.19 .

6.19. private-

public class TestPrivate1 {


private String s=" private";

public String get_s(){


return s;
}
}

, , :
public class TestPrivate2 extends TestPrivate1 {
}

, TestPrivate2, get_s(),
: " private":
TestPrivate2 tst=new TestPrivate2();
System.out.println(tst.get_s());

, s , -
, . , private-,
- , -
, .
protected -
-. ,
( , ), -

protected- -, . -
protected , -
, .
: private,
, -
get (, . . ) set (, . .
). .
252 6

,
.
. , -
. .
x y, ,
! setX
setY, , -
.
.
. -
-, : x1, y1 ,
x2, y2 , w , h , s
.
: w=x2-x1, h=y2-y1, s=w*h. - -
. , , x2
w s, . ,
, !
, -
, ,
. ,
.

NetBeans 6.5. UML- -
private public-
, get set ( ). -
, , , .
.
, - -
(, , ) .
- . ,
. super.
super.( ). super superclass.
,
, ,
super.super. .
super -
. (. . static) -
super .

6.7.
.
, , -
Java .
253

, -
.
static -
. ,
- ,
(. .
).
, . .
. Java
final (, ).
, static
.
Java , . . -
. -
, ,
. , -
( , ).
, ,
.
, ,
- ,
, , -
.

moveTo. ,
-.
, . -
- Figure
( 6.20).

6.20. moveTo, Figure

public void moveTo(int x, int y){


hide();
this.x = x;
this.y = y;
show();
}

, ,
.
Figure
. hide show
, . ., , !
hide show , , , ,
.
254 6

, Figure, ,
Figure! , , -
hide show .
dot1 Dot circle1 Circle,
. ,
dot1.moveTo(x1,y1) circle1.moveTo(x2,y2).
dot1.moveTo(x1,y1) Figure moveTo. -
, Dot , , Figure.
moveTo hide. -
, dot1, -
(. . Dot). , . -
, show. -
, dot1,
(. . Dot). , -
.
circle1.moveTo(x2,y2)
hide show , circle1,
. . Circle. ,
.
, , -
, . , -
- , , FilledCircle ( . .
),
Circle, FilledCircle filledCircle =new FilledCircle(...),
filledCircle.moveTo(...) .
, FilledCircle -
hide show. , - -
Figure. ,
moveTo
-
moveTo.
-
. -
.

6.8. Object
Object Java, -
. Object :
public Boolean equals(Object obj) true ,
, , ,
obj . , false.
Object
==. ,
255

(, -
). :
Double d1=1.0,d2=1.0;
System.out.println("d1==d2 ="+(d1==d2));
System.out.println("d1.equals(d2) ="+(d1.equals(d2)));

d1==d2 =false, d1.equals(d2) =true.


equals hashCode
[11];
public int hashCode() - . , -
- , -
.
. Java - ,
- ;
protected Object clone() throws CloneNotSupportedException -
() .
Object , -
, Clonable. ,
,
CloneNotSupportedException ( ). -
.
: (shallow), -
, (deep),
, ,
. ,
. -
, . -
, , -
.
, . -
.

[11];
public final Class getClass() .
, ,
;
protected void finalize() throws Throwable -
. Object, -
- (
, , - . .). ,
.
. 6.10;
public String toString() (
, ). Object
256 6

( ), @,
- .
.
, ,
( !).

6.21. toString()

Object obj=new Object();


System.out.println(" obj.toString() "+obj.toString());
Double d=new Double(1.0);
System.out.println(" d.toString() "+d.toString());
Character c='A';
System.out.println("c.toString() "+c.toString());

, 6.21 :
obj.toString() java.lang.Object@fa9cf
d.toString() 1.0
c.toString() A

notify(), notifyAll()
wait, (threads).
. 10.3.

6.9. .
super this.
, Java
new, ,
.
Java .
,
new .
( , ),
( this).
, -
, .
, Java
, .
,
,
. , (
). , -
.
, -
. Dot Circle.
257

Dot Circle ,
. , . . , -
( ), -
. -
. , -
super ( superclass),
.
, (
). , FilledCircle Circle, -
( 6.22).

6.22. FilledCircle

package java_gui_example;
import java.awt.*;

public class FilledCircle extends Circle{

/** Creates a new instance of FilledCircle */


public FilledCircle(Graphics g,Color bgColor, int r,Color color) {
super(g,bgColor,r);
this.color=color;
}

public void show(){


Color oldC=graphics.getColor();
graphics.setColor(color);
graphics.setXORMode(bgColor);
graphics.fillOval(x,y,size,size);
graphics.setColor(oldC);
graphics.setPaintMode();
}

public void hide(){


Color oldC=graphics.getColor();
graphics.setColor(color);
graphics.setXORMode(bgColor);
graphics.fillOval(x,y,size,size);
graphics.setColor(oldC);
graphics.setPaintMode();
}
}


: , -
, Object, , ,
. -
super(_), . .
258 6

, -
, .
-
. -
XOR ( ). setXORMode.

.
setPaintMode.
this,
,
.
, -
. , -
. , Circle ,
x, y r ( 6.23).

6.23. Circle

Circle(Graphics g, Color bgColor){


graphics=g;
this.bgColor=bgColor;
size=(int)Math.round(Math.random()*40);
}

, x y, -
size , :
Circle(Graphics g, Color bgColor, int r){
this(g, bgColor);
size=r;
}

this , this -
.
(
):
1. , (
).
2. .
3. (
), -
, , Object.
4. , -
.
5. .
259

6. , -
.
7. .
, -
, ,
.
, -
. Java, -
,
. -
6.24.

6.24.

class extends {
;
static {

}
{

}
,
}

.

( main):
1. ( -
).
2. main.
3. .
4. .
, main:
1. ( -
).
2. .
3. .
? , -
, : , -
. ,
,
. -
, - -
260 6

, -
.

6.10.
finalize.

, ,
.
. , C++ Object
Pascal, ,
.
, , ,
- .
, -
, "".
. , : -
, , .
,
.
Java finalize(). , -
, ,
, , .
-
, finalize -
. System.gc()
finalize() , . . -
,
finalize(). ,
.
-
destroy() (, ), -
.
dispose() (, ), free() ().
-.
, ,
super.destroy(). , -
, -
. , , -
, .
. -
, , , -
, , , -
261

. -
super.destroy().

6.11.
,
.
. ,
(overloading) . ,
, , .
, .
Java -
. ,
.
, . .
.
, :
Circle(Graphics g, Color bgColor){
...
}

Circle(Graphics g, Color bgColor, int r){


...
}

, .
, -
- ,
. , ,
. ,
, .
Math1, - product,
.
,
, (-
6.25).

6.25.

public class Math1 {

public static byte product(byte x, byte y){


return x*y;
}
262 6

public static short product(short x, short y){


return x*y;
}

public static int product(int x, int y){


return x*y;
}

public static char product(char x, char y){


return x*y;
}

public static long product(long x, long y){


return x*y;
}

, . . .
-
. (static),
.

6.26.

public static byte product(byte x, byte y){


return x*y;
}

public static int product(byte a, byte b){


return a*b;
}

6.26, -
, . . .
, .
product ,
, . ,
byte int? ?
,
. product(int x, int y) product(long x, long y). -
- -
, -
. , , . .
product(int x, int y).

, , , -
.
Math1.product(b1,b2), -
Math2 ( 6.27) byte b1, b2.
263

6.27.

public class Math2 {

public static int product(int x, byte y){


return x*y;
}

public static int product(byte x, int y){


return x*y;
}

, -
. , Math2
. , .
, -
. ,
, -
.
.
, , -
. , ,
, , , -
.

6.12.
.

, -
. ? -
.

1
,
-.

-
.

2
-
, -.

, -
( new, ),
( ).
264 6

, -
, ,
- (
).
, , , -
( moveTo), -
dx dy . -
( ).
FiguresUtil ( Utilities (, -
)), moveFigureBy ( ) ( 6.28).

6.28.

public class FiguresUtil{

public static void moveFigureBy(Figure figure,int dx, int dy){


figure.moveTo(figure.x+dx, figure.y+dy);
}
}

figure -
, . , , -
,
: ,
Dot. , -
Circle. ,
FilledCircle. , FilledCircle
Figure, Dot Circle.
6.29 .

6.29. moveFigureBy

Figure figure;
java.awt.Graphics g=jPanel1.getGraphics();

//
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jRadioButton1.isSelected() )
figure=new Dot(g,jPanel1.getBackground());
if(jRadioButton2.isSelected())
figure=new Circle(g,jPanel1.getBackground());
if(jRadioButton3.isSelected())
figure=new FilledCircle(g,jPanel1.getBackground(),20,
java.awt.Color.BLUE);
figure.show();
}
//
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
265

int dx= Integer.parseInt(jTextField1.getText());


int dy= Integer.parseInt(jTextField2.getText());
FiguresUtil.moveFigureBy(figure,dx,dy);
}

, ,

. - -
.

FiguresUtil.moveFigureBy(figure,dx,dy);.
, 6.30.

6.30.

FiguresUtil.moveFigureBy(
figure,
Integer.parseInt(jTextField1.getText()),
Integer.parseInt(jTextField2.getText())
);

( 8 !), -
, .
: -
( 6.31).

6.31.

Figure figure;
Circle circle;
...
figure =new Circle (); //
...
circle= figure; /* ! .
figure Circle
,
.*/

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

6.32.

Figure figure;
Circle circle;
Dot dot;
...
266 6

figure =new Circle (); //


...
circle= (Circle)figure; // !
dot=(Dot) figure; // !

, , -
.
. -
,
, . Java
, . , -
,
(. .
).
, .
, . . - -
, .
, -
, , , .
, (Circle)figure , figure -
Dot, Circle.
(typecast).
, :
if(figure instanceof Circle)
System.out.println("figure instanceof Circle");

. -
.class .
:
Class c=Circle.class;

. ,
-
newInstance():
Circle circle=(Circle)c.newInstance();


:
if(figure.getClass()==Circle.class)
circle= (Circle)figure;
...;

, ,
. isInstance ( -
instanceof) , figure ,
c:
267

if(c.isInstance(figure))
System.out.println("figure isInstance of Circle");


. -
, . -
(ancestor),
(descendants). , .
, , .
, , (
), .
, ,
.
, .
, ,
(general) . ,
(specialized).
-
- -
, .
Java - -
.
( ).
, , ,
.
-
, . ,
,
.
Java .
. , .
Java private (, ), ( -
), protected () public (). -
(default) , -
private, protected public.
this . -

.
this
,
this().
268 6

- . -

.
(overloaded) , -
. , -
, .
,
-.
-
, -.
.
, (
).
, ,
, ,
.
, ,
instanceof: if(figure instanceof Circle)...
-
: if(figure.getClass()==Circle.class)... -
- Circle false, -
Circle.
isInstance ,
c: if(c.isInstance(figure))... , -
figure, c ,
true.


,
- . ,
, .

(
), .
, ( ).
-
, .
, ,
.
. , Object object
Dot, (Circle) object.
-
269

(invalid typecast)
.
instanceof instanceOf.
instanceof -
, , ,
.
,
-. , - Figure -
-
if( this instanceof Dot ) op1;
else if( this instanceof Circle ) op2;
else if( this instanceof Rectangle ) op3;


if( this.getClass() == Dot.class ) op1;
else if( this.getClass() == Circle.class ) op2;
else if( this.getClass() == Rectangle.class ) op3;

. -
!
, . -
, -
.

MathUtil public static


double factorial(int n).
static (. . -
).
, n -
1 n:
n!=12...(n-1)n

, 0! 1. n! -
, Java ! . -
:
public static long factorial_long(int n)

public static int factorial_int(int n)

n=0,1,5,10,20,50,100. .
. -
show hide. -
270 6


show hide, x y .
,
. -
. -
, .
, figure.
dot., Figure figure Dot dot.
Figure Dot -
.
7

UML-.
.

-
, 1020 . -
(IDE), -
, , (

, , NetBeans). , -
, -
, , ,
.

7.1. UML-
Java, ,
. , , C++
Object Pascal, Java (
) . NetBeans
UML-.
UML Pack. UML Unified Modeling Language (
).
, . . -
(Object-Oriented Architecture, OOA).
UML-, -
NetBeans, , -
( , ).
, UML- -
(
UML-), Software Engineering (-
).
Software Engineering : (-
UML-, Forward Engineering) -
( UML- , Reverse
Engineering).
272 7

-
, NetBeans 6.5.

, -
, .
NetBeans -
, UML- NetBeans 6.5 -
. ,
, UML-
NetBeans . , UML-
(Undo/Redo). UML-
. -
, .
, . .
. ,
,
. .
NetBeans , -
UML-.
- UML pack,
UML-, NetBeans 6.5,
( -
- ).
NetBeans 6.5 uml6.zip
DVD, uml6
NetBeans 6.5 (. . C:\Program Files\NetBeans 6.5, -
). NetBeans
.
UML- NetBeans.
File/New Project...
Categories () UML, Projects ()
Java-Platform Model Next > () (. 7.1).
,
(. 7.2).
Finish () UML-
, , -
. ,
Class Diagram Finish (. 7.3).
Palette, ,
Class
. , , -
(. 7.4). - -
Class .
UML-. . 273

. 7.1. UML-. 1

. 7.2. UML-. 2

Class Diagram1. -
, - .
, Figures Diagram. -
-, NetBeans
,
( ) -
, , .
. -
Class Diagram 1 Projects ( )
Diagrams. ( !), ,
.
<Enter>, (. 7.5),
: " Class Diagram 1 .
. ?"
274 7

. 7.3. UML- . 1

. 7.4. UML- . 2
UML-. . 275

. 7.5.

Save .
Cancel (), , ( -
).

Rename... ().
Properties (). -
,
Properties .
. ,
-
.
Unnamed ( ). -
(attributes) (operations ) . -
Figure, Dot.
Operations ( , ) -
Projects public
Figure() public Dot().
Figure Dot . ,
Dot Figure, Dot
Figure. , , -
, -
, , -
. .
- ,
(Generalization ),
. . (. . 7.4).
.
Generalization (, ) ,
, .
,
Unnamed, , -
.
-,
, , . . -
. , UML-
, -
276 7

, , Generalization.
.
Implementation () ,
(. 9)
, . -
,
.
, -.
Association () , -
(. 9). , -
.
Containment () ,
(. 12).
. , ,
. .
, ,
.
Dependency () , ,
. , ,

. ,
.
, - -
. .
Link Comment ( )
.
, - (. ).
Dot, Generalization,
Figure , -
Figure. , -
(. 7.6).
Projects
Relationships (), Generalization. Dot
Generalization Figure, .
Figure Generalization Dot -
. , : Generalization (-
, ) Inheritance (), -
, .
.
-, -
, .
-, -
.
.
UML-. . 277

,
, .

. 7.6.

UML- NetBeans 6.5


UML
Documentation ( . 7.6). -
- . -
, Figure, " ,
, " (. 7.7).
, -
. , -
,
, .
UML Documentation (. 7.7) -
(, , -
, ), ( ,
). - , -
NetBeans Window/
Other/UML Documentation.
<Ctrl>+<Shift>+<D>,
( Project, Navigator, Output, . .).
278 7

. 7.7.

UML-

.
Properties Documentation (. . 7.4).
Documentation
, (. 7.8).

. 7.8. Documentation UML-


, . . -
HTML-. , UML-
, ,
.

UML- Comment.
(Palette), Netbeans 6.5 Comment Basic ( -
). ,
,
Link Comment ( ) (. 7.9).
- .
Link Comment -
. , -
- (. 7.10).
UML-. . 279

. 7.9. . 7.10.
Comment Comment, Figure

-
.
Comment -
,
.
Comment , -
. Link
Comment - (. . 7.4, -
) .

7.2.
UML-
UML-.
Projects .
.
. .
Palette () ,
. (. 7.11).
Basic () , -
.
Class () .
Interface () . -
.
, , 9.
Enumeration () (. 8).
Package () .
Datatype ( ) ,
, . Java .
280 7

. 7.11.

Artifact () ,
- ( ,
. .),
(, UML-, , , ).
Aliased Type (, ) C++
.
Actor () . ,
, -, -
(, ), , -
, (, ). ,
"" , -
( ).
Utility Class (-) ,
. , . . -
( ),
.
Comment () , .
Robustness () , -
.
Boundary Class ( ) ,
, . . ,
.
Control Class ( ) ,
, ,
-. -
(/ , )
- .
, .
. -
(,
UML-. . 281

) . -
- -
- .
-
, -
/ -.
Entity Class ( , -) ,
- ( ).
.
Templates (, ).
Template Class (, ) ,
, -
. (templates, generics)
.
Derivation Classifier ( ) , -
,
.
Design Pattern ( ).


, .
.

(. http://barsic.spbu.ru/www/
comlan/patterns.html, -
).

Design Pattern ( ) ,
.
Role () ,
.
Interface Role ( ) , -
.
Actor Role ( ) , -
.
Class Role ( ) , -
.
Use Case Role ( " , ...") ,
.
Role Binding ( ) -
.
Properties (),
, ( )
282 7

. ,
.
, . ,

Abstract.
( Final
public protected,
private package. -
( ), -
. , , -
,
.

, . Documentation,
. 7.1. ,
, .

7.3.
UML-
( )
(), (. 7.12).

. 7.12.


( ). -
.
( ).
(Select ) -
( , ).
<Esc>.
(Pan )
-
. , -

<Ctrl>+< >. Pan, ,
"" <Esc>.

-:
<Ctrl>+<A>, . -
UML-. . 283


<Ctrl> <Shift>, -
.

(Marquee Zoom
) -
.
(Interactive Zoom ) -
/
. -
( ), .
(Navigate Link )
, -
, .
.
( ), ,
.
, Dot , -
. , .
Navigate Link, -
Figure. Navigate Link,
Dot.
NetBeans , -
. . NetBeans 6.5
.
(Discover Relationship )
, -
. , -
, ,
Discover Relationship .
, -
, , .
(Sync Diagram Synchronization Synchronize
Diagram, )
, . ,
(,
). -
.
(Export Image )
JPEG, PNG SVG.
JPEG ,
, . . . -
PNG SVG.
PNG GIF, -
, -
284 7

,
, -
. , -, -
.
SVG (Scalable Vector Graphics ),
, , . . -
, -
. -
, PNG,
,
.
(Fit Diagram ) -
,
. ( )
.
() (Fit Width
) ,
. -
. ( -
) .
() (100%)
1:1, . .
100%.
. 7.13.

. 7.13.

:
( ),
. -
.
:
(Zoom In );
(Zoom Out ).
/ 5%
.

:
Move Forward ;
Move To Front ;
UML-. . 285

Move Backward ;
Move To Back .
, -
(
, ). -
, .
(Hierarchical Layout )
.
-
(. 7.14).

- ,
. NetBeans 6.5
/ -
Show/Hide List Compartment/Collapse All
( ) Show/Hide List Compartment/Expans All ( ). -
/ Show/Hide List Compartment/Attributes
Compartment, / Show/Hide List
Compartment/Operations Compartment.

. 7.14. ,

Hierarchical Layout
. -
(. 7.15).

. 7.15. , ( undo)
Hierarchical Layout
286 7

-
, , . 7.16.

. 7.16.

7.4.
(Forward engineering)
UML-
NetBeans 6.5 .
07_4_1_UML_Figures
, ,
, (attributes
) (operations ).
Figure x, -
x, -
, New/Attribute (. 7.17).

Attributes Figure Create Attribute
( ) (. 7.18).
Figure :
private int Unnamed

Unnamed x . -

. -
<Enter> -
. -
. private,
get set (
).
UML-. . 287

. 7.17.

. 7.18.

Java (getters) (setters). UML-


NetBeans -
. x -
public int getX() public void setX(int val)
(. 7.19). , -
.
288 7

. 7.19.

int, , -
, .
y, Figure
- ,
. , NetBeans , -
, .
-
Show/Hide List Compartments (/ ).
( Properties) Figure -
. Abstract Figure -
(. 7.20). -
.
Figure().
,
, Figure()
Figure . -
, . -
Figure , Figure(int x, int y)
-. -
, protected. -
Properties
Visibility () protected (. 7.21).

int x int y. ,
Properties Parameters. (. 7.22).
New Parameter..., (. 7.23) -
x
int.
OK , -
.
UML-. . 289

. 7.20. . 7.21.
Abstract Figure Figure()

. 7.22.

. 7.23.


290 7

int y. , -
. 7.24.
. Move Up (
) Move Down ( ) -
. : Name (),
,
; Type (), ; Direction ()
Kind () . Java
, Direction
in ( ), Kind byValue ( )
addressOf ( , . . ) .

. 7.24. x

,
Update () ,
. , -
Remove ().
. ( -
),
Delete ().
Figure show() hide(), moveTo(int
newX, int newY). ScalableFigure , -
int size. Circle getR setR,
Circle() int x, int y, int r.
Dot Circle show() hide()
Figure.
- -
,
UML-. . 291

(. 7.25). , -
.
7_4_3_UML_Figures , -
.

. 7.25.

Java .
7_4_3_JavaLibrary1 : File/New Project
/Java/Java Class Library/Next>, 7_4_3_JavaLibrary1, Finish.
UML- -
(Figure, Dot . .). ,
. ,
NetBeans.

Generate Code... ( ).
(. 7.26), Target Project
(-) .

. 7.26. , Generate Code

Java- (7_4_3_JavaLibrary1) ""


.
:
Backup Existing Source Files ( -
). -
, , .
java java1~, java2~ . . ( -
292 7

java). -
;
Generate Markers for Source File Merging (
). ,
UML-.
, , ()
UML-;
Add Merge Markers to Existing Source Elements (
).
. , -
, UML-;
Prompt Before Generating Code ( ).
Show Templates ( )
,
( ).
Dot, ScalableFigure, Circle,
07_4_3_JavaLibrary1 . -
Figure UML- . 7.27.

. 7.27. Figure
UML-. . 293

Dot, Circle ScalableFigure


( ).
Dot -
Dot(int x, int y).
public Dot (int x, int y) {
}

super(x,y) :
public Dot (int x, int y) {
super(x,y);
}

Circle ScalableFigure -
.
07_4_3_JavaLibrary1
(default package). -
. .
. , . 7.6.
Java-
, UML-.
UML- Java-.

, ,
, .

7.5.
(Reverse engineering) UML-

NetBeans 6.5 UML--
. ( 7_5_JavaLibrary_Figure),
, -
, Reverse Engineer... (. 7.28).
(. 7.29).
UML- Java, -
-Model. , Java -
UML-, .
OK UML- (. 7.30),
, .
Figure (. 7.31).
UML- UML-. -
, (. 7.32).
Circle Create Diagram From Selected Elements (-
), Class
294 7

Diagram Finish, ,
. 7.33.

. 7.28. UML-

Class Diagram 1 Circle


Class Diagram. , -
Rename
(), ( !) -
.
Projects Circle, Dot, Figure,
ScalableFigure ,
(. 7.34), Inheritance Class Diagram.
- Generate Dependency
Diagram ( ), ,
. -
, Dependencies
(). , Circle
CircleDependencies.
UML-. . 295

. 7.29. UML-

. 7.30. UML-, . 7.31. UML-,


Circle Figure
296 7

. 7.33.
. 7.32. Circle
UML-

. 7.34.



UML-. . 297

. -
, Circle
public Circle(java.awt.Graphics g, int x, int y, int r)

7_5_JavaLibrary_Figure Circle
Reverse Engineer..., -
Circle (. 7.35).

. 7.35. Circle

Circle,
, . 7.36.
Navigate to Source
, ,
.

. 7.36. Circle

, -
, . ,
, UML-.
Java,
298 7

(Forward Engineering)
Generate Code... .
, Java, -
UML. -
Reverse Engineer...
. -
Sync Diagram.
UML-
Open
Required Projects ( ) (. 7.37).

. 7.37.

UML-,
. -
Projects
Close 2 Projects.
UML-
,
UML- NetBeans 6.5 UML- -
. ,
. , , -
.

7.6.

.
?
UML-. . 299

.
, -
. , ,
, ,
. -
, , . -
, , . -
, -
,
.
07_6_refactoring1, Integrator,
Integrator
Refactor,
(. 7.38). Refactor
, -
. ( ,
-) , -
.

. 7.38.

:
Rename (, , ,
, );
Move ;
Copy ;
300 7

Safely Delete ;
Change Method Parameters ;
Encapsulate Fields (
-
).
, , :
Pull Up ;
Push Down ;
Extract Interface ( , -
). -
9;
Extract Superclass (
,
);
Use Supertype Where Possible , , -
( -
);
Move Inner to Outer Level
( 12);
Convert Anonymous to Member
( 12).
,
:
Introduce Variable ( );
Introduce Constant ;
Introduce Field ( );
Introduce Method .
, , :
Undo [ ] , -
( ).
;
Redo [ ] , -
, Undo. -
.
, NetBeans -
. . [10].
, ,
( ),
. .
UML-. . 301




05_8_effectiveCalc. ,
07_6_refactoring1.
NetBeans (, , ,
, ), . -
, ApplicationCalc ExampleCalc.
, Projects Navigator.
Refactor/Rename...,
Preview Refactor (. 7.39).

. 7.39. . 2

New Name ApplicationCalc ExampleCalc


Preview ( ) -
, Output
(), Refactoring.
,
(. 7.40), -
, (. 7.40,
. 7.41). , -
.

. 7.40. . 3.

: -
Refactoring Do Refactoring,
Output .
302 7

. 7.41. .

.

, , -
.
-
.
, (
).
-
( occurrence).
Do Refactoring ( ) -
. -
Refactor 2 , -
, , .
, -
. -
.

, , -
, , ( -
NetBeans ,
).
, -
(, Undo). -
( Undo Edit/Undo),

Refactor/Undo.
.
Redo
.
NetBeans 6.5 - -
.
UML-. . 303

-
, <Enter>
, .


, . -
Projects , , -
. , , -
.
, . ,
. , -
, .
, -
, . -
, , -
.
. -
,
.
, ,
Refactor/Move (
NetBeans, , ).



Copy -
. , ApplicationCalc ( 07.6_refactoring) -
(Fnc, Fnc1, Fnc1_x, FncSin . .), . -
, , -
Refactor/Copy.
(. 7.42).

. 7.42.
304 7

-
1 . , .
, .



Fnc1,
. Refactor/Safely Delete ( / -
) , ,
, .
.


- -
FncSin1 f1 (
f) - -
(. 7.43). f , . . -
f .

. 7.43.

,
(-, Java -
. ,
).
.
, Add ,
Remove ,
. , Remove,
UML-. . 305

, Add,
, . -
Object null,
, . MoveUp MoveDown
.


, -
. .
-
public , -
. -
.
, Integrator ,
, ,
(. 7.44).

. 7.44. , ,

private, -
( , accessors, .
access ) public. .
Use Accessors Even When Field Is Accessible (
), ,
( ) , -
. , private-
, . . - -
306 7

. -
,
.
, -
Java, [10]. , -
NetBeans
[10] .


UML-.
(Forward Engineering)
UML-.
(Reverse Engineering) -
UML- .
UML-, Java-, ,
Java, UML, .

. :
Rename (, , -
, , );
Move ;
Copy ;
Safely Delete ;
Change Method Parameters ;
Encapsulate Fields .
, (-
) ().


" ",
<default package>.
.
, -
UML- UML-. ,
.
Preview -
Refactoring Do Refactoring, Output
. , .
, Undo Redo
Refactor, Undo Redo.
UML-. . 307

07_4_3_UML_Figures.
UML- Java- .
07_5_JavaLibrary_Figure/07_5_JavaLibrary_Figure-Model
MyFigures, figures.
figures.
Reverse Engineering UML- -
figures.
8

8.1.
(array) , -
. , a1, a1[i]
, i.
Java ,
. -
, ,
Java. () -
, , .
.
, ,
.
,
.
, :
int[] a1;

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

:
int[] a1=new int[10];

Java .
,
. ,
null.
309

, (. .
0, 1 . .). n,
n1. C
C++, Java , -
.
length,
, . . -
.
:
int[] a=new int[100];
for(int i=0;i<a.length;i++){
a[i]=i+1;
}

, ,
,
a1=new int[20];

-, ,
.

.
, :
int[] a2;

null ( " ") (. 8.1).

. 8.1. ( )

a2=a1;

, a1 a2
, (. 8.2), . .
, -
,
, -
.
310 8

. 8.2. ( )

. -
,
. , Circle
() x, y r, show() hide(), circles
10 , , ,
8.1.

8.1. 10

int n=10;
Circle[] circles=new Circle[n];
for(int i=0;i<n;i++){
circles[i]=new Circle();
circles[i].x=40*i;
circles[i].y= circles[i].x/2;
circles[i].r=50;
circles[i].show();
}

-
, .
circle.
( ),
( 8.2).

8.2.

int n=10;
Circle[] circles=new Circle[n];
Circle circle;
for(int i=0;i<n;i++){
circle=new Circle();
circle.x=40*i;
circle.y= circle.x/2;
circle.r=50;
311

circle.show();
circles[i]= circle;
}

circle
, .
, -
. . , -
:
int[][] a=new int[10][20];

,
, 10 , 20 (. .
10 ,
20 ).
int[], int.
-
( 8.3).

8.3.

int m=10;//10
int n=20;//20
int[][] a=new int[m][n];
for(int i=0;i<m;i++){ //
for(int j=0;j<n;j++){ //
a[i][j]=(int)(100*Math.random());
System.out.print(a[i][j]+" ");
}
System.out.println();//
//
}

,
. , , -
3, .
-
, - . -
. Java, ,
,
- . "" -
. . -
, . . -
.

8.4.
312 8

8.4.

int n=9;
int[][] a=new int[n][];
for(int i=0;i<a.length;i++){ //
a[i]=new int[i+1]; // i+1
for(int j=0;j<a[i].length;j++){ //
a[i][j]=100*i+j;
System.out.print(a[i][j]+" ");
}
System.out.println();//
//
}

-
.
, . ,
:
int[] a=new int[4];
a[0]=2;
a[1]=0;
a[2]=0;
a[3]=6;

:
int[] a=new int[] {2,0,0,6};

-
.
(,
, ).
, .
, ,
:
a=new int[] {2,0,0,6};

-
, .
, 8.5 -
b, , . . int[6][4].

8.5.

int[][] b= new int[][]


{
{2,0,0,0}, // b[0]
{2,0,0,1}, // b[1]
{2,0,0,2}, // b[2]
313

{1,0,0,0}, // b[3]
{2,0,0,0}, // b[4]
{3,0,0,0}, // b[5]
};

, .
, -
, .
, 8.6 , -
.

8.6.

int[][] b= new int[][]


{
{2,0,0,0}, // b[0]
{2,0,0,1}, // b[1]
{2,0,0,2}, // b[2]
{1,0,0,0}, // b[3]
{2,0,0,0}, // b[4]
{3,0,0}, // b[5]
};

- clone(),
() :
a=new int[] {2,0,0,6};
int[] a1=a.clone();

,
int[] b=a;

b
-.
, System.arraycopy,
:
int[] b=new int[a.length+10];
System.arraycopy(a,index1a,b, index1b,count);

a b count , index1a a. -
b, index1b. b
. , b
(
. . 8.8).
Arrays.fill(,
). Arrays java.util.

Arrays.equals(a,a1).
314 8

, equals, Object
. , , -
, . a.equals(a1)
, a==a1. false, . . , -
a a1, , a1 a.
, Arrays.equals(a,a1) true.
( ) a
Arrays.sort(a) Arrays.sort(a,index1,index2).
, ( index1
index2). .
( ).
Arrays.deepEquals(a1,a2) a1
a2 ( , , -
).
JDK 6 :
Arrays.copyOf(_,_) -
. , ,
, (
);
copyOfRange(_,_,_)
- ,
1.
Arrays.toString() -
, . ,
.toString() , -
(. . 8.4).
Arrays asList ,
binarySearch -
.

8.2. , ,
Java (Collections) ""
,
.
java.util.AbstractCollection (
AbstractCollection ,
Collection).
( , . -
9) :
Set, SortedSet; HashSet, TreeSet, EnumSet, LinkedHashSet -
( -
);
315

java.util.List; java.awt.List, ArrayList, LinkedList, Vector -


( , -
);
Map, SortedMap; HashMap, HashTable, ConcurrentHashMap, TreeMap,
EnumMap, Properties ( "-").
,
. . . -
(iterator).
(collection) , ,
:
Iterator iter = collection.iterator()

:
boolean hasNext() , ;
Object next() ;
void remove() , . . ,
next().
8.7
, .

8.7.

java.util.List components=
java.util.Arrays.asList(this.getComponents());

for (Iterator iter = components.iterator();iter.hasNext();) {


Object elem = (Object) iter.next();
javax.swing.JOptionPane.showMessageDialog(null,": "+
elem.toString());
}

. 8.1 .

8.1.

boolean add(Object obj) ( ).


true
( ). -

-

boolean addAll(Collection c)
. true
(. . -
)
316 8

8.1 ()


void clear()
. ,
-
,
boolean contains(Object obj) true ,
obj.
obj.equals(e)
e,
boolean containsAll(Collection c) true ,
c
boolean isEmpty() true ,
(. . )
Iterator iterator() , -

.
- ( -
). -
. -
-
next()

boolean remove(Object obj) -
obj.
. true ,
(. . -
)
boolean remove All(Collection c) c. -
true ,
(. . )
boolean retainAll(Collection c)
, c
int size()
Object[] toArray() , -
(. . )
T[] toArray(T[n] a) T,
, -
(. . -
).
n a, -
,
.
n, -
-
, -
, a

317

8.1 ()


String toString()
.
-
, ", "
( )

(Lists)
, ,
, , .
java.util.List Collection (
. 9)
:
list.get(i) list i;
list.indexOf(obj) obj list. 1,
;
list.listIterator() ListIterator,
Iterator;
list.listIterator(i) -
i;
list.remove(i) i;
list.set(i,obj) i obj;
list.subList(i1,i2) ,
i1 i2.
, List .
Collections:
Collections.addAll(c,e1,e2,...,eN) c
e1,e2,...,eN;
Collections.frequency(c,obj) obj -
c;
Collections.reverse(list) list
( );
Collections.sort(list) . -
e1.compareTo(e2) e1 e2.
, Collections .
Arrays :
Arrays.asList(a) T, -
T[] a. , -
, , .
318 8


equals. , , collection
obj, collection.contains(obj), equals.
Java ,
Hash ( " "). -

"" (, -
, ). -, " -
" . -
, -, hashCode().
. 6.8. - -
. , -
, , n ,
n/2 . n.
- ,
n. n .
Linked ( -
""), , ,
. Array -
. (List),
, -
( ). -
,
, (
).

8.3. .
for-each
Java ( JDK 5) for
(, , ). ,
for -
.
jTextArea1 -
, -
( 08_3_for_each, 8.8).

8.8. for

java.util.List components=
java.util.Arrays.asList(this.rootPane.getComponents());
for (java.util.Iterator iter = components.iterator();iter.hasNext();) {
Object elem = (Object) iter.next();
jTextArea1.setText(jTextArea1.getText()+"Component: "+
elem.toString()+"\n");
}
319

components -
GUI_application,
javax.swing.JFrame. for iter
- . -
iter.hasNext(), . . , -
( ). -
for ,
iter.next().
Java, JDK 5, for,
, JavaScript C#, for-each ( ). -
for ,
( ), -
( ), .
elem:components. : elem components.
8.8 8.9.

8.9. for-each

java.util.List components=
java.util.Arrays.asList(this.rootPane.getComponents());
for (Object elem:components) {
jTextArea1.setText(jTextArea1.getText()+"Component: "+
elem.toString()+"\n");
}

8.4. Java.
. String, StringBuffer
StringBuilder
String . String ,
( 0 2 109).
String ,
:
"A", "abcd", "abcd", " ", " ".

. -
-
.
. -
, "\n".
,
(JLabel,JButton .). JTextArea
.
320 8

, . ,

String s;


s="";
.
, ,
( s ), ,
. -
null, -,
.
. , s.length() , .
( s.length()) , s
null, NullPointerException
. . 8.8.
Java :
"A" ;
'A' ASCII- "A".
.
.
s1 s2 , -
s1+s2 , () ,
s1 s2.
, :
String s=" "+" ";

s " ".
"+=". s1 s2 s1+=s2
s1=s1+s2.
( ) String. -
String ,
,
.
, .
, .
==.
, 8.10
:
s1 s2

. . - .
321

8.10.

String s1=" String";


String s2="";
s2+=" String";
if(s1==s2)
System.out.println("s1 s2");
else
System.out.println("s1 s2");

equals .
s1==s2 s1.equals(s2), :
s1 s2.

, 8.11 -
:
s1 s2.

8.11.

String s1="";
String s2="";
if(s1==s2)
System.out.println("s1 s2");
else
System.out.println("s1 s2");

, Java

-. s2
String s2 = ""+"";

.

String s2 =new String("");

, , s2
String s2 = jTextArea1.getText();

, s1 s2.
, , -
, ,
.
String , -
-. -
.
:
s1, s2, charsetName subS String;
charArray char[];
322 8

byteArray byte[];
i, index count (, ) .
:
String() - .
s1=new String() s="" ( ,
"" ,
, String() ,
).
String(s1) -, -
s1.
String(charArray) -.
String(charArray,index,count) , , count
, , index.
IndexOutOfBoundsException . . 8.8.
String(stringBuffer) -
stringBuffer, StringBuffer, String.
StringBuffer .
String(stringBuilder) -
stringBuilder, StringBuilder, String.
StringBuilder .

String(byteArray) ()
- - . ,
(charset), -
(default) . -
-
.
-
.
String(byteArray,index,count) , ,
count , index. -
IndexOutOfBoundsException . . 8.8.
String(byteArray,charsetName) (-
) - - . ,
, -
charsetName. ,
"ISO-8859-1" ( 8- ), "UTF-8", "UTF-
16" ( Unicode) . -
, UnsupportedEncodingException . . 8.8.
String(byteArray,index,count,charsetName) , -
, , count ,
index. -
IndexOutOfBoundsException . . 8.8.
323

String .
:
String.valueOf() String,
.
.
String.valueOf(charArray, index, count) , -
, , count -
, , index.
String , . . ,
String. , -
.
:
s1.length() ( 16- Unicode, -
). ;
s1.isEmpty() true , , -
s1, . , false;
s1.intern() -,
.
, -, s1, -
, .

-.
:
s1.getBytes() byte[], -
- ;
s1.getBytes(charsetName) , (charset). , -
"ISO-8859-1", "UTF-8", "UTF-16" ( Unicode) .;
s1.toCharArray() , s1.
:
s1.toLowerCase() , s1
( ). -
, (locale);
s1.toUpperCase() , s1
( ). -
, (locale).
:
s1.equals(s2) true , s2 String -
( ) s1.
s1 s2 s2
, String, false;
324 8

StringBuffer StringBuilder (. )
false, s2 -
s1. StringBuffer StringBuilder -
contentEquals.

s1.equalsIgnoreCase(s2) ,
( );
s1.contentEquals(sb1) ,
s1 String sb1. sb1 ,
String, StringBuffer StringBuilder (. ), (-
) s1, true. -
false;
s1.startsWith(subS) true , s1 -
subs;
s1.startsWith(subs,index1) true , s1
index1 subs;
s1.endsWith(subS) true , s1 -
, subS;
s1.regionMatches(index1,s2,index2,count) , -
, s1 s2. index1
index2 , count . -
true, false.
index1, index2 count false;
s1.regionMatches(ignoreCase,index1,s2,index2,count) ,
ignoreCase. false, -
, (). true -
, . .
, .
:
s1.substring(index1) String ,
s1, index1.
IndexOutOfBoundsException .
. 8.8;
s1.substring(index1,index2) String , -
s1, index1 index2-1.
index2-index1. -
IndexOutOfBoundsException .
. 8.8;
s1.subSequence(index1,index2) , , -
CharSequence.
String,
StringBuffer StringBuilder (. ), -
.
325

:
s1.indexOf(subS) , s1 -
subS. , -1;
s1.indexOf(subS,i) , , i;
s1.lastIndexOf(subS) , s1
subS. , -
-1;
s1.lastIndexOf(subS,i) ,
i, .
:
s1.replaceFirst(oldSubS,newSubS) s1,
oldSubS
newSubS;
s1.replaceAll(oldSubS,newSubS) s1,
oldSubS
newSubS;
s1.trim() s1, -
.
:
s1.split(separator) String[],
s1 ,
separator. , separator, -
. -
;
s1.split(separator, i) , i
.
s1,
.
i = 0 , -
.
i < 0 ,
.
String,
. Object toString(), -
. ,
, . -
Object
( ), @, -
- (,
) . -
, , .
326 8

. ,
toString() -
. , -
( char) .
+ += , , ,
toString() . -
() .
char -
toString(), . .
.
char . ch1 char. ch1+""
String.
, . .

.

String s=1+2+3;

s=="6".

String s=" ="+1+2+3;

:
" =123".
, ,
.
:
" ="+1.
, . -
toString() .
:
" =1".
" =1" 2.
toString() .
:
" =12".
" =12" 3.
-

String s=1+2+" "+1+2;


327

, , :
"3 12"

String char . , -
, char , 'S'==83,
String s='S'+ "";

s "S", "83". - ,
'S' Character, -
toString() "S".

String s=0+'S'+ "";

s "83", 0+'S' int


83. 83+"" "83".
,
String s='S'+ "t"+"ring";

s "String".
String s='S'+'t'+ "ring";

s "199ring", . .
'S', 83, 't', 116. 199 -
"ring" "199ring".

, -
. ,
? : , .
, , -
. , -
:
Byte.parseByte()
Short.parseShort()
Integer.parseInt()
Long.parseLong()
Float.parseFloat()
Double.parseDouble()

, ,
Byte, Short, Character, Integer, Long, Float, Double:
valueOf()

:
Byte.valueOf()

. .
, Integer Long -
:
328 8

Integer.toBinaryString()
Integer.toHexString()
Long.toBinaryString()
Long.toHexString()

-
(Byte, Short, Integer, Long) decode:
Byte.decode()

. .
, String
Character:
s1.charAt(i) s1, i (
). IndexOutOfBoundsException
. . 8.8;
s1.indexOf() , s1 ;
s1.indexOf(,i) , i, s1
.
-1;
s1.lastIndexOf() , s1
;
s1.lastIndexOf(,i) ,
i, ;
Character.isDigit() , , -
;
Character.isLetter() , ,
;
Character.isLetterOrDigit() , , -
;
Character.isLowerCase() , ,
;
Character.isUpperCase() , ,
;
Character.isWhitespace() , ,
" " (, ,
. .).
-
, StringBuffer StringBuilder. -
, (
, , ).
, -
, String.
, 17, -
StringBuffer String -
329

30 -
4000 . ,
.
StringBuffer , -
(threads), , String StringBuilder, -
(. 10). StringBuilder, JDK 5,
, .
.
, String,
StringBuffer StringBuilder . StringBuffer StringBuilder
sb.append(s), sb (
StringBuffer StringBuilder) s.
sb.insert(index,s), , ,
index, s. StringBuffer StringBuilder String
toString() ( 8.12).

8.12. StringBuffer

StringBuffer sb=new StringBuffer();


sb.append(" StringBuffer");
sb.insert(0, " ");
System.out.println(sb);
String s=sb.toString();

, append insert -
.
String.valueOf() String,
append insert, , String.
- StringBuffer
StringBuffer(String str). , -
-
:
StringBuffer sb=new StringBuffer(" StringBuffer");

.
contentEquals.
s1.contentEquals(sb) true , s1
, sb.
( StringBuffer StringBuilder)
capacity ("") -
. , capacity length.
-
.
StringBuffer (
StringBuilder , , , -
).
330 8

:
StringBuffer() - StringBuffer
16 .
StringBuffer(capacity) , ,
capacity, int.
StringBuffer(s1) - StringBuffer c -
- String, s1.
StringBuffer(sb) - StringBuffer c -
sb, StringBuffer StringBuilder.
, ,
, - StringBuffer, String,
.
, String, StringBuffer StringBuilder -
.
, String.valueOf() String.valueOf(charArray,index, count),
.
StringBuffer StringBuilder ,
, String. -
, , String.
:
sb.length() ( 16- Unicode, -
). ;
isEmpty(), String, ,
sb.length()==0;
intern(), String, .
:
sb.getChars(index1,index2,charArray,index) char[], -
sb charArray. -
, index1, -
index2-1. ,
index. index2-index1,
charArray index+index2-index1-1.

IndexOutOfBoundsException . . 8.8;

sb.toString() StringBuffer
String;
getBytes(charsetName), String, .
:
toLowerCase() toUpperCase(), String, -
.
331

:
sb.equals(subS) , Object.
, , . . -
==.
-
s1.contentEquals(sb1). StringBuffer StringBuilder
contentEquals, , . -
;
s1.equalsIgnoreCase(s2) ;
startsWith endsWith ;
regionMatches .
:
sb.charAt(index) index;
sb.subSequence(index1,index2) ,
sb, index1 index2-1. -
index2-index1. -
IndexOutOfBoundsException (. . 8.8). -
CharSequence, String,
StringBuffer StringBuilder. -
String, StringBuffer
StringBuilder,
. substring (. )
String;
sb.substring(index1) String , -
sb, index1. -
StringIndexOutOfBoundsException
(. . 8.8);
sb.substring(index1,index2) String , -
sb, index1 index2-1.
index2-index1. -
StringIndexOutOfBoundsException
(. . 8.8).
:
sb.indexOf(subS) , sb -
subS, String. -
, -1;
sb.indexOf(subS,i) , i;
sb.lastIndexOf(subS) , sb
subS, String.
, -1;
sb.lastIndexOf(subS,i) ,
i, .
332 8

, , -
.
:
sb.replace(index1,index2,newSubS) sb
index1 index2-1 newSubS, String. -
sb ( , . .
sb). , , -
.
replaceAll, String;
replaceFirst ;
trim() .
:
split .
StringBuffer StringBuilder , -
String, ,
, String, ,
. (mutable)
,
(immutable) String. :
sb.append(v) v, -
.
String.valueOf(v),
;
sb.insert(index,v) index -
v,
. String.valueOf(v),
.
IndexOutOfBoundsException
(. . 8.8);
sb.insert(index,sb2,index1,index2) sb index
sb2, index1 index2-1. sb2
String, StringBuffer, StringBuilder ,
CharSequence. -
IndexOutOfBoundsException (. . 8.8);
sb.deleteCharAt(index) sb index.

StringIndexOutOfBoundsException(. . 8.8);
sb.setCharAt(index,) sb index
. -
IndexOutOfBoundsException . . 8.8;
sb.delete(index1,index2) sb index1
index2-1. -
StringIndexOutOfBoundsException . . 8.8;
333

sb.setLength() ;
sb.capacity() ;
sb.ensureCapacity(n) ( ), -
n, int. old_n -
, :
n 2*old_n+2. n , -
;
sb.trimToSize() sb -
;
sb.reverse() sb, . .
, . .
sb ( , . . sb).
.
String StringBuffer StringBuilder. -
, -
, String -
. -, intern()
(,
).
String
.
- String -
(. 17). -
StringBuffer StringBuilder,
, -
String.

8.5. - (enum)
, , ,
. -
, . .
- enum
( enumeration ), ,
. -
( -
1.2).
- -
, - . - .
,
( -
).
-:
.
334 8

,
( ).
0, 1 . . ordinal(),
. compareTo(), -
( -
).
name(). -
""
valueOf, .
, -
values() , -
.
:
.values()

- Months () Spring (), -


:
enum Months {jan, feb, mar, apr, may, jun, jul, aug, sept, oct, nov, dec}
enum Spring {march, apr, may }

, ,
, . -
Months Spring, .
"" , ,
, :
public Months m1 ,m2=Months.mar, m3;

( m1, m2 m3),
Spring spr1=Spring.apr, spr2;

( spr1 -
).
:
spr2=spr1;
spr1=Spring.may;
System.out.println(" ="+spr2.compareTo(Spring.march));

spr2 Spring.apr,
, Spring.march, . -
:
=1

spr2 Spring.may. ,
, spr2.ordinal(). -
2, . . may (
- , ).
335

, spr2,
spr2.name(). may -
.
"" ,
null.

System.out.println("spr2="+spr2);

spr2 , :
spr2=null

spr2.ordinal() spr2.name() -
( ) :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

Spring , i, -
:
spr1=Spring.values()[i];

Spring :
spr1=Spring.valueOf("march");

, Enum,
.
.

8.6. .
GregorianCalendar
System.currentTimeMillis(),
, 0 0 1 1970 .
Java
java.util.Time java.util.Date. -
(deprecated), -
. , Time Date -
, java.util.GregorianCalendar.
GregorianCalendar() ,
, , -
. , -
. clear(), ,
.
GregorianCalendar get(),
, ,
. , -
:
336 8

ERA . get
AD==1 ( Anno Domini ) BC==0 ( Before
Christ ). AC.
YEAR . 1970.
MONTH . JANUARY DECEMBER (. . 0 11).
JANUARY==0.
DAY_OF_MONTH . 1 31. -
1.
DAY_OF_WEEK . SUNDAY SATURDAY. -
SUNDAY==1.
WEEK_OF_MONTH . 0 6.
0. -
, 7 .
DAY_OF_WEEK_IN_MONTH (, -
, . .) . , . -
,
.
1.
AM_PM . AM (
Ante Meridiem ) PM ( Post Meridiem )
int. AM.
HOUR 12- -
. 0 11.
HOUR_OF_DAY 24-
. 0 23.
MINUTE . 0
59.
SECOND . 0
59.
MILLISECOND . -
0 999.
-
:
set(int year, int dayOfMonth, int date)
set(int year, int month, int dayOfMonth, int hourOfDay, int minute)
set(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second)
setTimeInMillis(long millis).

setFirstDayOfWeek(int value) ,
. (GregorianCalendar.SUNDAY), .
(GregorianCalendar.MONDAY),
calendar.setFirstDayOfWeek(GregorianCalendar.MONDAY);
337

, ,
calendar.get(DAY_OF_WEEK), calendar.getFirstDayOfWeek().
.
,
GUI_application ( 8.13) 08_6_DateTime
DVD.

8.13. ,

package javaapplication;
import java.util.GregorianCalendar;
import static java.util.GregorianCalendar.*;

public class GUI_application extends javax.swing.JFrame {

enum WeekDays {
,
,
,
,
,
,
;
}

public static void main(String[] args) {


GregorianCalendar calendar = new GregorianCalendar();
//calendar.setTime(new Date());
System.out.println(" "+calendar.get(ERA));
System.out.println(" "+calendar.get(YEAR));
System.out.println(" "+calendar.get(MONTH));
System.out.println(" "+
calendar.get(DAY_OF_WEEK));
calendar.setFirstDayOfWeek(MONDAY);
System.out.println(" : " +
calendar.get(DAY_OF_WEEK));
System.out.println(" "+
calendar.get(DAY_OF_MONTH));
System.out.println(" "+
calendar.get(DAY_OF_YEAR));
System.out.println(" "+calendar.get(HOUR));
System.out.println(" "+calendar.get(MINUTE));

System.out.println(" " +
calendar.getDisplayName(DAY_OF_WEEK,LONG,
new java.util.Locale("RU")));
System.out.println(" " +
calendar.getDisplayName(DAY_OF_WEEK,LONG,java.util.Locale.US));
338 8

WeekDays w=WeekDays.values()[calendar.get(DAY_OF_WEEK)-1];
System.out.println(" "+w);
String s=w.name();
System.out.println(" "+s);
}
}

.
-, , ,
calendar.get(GregorianCalendar.ERA), calendar.get(GregorianCalendar.YEAR) . ., -
GregorianCalendar ( ).
-,
:
getDisplayName (-
LONG ) ( SHORT) -
(locale). -
,
: Locale.US , Locale.FR , Locale.CHINA
. .
-
.
, 1 7,
0 6. 8.11 -
, ( name())
.
,
java.util.Timer. (. 10).

8.7.

-

, , -
, . ,
; , ;
. .
, , -
. , -
, -.
.
. , -
, ,
339

.
, .
, - ,
.
, , -
, / , -
.
-, , -
, .
-, .
- .
,
. -
- -
,
. ,
.


java.awt.Graphics.
, . 8.2.
, :
w ;
h ;
x, y (
, ).

8.2. ,



Color getColor()
setColor(Color c)
Font getFont()

setFont(Font f)
.
-
Font(,,)

FontMetrics getFontMetrics()

FontMetrics getFontMetrics(Font f) f
340 8

8.2 ()


setXORMode(Color c1) XOR (
) c1. color
, color ^ c1
(. . color XOR c1) RGB-
.
-

setPaintMode()
XOR

translate(x0,y0)
x0,y0. ,
,


drawLine(x1,y1,x2,y2) x1,y1
x2,y2
drawRect(x,y,w,h)

drawRoundRect(x,y,w,h,arcWidth,
arcHeight)

draw3DRect(x,y,w,h,isRaised) .
isRaised ==true, (raised),

drawPolygon(Polygon p); (nPoints
drawPolygon(int[] xPoints, int[] )
yPoints, int nPoints)

drawPolyline(int[] xPoints, int[]


yPoints, int nPoints) (nPoints )
drawOval(x,y,w,h)

drawArc(x,y,w,h,startAngle, . startAngle
arcAngle) , arcAngle, -

drawImage(Image img,int x,
int y, ImageObserver observer)


clearRect(x,y,w,h) ( )

fillRect(x,y,w,h) ,

fillRoundRect(x,y,w,h,arcWidth, ,
arcHeight)
341

8.2 ()

fill3DRect(x,y,w,h, isRaised) ,
. isRaised
true, (raised),

fillPolygon(Polygon p) ,
fillPolygon(int[] xPoints, int[]
yPoints, int nPoints)

fillOval(x,y,w,h) ,

fillArc(x,y,w,h,startAngle, ,
arcAngle) . , -

copyArea(x,y,w,h,dx,dy) , -
dx,dy


drawString(s,x,y) s
drawChars(char[] data,int offset,int
length,int x,int y)

drawBytes(byte[] data,int offset,int , -


length,int x,int y)


setClip(x,y,w,h) .
setClip(Shape clip) -
( )

clipRect(x,y,w,h)

Rectangle getClipBounds() ,
Rectangle getClipBounds(Rectangle r)

Graphics create() g1=g.create()


g

dispose()

( , )

,
8.14 ( 08_7_Graphics1 DVD) -
. ,
.
342 8

8.14. JPanel

java.awt.Graphics g,g1;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
java.awt.Graphics g,g1;
g=jPanel1.getGraphics();
int x1=20,x2=120,y1=20,y2=120;
int x3=20,y3=20,w3=60,h3=80;
int x4=30,y4=60,w4=30,h4=40;
int x0=10,y0=10,w0=10,h0=10;
int w1=80,h1=120;
g.setClip(0,0,60,80);//
g.drawLine(x1,y1,x2,y2);//
g.drawOval(x3,y3,w3,h3);//
g.clipRect(x4,y4,20,20);//
g.clearRect(x4,y4,w4,h4);//
g.setClip(0,0,200,280); //
g.copyArea(x1,y1,w1,h1,60,0);
g.draw3DRect(10,20,w1,h1,false);
g.drawPolygon(new java.awt.Polygon(new int[]{10,10,20,40},
new int[]{10,20,30,60},4) );
}

: -
. -
, -
.
, -
paint, .
, 8.15.

8.15. paint

public void paint(java.awt.Graphics g){


super.paint(g);
g=jPanel1.getGraphics();
...
}

, ,
:
private void jPanel1ComponentResized(java.awt.event.ComponentEvent evt) {
...
}

, ,
-
. -
343

. -
.
, - -
. -
-
, . -
:
update(Graphics g).

:
for(int i=0;i<=100;i++){
FiguresUtil.moveFigureBy(figure,dx,dy);
update(g);
}

-
. -
, .
-
, -
. , , .
Swing (, JPanel) -
, doubleBuffered true.
- ,
, - -
paint() ( 08_7_Graphics2
DVD).
8.16 -.

8.16. JPanel

package examples;

import java.awt.Graphics;
public class JPanelVM extends javax.swing.JPanel {

public JPanelVM(java.awt.LayoutManager layout, boolean isDoubleBuffered) {


super(layout, isDoubleBuffered);
}

public JPanelVM(boolean isDoubleBuffered) {


this(null, isDoubleBuffered);
}

public JPanelVM() {
this(true);
}
344 8

@Override
public void paint(Graphics g) {
super.paint(g);
int x1 = 20, x2 = 120, y1 = 20, y2 = 120;
int x3 = 20, y3 = 20, w3 = 60, h3 = 80;
int x4 = 30, y4 = 60, w4 = 30, h4 = 40;
int x0 = 10, y0 = 10, w0 = 10, h0 = 10;
int w1 = 80, h1 = 120;
g.setClip(0, 0, 60, 80);//
g.drawLine(x1, y1, x2, y2);//
g.drawOval(x3, y3, w3, h3);//
g.clipRect(x4, y4, 20, 20);//
g.clearRect(x4, y4, w4, h4);//
g.setClip(0, 0, 200, 280); //
g.copyArea(x1, y1, w1, h1, 60, 0);
g.draw3DRect(10, 20, w1, h1, false);
g.drawPolygon(new java.awt.Polygon(new int[]{10, 10, 20, 40},
new int[]{10, 20, 30, 60}, 4));
}
}

, -
paint().
. : -
- , -
.
. JButton -
jButton1 ( 8.17).

8.17.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {


btn1 = new javax.swing.JButton();
btn1.setBounds(200, 20, 300, 30);
getContentPane().add(btn1);
btn1.setText(" ");
}

-, setBounds(200,
20, 300, 30) (x=200, y=20) -
( width=300, height=30). add (-
) ,
getContentPane().
, ,
.
, -
. -
, 8.18.
345

8.18. update

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {


btn1 = new javax.swing.JButton();
btn1.setBounds(200, 50, 300, 30);
btn1.setText(" ");
getContentPane().add(btn1);
btn1.update(btn1.getGraphics());
}

update . -
JButton, JPanel -
JPanelVM, JPanel, -
.
-
. , JPanelVM
, Tools/Add to Palette...,
Beans OK. JPanelVM
Beans,
.
. -
. , paint() -
, .
, .
false,
. true, -
paint() .

8.8.


( ).
(exceptions), : 0, -
, -
(, ) . -
(),
( , -
).


. , -
, , ,
- .
Java, , -
. -
346 8

try (),
catch,
finally.
, -
. throw (). -
" -
".
8.19 -
.

8.19.

try{
0;
}
catch (1 1){
1;
}
catch (2 2){
2;
}
catch (N N){
N;
}
finally{
;
}

, try-catch-finally -
( , ),
.
, 0 try
, finally.
try, -
, catch ().
catch ,
, . -
e ( exception). , -
, ,
catch .
, , catch
finally. -
. -
finally .
finally , try...finally,
try catch break, continue
347

return, . . , .
finally -
.
System.exit(n) try
finally.
8.20 .

8.20.

void myETest(String s,double y){


double x, z=0;
int i;
try{
x=Double.parseDouble(s);
z=Math.sqrt(y/x);
i=10/(int)x;
System.out.println("x="+x+" z="+z+" i="+i);
} catch(ArithmeticException e){
System.out.println(": ");
} catch(NumberFormatException e){
System.out.println(" !");
}
System.out.println(" z="+z);
}

myETest("5",5.0) -
:
x=5.0 z=1.0 i=2
z=1.0

myETest("0",5.0) ArithmeticException
,
catch.
:
:
z=Infinity

y/x x=0.0 -
. ,
System.out.println("x="+x+" z="+z+" i="+i) - -

.
y/x , , . . -
Java NaN. , -
,
myETest("-5",5.0)
348 8

:
x=-5.0 z=NaN i=-2
z=NaN

s Double, -

NumberFormatException. catch.
:
!
z=0.0

, "" myETest
,
System.out.println(" z="+z).


Java . -
Throwable ( throw able -
). Throwable Error () Exception (). -
Error , -
catch. -
, .
Exception -
, RuntimeException ( ). -
" ".
RuntimeException, Error, -
, , ,
throws ( ). , -
Error, RuntimeException -
Java- (JVM).
(-
ArithmeticException
java.lang, IOException java.io . .),
Exception .
Java - , "Exception" (-
) "Error" () .
java.lang ( ,
, -
).
Throwable.

.
349

:
Exception ,
JVM ( - RuntimeException):
ClassNotFoundException ;
CloneNotSupportedException ;
IllegalAccessException reflection;
InstantiationException ;
InterruptedException ;
NoSuchFieldException ;
NoSuchMethodException ;
RuntimeException
, -
JVM:
ArithmeticException ( 0);
ArrayStoreException -
;
ClassCastException ;
EnumConstantNotPresentException ;
IllegalArgumentException :
IllegalThreadStateException , -
;
NumberFormatException ;
IllegalMonitorStateException
( wait, notify, notifyAll);
IllegalStateException JVM ;
IndexOutOfBoundsException , -
:
ArrayIndexOutOfBoundsException ;
StringIndexOutOfBoundsException ;
NegativeArraySizeException ;
NullPointerException null;
SecurityException ;
TypeNotPresentException ;
UnsupportedOperationException ;
Error :
AssertionError ,
(assertion) ;
350 8

LinkageError , :
ClassCircularityError;
ClassFormatError;
UnsupportedClassVersionError;
ExceptionInInitializerError;
IncompatibleClassChangeError:
IllegalAccessError;
InstantiationError;
NoSuchFieldError;
NoSuchMethodError;
NoClassDefFoundError;
UnsatisfiedLinkError;
VerifyError;
VirtualMachineError JVM :
InternalError JVM;
OutOfMemoryError JVM ;
StackOverflowError - -
;
UnknownError JVM , -
.
- -
. -
catch :
-, -
.
(. 8.20) NumberFormatException
Exception, . . , NumberFormatException,
.
8.21 , .

8.21.

void myETest(String s,double y){


double x, z=0;
int i;
try{
x=Double.parseDouble(s);
z=Math.sqrt(y/x);
i=10/(int)x;
System.out.println("x="+x+" z="+z+" i="+i);
} catch(ArithmeticException e){
System.out.println(": ");
351

} catch(Exception e){
System.out.println(" !");
}
System.out.println(" z="+z);
}

-
catch, Exception
NumberFormatException .
8.22 .

8.22.

void myETest(String s,double y){


double x, z=0;
int i;
try{
x=Double.parseDouble(s);
z=Math.sqrt(y/x);
i=10/(int)x;
System.out.println("x="+x+" z="+z+" i="+i);
} catch(Exception e){
System.out.println(" !");
} catch(ArithmeticException e){
System.out.println(": ");
}
System.out.println(" z="+z);
}

NetBeans
:
exception java.lang.NumberFormatException has already been caught
( java.lang.NumberFormatException ),
.


throw
,
, - -
.
, , -
:
class WrongPasswordException extends Exception {
WrongPasswordException(){ //
System.out.println("Wrong password!");
}
}
352 8

-
, ,
.
-
throw, -:
throw new ();

:
throw new WrongPasswordException();

-
e, :
throw e;

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

. , -
. ,
. .
, .
, -
. ,
, ,
.

, , -
. ,
.

WrongPasswordException ,
.

,
.
throws
,
, :
( )
throws 1, 2,..., N
353

{

}

, -
:
( )
throws 1, 2,..., N
{

}

throws " " ( ).


,
, . -
, throws .
, -
, ,
-
. -
, - catch
(), .
,
catch(ArithmeticException e)?

s="0" -
. , 8.23.

8.23. ,

void myETest1(String s,double y) throws ArithmeticException {


double x, z=0;
int i;
try{
x=Double.parseDouble(s);
z=Math.sqrt(y/x);
i=10/(int)x;
System.out.println("x="+x+" z="+z+" i="+i);
} catch(NumberFormatException e){
System.out.println(" ! ");
}
System.out.println(" z="+z);
}

:
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {
myETest1(jTextField1.getText(),5.0);
}
354 8

myETest1("0",5.0),
ArithmeticException,
-
GUI_application
jButton9 ( 8.24).

8.24.

Exception in thread "AWT-EventQueue-0" java.lang.ArithmeticException: / by zero


at java_gui_example.GUI_application.myETest1(GUI_application.java:273)
at java_gui_example.GUI_application.jButton9ActionPerformed(GUI_application.java:244)
at java_gui_example.GUI_application.access$900(GUI_application.java:17)
at java_gui_example.GUI_application$10.actionPerformed(GUI_application.java:131)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java: 2169)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel. java:420)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(
BasicButtonListener.java:234)
at java.awt.Component.processMouseEvent(Component.java:5488)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3126)
at java.awt.Component.processEvent(Component.java:5253)
at java.awt.Container.processEvent(Container.java:1966)
at java.awt.Component.dispatchEventImpl(Component.java:3955)
at java.awt.Container.dispatchEventImpl(Container.java:2024)
at java.awt.Component.dispatchEvent(Component.java:3803)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
at java.awt.Container.dispatchEventImpl(Container.java:2010)
at java.awt.Window.dispatchEventImpl(Window.java:1774)
at java.awt.Component.dispatchEvent(Component.java:3803)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread. java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

, throw, -
. - ,
-
. , throw
catch.
, -
, - , -

. , -
355

. -
.
( , ) 8.25.

8.25.

class CheckPasswordDemo{
private String password="";

public String getPassword(){


return password;
}

public void setPassword(){


...//
}

public void checkPassword(String pass)


throws WrongPasswordException {
if(!pass.equals(password))
throw new WrongPasswordException();
}
}
}

checkPassword , -
, . ,
pass!=password true, . . -
(. . == ,
).
, : -
!
else if!
,
. ,

-
.

8.9.
Java :
File.
(
, ,
);
356 8

/.
, , -
/.


File
File ,
. , -
.
File , :
File( )
File( )
File( , ).
()
, () . . 8.3
, File. () -
.
Windows \ , ,
\\.

8.3. , File



String pathSeparator
. "/" UNIX- "\" Windows
char pathSeparatorChar .
'/' UNIX- '\' Windows
String separator

char separatorChar -


boolean exists() true, ( ) -
, false
long length() , -
-
, 0L
boolean canRead() true, ( ) -
,
false. ( UNIX- , -
.) SecurityException
boolean setReadOnly() true , ( )
,
" ", false
357

8.3 ()


boolean canWrite() true, ( ) -
,
false. ( , -
.) SecurityException
boolean isDirectory() true ,
,
false
boolean isFile() true, -
, false
boolean isHidden() true, -
, false.
UNIX- ,
, Windows ,
hidden ()
long lastModified() ,
, 0L. -
, 0 1
1970 ( )
Boolean . -
setLastModified( true, , -
long time) false. , -
0 1 1970 ( )
()
String getName()
String getParent() , . . ,
( ), -

String getAbsolutePath() ,
. -
,

String getCanonicalPath() ,
. -
,

. -
IOException, -

int compareTo(File f) (),
f. 0 ,
() , -
, -
. -
UNIX-
, Windows . -
(
)
358 8

8.3 ()

boolean isAbsolute() true ,


() .
,
. .
boolean equals(Object obj) true ,
obj ()
( ,
).
( )
//

Boolean createNewFile() ,
.
true, false. IOException,
(, )
File createTempFile( . ( -
String prefix, ), prefix+suffix -
String suffix) , .
File createTempFile( .
String prefix, . IOException,
String suffix, (, )
File folder)
boolean mkdir() ,
. true -
false
boolean mkdirs() ,
,
, , . -
true false

boolean delete() ,
. true
false
boolean renameTo(File dest)
, , -
, dest. true
false

File getAbsoluteFile() , -

File getCanonicalFile() , -
.
IOException,
File getParentFile() , -


359

8.3 ()



String[] list() () ,
. ,
String[] list( , .
FilenameFilter filter) , null.
, -

File[] listFiles() ,
, ,
File[] listFiles( . , -
FilenameFilter filter) , .
, null.

,
File[] listRoots() ,
. UNIX
"/", Windows -

8.26 .

8.26.

File f1=new File(".."); // ". ", "/ ", "C:/../ "


System.out.println("getAbsolutePath():"+f1.getAbsolutePath());

try{
System.out.println("getCanonicalPath():"+f1.getCanonicalPath());
}
catch(Exception e){
System.out.println(" getCanonicalPath()");
}

System.out.println("exists():"+f1.exists());
System.out.println("canRead():"+f1.canRead());
System.out.println("canWrite(): "+f1.canWrite());



-
. 08_9_1_File (
)
Swing JLabel (). .
, .
360 8

, -
openMenuItem () [JFrame]/menuBar[JMenu]/
fileMenu [JMenu]/openMenuItem[JMenuItem].
openMenuItem
openMenuItemActionPerformed .
JFileChooser, -
.

package examples;

:
import javax.swing.*;, ,
javax.swing.
, , -
. GUI_application fileChooser:
javax.swing.JFileChooser fileChooser = new javax.swing.JFileChooser();

( 8.27).

8.27.

private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {


if(fileChooser.showOpenDialog(null)!= fileChooser.APPROVE_OPTION){
System.out.println(" ");
return;
}
System.out.println(" Open");
jLabel1.setText(fileChooser.getSelectedFile().getName());
jLabel2.setText(fileChooser.getSelectedFile().getParent());
}

: fileChooser.showOpenDialog(openMenuItem).
. -
openMenuItem.
APPROVE_OPTION ,
Open () .
-
return , .
, 8.28.

8.28.

if(fileChooser.showOpenDialog(openMenuItem)==
fileChooser.APPROVE_OPTION){
System.out.println(" Open");
jLabel1.setText(fileChooser.getSelectedFile().getName());
361

jLabel2.setText(fileChooser.getSelectedFile().getParent());
}
else
System.out.println(" ");

. -
, , -
, , , .
-
if. . if
, -
.
:
javax.swing.JFileChooser fileChooser = new javax.swing.JFileChooser()

.

/ -. -
. ,
.
, . ,
, -
.
, -
:
File folder=...;
fileChooser.setCurrentDirectory(folder);

showSaveDialog.
,
.
. , JFileChooser
-
.
8.29 -
.

8.29.

package example;

import java.io.*;

public class SimpleFileFilter extends javax.swing.filechooser.FileFilter{


String ext;
362 8

SimpleFileFilter(String ext){
this.ext=ext;
}

public boolean accept(File f){


if(f == null)
return false;
if(f.isDirectory()){
return true ;
}
else
return (f.getName().endsWith(ext));
}
}

/**
* ,
* @see FileView#getName
*/
public String getDescription(){
return "Text files (.txt)";
}

:
:
javax.swing.filechooser.FileFilter fileFilter = new
SimpleFileFilter(".txt");

:
fileChooser.addChoosableFileFilter(fileFilter);

(-
) . , -
.
08_9_2_File, DVD,
.
. -
, ,
, , . .
:
fileChooser.setFileFilter(fileFilter);

-
showCustomDialog -
.
. -
:
fileChooser.setMultiSelectionEnabled(true);
363

8.30
.

8.30.

java.io.File[] files = fileChooser.getSelectedFiles();


if (files != null && files.length > 0) {
String filenames = "";
for (int i=0; i<files.length; i++) {
filenames = filenames + "\n" + files[i].getPath();
}
}

, . , -
:
fileChooser.setFileSelectionMode(fileChooser.DIRECTORIES_ONLY);

, :
fileChooser.setFileSelectionMode(fileChooser.FILES_AND_DIRECTORIES);

:
fileChooser.setFileSelectionMode(fileChooser.FILES_ONLY);

, -
File folder, :
String[] filenames= folder.list(filter);

.
filter, , java.io.FilenameFilter.
, , 9.
8.31 SimpleFilenameFilter.

8.31.

package example;
import java.io.*;
public class SimpleFilenameFilter implements FilenameFilter{
String ext;
public SimpleFilenameFilter(String ext) {
this.ext=ext;
}

public boolean accept(File dir,String fileName){


return ext==""||fileName.endsWith(ext);
}
}

8.32 , -
, jTextArea1 ( ) JTextArea, -
.
364 8

8.32. ,

String[] filenamesArray;
File folder=fileChooser.getSelectedFile();
SimpleFilenameFilter filter=new SimpleFilenameFilter("");
String filenames = "";
if(folder.isDirectory()){
filenamesArray=folder.list(filter);
for (int i=0; i<filenamesArray.length; i++) {
filenames = filenames + "\n" + filenamesArray[i];
}
jTextArea1.setText(filenames);
}

"",
/ 8.33.

8.33. ,

java.io.File[] files = fileChooser.getSelectedFiles();


if (files != null && files.length > 0) {
String filenames = "";
for (int i=0; i<files.length; i++) {
filenames = filenames + "\n" + files[i].getPath();
}
jTextArea1.setText(filenames);
}

08_9_3_File
DVD.

/
Java, (
, String StringBuffer, . .),
. -
( ) -
(Streams).
,
- . ,
. "
".
(, , ),
( ).
. , -
, . -
, , ,
. -
365

.
. -
, -
.
,
.
/,
() - ,
, ( -
).
InputStream ( ) -
, .
. 8.4.

8.4. InputStream


int available() ,

int read() -
, 0 255.
1
int read(byte[] b) b.length b. -
int read(byte[] b, int .
offset, int count) 1

long skip(long count) () count (


count 0, ). -

boolean markSupported() true , mark
reset, false
void mark(int limit) .
reset,
.
(. markSupported)
void reset() -
,
(. . -
).
-
IOException. (.
markSupported mark)
void close() . -
IOException

InputStream, markSupported mark,


IOException ( ).
366 8

OutputStream ( ) , -
.
. 8.5.

8.5. OutputStream


void write(int b) . int
-
byte. , -
int
void write(byte[] b) . offset
void write(byte[] b, int count, , count ,
offset, int count) offset
void flush() . -
, -
-
write, .
, (
) , -
,
write, , -
flush
void close() . -
IOException

IOException .
, InputStream OutputStream,
-.
InputStream/OutputStream.
( ) java.io.Reader
() ( , FileReader).
- java.io.Writer () ( ,
FileWriter).
,
InputStream/OutputStream Reader/Writer.
RandomAccessFile ( ), -
.
RandomAccessFile , .
RandomAccessFile , -
.
,
.
(), .
,
.
367

RandomAccessFile . 8.6.

8.6. RandomAccessFile



long getFilePointer() -
/ . -

long length() ( )
void setLength(long newLength)
newLength. newLength ,
.
,
,
.
newLength ,
,

void close() .
IOException

void seek(long pos) pos
int skipBytes(int n) n . -
/ n ( n>0,
, n0, ).
( -
n, , - -
)

int read()
, 0 255.
1
int read(byte[] b) b.length b.
.
-
1
int read(byte[] b, int offset, count b, -
int count) offset. -
.
1
void readFully(byte[] b) b.length ,
,
b

void readFully(byte[] b, count , -


int offset, int count) , offset
368 8

8.6 ()


void write(int b) b ( , writeByte(b))

void write(byte[] b) b (. . b.length


)

void write(byte[] b, int count b,


offset, int count) , offset


boolean readBoolean() boolean

byte readByte() byte

short readShort() short

int readInt() int

long readLong() long

int readUnsignedByte() (
Java) int

int readUnsignedShort() (
Java) int

char readChar() char

float readFloat() float

double readDouble() double


void writeBoolean(boolean v) boolean
void writeByte(int v) byte.
int
byte
void writeShort(int v) short. -
int -
short
void writeInt(int v) int
void writeLong(long v) long
void writeChar(int v) char.
int -
char
void writeFloat(float v) float
void writeDouble(double v) double
369

8.6 ()


String readLine()

( \n)
.
Unicode , . .
. -
, ANSI
String readUTF UTF-8
.
UTF-8 -


void writeBytes(String s) s ,
. -
, . .
Unicode (-
). -
ANSI (. writeChars,
)
void writeChars(String s) s ,
.
Unicode
void writeUTF(String s) s ,
UTF-8

, RandomAccessFile ( getChannel()), -
IOException ( -
).
: -
, .
:
"r" read ( );
"rw" read and write ( );
"rws" read and write synchronously ( -
) ( . 10);
"rwd" read and write to device (
).
:
java.io.RandomAccessFile rf1=new java.io.RandomAccessFile("q.txt","r");
java.io.RandomAccessFile rf2=new java.io.RandomAccessFile(file,"rw");
370 8

, .
8.34 .

8.34.

File file;
javax.swing.JFileChooser fileChooser=new javax.swing.JFileChooser();
javax.swing.filechooser.FileFilter fileFilter=
new SimpleFileFilter(".txt");

private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {


fileChooser.addChoosableFileFilter(fileFilter);
if(fileChooser.showOpenDialog(null)!=fileChooser.APPROVE_OPTION){
return;// Cancel
}
file = fileChooser.getSelectedFile();
try{
InputStream fileInpStream=new FileInputStream(file);
int size=fileInpStream.available();
fileInpStream.close();
char[] buff=new char[size];
Reader fileReadStream=new FileReader(file);
int count=fileReadStream.read(buff);
jTextArea1.setText(String.copyValueOf(buff));
javax.swing.JOptionPane.showMessageDialog(null,
" "+ count+" ");

fileReadStream.close();
} catch(Exception e){
javax.swing.JOptionPane.showMessageDialog(null,
" \n"+file.getAbsolutePath());
}

fileInpStream,
FileInputStream, InputStream.

,
FileInputStream .
:
fileInpStream=new FileInputStream(file);

fileInpStream.available() ,
. fileInpStream -
. FileReader available(),
FileInputStream.
buff , .
,
, ,
371

, . ,
. .
available()
FileInputStream.

Reader fileReadStream=new FileReader(file);

Reader, FileReader, ,
InputStream, FileInputStream.
, -
ANSI. -
readUTF writeUTF RandomAccessFile
.
, try -
8.35.

8.35.

FileReader filReadStream=new FileReader(file);


BufferedReader bufferedIn=new BufferedReader(filReadStream);
String s="",tmpS="";
while((tmpS=bufferedIn.readLine())!=null)
s+=tmpS+"\n";
jTextArea1.setText(s);
bufferedIn.close();

, , . .
( 8.36).

8.36.

private void saveAsMenuItemActionPerformed(


java.awt.event.ActionEvent evt) {
fileChooser.addChoosableFileFilter(fileFilter);
if(fileChooser.showSaveDialog(null)!=fileChooser.APPROVE_OPTION){
return;// Cancel
}
file = fileChooser.getSelectedFile();
try{
Writer filWriteStream=new FileWriter(file);
filWriteStream.write(jTextArea1.getText() );
filWriteStream.close();
} catch(Exception e){
javax.swing.JOptionPane.showMessageDialog(null,
" \n"+file.getAbsolutePath());
}
}
372 8

DVD -
08_9_4_FileStream.


Java ,
. .
Java new -
,
-. , -
( )
.
,
.
. -
.
System.arraycopy.
Arrays.fill (
Arrays java.util).
Arrays.equals (
) Arrays.deepEquals ( , . . -
, ). (-
) Arrays.sort.
(Collections) "" ,

. -
, . . .
(iterator).
, .
String . String ,
0 2 109.
String ,
. toString() Object -
.
String
-. -
StringBuffer StringBuilder.
, , ,

(, ). -
.
java.awt.Graphics.
, -
paint, ,
ComponentResized.
373

Java . -
Throwable. Throwable Error ()
Exception (). Error -
, catch.
Exception (
RuntimeException ).
-
, , .
, throws .
, -
, , -
-
.
File ( -
,
, ).

JFileChooser ( javax.swing).
/ , ,
/. -
java.io. InputStream ( ) -
, . -
OutputStream ( ) ,
.
( )
Reader() ( , FileReader).
- Writer () ( -
, FileWriter).
RandomAccessFile (
), -
. RandomAccessFile -
, . RandomAccessFile -
, .


, , ,
n n-1.
-

. .
-
==. equals.
374 8

( null)
, String.

Java , -
Spring (), , -
m2=m1 m2. Spring
m1 m2 ( m1 April,
m2 ). m2=m1 m2
m1. m2
m2.
-

FileInputStream FileOutputStream ( InputStream OutputStream).
-

RandomAccessFile.
-
JTextArea -
RandomAccessFile.
-
(ANSI, Unicode, UTF-8).
.
, , -
, . -
JTable.
double.
, -
,
.
9

9.1.
.
,
.
, -
. , . ,
,
, . , -
, -
. ,
, . .
, .
C++ . -
, , .

, -.
-
, Java . -
: , -
.
, , A
B C, D. D
, A,
B, C.
, C++ . ,
, ,
,
.
-
, -
376 9

A. -
,
, . Java -
, -
.
,
, . -
Java Objective-C,
.
Java,
, C++.

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

-
. , add, addAll,
clear, contains , , -
Collection. , -
Iterator . .
, JDK 5, -
, (marker). -
@, -
. , , @Action,
Action , application,
action (. . 13.5).
( 9.1).

9.1.

interface
extends 1, 2,..., N{
;
;
}

. -
public, . -
, .
, , -
1, 2 . .
, .
377

Java , ,
( ) .
I ( Interface),
.
i. , IScalable, iScalable.
, :
= ;

public. -
, public, -
. :
( final), . . -
, ( static).
static final .

:
()
throws ;

, ,
public. public, -
. -
( Exception), . throws -
.
(public) (abstract).
9.2 .

9.2.

package figures_pkg;

public interface IScalable {


public int getSize();
public void setSize(int newSize);
}

-
. extends -
implements (). , -
, . . .
, , ,
, -
.
, . ,
, .
378 9


, ,
.

(implements) , -
(generic declaration ).
.

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

9.2. .

:
, . . ,
( , , -
,
);
,
;
379

public (
). , public;
;
, , ,
abstract;
static, native, synchronized, final, private, protected;
, , ,
, (. .
, );
. -
, -
;
; -
, ;
.
,
. , -
(, , ). -
? , -
, .
.
, , ,
.

(
). 9.3.

9.3.

public interface I1 {
Double PI=3.14;
}

public interface I2 {
Double PI=3.1415;
}

class C1 implements I1,I2 {


void m1(){
System.out.println("I1.PI="+ I1.PI);
System.out.println("I2.PI="+ I2.PI);
}
}

.
, , . -
, , .
380 9

, , . -
, -
,
. , ,
(. .
, , -
).
.
, A2 , A1, ,
, , -
(. . A2 A1). :
"A2 A1" (A2 is A1).
A1, B1,...
, I,
, . -
, :
" A1, B1,... I" (- "A1, B1,... is I").
Java :
, ;
, .
- - ,
.

9.3.
9.4 , Figure
IScalable.

9.4. ScalableFigure IScalable

package figures_pkg;

public abstract class ScalableFigure extends Figure implements IScalable {


private int size;

public int getSize() {


return size;
}

public void setSize(int size) {


this.size=size;
}
}
381

Circle ( 9.5).

9.5. Circle ScalableFigure

package figures_pkg;
import java.awt.*;

public class Circle extends ScalableFigure {

public Circle(Graphics g,Color bgColor, int r){


setGraphics(g);
setBgColor(bgColor);
setSize(r);
}

public Circle(Graphics g,Color bgColor){


setGraphics(g);
setBgColor(bgColor);
setSize( (int)Math.round( Math.random()*40 ) );
}

public void show(){


Color oldC=getGraphics().getColor();
getGraphics().setColor(Color.BLACK);
getGraphics().drawOval( getX(), getY(), getSize(), getSize() );
getGraphics().setColor(oldC);
}

public void hide(){


Color oldC=getGraphics().getColor();
getGraphics().setColor(getBgColor());
getGraphics().drawOval( getX(), getY(), getSize(), getSize() );
getGraphics().setColor(oldC);
}

9.6.

9.6.

package figures_pkg;

public interface IStretchable extends IScalable{


double getAspectRatio();
void setAspectRatio(double aspectRatio);
int getWidth();
void setWidth(int width);
int getHeight();
void setHeight(int height);
}
382 9

IScalable , (size).
(AspectRatio )
. IStretchable ,
, ( ).
instanceof, . ,
9.7 -
IScalable.

9.7. instanceof

Object object;
...
object= new Circle(...);//
...
if(object instanceof IScalable){
((IScalable) object).setSize( (int)(Math.random()*80) );
}

ScalableFigure ( 9.8).

9.8. instanceof

ScalableFigure figure;
...
figure = new Circle(...);//
...
if( figure instanceof ScalableFigure){
figure.hide();
((ScalableFigure)figure).setSize( (int)(Math.random()*80) );
figure.show();
}

figure Figure, . . -
, object -
. , Object
, object (. . instanceof)
Figure.
IScalable ( 9.9).

9.9.

IScalable scalableObj;
...
scalableObj = new Circle(...);//
...
scalableObj.setSize( (int)( Math.random()*80 ) );

, Object object= new Circle(...) , . . Circle -


Object.
383

, Figure figure = new Circle(...) , . . Circle


Figure.
, , scalableObj = new Circle(...) , . . Circle -
IScalable.
Circle(...) Dot(...)
, scalableObj = new Dot(...) -
, . . Dot IScalable, . . .

9.4.

, , -
, . , .
, , . -
, :
, -
.
, -
, , (
), ( -
).
, .
"is-a" ( , ), -
"has-a" ( , ) "use-a"
().
,
.
,
.
.
, , , , . .
, , . . ,
, .
, ,
. , -
, ,
. , -
, - .
, -
(. . , -
). ,
, .
384 9

Java
. -
.
-
.
, .
-
, , -
. ,
.
.
: Car (), Driver () Speed (-
), . MovingCar (-
):
public class MovingCar extends Car{
Driver driver;
Speed speed;
...
}

MovingCar , -
, Driver
Speed.
, : movingCar,
movingCar.driver (, ,
null), ( !) -
. speed. -
-, Car, Driver Speed -
( -,
).
- , -
/ .
:
, . . -
Driver Speed. , Driver
Speed, MovingCar . -
movingCar.driver movingCar.speed,
(, ). ,
, .
,
-
.
385


,
, .
. , -
, . , ,
( ),
.
, --
.
,
. . -
, .
, -
, .
, -
, , (
), (
). -
.
: "is-a" ( , ), -
"has-a" ( , ) "use-a" (-
).
,
.


, , -
- , ,
, . -
,
.

Square ScalableFigure. -
AdditionalFigures.
AdditionalFigures IScalable.
, ,
StretchableFigure. AdditionalFigures.
Rectangle StretchableFigure. -
AdditionalFigures.
386 9

, -
, -
, , , . -
, show, hide, moveTo
.
, -
, .
, , (dot1,
circle3 . .). , show, hide, moveTo -
, .
. -
ScalableFigure, -
. StretchableFigure,

.
AdditionalFigures IBordered, -
, (border)
. BorderedCircle,
BorderedSquare, BorderedRectangle.
10

10.1. (threads)

(MS Windows, Linux .) , -
(), -
(application) (process).
( )
. -
-
.
.
.
(subprocesses)
( ) threads. threads .
(lightweight processes), . .
, .
" ", multithreading (
) -
. , threads
/ (streams).
, -
. (-
),
(. . ,
).
() .
. , -
() .
- (daemons),
. -
, .
388 10

- - -
.
Java . -
Java- (JVM) main , , -
. "main".
( ) , -
. Java- -
Java ,
-.
Java . ,
Java , Thread, -
, Object
, .
notify() (), notifyAll() ( ), wait() (), wait(timeout) (
-). .

10.2.

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

.
. -
" ".
.
. -
, -
.
-
, . ( -
) ; ,
; ; ;
. .
,
.
, -
.
389

-, . ,
.
-, , ,
. -
, ,
.

. , ,
,
(debugger), (profiler) . -
17. NetBeans 6.5 , -
.

10.3.


, .


,
, -
, -
, . ,
. Java
synchronize ().
, -
.
Java -
. ,
. -

, , -
. ,
, . -
, ,
.
: -
.
obj1 ( ) -
:
synchronized(obj1) ;

10.1 .
390 10

10.1.

synchronized(obj1){
...
m1(obj1);
...
obj1.m2();
...
}


. obj1 -
. , -
,
.
, -
.
, -
. ,
( -
), -
synchronized ( 10.2).

10.2.

public class {
...
public synchronized (...){
...
}
}


( 10.3).

10.3.

public class C1{


public synchronized void m1(){
}
}
C1 obj1=new C1();
obj1.m1();

obj1.m1(), obj1


m1().
391

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


, -
-
, . -
: wait () notify ().
Java ,
Object :
void wait() , - (-
), . -
run() ,
() , notify() notifyAll(). -
, -
llegalMonitorStateException;
void wait(long millis) , millis -
;
void wait(long millis, int nanos) , millis
nanos ;
void notify() , , -
. ,
( );
void notifyAll() , ,
.
wait obj : -
while, wait (-
10.4).

10.4. wait

synchronized(obj){
while(not )
obj.wait();
...// , true
}

, while
. , obj.wait()
, , ""
392 10

. wait
obj, synchronized(obj),
obj.notify() obj.notifyAll().

10.4. Thread
Runnable Callable.

, -
:
java.lang.Thread;
java.lang.Runnable ().
public void run(),
.
Thread Runnable, run().
Thread , . -
run(). -
, . ,
run() ;
java.util.concurrent.Callable ().
Runnable, call() -
.

, Thread, -
run().
- .
, .
, Thread :
public Thread() . system;
public Thread(String name) , name.
. ,
,
.
- ( )
,
super( ). - Java -
,
Thread. , . -
Runnable, -
.
10.5 .
393

10.5.

public class T1 extends Thread{


public void run(){
...
}
...
}

Thread thread1= new T1();


thread1.start();

, ,
, java.lang.Runnable. -
, , public void run().
, Thread
( 10.6).

10.6.

public class R1 implements Runnable{


public void run(){
...
}
...
}

Thread thread1= new Thread(new R1());


thread1.start();

, . .
Thread. ,
, , ,
Thread , -
. -
run(), ,
Thread, .
Thread.
, , -
run() :
System.out.println(" ="+this.getPriority());

. -, -
R1 thread ( 10.7).

10.7. Runnable

public class R1 implements Runnable{


public Thread thread;
394 10

public void run() {


System.out.println(" ="+thread.getPriority());
}
}

-. -
-
. , :
R1 r1=new R1();
Thread thread1=new Thread(r1, "thread1");
r1.thread=thread1;
thread1.start();//, , r1.thread.start()

thread
, run().
( R1 r1=new R1();,
r1.thread=thread1;, R1 public Thread thread;).
Thread -
Runnable:
public Thread(Runnable target) system ;
public Thread(Runnable target, String name) .
.

, ,
, java. util.concurrent.Callable,
call().
JDK 5. Callable Callable<V>, -
. call
V. , ,
implements Callable V
call .

10.5. ,
Thread
Thread ,
.
Thread.
MIN_PRIORITY . -
JVM. 1.
NORM_PRIORITY . -
, .
5.
MAX_PRIORITY .
10.
395

static int activeCount() .


static Thread currentThread() .
static void sleep(long millis) ()
millis. () . -
sleep(long millis, int nanos), nanos
. interrupt() -
InterruptedException.
static void yield() ( )
.
static boolean holdsLock(Object obj) true , -
obj.
static boolean interrupted()
, false.
Thread.
void run() ,
. Thread ,
. run() .
void start() , -
run() . .
void setDaemon(boolean on) on==true ,
.
boolean isDaemon() true , -
.
long getId() . -
()
.
String getName() ,
setName.
void setName(String name) .
int getPriority() .
void setPriority(int newPriority) .
void checkAccess() -
. , ,
, , SecurityException.
String toString() , -
, , .
void interrupt() wait(...) sleep(...),
( true). -
InterruptedException.
boolean isInterrupted()
.
396 10

void join() ("") , ,


() , join().
, thread1 thread2.join(), -
thread1 ,
thread2. ( join())
, join()
(. .
).
join(long millis)
millis . join(0) join() . -
join(long millis, int nanos), nanos -
.
interrupt() InterruptedException. join()
join UNIX
("" ).
boolean isAlive() true , ( ).
, , -, -
isAlive() false (. . , ).

10.6.



2007 -
.
, ,
.
,
.
, -
, .
, ! -
.
3 . -
.
-, - ,
.
, -
, .
-, .
, -
, .
397

300 000 / = 3 1010 /c, , ,


30 / (1 = 109 ). ,
.
, 10 /. , -
t = 0,3 .
, -
, -
, 1/t = 3,3 .
,
( ). -

, .
, ,
-
,

. , -
. , -
.

?
, , , -
, -
, , -
, ,
.
, , .
10 10 , 100 100
. . -
.

. -
.
, , -
.
,
. , , ,

. -
, .
, -
.
, -
. -

398 10

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

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

, . 2007 Intel
AMD .
2008 4- -
, 2009 6-.
Intel 128.
. ,
Sun Microsystems 8- Niagara.
, -
, ,
.


, -
, . ,
,
. , - , -
399


.
,
.
: ,
.

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

. -
(-) ,
.
-
-
. -
Java
. Java, -
, -
,
- .
,
. , ,
, -
, -
, , .
-
, .
, ,
9 [11]. -
JDK 5 java.util.concurrent
java.util.concurrent.atomic. , -
(,
) .
, 10_6_Threads
.
,
5.
MiddleRectangles integral -
, fnc, -
400 10

. fnc.f , .
- , Java
( 10.8).

10.8.

/**
*
* @author monakhov
*/
public class MiddleRectangles {

/**
* Creates a new instance of MiddleRectangles
*/
// public MiddleRectangles() {
// }

public static double integral(double a,double b, double n, Fnc fnc) {

double r=0;
double h=(b-a)/n;
for(int i=0;i<n;i++)
r=r+fnc.f(a+i*h+h/2);
return r*h;
}

10.9.

10.9.

Fnc fnc;
double a=0,b=10;
int n=1000;
double result=0;

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {


a=Double.parseDouble(jTextField2.getText());
b=Double.parseDouble(jTextField3.getText());
n=Integer.parseInt(jTextField4.getText());
if( jRadioButton1.isSelected() ) fnc=new Fnc();
if( jRadioButton2.isSelected() ) fnc=new FncX2();
if( jRadioButton3.isSelected() ) fnc=new FncSin();
if( jRadioButton4.isSelected() ) fnc=new FncSqrt();
long t0=System.currentTimeMillis();
result=MiddleRectangles.integral(a,b,n,fnc);
401

long t=System.currentTimeMillis()-t0;
jLabel4.setText("integral="+result);
jLabel8.setText("t="+t+" ms");
}

jButton2. ,
, , .
.
.
, .
, , -
, . -
. -
, , -
. ,
, .
Integrator. -
, result (-
10.10).

10.10. Integrator,

package examples;
/**
*
* @author monakhov
*/

public class Integrator {

public double result=0;


public int activeThreadsCount=0;
/**
* Creates a new instance of Integrator
*/
public Integrator() {
super();
}

ThreadedCalc, Thread.
-

,
integrator ( result -
) ( 10.11).
402 10

10.11.

/*
* ThreadedCalc.java
*
*/

package examples;

/**
*
* @author monakhov
*/

public class ThreadedCalc extends Thread{


/** Creates a new instance of ThreadedCalc */
double result=0;
double a;
double b; double n;
Fnc fnc;
Integrator integrator;

public ThreadedCalc(double a,double b, double n, Fnc fnc,


Integrator integrator) {
super();
this.a=a;
this.b=b;
this.n=n;
this.fnc=fnc;
this.integrator=integrator;
integrator.activeThreadsCount++;
}

public void run(){


result=MiddleRectangles.integral(a,b,n,fnc);
synchronized(integrator){
integrator.notify();
integrator.result+=result;
integrator.activeThreadsCount--;
}
}
}

ThreadedCalc
activeThreadsCount, integrator.
:
integrator.activeThreadsCount++;

,
, .
403

- ,
.
, -
:
synchronized(integrator){
integrator.activeThreadsCount++;
}

-
. ,
. Java
boolean, int float, -
. , . .
. -
.
, Integrator activeThreadsCount -
volatile, -
, .
( ,
. .) .
,
integrator.activeThreadsCount=1;
for(i=0;i<=n;i++){
, integrator.activeThreadsCount
};
count = integrator.activeThreadsCount;

count 1, -
activeThreadsCount . volatile
, -
, count , -
. ,
Java- -
.
volatile , .
JDK 5 java.util.concurrent.atomic -
, .
10.11. run -
. result . -
integrator
-
. notify(), . .
(. ) integrator.wait()
, activeThreadsCount==0.
jButton2 -
( 10.12).
404 10

10.12.

Integrator integrator;

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {


double aForThread,bForThread,h,step;
int nForThread,threadCount;
threadCount=(Integer)(jSpinner1.getValue());
n=Integer.parseInt(jTextField4.getText());
nForThread=n/threadCount;
n=nForThread*threadCount;
jLabel7.setText(nForThread+" intervals for 1 thread");
h=(b-a)/n;
step=h*nForThread;
jTextField4.setText(n+"");
ThreadedCalc[] threads=new ThreadedCalc[threadCount];
ThreadedCalc thread;
integrator=new Integrator();
long t0=System.currentTimeMillis();
for(int i=0;i<threadCount;i++){
aForThread=a+i*step;
bForThread=aForThread+step;
if( jRadioButton1.isSelected() )
fnc=new Fnc();
if( jRadioButton2.isSelected() )
fnc=new FncX2();
if( jRadioButton3.isSelected() )
fnc=new FncSin();
if( jRadioButton4.isSelected() )
fnc=new FncSqrt();
thread=new ThreadedCalc(aForThread,bForThread,nForThread,fnc,
integrator);
threads[i]=thread;
}

for(int i=0;i<threadCount;i++){
threads[i].start();
}

synchronized(integrator){
while(!(integrator.activeThreadsCount==0) )
try{ integrator.wait();
}catch(Exception e){
JOptionPane.showMessageDialog(null,
"activeThreadsCount="+integrator.activeThreadsCount+
""+e.getMessage(),"",JOptionPane.INFORMATION_MESSAGE);
}

}
405

long t=System.currentTimeMillis()-t0;
jLabel8.setText("t="+t+" ms");
jLabel6.setText(integrator.result+"");
}

n , threadCount .
jSpinner1 -
, , -
, .
, .
:
NForThread = n/threadCount.

, , -
.
, .
,
n=(int)(nForThread*threadCount).
, threads, -
.
, ,
. 10_6_Treads, -
DVD, ,
threads, -
:
new
ThreadedCalc(aForThread,bForThread,nForThread,fnc,integrator)).start();

, ,
, , ( 10.13).

10.13.

synchronized(integrator){
while(!(integrator.activeThreadsCount==0) )
try{ integrator.wait();
}catch(Exception e){
JOptionPane.showMessageDialog(null,
"activeThreadsCount="+integrator.activeThreadsCount+
" "+e.getMessage(),"",
JOptionPane.INFORMATION_MESSAGE);
}
}

, , . -
-
, result integrator, ().
, . integrator.activeThreadsCount
. threadCount,
406 10

. , -
.
, , integrator.activeThreadsCount==0
( , integrator.result ). -
integrator ,
integrator.wait()
, - .
, , -
. , , -
notify() notifyAll().
, integrator.wait() try...catch.



10_6_Threads, ,
() Dell Inspiron MXC061 -
Intel Core 2 Duo T5300, 1,73 , 1,5 , Microsoft
Windows XP Home Edition SP2.

. 10.1 10.2.

10.1. 100 ,



x x*x sqrt(x) sin(x)
0 1,5 1,6 3,8 12,7
1 1,5 1,6 3,8 12,7
2 0,8 0,9 2,0 6,9
10 0,9 0,8 1,9 6,5
100 0,9 0,8 2,0 6,5
1 000 1,0 1,0 2,2 7,3
10 000 3,2 3,2 4,3 9,6
100 000 26 27 28 32

10.2. ,



x x*x sqrt(x) sin(x)
0 1,0 1,0 1,0 1,0
1 1,0 1,0 1,0 1,0
407

10.2 ()



x x*x sqrt(x) sin(x)
2 1,9 1,8 1,9 1,8
10 1,7 2,0 2,0 2,0
100 1,7 2,0 1,9 2,0
1 000 1,5 1,6 1,7 1,7
10 000 0,5 0,5 0,9 1,3
100 000 0,06 0,06 0,14 0,4

-
. ; -
; , 16
100. , 2,7
1000 0,5 10 000 .
:
-
;
2 100
1,7 2,0 -
;
16 100 -
3,6 4,0
;

, , 10100 ;
-
, ;
, -
1000.
:
Java, JDK 6,
;
-
( ) ;
-
,
, .
408 10

10.7.
Lock Condition
Lock
JDK 5 , -
java.util.concurrent.locks.Lock. lock "", "".
, -,
, Lock. ,
( ,
). -
. ,
, -
, -
, . -
, . . -
, Lock:
lock, lockInterruptibly, tryLock, newCondition, unlock.

: tryLock unlock. 10.14 -


- lock.

10.14. - lock

Lock lock = new MyLock();


if (lock.tryLock()) {
try {
...
} finally {
lock.unlock();
}
} else {
...
}

Lock . 10.3.

10.3. Lock




void lock() . ,
, (-
, ), ,
,
, -
.
unlock()
409

10.3 ()

void lockInterruptibly() . ,
throws InterruptedException , (-
, ), ,
,
, -
, -
interrupt() (. Thread).
-
InterruptedException
Condition newCondition()
throws Condition.
UnsupportedOperationException


Condition wait, notify
notifyAll Object
boolean tryLock() . -
true , false
(-
, -
)
boolean tryLock(long -
time,TimeUnit unit) throws . true
InterruptedException , false
(, -

). -
-

InterruptedException
void unlock()

tryLock(long time, TimeUnit unit) -


.
java.util.concurrent.TimeUnit -
( 10.15).

10.15. ,

NANOSECONDS
MICROSECONDS
MILLISECONDS
SECONDS
MINUTES
HOURS
DAYS
410 10

JDK 5 Lock ReentrantLock,


java.util.concurrent.locks.
, .
-
.
java.util.
concurrent.locks.LockSupport, ,
park (), (
), unpark (), .
NetBeans FIFOMutex ( -
FIFO "First In First Out" ( )),
Lock. , -
lock() unlock(), .

Thread ( 10.16).

10.16. FIFOMutex

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;

class FIFOMutex {
private final AtomicBoolean locked = new AtomicBoolean(false);
private final Queue waiters = new ConcurrentLinkedQueue();

public void lock(){


Boolean wasInterrupted = false;
Thread current = Thread.currentThread();
waiters.add(current);//

// ("") ,
// , ,
while (waiters.peek() != current ||
!locked.compareAndSet(false, true)){
LockSupport.park(this);
if (Thread.interrupted()) //
wasInterrupted = true; // ,
} //

waiters.remove();//
if (wasInterrupted)
current.interrupt();
}

public void unlock() {


locked.set(false);
411

LockSupport.unpark((Thread)waiters.peek());//
} //


. -
lock , . -
unlock , - ,
(, , "" ).
10_7_Lock.
.
, . locked -
, . AtomicBoolean,
JDK 5 () ,
java.util.concurrent.atomic.
waiters () Queue () -
.
ConcurrentLinkedQueue , JDK 5
-
.
lock, - ,
(. . , ).
waiters -
.
waiters.peek()
(head "" ) (. . , -
).
, LockSupport.park(this). -
, -
unpark interrupt.
(. . -
Thread.interrupted()==true).
, wasInterrupted, ,
.
.
,
.
locked.compareAndSet(false, true) true.
atomicBool.compareAndSet(expectedValue,newValue) true , -
atomicBool expectedValue.
atomicBool newValue.
, , -
locked false, . . .
412 10

waiters.remove() ( ) -
, -, ,
() ,
interrupt(), . -
, interrupted.
unlock locked false
.

Condition
Condition (), JDK 5, , -
, wait, notify
notifyAll, Object.
Lock.
, , -
. 10.4.

10.4. Condition




void await()
(),
throws InterruptedException
signal(), signalAll() -
interrupt().
(
),
.
, -

-
boolean await(long time, ,
TimeUnit unit) , .
, .
true ,
,
, false

long awaitNanos(long , , -
nanosTimeout) , .
,
-
-
.
-

void awaitUninterruptibly() , -


413

10.4 ()




boolean awaitUntil(Date , ,
deadline) , . true -
,
, ,
false

void signal() - . -
-

void signalAll() - . -
-

Condition
awaitUntil ( 10.17).

10.17. awaitUntil

synchronized boolean aMethod(Date deadline) {


boolean stillWaiting = true;
while (!__) {
if (stillwaiting)
stillWaiting = theCondition.awaitUntil(deadline);
else
return false;
}
// ...
}

theCondition , Condition.
aMethod , -
deadline .
awaitNanos ( 10.18).

10.18. awaitNanos

synchronized boolean aMethod(long timeout, TimeUnit unit) {


long nanosTimeout = unit.toNanos(timeout);
while (!__) {
if (nanosTimeout > 0)
nanosTimeout = theCondition.awaitNanos(nanosTimeout);
else
return false;
}
// ...
}
414 10


, ,
(process) . -
. (threads) ,
. -
(),
, . .
, .
() . , -
. -
-, -
.
Java .
Java- (JVM) main , , -
. "main".
,
, -
. ,
-
. , . Java -
synchronize ().
( ) .
, ,
. ,
, .
:
.
obj1 :
synchronized(obj1) ;

synchronized :
public synchronized (...){...}

,

, .
: wait () notify ().
, -
. Java
boolean, int float, -
.
, :
java.lang.Thread, java.lang.Runnable,
java.lang.Callable.
415

java.lang.Runnable public void


run(), .
Thread Runnable, run(). -
Thread run().
java.lang.Callable call(), -
.
.
JDK 6 .
-
( ) .
-
, -
, .
JDK 5 , -
Lock Condition.
JDK 5 java.util.concurrent.locks.ReentrantLock, -
Lock. -
, .


-
, -
.
,
.
, ( , -
, - -
).
,
,
( " ", deadlock).
, ,
, .
, ,
.
, , ,
boolean, int float, . ,
(++, --, +=, -=, *=, /=) , .
, long double -
.
volatile, . . , -
, -
, .
416 10

volatile, , Java- -
.

, . -
Thread.
run
1 100 10 , -
,
"Thread 1:" , "Thread 2:" . .
print10.

, .
, -
print10 run .
, ,
101 200,
Runnable, print10 .
.
11


Java -
WWW. -
HTML, WWW -
.
Java WWW. , , Java-
, .

11.1. HTML
HTML , -
WWW, , -
, Java, Flash-
. Java HTML-,
.
, , , HTML,
XML. , XML, . .
WWW- Java
HTML.

WWW HTML
World Wide Web ( ) , , WWW -
, . -
-
(), .
,
( ), , ,
( ). HTML-, -
, ,
.
/ ( -
).
418 11

, ,

, .

. HTTP
(HyperText Transport Protocol) , -
. , ,
( ).
HTML-
WWW- (WWW-browsers).
, Microsoft Internet
Explorer, Mozilla ( , Firefox), Opera, -
Netscape Navigator.
WWW-, , ,
. -
, HyperText Markup Language
(HTML) . () , -
, .
HTML,
HTML 4.01 W3C (World Wide Web
Consortium), HTML WWW-. XML-
HTML, XHTML, .
WWW-
HTML 3.2. , HTML--
. ,
HTML- .
, HTML, , -
, , (murkup
tags). , -
(< >).

, , -
, .
, >, -
() .
HTML html htm. WWW-
,
.
HTML ,
:
<
>
&
"
419

:
&lt;
&gt;
&amp;
&quot;

-
.
,
( ) .
:
&nbsp;

(non-breaking space),
. , ,
, , -
.


.
() . <-
</, -
/.
:
<html> html </html>

, . ,
<br> .
, , -
,
<pre> </pre>. , -
,
.
.
, , ,
, .
,
<img src="MyFile.gif" width=100 height=40>

MyFile.gif,
100 40 () .
src, , , width height -
( ).
, ( !),
HTML . HTML ,
420 11

HTML- (,
), ( ).
XHTML
(, ).
HTML- .
<html> </html>.
:
<head>, </head>

HTML-, -
,
:
<title> </title>

,
.

:
<meta http-equiv="content-type" content="text/html; charset=Windows-1251">

( ISO 1251);
<meta http-equiv="content-type" content="text/html; charset=UTF-8">

( UTF-8) . .
:
<body>
html-, - .
</body>

:
html-, - .

HTML-
.
(hypertext link), ,
. .
, ,
(URL Uniform Recourses Location) :
. ,
, .
, ,
. :
<a href="_">_</a>
421

:
_ ( ), ,
;
_ , . . , ,
.
URL- -
.
:
<a href="_#_"></a>

HTML ,
. ,
, :
<a name="_"> </a>

:
_ , (
);
_ ( ), ,
- .
, , -
. -
.

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

,
.

. :
<p> </p>
<p align="left"> </p>
<p align="right"> </p>
<p align="center"> </p>

</p> .
<hr> -
.
.
. -
1 6 ( 11.1).
422 11

11.1.

<h1> </h1>
<h2> </h2>
<h3> </h3>
<h4> </h4>
<h5> </h5>
<h6> </h6>

11.2 .

11.2.

<ol>
<li>...</li>
<li>...</li>
<li>...</li>
...
</ol>

</li> , .
11.3 HTML- (
) ( ).

11.3.


:
<ol>
<li></li>
<li></li>
<li></li>
</ol>

:
1.
2.
3.

11.4 HTML- .

11.4.


:
<ul>
<li></li>
<li></li>
<li></li>
</ul>
423

HTML :
(bold):
<b> (bold)</b>

(italics):
<i> (italics)</i>

:
<big> </big>

:
<small> </small>

(subscript):
<sub>(subscript)</sub>
(superscript)
:
<sup>(superscript)</sup>

, ,
( ).
HTML .
<pre>...</pre> , -
, -
. , ,
.
HTML , -
. :
<img src="_" width= height= border=_
hspace=_ vspace=_
alt=_>

:
_ ( ), -
;
;
;
_ ;
424 11

_ , ,
, , .
( ).
width height, -
.
border , , -
.
hspace vspace
.
,
-
, ,
. width height , ,
. ,
, , , , -
.
, img
<a href=""> :
<a href=... ><img src=...></a>

HTML- .
<table>, , border
( : border border=_), </table>.
. <tr>
</tr>. (. . , )
<td> </td> ( , ).
-
. ,
, . .
11.5 .

11.5.

<table border>
<tr> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr>
<tr> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr>
...
</table>

(). HTML -
, ,
HTML- ,
. 11.5 -
11.6.
425

11.6.

<table border>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
</table>

HTML- (browser), , -
.
, <hr>...</hr>.
( , plug-ins)
<object> ( 11.7).

11.7. (plugins)

<object

>
<param name=1 value=1>
<param name=2 value=2>
...
<param name=N value=N>
_
</object>

Java, . .
_
, , -
.

,

HTML . 11.1 (
).
HTML . 11.2.
HTML . 11.3.
426 11

11.1.

&part; &prod; &sum; &radic; &infin;


&cap; &int; &plusmn; &equiv; &asymp;
&ne; < &lt; > &gt; &le; &ge;
&ne; &circ; &tilde; &Oslash; &oslash;
&divide;

11.2.

&deg; &bull; ... &hellip; &prime; &Prime;

&oline; &trade; &copy; &reg; &diams;
&loz; &mdash; &ndash; &rsquo; &dagger;
&Dagger; " &laquo; " &raquo;

11.3.

&#0913; &#0914; &#0915; &#0916; &#0917;


&#0918; &#0919; &#0920; &#0921; &#0922;
&#0923; &#0924; &#0925; &#0926; &#0927;
&#0928; &#0929; &#0931; &#0932; &#0933;
&#0934; &#0935; &#0936; &#0937;
&#0945; &#0946; &#0947; &#0948; &#0949;
&#0950; &#0951; &#0952; &#0953; &#0954;
&#0955; &#0956; &#0957; &#0958; &#0959;
&#0960; &#0961; &#0962; &#0963; &#0964;
&#0965; &#0966; &#0967; &#0968; &#0969;

: -
&; (. 11.4).
:
&alpha;
&beta;
&gamma;
. .
:
&Alpha;
&Beta;
&Gamma;
. .
427

11.4.

&Alpha; &Beta; &Gamma; &Delta; &Epsilon;

&Zeta; &Eta; &Theta; &Iota; &Kappa;

&Lambda; &Mu; &Nu; &Xi; &Omicron;

&Pi; &Rho; &Sigma; &Tau; &Upsilon;

&Phi; &Chi; &Psi; &Omega;

&alpha; &beta; &gamma; &delta; &epsilon;

&zeta; &eta; &theta; &iota; &kappa;

&lambda; &mu; &nu; &xi; &omicron;

&pi; &rho; &sigma; &tau; &upsilon;

&phi; &chi; &psi; &omega;

11.2.

, 1.
Java ,
WWW- . ,
HTML- ( WWW-).
(applications) (applets) Java
. -
. -
WWW , -
WWW-, , -
. WWW
, . , -
-
, ,
.
(core library), -
java.applet , javax.swing.JApplet
, Swing, / Sun JFC (Java
Foundation Classes).
,
java.applet.Applet, java.awt.Panel.
( 11.8).
428 11

11.8.

public class Applet1 extends java.applet.Applet{

public void init(){


// .
//
// start()
}

public void start(){


// .
//
// init().
//
// HTML- .
}

public void update(java.awt.Graphics g){


//
}

public void paint(java.awt.Graphics g){


// .
//
}

public String getAppletInfo(){


return " ";
}

public void stop(){


// .
// ,
// HTML- .
}

public void destroy(){


// .
// , .
//
// stop()
// .
}
}

, , Applet ,
:
getSize() (
getSize().width getSize().height);
429

showStatus(String s) s;
AppletContext getAppletContext() ,
, ;
add(Component comp) ;
AudioClip getAudioClip(URL url)
WWW- url. Java, ;
URL getDocumentBase() WWW-,
.
, -
Panel.
. -
JDK 5, Windows XP SP1 MS Internet Explorer 6.0 -
, JDK ( Java
, ). -
appletviewer javac . ,
JDK 6 . Internet Explorer
,
(, , -
, ).
. Mozilla FireFox 3.05 ,
HTML- <applet>, -
<object> Mozilla FireFox .

. JDK Java , -
, , -

. , WWW, -
JDK, .
.
.
, .
,
HTML JavaScript.
HTML- (
).

. , JVM
, , -
.

. @Override
JDK demo/applets.
.
430 11

, 11_2_applets.
(Applet1, Applet2 Applet3), HTML-, -
.
example1.html, example2.html, example3.html, example4.html -
1, 2, 3 4 .
. 1 11.9 11.10.

11.9. Applet1

/**
* The Applet1 class demonstrates
* applet code.
* It displays "Hello World!" greeting.
* Run example1.html to see working applet.
*/
public class Applet1 extends java.applet.Applet {
@Override
public void paint(java.awt.Graphics g) {
g.drawString("Hello world!", 50, 50);
}
}

@Override , ,
, . -
. -
@Override, (,
), -
.

11.10. HTML- example1.html,


Applet1

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> Hello world </title>
</head>

<body bgcolor=#C0C0C0>
<h3> 1. Hello world</h3>

,
, .

<p> object HTML-:


<hr>
431

<object
codebase="."
code="Applet1.class"
width=200
height=150
>
: Hello world. ,
, .
</object>
</body>
</html>

NetBeans Projects -
Applet1.java -
Run File.
Run | Run File,
<Shift>+<F6>. appletViewer (" -
"), JDK .
appletViewer -
HTML-.
HTML-
Projects HTML-
View ("").
NetBeans -
"" ( Internet Explorer),
HTML- . -
View HTML-
.
, -
Far 11_2_applets\build\classes -
example1.html. -
. ,
HTML- -
build\classes
Java (.class).

WWW Applet1.class example1.html
.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

HTML, HTML--
.

<meta http-equiv="content-type" content="text/html; charset= UTF-8">


Unicode.
432 11

:
<title> Hello world </title>

, .
, object, -
appletviewer.
codebase .
, ( Java, ),
, . , , -
, HTML-.
code .
width height .
( ).
1024 768 ( 1024 768).
11.11 11.12 2 (
example2.html). , , . Java
( 11.11) (. 11.9),
- , ,
, .

11.11. Applet2

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;

/**
* The Applet2 class demonstrates
* applet code.
* It displays an oval and "Hello World!" greeting.
* Run example2.html to see working applet.
*/
public class Applet2 extends Applet {

@Override
public void paint(Graphics g) {
g.setColor(Color.green);
g.fillOval(0, 0, 100, 50);
g.setColor(Color.black);
g.drawString("Hello world!", 50, 50);
}
}

11.12 example2.html ,
Applet2. (<object ...>
<applet...>) HTML-.
433

11.12. HTML- example2.html,


Applet2

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> . Hello world </title>
</head>

<body bgcolor=#C0C0C0>
<h3> 2. Hello world </h3>

,
, .
<p> object:

<hr>
<object
codebase="."
code="Applet2.class"
width=200
height=150
>

: Hello world.
, ,

</object>

applet:<p>

<applet code=Applet2.class width=300 height=120>


alt=" &lt;APPLET&gt;, - !"
&lt;APPLET&gt; !
</applet>
</body>
</html>

example2.html example1.html (. 11.10) ,


, -
<applet> (. 11.1).
appletviewer ,
, HTML 4 (deprecated).
3 ( Applet3.java example3.html CD) , -
.
4 ( example4.html, Applet1.java, Applet2.java Applet3.java DVD) -
, HTML- . ,
434 11

appletviewer HTML- .
( 2 4),
.

. 11.1. <applet> NetBeans

, ,
Java ,
example3.html example4.html.


,
HTML-,
.
NetBeans
File/New Project..., Java/Java Class
Library Next >.
, . -
, , 11_2_Applet1.
11_2_Applet1.
, -
<default package> -
New/Other/Java/JApplet. -
, , New/Java Class.
, ,
, . Applet1.
435

(warning) , -
(Warning: It is highly recommended that
you do NOT place Java classes in the default package). -
Finish.
, 11.13.

11.13.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author User
*/
public class Applet1 {

: (, -
<Ctrl>+<A>)

(Comment ).
, 1
(. 11.9). HTML-.
(
), ,
Other... ().
File/New File..., -
<default package> , -
New/Other... (/...)
(. 11.2).
New File (. 11.3)
Other ( Categories), HTML File ( File Types),
Next >.
, ( -
) . index
index.html ( ). -
index.html
, ( ).
Finish HTML-,
11.14.
436 11

. 11.2. HTML- , 1

. 11.3. HTML-, 2

11.14. HTML-, NetBeans

<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
437

<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
TODO write content
</body>
</html>

<body> , (. 11.10).
Applet1\build\classes index.html Applet1.class.
index.html, , , -
. , <applet>, . .
, ,
FireFox.
, HTML- -
, . . HTML....
,
, .
Swing, ,
JApplet Form.
<default package>
New/Other/Swing GUI Forms/JApplet
Form.

HTML-, CSS
JavaScript
NetBeans HTML-
CSS. ,
, ,
, -
-
, (. 11.4).
,
</object>

</obgect>, ,
:
<object : Unmatched teg ( ),
, , ;
</obgect> -
.

, .
438 11

. 11.4. HTML-

HTML-
. - ,
-
<Ctrl>+<>, (. 11.5 11.6).

. 11.5. bgcolor

, .
. -
XML- ( -
, ).
439

. -
- (deprecated), -
( <p> ), .

. 11.6. <p>


<Ctrl>+<>, -
. HTML-

<Ctrl>+<>.
,
<Ctrl>+<>, .
HTML-
.
, HTML- -
, Java-: -
<Shift>+<Alt>+<F>
Format.

HTML- (. 11.7).
HTML-
. , -
, HTML- -
. , , -
. 11.8.
440 11

. 11.7. HTML- . 11.8. HTML-

OK HTML- , -
11.15.

11.15. HTML-, NetBeans

<table border="1">
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>

, HTML- . -, Sun
Microsystems .
, HTML, (script) JavaScript,
Java .
.
, , 11.16, -
, . 11.9.
441

. 11.9. JavaScript

11.16. JavaScript HTML

<!--
Document : newhtml
Author : V.Monakhov
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<script >
var x=0
var y=sin(5.5*x)+1
x=exp(y)
function f(t){
442 11

return t*t
}
</script>
</body>
</html>

, JavaScript,
, -
(
, -
).
CSS (
).
, HTML- -
Projects -
View ().
HTML-, JavaScript -
CSS NetBeans WWW- -
Java.

11.3.
, Java, .


. -
, ( ),
. -, ,
. , WWW- -
HTML-
. , FTP- -
FTP.
. .
( Java) -
.

. 1.2, -
, HTTP-
. JSP
HTML- XML-, -
. -
,
.
JSP
, JSP (, , , -
Java-).
443

, Java EE (Java Platform,


Enterprise Edition). , ,
-.
, ,
, NetBeans Web & Java EE GlassFish
Tomcat Apache (. . 2.2).
,
. , -
http://localhost:8080/.
localhost ( ),
,
. GlassFish -
8080, Tomcat Apache 8084. -
.
JSP JSTL, .
;
JSP ; -
JSTL; , JSP.
, , -
11.17.

11.17. ,
"!"

/**
* @author Vadim Monakhov
*/

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Hello extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<meta http-equiv=\"content-type\"
content=\"text/html; charset=UTF-8\">");
out.println("<title> </title>");
out.println("</head>");
444 11

out.println("<body>");
out.println(
"<h1> , </h1>");
out.println("!");
out.println("</body>");
out.println("</html>");
}
}

11.18 HTML-, ,
11.17.

11.18. HTML-,

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> </title>
</head>
<body bgcolor="#FFFFFF">
<a href="servlet/Hello"> </a>
</body>
</html>

,
. -
. UTF-8.
NetBeans UTF-8 .



,
WWW-.
WWW-. NetBeans
(. . 2.2) ,
NetBeans, NetBeans GlassFish
Tomcat Apache (. . 2.2).
. -
, : File/New Project.../Samples/Java
Web/Servlet Examples.
NetBeans , , -
NetBeans,
.
,
(. 11.10).
445

. 11.10.

The Apache Software Foundation (http://www.


apache.org/), ,
http://www.apache.org/licenses/LICENSE-2.0.
Next >, Finish
Servlet Examples.
.
(deployed) GlassFish,
WWW , WWW-: http://localhost
( ).
. 11.11 ( -
, ).
. Execute
() , -
HTML-. , Execute
Hello World! ( ) , -
. 11.12.
( Execute Request Info)
, . 11.13.
, Hello
World! ( HelloWorldExample.java . 11.14).
, -
Source HTML- . -
, HTML-, ,
Projects... Web Pages/helloworld.html.
( 11.19) ,
Source Packages/<default package>/HelloWorldExample.java. -
.
446 11

. 11.11.

. 11.12. Hello World!

. 11.13. Request Info


447

. 11.14. Hello World!

11.19. Hello World!

/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
448 11

* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id: HelloWorldExample.java,v 1.3 2006/10/12 14:31:28 abadea Exp $
*
*/

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
* The simplest possible servlet.
*
* @author James Duncan Davidson
*/

public class HelloWorldExample extends HttpServlet {

@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
ResourceBundle rb =
ResourceBundle.getBundle("LocalStrings",request.getLocale());
response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.println("<html>");
out.println("<head>");

String title = rb.getString("helloworld.title");

out.println("<title>" + title + "</title>");


out.println("</head>");
out.println("<body bgcolor=\"white\">");

// note that all links are created to be relative. this


// ensures that we can move the web application that this
// servlet belongs to to a different place in the url
// tree and not have any harmful side effects.

// XXX
// making these absolute till we work out the
// addition of a PathInfo issue
449

out.println("<a href=\"../helloworld.html\">");
out.println("<img src=\"../images/code.gif\" height=24 " +
"width=24 align=right border=0 alt=\"view code\"></a>");
out.println("<a href=\"../index.html\">");
out.println("<img src=\"../images/return.gif\" height=24 " +
"width=24 align=right border=0 alt=\"return\"></a>");
out.println("<h1>" + title + "</h1>");
out.println("</body>");
out.println("</html>");
}
}

( . 11.14), -
DVD @Override -
.
NetBeans,
, :
-,
(, , -
), ( -
doGet . 11.14).
. -
. -
.
SetCharacterEncodingFilter.java NetBeans -
, encoding.
String encoding = selectEncoding(request);


"local variable hides a field" (
).
"Rename the field" ( ), , , -
. -
, (. 11.15).
(
) -
.
NetBeans ,
. Projects -
Properties () (
).
(. 11.16) Server
.
Context Path (. 11.16) , ,
, . , -
11_3_ServletExamples_2 servlet-examples
ServletExamples, http://localhost:8080
450 11

/ServletExamples/. HelloWorldExample
http://localhost:8080/ServletExamples/servlet/HelloWorldExample ( -
Tomcat Apache 8080, 8084).

. 11.15. ,

. 11.16.

, Tomcat Apache GlassFish v3 ,


GlassFish v2, NetBeans -
.
Tomcat Apache GlassFish v3. -
GlassFish v2 NetBeans .
: GlassFish v2

Deployment error,
451

NetBeans . ,
. -
, Open Recent Project ( ),
. -
. -
-
. Clean and build,
NetBeans ( -
) .
Tools/Servers NetBeans
. ,
, Apache Tomcat , -
, Java .



, , 11.19,
11.17, , ,
. , ,
:
UTF-8 :
response.setCharacterEncoding("UTF-8");

UTF-8 HTML-:
out.println("<meta http-equiv=\"content-type\"
content=\"text/html; charset=UTF-8\">");

:
String title = rb.getString("helloworld.title");

-
( ).
Projects HelloWorldExample.java -
LocalStrings.properties. :
default language ( );
en ;
es ;
fr .
-
:
1=1
2=2
...
452 11

, default language, -
11.20. , -
.

11.20. default language


( )

helloworld.title=Hello World!

requestinfo.title=Request Information Example


requestinfo.label.method=Method:
requestinfo.label.requesturi=Request URI:
requestinfo.label.protocol=Protocol:
requestinfo.label.pathinfo=Path Info:
requestinfo.label.remoteaddr=Remote Address:
requestheader.title=Request Header Example

requestparams.title=Request Parameters Example


requestparams.params-in-req=Parameters in this request:
requestparams.no-params=No Parameters, Please enter some
requestparams.firstname=First Name:
requestparams.lastname=Last Name:
...


. ,
locale ( ).
, . , -
en_US, -
en_GB. es_ES,
es_MX.
ru_RU.
, . -
: ru_RU.KOI8-R.
, (
Windows ),
. -
, default language (. 11.17). -

. ,
rb.getString("helloworld.title") (. 11.19). -
( 11.21).

11.21. fr ( )

helloworld.title=Salut le Monde!

requestinfo.title=Exemple d''information sur la requte


requestinfo.label.method=Mthode:
453

requestinfo.label.requesturi=URI de requte:
requestinfo.label.protocol=Protocole:
requestinfo.label.pathinfo=Info de chemin:
requestinfo.label.remoteaddr=Adresse distante:

requestheader.title=Exemple d''information sur les entte de requte

requestparams.title=Exemple de requte avec paramtres


requestparams.params-in-req=Paramtres dans la requte:
requestparams.no-params=Pas de paramtre, merci dans saisir quelqu'uns
requestparams.firstname=Prnom:
requestparams.lastname=Nom:
...

Hello World! Salut le


Monde!.

. 11.17. LocalStrings.properties default language

, UTF-8 Java, HTML-


.
, default language
-,
.
11_3_ServletsExamples_2 HelloWorldExample
,
:
response.setCharacterEncoding("UTF-8");
out.println("<meta http-equiv=\"content-type\"
content=\"text/html; charset=UTF-8\">");
454 11

-
. , .

LocalStrings.properties Add
Locale... ( ) (. 11.18).
, Predefined Locales (
) ru_RU OK (. 11.19).
LocalStrings.properties :
default language
en
es
fr
ru_RU ()
LocalStrings.properties/ru_RU () -
LocalStrings.properties/default language.
, -
. , , 11.22,
Hello World! ,
. 11.20.

. 11.18. , 1
455

. 11.19. , 2

11.22. HelloWorldExample

helloworld.title=, !
requestinfo.title=
requestinfo.label.method=:
requestinfo.label.requesturi=URI :
requestinfo.label.protocol=:
requestinfo.label.pathinfo= :
requestinfo.label.remoteaddr= :

. 11.20. Hello World!

Request Info ,
(. 11.21).

. 11.21. Request Info


456 11

UTF-8 ( , ) -
HelloWorldExample.java,
RequestInfoExample.java . -
.
, Java
, 13.

11.4. JSP Java Server Pages



JSP Java Server Pages. , -
, JSP . JSP -
HTML- ,

.
NetBeans JSP Example JSTL Example (. . 11.10).

JSTL, -
, JSP, , Servlet, -
. , . . JSP -
, JSTL JSP. -
.
JSP Example JSP, ,
File/New Project.../Samples/Java Web/JSP
Example.

, NetBeans , . -
Clock2.java Web Pages/WEB-INF/jsp/applet.
Source Packages.

(JSTL Example) JSP,


JSP, .
, File/New Project.../
Samples/Java Web/JSTL Example. NetBeans -
, NetBeans 6.5 -
.
The Apache Software Foundation
(http://www.apache.org/),
http://www.apache.org/licenses/LICENSE-2.0.
JSP Example ( , -
- ).
,
Execute
JSP (. 11.22). Source -
457

HTML- . , -
, HTML-,
.

4
. 11.22. JSP

JSP HTML-, -
.jsp, .html .htm. HTML-,
-. HTML-
,
HTML- .
, ${1 + 2} -
3. \$ , ${...} , -
(. 11.23). JSP
, -
JSP (
).
JSP Java,
:
request . , javax.servlet.http.
HttpServletRequest;
response . ,
javax.servlet.http.HttpServletResponce;
458 11

. 11.23. JSP-

pageContext JSP.
(, ). javax.servlet.jsp.
PageContext;
session ( ). , -
javax.servlet.http.HttpSession;
application . ,
javax.servlet.ServletContext;
out . javax.servlet.jsp.JspWriter;
config .
, javax.servlet.ServletConfig;
page , .
Object.
JSP :
<%@ 1=1 2=2 ... %>
:
<%@ page session=true import="java.util.*" %>
( ) -
:
<%@ %>
Java .
459

:
<%
for(int i=0; i<table.getEntries().getRows(); i++) {
cal.Entry entr = table.getEntries().getEntry(i);
%>

, :
<%@ prefix="" uri=" " %>

:
< :>

Hello World Tag ( Web Pages/ jsp2/simpletag/hello.jsp).


JSP- JSP--
:
mytag :
<%@ taglib prefix="mytag" uri="/WEB-INF/jsp2/jsp2-example-taglib.tld" %>

:
<mytag:helloWorld/>

11.23 Java.

11.23. HelloWorldSimpleTag

public class HelloWorldSimpleTag extends SimpleTagSupport {


@Override
public void doTag() throws JspException, IOException {
getJspContext().getOut().write( "Hello, world!" );
}
}

- (handler) mytag.
Source Packages/jsp2.examples.simpletag/HelloWorldSimpleTag.java,
jsp2.examples.simpletag.HelloWorldSimpleTag.
.
JSP Example @Override
doTag() , ,
.
SimpleTagSupport ( javax.servlet.jsp.tagext.SimpleTagSupport) -
JSP.
mytag, prefix=" mytag ",
helloWorld jsp2-example-taglib.tld .
HelloWorldSimpleTag ( jsp2.examples.simpletag.
HelloWorldSimpleTag) helloWorld XML--
, 11.24.
460 11

11.24. XML- helloWorld

<tag>
<description>Outputs Hello, World</description>
<name>helloWorld</name>
<tag-class>jsp2.examples.simpletag.HelloWorldSimpleTag</tag-class>
<body-content>empty</body-content>
</tag>

, JSP , .
, JSP ,
, , ,
.

11.5. JSTL
JSP Standard Tag Library
JSP
JSTL JSP Standard Tag Library ( JSP).
, JSTL,
JSTL Example. File/New Project.../Samples/Java Web/JSTL
Example.
, JSP <:>.
out JSTL Example ( 11.25).

11.25. JSTL- out

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


<html>
<head>
<title>JSTL: Expression Language Support -- Expr Example</title>
</head>
<body bgcolor="#FFFFFF">

<h3><c:out></h3>

<table border="1">
<c:forEach var="customer" items="${customers}">
<tr>
<td><c:out value="${customer.lastName}"/></td>
<td><c:out value="${customer.phoneHome}" default="no home phone specified"/></td>
<td>
<c:out value="${customer.phoneCell}" escapeXml="false">
<font color="red">no cell phone specified</font>
</c:out>
</td>
461

</tr>
</c:forEach>
</table>

c ( customer ),
prefix="c", out, taglib -
http://java.sun.com/jsp/jstl/core. taglib
JSTL:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

, JSTL ( ,
) . out
org.apache.taglibs.standard.tag.el.core. Projects
Libraries, JSTL 1.1 standard.jar.
Examples
General-Purpose Tags.
, . 11.24.
"" (. 11.25).

. 11.24. General-Purpose Tags

. 11.25. c:out

(. 11.25) customer (),


Customer.java, org.apache.taglibs.standard.examples.beans,
. . Source Packages .
customers (), Customers.java,
.
462 11

customer lastName, phoneHome, phoneCell ., ,


. forEach (
out) customer, -
customers ( ). <c:out>
.
.
JSP JSTL ,
HTML-,
.
-
.

java.net , -
.
Web- ( URL, HttpURLConnection, URI, JarURLConnection, URLClassLoader),
IP- ( InetAddress, InetAddress4, InetAddress6, NetworkInterface), -
( Socket, SocketAddress, InetSocketAddress,
ServerSocket, SocketPermission). NetPermission, Authentificator
PasswordAuthentification (
).
. Java
, NetBeans
, .
EJB (Enterprise Java Beans)
Java EE (Enterprise Applications) -
Java-.
: Java -
, , -
,
.
Java -
.


HTML . () , -
, . , -
HTML, , -
, , (murkup tags).
, -
< >. .
463

() . -
-
, /.
, ,
(URL Uniform Recourses Location) :
. ,
, .
:
<a href="_">_</a>.

-
java.applet.Applet, , Swing / -
Sun JFC (Java Foundation Classes), - -
javax.swing.JApplet.
:
init, start, update, paint, getAppletInfo, stop, destroy.

@Override , , -
, . -
.
@Override, (,
),
.
Java, .

, javax.servlet -
JSP.
JSP HTML-
XML-, (),
Java.
.


HTML- NetBeans
Run Main Project.
, ,
, HTML-,
, (AppletViewer
; ; NetBeans -
).
GlassFish v2
( GlassFish v3 Tomcat Apache -
).
464 11

, , HTML-,
. HTML- AppletViewer .
HelloWorldExample.
. HelloWorldExample.java
, : , ,
(
). . -
Date GregorianCalendar ( , -
).
12

12.1.
JDK 1.2, Java ,
-
(nested) .
:
(static)
.
static. -
static.
, -
;
(non-static), , , (inner)
, (. .
).
,
.
(inner object), -
(outer object). -
:
(
), ( -
). , , . .
, -
;
(local)
. -
, -
. -
, . . -
, ""
. , -
466 12

, -
;
(anonimous) ( )
, . , -
(
). -
.

12.2. (static)



. 12.1
.

12.1.

class {

static class {

}

, -
.
, :
..,

:
..( ).

C1, C_nested.
, , :
C1.C_nested obj=new C1.C_nested();

,
, . -
. ,
, ,
.
12.2.
467

12.2.

class C1{
private C_nested obj1;

static class C_nested {



}

C_nested getNested(){
return obj1;
}
}


.class, :
$.class


.getClass().getName()

,
.toString().


.getClass().getCanonicalName()

.
(-
12.3).

12.3. ( )

class {

interface {

}

static.
, -
.
, .
468 12

12.3. (inner)
( )
, , static -
( 12.4).

12.4.

class {

class {

}

,

.
:
:
= new ();

:
. 1 =
.new ();

. 2 =
.new ();

. .
.
this
:
.this

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

, Java, JavaScript,
parent . ,
Java .
12.5.
469

12.5.

package java_gui_example;
public class OuterClass {
int a=5;
public OuterClass() {
}

public class InnerClass{


int x=1,y=1;

public class InnerClass2 {


int z=0;
InnerClass2(){
System.out.println("InnerClass2 object created");
}

void printParentClassNames(){
System.out.println("InnerClass.this.x="+
InnerClass.this.x);
System.out.println("OuterClass.this.a="+
OuterClass.this.a);
}
}

InnerClass inner1;
InnerClass.InnerClass2 inner2;

public void createInner() {


inner1=this.new InnerClass();
inner2=inner1.new InnerClass2();
System.out.println("inner1 name="+inner1.getClass().getName());
System.out.println("inner1 canonical name="+
inner1.getClass().getCanonicalName());
}
}

12.5 , OuterClass ( ).
InnerClass ( ).
OuterClass
:
OuterClass outer1=new OuterClass();

:
outer1.createInner();

:
outer1.inner2.printParentClassNames();
470 12

, , -
OuterClass,
InnerClass inner1=this.new InnerClass();

InnerClass.InnerClass2 inner2= inner1.new InnerClass2();

:
OuterClass.InnerClass inner3=outer1.new InnerClass();
OuterClass.InnerClass.InnerClass2 inner4=inner3.new InnerClass2();

InnerClass()

OuterClass.InnerClass.InnerClass2 inner4=
inner3.new OuterClass.InnerClass2();

!
,
, , -
, . -
, ,
, , ,
, , . -
.
(
), .
.
.
, - ,
, .
,
,
, ,
.
, -
.
, , .
"",
.
. ,
, . -
" "
Java. -
(inner class object). , -
. -
!
471

12.4. (local)
, ,
, ,
. 12.6 .

12.6.

class LocalClass1 {
public LocalClass1(){
System.out.println("LocalClass1 object created");
}
}
LocalClass1 local1=new LocalClass1();

(,
). , .

12.5. (anonimous)

()
-
. ,
.
new. -
, -
.
:
new ( ) {

}

, ,
, ,
Java .
"" (
) 12.7.

12.7.
""

addMouseMotionListener(
new java.awt.event.MouseMotionAdapter(){
public void mouseDragged(java.awt.event.MouseEvent e){
472 12

System.out.println("Mouse dragged at: x="+


e.getX()+" y="+e.getY()
);
}
}
);

12.6. (anonimous)
(listeners)
Java ( , -
) , -
(
). , .
-
, , , .
,
(, , -
jButton1 ).
Java , , -
(listeners) - .
Listeners, , -
.
:
java.awt, java.awt.event javax.swing.event.
java.awt:
java.awt.AWTEvent , .
java.awt.event:
ActionEvent ( , );
AdjustmentEvent ( -
);
ComponentEvent , (visibility)
( );
ContainerEvent - (- -
);
FocusEvent ;
HierarchyEvent (-
). , ,
( ) . .;
InputEvent .
(KeyEvent, MouseEvent);
473

InputMethodEvent . -
;
ItemEvent , , (item)
(selected) (deselected);
KeyEvent ;
MouseEvent ;
PaintEvent .
paint
update;
TextEvent , , -
;
WindowEvent (, , ,
, , ).
javax.swing.event.
- ,
event listener ( ) .
, ,
java.util.EventListener.
Listener.
, Java
(adapters) ,
-
.
, . -
:
ActionEvent ActionListener;
AdjustmentEvent AdjustmentListener;
ComponentEvent ComponentListener ComponentAdapter;
ContainerEvent ContainerListener ContainerAdapter;
FocusEvent FocusListener FocusAdapter;
HierarchyEvent HierarchyBoundsListener HierarchyBoundsAdapter;
InputEvent ;
InputMethodEvent InputMethodListener;
ItemEvent ItemListener;
KeyEvent KeyListener KeyAdapter;
MouseEvent MouseListener MouseAdapter:
MouseMotionListener MouseMotionAdapter (motion ). -
;
MouseWheelListener MouseWheelAdapter (wheel ).
;
474 12

PaintEvent ;
TextEvent TextListener;
WindowEvent WindowListener WindowAdapter:
WindowFocusListener. ;
WindowStateListener. .
Swing javax.swing.JComponent.
-
:
addComponentListener, addFocusListener . .

, , -
.
12.8 12.7 .

12.8. MouseDragged

addMouseMotionListener(
new java.awt.event.MouseMotionAdapter(){
public void mouseDragged(java.awt.event.MouseEvent e){
System.out.println("Mouse dragged at: x="+
e.getX()+" y="+e.getY()
);
}
}
);

addMouseMotionListener
java.awt.event.MouseMotionAdapter, mouseDragged.
MouseMotionListener :
mouseDragged(MouseEvent e);
mouseMoved(MouseEvent e).
mouseMoved, - -
MouseEvent ( ) -
.
mouseDragged - ,
( )
.
,
- (, jButton1). -
( , ) -
MouseMotion.
, , -
-
475

. , ( -
).
jPanel1 addMouseMotionListener
( this.addMouseMotionListener) jPanel1.addMouseMotionListener,
( this), . -
. , -
, ,
, , -
.
,
- MouseEvent.
, . -
. , -
. ,
- , -
, - .
, , ( )
. , MouseEvent c MouseListener
MouseAdapter, :
mouseClicked(MouseEvent e);
mouseEntered(MouseEvent e);
mouseExited(MouseEvent e);
mouseReleased(MouseEvent e).
- MouseAdapter -
MouseEvent. MouseMotionListener,
, .
, , , -
, .


Java , -
. -
:
(nested) -
. -
static. -
,
;
(inner) ,
(. .
). -
. , -
476 12

, static .
Java
( -
);
(local) -
. ,

. ,
Java -
( );
(, anonimous) , -
. , .
.
-
.
,
.
new. -
,
.
:
new ( ) {

}

Java , , ,
. ,
.
Java
Listeners (). , -
. -
, .
-
: java.awt, java.awt.event javax.swing.event.
, , -
( java.util.EventListener). -
, Java -
(adapters) , -
.
-
, .
, , .
477


.

.
-
.
-
new .

, , -
.
,
.
13


DesktopApplication
,
, (skeleton) DesktopApplication
,
NetBeans 6.5. . 2.16.
Java , .

13.1.
DesktopApplication
. 13.1 DesktopApplication1. , -
DesktopApplication DesktopApplication2
. .
.
META-INF.services, org.jdesktop.applica-
tion.Application (
desktopapplication1.DesktopApplication1, -
Application).
JDK 3, Java (service
providers ). (
) classPath,
.
classPath , Java-
. .
, ,
, . -
( META-INF.services, -
META-INF\services) ( ),
, . -
newInstance .
JDK 6 java.util.ServiceLoader.
DesktopApplication 479

. 13.1. DesktopApplication1

desktopapplication1 :
DesktopApplication1.java , DesktopApplication1. -
, ;
DesktopApplication1AboutBox.java , -
, Help/About.
(About Box);
DesktopApplication1View.java ,
.
desktopapplication1.resources 11.
desktopapplication1, -
, .
desktopapplication1.resources.busyicons -,
.

. ,
.
(,
) (jar-) Libraries (-
). Swing Application Framework, -
org.desktop.application org.jdesktop.swingworker,
JDK 1.6, Java (default).
480 13

13.2. DesktopApplication
DesktopApplication1 ( 13.1), , -
. SingleFrameApplication, -
. DesktopApplication,
DesktopApplication1, . . DesktopApplication2,
DesktopApplication3 . .

13.1. DesktopApplication1

/*
* DesktopApplication1.java
*/

package desktopapplication1;

import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;

/**
* The main class of the application.
*/
public class DesktopApplication1 extends SingleFrameApplication {

/**
* At startup create and show the main frame of the application.
*/
@Override protected void startup() {
show(new DesktopApplication1View(this));
}

/**
* This method is to initialize the specified window by injecting
* resources. Windows shown in our application come fully initialized
* from the GUI builder, so this additional configuration
* is not needed.
*/
@Override protected void configureWindow(java.awt.Window root) {
}

/**
* A convenient static getter for the application instance.
* @return the instance of DesktopApplication1
*/
public static DesktopApplication1 getApplication() {
return Application.getInstance(DesktopApplication1.class);
}

/**
* Main method launching the application.
*/
DesktopApplication 481

public static void main(String[] args) {


launch(DesktopApplication1.class, args);
}
}

, DesktopApplication1.
startup().
@Override protected void startup() {
show(new DesktopApplication1View(this));
}

Application -
( !),
launch, Application. -
.
, @Override , -
, . -
. @Override,
(,
),
.
configureWindow(Window root).
@Override protected void configureWindow(java.awt.Window root) {
}

. -
, . .
DesktopApplication1View.
Window, ,
.
getApplication().
public static DesktopApplication1 getApplication() {
return Application.getInstance(DesktopApplication1.class);
}

getApplication(), ,
- .
Application.
getInstance(DesktopApplication1.class), DesktopApplication1.
.
- , -, -
.
. ,
Application.getInstance
(DesktopApplication1.class),
-, getInstance.
482 13

, , -
-
getContext(). " "
. , getApplication()
-, getClipboard() -
, getFocusOwner() , ,
. . . 13.4.
- -
this? getApplication?
(, DesktopApplication1View)
-, .
Application getApplication. -
, -
(static), -
( ) ( ).
this DesktopApplication1View,
DesktopApplication1.
main.
public static void main(String[] args) {
launch(DesktopApplication1.class, args);
}

main, , -
. ,
- main .
-, DesktopApplication1, main
launch(DesktopApplication1.class, args). -
( . . 6.12),
args ( -
) , . . .

13.3.
DesktopApplicationView
DesktopApplication1View ( 13.2),
.
.

13.2. DesktopApplication1View

/*
* DesktopApplication1View.java
*/

package desktopapplication1;
DesktopApplication 483

import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;

/**
* The application's main frame.
*/
public class DesktopApplication1View extends FrameView {

public DesktopApplication1View(SingleFrameApplication app) {


super(app);

initComponents();

// status bar initialization message timeout, idle icon and


// busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout =
resourceMap.getInteger("StatusBar.messageTimeout");

messageTimer = new Timer(messageTimeout, new ActionListener() {

public void actionPerformed(ActionEvent e) {


statusMessageLabel.setText("");
}

});

messageTimer.setRepeats(false);
int busyAnimationRate =
resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] =
resourceMap.getIcon("StatusBar.busyIcons["+i+"]");
}

busyIconTimer= new Timer(busyAnimationRate, new ActionListener() {


public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});

idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
484 13

// connecting action tasks to status bar via TaskMonitor


TaskMonitor taskMonitor = new TaskMonitor(getApplication().
getContext());
taskMonitor.addPropertyChangeListener(new
java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String)(evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer)(evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
}

@Action
public void showAboutBox() {
if (aboutBox == null) {
JFrame mainFrame =
DesktopApplication1.getApplication().getMainFrame();
aboutBox = new DesktopApplication1AboutBox(mainFrame);
aboutBox.setLocationRelativeTo(mainFrame);
}
DesktopApplication1.getApplication().show(aboutBox);
}

/** This method is called from within the constructor to


* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
DesktopApplication 485

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
...
}// </editor-fold>

// Variables declaration do not modify


private javax.swing.JPanel mainPanel;
private javax.swing.JMenuBar menuBar;
private javax.swing.JProgressBar progressBar;
private javax.swing.JLabel statusAnimationLabel;
private javax.swing.JLabel statusMessageLabel;
private javax.swing.JPanel statusPanel;
// End of variables declaration

private final Timer messageTimer;


private final Timer busyIconTimer;
private final Icon idleIcon;
private final Icon[] busyIcons = new Icon[15];
private int busyIconIndex = 0;

private JDialog aboutBox;


}

DesktopApplication1View ,
(DesktopApplication1), ,
(. 13.413.6).
13.2 .
, :
import org.jdesktop.application.*;

,
, , ,
. , -
, -
.
DesktopApplication1View View,
Java . ,
, .
, DesktopApplication1View:
public DesktopApplication1View(SingleFrameApplication app) ;
public void showAboutBox() ( );
private void initComponents()
.
(), DesktopApplication1View:
private javax.swing.JPanel mainPanel . ,
;
486 13

private javax.swing.JMenuBar menuBar ;


private javax.swing.JPanel statusPanel .
, -
-
;
private javax.swing.JProgressBar progressBar .
, " ",
;
private javax.swing.JLabel statusAnimationLabel ,
, ;
private javax.swing.JLabel statusMessageLabel , -
, ;
private final Icon idleIcon , -
(idle ). (icon) -
. ,
, , -
;
private final Icon[] busyIcons = new Icon[15] ,
15 , -
( );
private int busyIconIndex = 0 ;
private final Timer messageTimer statusMessageLabel;
private final Timer busyIconTimer busyIcon ( ).

, ;
private JDialog aboutBox .
@SuppressWarnings("unchecked"), ,
, -
. -,
,
- - Look and Feel.

13.4. .


13.3 . -
.

13.3. DesktopApplication1View

public DesktopApplication1View(SingleFrameApplication app) {


super(app);
DesktopApplication 487

initComponents();

// status bar initialization message timeout, idle icon and busy


//animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout =
resourceMap.getInteger("StatusBar.messageTimeout");

messageTimer = new Timer( messageTimeout, new ActionListener() {

public void actionPerformed(ActionEvent e) {


statusMessageLabel.setText("");
}

});

messageTimer.setRepeats(false);
int busyAnimationRate =
resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] =resourceMap.getIcon("StatusBar.busyIcons["+i+"]");
}

busyIconTimer = new Timer( busyAnimationRate, new ActionListener() {


public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
}

DesktopApplication1View(...) -
- app, ,
SingleFrameApplication. ,
startup() :
show(new DesktopApplication1View(this));

, , .
initComponents() -
(
). resourceMap -
, src\desktopapplication1\DesktopApplication1.resources. -
DesktopApplication1.resources.
getResourceMap().
,
Java,
-, . -
-
() "-- " Model-View-Controller
(MVC).
488 13

getResourceMap() :
org.jdesktop.application.Application.getInstance().
getContext().getResourceMap()

, . . - -
:
app.getContext().getResourceMap()

getContext() -, -
-.
(shared objects), . . ,
. , (actions), (resources) (tasks).
- ,
. -

( )
. , ,
( ) ,
( ) .
,
,
(.), .
Java :
:
ResourceMap resourceMap = org.jdesktop.application.Application
.getInstance().getContext().getResourceMap();

:
ResourceMap resourceMap = org.jdesktop.application.Application.
getInstance().getContext().getResourceMap();

getResourceMap -
, . . ( ) -
:
ResourceMap resourceMap = org.jdesktop.application.Application.
getInstance().getContext().
getResourceMap(DesktopApplication1View.class);

getResourceMap()
DesktopApplication1, getResourceMap
(DesktopApplication1.class).
, Java map (-).
. ,
("-"), ,
PNG ( GIF).
DesktopApplication 489

("-") (properties),
:
DesktopApplication1 DesktopApplication1.properties;
DesktopApplication1View DesktopApplication1View.properties;
DesktopApplication1AboutBox DesktopApplication1AboutBox.properties.
() desktopapplication1.resources
, . -
, .
, . -
, NetBeans .
Java. -
,
New/Other/, Other/ Property File,
Finish.
, Property File,
New/Property File. ,
() NetBeans -
, , -
, .
messageTimeout (- ) -
, :
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");

resourceMap ResourceMap -
: getBoolean, getByte, getColor, getDouble, getFloat, getFont, getIcon,
getImageIcon, getInteger . . , -
.
(. . , ) -
, . ,
DesktopApplication1View (Default Language) ,
13.4.

13.4. DesktopApplication1View

# Resources for the ShellFrame class

# top-level menus

fileMenu.text = File
helpMenu.text = Help

# @Action resources

showAboutBox.Action.text = &About...
showAboutBox.Action.shortDescription = Show the application's information dialog
490 13

# status bar resources

StatusBar.messageTimeout = 5000
StatusBar.busyAnimationRate = 30
StatusBar.idleIcon = busyicons/idle-icon.png
StatusBar.busyIcons[0] = busyicons/busy-icon0.png
StatusBar.busyIcons[1] = busyicons/busy-icon1.png
StatusBar.busyIcons[2] = busyicons/busy-icon2.png
StatusBar.busyIcons[3] = busyicons/busy-icon3.png
StatusBar.busyIcons[4] = busyicons/busy-icon4.png
StatusBar.busyIcons[5] = busyicons/busy-icon5.png
StatusBar.busyIcons[6] = busyicons/busy-icon6.png
StatusBar.busyIcons[7] = busyicons/busy-icon7.png
StatusBar.busyIcons[8] = busyicons/busy-icon8.png
StatusBar.busyIcons[9] = busyicons/busy-icon9.png
StatusBar.busyIcons[10] = busyicons/busy-icon10.png
StatusBar.busyIcons[11] = busyicons/busy-icon11.png
StatusBar.busyIcons[12] = busyicons/busy-icon12.png
StatusBar.busyIcons[13] = busyicons/busy-icon13.png
StatusBar.busyIcons[14] = busyicons/busy-icon14.png

resourceMap - -
getIcon("...")
(: resourceMap.getIcon("StatusBar.idleIcon"))
-, .
13.4 ,
.
messageTimeout, ,
- messageTimer :
Timer(messageTimeout, new ActionListener(){... } )

(messageTimeout) , -
( ).
(new ActionListener()) .
-
Java . ,
. actionPerformed, ,
. statusMessageLabel.
messageTimer.setRepeats(false) ( )
( -
), .
busyAnimationRate
" " , .
30 ( ). 90,
.
, -
" ".
DesktopApplication 491

busyIconTimer -,
:
Timer(busyAnimationRate, new ActionListener() {...} )

- ActionListener, ,
busyIconTimer.
(, 0 14 1), -
statusAnimationLabel, JLabel.
statusAnimationLabel.setIcon.
, (Canvas) Swing ,
, . , -
, NetBeans ( ),
.
.

13.5. @Action
DesktopApplication1View -
showAboutBox , taskMonitor
( 13.5).

13.5. @Action

@Action public void showAboutBox() {


if (aboutBox == null) {
JFrame mainFrame =
DesktopApplication1.getApplication().getMainFrame();
aboutBox = new DesktopApplication1AboutBox(mainFrame);
aboutBox.setLocationRelativeTo(mainFrame);
}
DesktopApplication1.getApplication().show(aboutBox);
}

showAboutBox
@Action. , -
Action, . . actionPerformed - -
action (). ,
.
.
JDK 5, -
actionPerformed .
, -

, ,
. -
application.Application
application.ProxyActions, application.ApplicationActionMap
application.ApplicationAction.
492 13

, @Action, Properties -
(, ,
action -
). , -
null.
.
actionPerformed, .
aboutBox.
" " ,
aboutBox == null, , .
, .
DesktopApplication1AboutBox ( 13.6).

13.6. DesktopApplication1AboutBox

/*
* DesktopApplication1AboutBox.java
*/

package desktopapplication1;

import org.jdesktop.application.Action;

public class DesktopApplication1AboutBox extends javax.swing.JDialog {

public DesktopApplication1AboutBox(java.awt.Frame parent) {


super(parent);
initComponents();
getRootPane().setDefaultButton(closeButton);
}

@Action public void closeAboutBox() {


setVisible(false);
}

/** This method is called from within the constructor to


* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/

Generated Code

// Variables declaration do not modify


private javax.swing.JButton closeButton;
// End of variables declaration

DesktopApplication1AboutBox JDialog. -
, (Frame, View), -
DesktopApplication 493

(parent) ,
, , , -
( ).
-
, ( ,
).
closeButton, , -
(Default Button). , ,
<Enter> , -
.
setDefaultButton RootPane ( ),
getRootPane(). , -
, .
closeAboutBox() , .
.
showAboutBox DesktopApplication1View.

JFrame mainFrame = DesktopApplication1.getApplication().getMainFrame();

mainFrame, -
. (Main Frame).
, NetBeans -
-
( ).
( ) -
-
(variable) (field).

13.6. -.
TaskMonitor, Task
propertyChange
DesktopApplication1View.
taskMonitor,
TaskMonitor:
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());

-
(GUI).
Java
. (, )
, .
, .
494 13

. ,
, , -.
(, )
getModel.
setModel.

, - .
TaskMonitor ,
GUI ,
(background thread).
, -
( ApplicationContex),
( GUI), .
Task () -
( ) .
, (template).
, -
, .
.
Task -
:
doInBackground() ;
done() ;
finished() .
Task ,
doInBackground.
done ( final ).
done -
, -
:
succeeded ( ) ;
cancelled ( ) -
cancel(true);
interrupted () ;
failed () .
done, . .
, -
finished.
( doInBackground) -
:
setMessage(String message) ;
setProgress(float percentage) progress (
);
DesktopApplication 495

setProgress(float value, float min, float max) , -


: value, min max;
setProgress(int value, int min, int max) , int.
Task ,
.
, Save () -
. -
, DesktopApplication1View -
. , ,
, SaveTask
( 13.7).

13.7. SaveTask

private class SaveTask extends org.jdesktop.application.Task<Object, Void> {


SaveTask(org.jdesktop.application.Application app) {
// Runs on the EDT. Copy GUI state that
// doInBackground() depends on from parameters
// to SaveTask fields, here.
super(app);
}
@Override protected Object doInBackground() {
// Your Task's code here. This method runs
// on a background thread, so don't reference
// the Swing GUI from here.
return null; // return your result
}
@Override protected void succeeded(Object result) {
// Runs on the EDT. Update the GUI based on
// the result computed by doInBackground().
}
}

, ,
SaveTask ( ), .
, :
import org.jdesktop.application.Task;
import org.jdesktop.application.Application;

, SaveTask ( 13.8).

13.8. SaveTask

private class SaveTask extends Task<Object, Void> {

SaveTask(Application app) {
super(app);
}
496 13

@Override protected Object doInBackground() {


progressBar.setVisible(true);
try {
for(int i = 0; i < 10; i++) {
setMessage("Working... [" + i + "]");
Thread.sleep(150L);
setProgress(i, 0, 9);
}
Thread.sleep(150L);
} catch(InterruptedException ignore) { }
return null;
}

@Override protected void succeeded(Object result) {


// Runs on the EDT. Update the GUI based on
// the result computed by doInBackground().
}
}

SaveTask , . . static (. .
SaveTask -
). Task -
Object Void.
, Void
Task< Object, Void>
.
,
void.
doInBackground() ,
void. - Task -
, Void void.

doInBackground() -
Void,
return null. void, Void -
return, null Void.

SaveTask doInBackground(),
. @Override, , ,
,
.
for setMessage, Task,
: Working... (...) ,
. , -
message setMessage
propertyChange, ( -
). -
DesktopApplication 497

150 (0,15 ) Thread.sleep(150L).


try-catch, . . -
InterruptedException.
setProgress(i, 0, 9) progress (-
i) ( 0 9). ,
. -
, . -
.
finished() message setMessage.
, propertyChange -
.
propertyChange,
- taskMonitor. -
- , ,
( 13.9).

13.9. propertyChange

taskMonitor.addPropertyChangeListener(new
java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
//progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String)(evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer)(evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
498 13

propertyName ,
. "started",
"done", "message" "progress". equals -
-, :
if ("started".equals(propertyName))
...
if ("done".equals(propertyName))
...

. .
?
:
if (propertyName.equals("started"))
...
if (propertyName.equals("done"))
...

Java equals :
obj1 obj2,
obj2.equals(obj1) ,
obj1.equals(obj2)
, null;
obj1 null, obj2 () ,
obj2.equals(obj1),
equals obj1 NullPointerException ,
obj1==null.
, , "started" ().
, , -
. , busyIconTimer,
(!busyIconTimer.isRunning()),
( 0) . .
progressBar.setIndeterminate(true) -
.
progressBar.setIndeterminate(false), , -
. , -
-
, ().
, -
. -
, 13.9.
done (), . .
. busyIconTimer ,
statusAnimationLabel " ",
, progress 0 ( -
).
DesktopApplication 499

message (). , -
- getMessage(), -
. -
, -
(String)( evt.getNewValue() ). evt.getNewValue()
. Object,
String. , evt.getNewValue(),
, , -
evt.
,
evt.getOldValue().

propertyChanged
, message -
.

statusMessageLabel :
statusMessageLabel.setText((text == null) ? "" : text);

:
null, ;
( -
!), .
messageTimer.restart() (,
, ,
busyIconTimer).
, progress, -
DoNothing setProgress(i, 0, 9).

int value = (Integer)(evt.getNewValue())

-
evt.
, ,
Integer.
value (unboxing).
progressBar.setVisible(true) ,
progressBar.setIndeterminate(false)
(, , ?) -
progressBar.setValue(value).
File/Save , DVD (13_06_
DesktopApplication1), (. 13.2 13.3).
500 13

. 13.2. , i=4

. 13.3. , i=6

13.7. Task.

, -
. DesktopApplication -
.
DesktopApplication. File :
( ) Add From
Palette/Menu Item; Save ()
Exit ();
Set Action... (. 13.4).

. 13.4. . 1

, Action <none> ().


Create New
Action... ( ) . 13.5.
DesktopApplication 501

. 13.5. . 2

Action's Class desktopapplication1.


DesktopApplication1View (
desktopapplication1.DesktopApplication1), Action's Method (, -
), Background Task ( ) Attributes ()
(. 13.6).
Action's Method save, .
Background Task ( , -
) (. 13.6).
Attributes .
Text , (
).
Tool Tip .
Accelerator (. . 2.11).
: Small Icon... () Large Icon... ().
16 16 ( ) 32 32 -
(), NetBeans
.
502 13

. 13.6. . 3

OK Save() Task:
@Action
public Task save() {
return new SaveTask(getApplication());
}

, SaveTask,
. -
SaveTask.
, , -
.
. Swing Containers -
JToolBar. -
JButton Save
Set Action...,
Create New Action....
: save.png save24.png
Small Icon... Large Icon.... ,
Image Within Project (, -
DesktopApplication 503

) File,
Select... () . 13.7.

. 13.7.

, -
Import to Project.... ,
(deploy) .
,
.
13_07_DesktopApplication2
: , -
.
Copy () Paste ()
.
, , ,
.
, . ,
Swing , -
, .
Properties , icon (. 13.8). -
(. 13.9), ,
(. . 13.7), .
Define as a Resoure ( ),
.
Localized
, -
.
Key () , -
, ()
. .
504 13

. 13.8.

. 13.9. ,
DesktopApplication 505

Value () (
).
Scope ( ) ( )
.
-
, .
, . ,
( vm01810.jpg)
13_07_DesktopApplication3\src\desktopapplication1\resources.
(-
) ,
. 13.9 ( ,
, ).

13.8.
, Java
. , (-
), . -
. -
. DesktopApplication1.properties
(default language). 13.10.

13.10.
DesktopApplication1.properties

# Application global resources

Application.name = DesktopApplication1
Application.title = Basic Application Example
Application.version = 1.0
Application.vendor = Sun Microsystems, Inc.
Application.homepage = http\://appframework.dev.java.net
Application.description = A simple java desktop application based on Swing
Application Framework
Application.vendorId = Sun
Application.id = ${Application.name}
Application.lookAndFeel = system

(vendor), -
(homepage), (vendorID). -
, .
,
, ( JSP).
, lookAndFeel
.
506 13

, 13.11.

13.11. DesktopApplication1

# Application global resources

Application.name = DesktopApplication1
Application.title = Example of Localized Application
Application.version = 1.0
Application.vendor = Vadim V. Monakhov
Application.homepage = http\://barsic.spbu.ru/
Application.description = A simple localized java desktop application based on Swing
Application Framework
Application.vendorId = Monakhov
Application.id = ${Application.name}
Application.lookAndFeel = system

, , ,
.
desktopapplication1.resources
DesktopApplication1.properties .
Add Locale... ( ), -
ru_RU /
OK.
(-
13.12).

13.12. DesktopApplication1

# Application global resources

Application.name = DesktopApplication1
Application.title =
Application.version = 1.0
Application.vendor =
Application.homepage = http\://barsic.spbu.ru/
Application.description = ,
Swing Application Framework
Application.vendorId = Monakhov
Application.id = ${Application.name}
Application.lookAndFeel = system


, , -
.
DesktopApplication 507

,
. ,
. , -
.
DesktopApplication1Frame.properties .
13.13.

13.13. DesktopApplication1Frame

# Resources for the DesktopApplication1View class

# top-level menus

fileMenu.text = File
helpMenu.text = Help

# @Action resources

showAboutBox.Action.text = &About...
showAboutBox.Action.shortDescription = Show the application's information dialog

# status bar resources

StatusBar.messageTimeout = 5000
StatusBar.busyAnimationRate = 30
StatusBar.idleIcon = busyicons/idle-icon.png
StatusBar.busyIcons[0] = busyicons/busy-icon0.png
...1

jMenuItem1.text=Save

save.Action.text=Save

save.Action.shortDescription=Save file

jButton1.text=

save.Action.accelerator=ctrl pressed s

save.Action.largeIcon=save24.png

save.Action.smallIcon=save.png

save.Action.icon=save.png

...

1
, . 13.13 13.14
.
508 13

jLabel1.text=

#NOI18N
jLabel1.icon=vm01810.jpg

, -
13.14.

13.14. DesktopApplication1Frame

# Resources for the DesktopApplication1View class

# top-level menus

fileMenu.text =
helpMenu.text =

# @Action resources

showAboutBox.Action.text = & ...


showAboutBox.Action.shortDescription =

# status bar resources

StatusBar.messageTimeout = 5000
StatusBar.busyAnimationRate = 30
StatusBar.idleIcon = busyicons/idle-icon.png
StatusBar.busyIcons[0] = busyicons/busy-icon0.png
...

jMenuItem1.text=

save.Action.text=

save.Action.shortDescription=

jButton1.text=

save.Action.accelerator=ctrl pressed s

save.Action.largeIcon=save24.png

save.Action.smallIcon=save.png

save.Action.icon=save.png

...

jLabel1.text=

#NOI18N
jLabel1.icon=vm01810.jpg
DesktopApplication 509

& (),
, , About ( ). ,
, .
,
. ,
. , , .
Save, -
Working... . ?
doInBackground() DoNothing,
DesktopApplication1View,
DesktopApplication1View.
:
StatusBar.busyIcons[14] = busyicons/busy-icon14.png

:
StatusBar.Working = Working
StatusBar.Done = Done.

, :
StatusBar.Working =
StatusBar.Done = .

doInBackground() -
, ,
resourceMap. .

DesktopApplication1View, , . .
13.15 , 13.16.

13.15. resourceMap

public DesktopApplication1View () {
super(app);
initComponents();
// status bar initialization
ResourceMap resourceMap = getResourceMap();

13.16. resourceMap

ResourceMap resourceMap;

public DesktopApplication1View () {
super(app);
initComponents();
// status bar initialization
resourceMap = getResourceMap();
510 13

SaveTask
setMessage("Working... [" + i + "]");

setMessage(resourceMap.getString("StatusBar.Working")+"... [" + i + "]");


setMessage("Done.");

:
setMessage(resourceMap.getString("StatusBar.Done"));

13_08 _DesktopApplication2
, -
.
, . -
, , ,
. .
? !
, .
Java
Pascal. , C, C++, Basic JavaScript, -
, .
, .

13.9.

, -
.
, -:
Task<Object, Void> task;

,
:
SaveTask(org.jdesktop.application.Application app) {
super(app);
task=this;
}

, , , ,
:
long t=task.getExecutionDuration(java.util.concurrent.TimeUnit.SECONDS);

-
, , 13.17.
DesktopApplication 511

13.17.

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {


if (task==null){
System.out.println("t=0 , ");
return;
}

System.out.println("t=" + (float)task.getExecutionDuration(
java.util.concurrent.TimeUnit.MILLISECONDS)/1000 +" ");
}

null task.
,
NullPointerException
task.getExecutionDuration.
cancel,
org.jdesktop.swingworker.SwingWorker:
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
if (task!=null){
task.cancel(true);
}
}

13_09_DesktopApplication1
DVD.
( cancelled)
.

13.10.
lipboard


java.awt.datatransfer , , Clipboard -
.
: .

( 13_10_DesktopApplication1).
JTextArea ( , -
). 12,
.
doPaste() ( ). , -
.
13.18.
512 13

13.18.

import java.awt.Image; //vm


import javax.swing.ImageIcon;//vm
import java.awt.datatransfer.*; //vm
...

org.jdesktop.application.ApplicationContext appContext =
Application.getInstance(DesktopApplication1.class).getContext();
Clipboard clipboard = appContext.getClipboard();
Image img = null;
ImageIcon icon = null;

public void doPaste () {


System.out.println("do paste");
try{
Transferable clipData = clipboard.getContents(null);
if (clipData.isDataFlavorSupported(DataFlavor.stringFlavor)){
String s=(String)clipData.
getTransferData(DataFlavor.stringFlavor);
jTextArea1.replaceSelection(s);
}else
if (clipData.isDataFlavorSupported(DataFlavor.imageFlavor)){
img = (Image)clipData.
getTransferData(DataFlavor.imageFlavor);
if (img!=null){
icon = (ImageIcon)jLabel1.getIcon();
icon.setImage(img);
}
}
} catch(Exception e){
}
}

, , . -
clipboard, . ,
img () -
Image. Sun -
Image (
, ), Icon
ImageIcon ( ).
doPaste() System.out.println("do paste").
, -
.
try-catch getTransferData.
paste(),
try-catch, .
DesktopApplication 513

Transferable clipData = clipboard.getContents(null)


Java. clipboard.getContents
Object. , JDK, -
, null.
, -
, Image.
isDataFlavorSupported(DataFlavor flavor) ( ).
:
Data ;
Supported ;
Flavor "", "".
, DataFlavor.stringFlavor, ,
. DataFlavor.imageFlavor, .
:
String s=(String)clipData.getTransferData(DataFlavor.stringFlavor)

, -
clipData, .
, , getTransferData,
(Transfer "", "", "").
,
Object, .
String, Image.
jTextArea1.replaceSelection(s) ,
jTextArea1, , . , -
, .
, , -
, .
, -
Image ImageIcon. Image, , -
jLabel1.
:
-, :
icon = (ImageIcon)jLabel1.getIcon();

Image:
icon.setImage(img);

.
doPaste() , (-
, paste doInBackground()):
@Override
protected Object doInBackground() {
514 13

doPaste();
return null;
}

, JDK ,
, . -
.

.
StringSelection
. copyStringToClipboard()
( 13.19) copy.

13.19.

public void copyStringToClipboard() {


System.out.println("copyStringToClipboard ");
String s= jTextArea1.getSelectedText();
if (s==null)
return;
StringSelection clipData=new StringSelection(s);
clipboard.setContents(clipData,clipData);
}

( -
, , ).
s , -
jTextArea1. , .
, .
s StringSelection, -
setContents .
.
, clipboard.setContents(clipData,clipData) -
. ,
, .
copyStringToClipboard() doInBackground() copy ,
,
jTextArea1 . , ,
, Paste.


, copyStringToClipboard() -
? ?
.

: -
.
DesktopApplication 515

String, -
. :
copyStringToClipboard(jTextArea1.getSelectedText());

.
StringSelection, , -
.
Transferable ClipboardOwner.
public DataFlavor[] getTransferDataFlavors()
(flavors), . : DataFlavor.stringFlavor
, (deprecated) DataFlavor.
plainTextFlavor.
public boolean isDataFlavorSupported(DataFlavor flavor) ,
flavor.
, true, false. flavor==null, -
NullPointerException.
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException,
IOException Object
UnsupportedFlavorException , flavor
, StringSelection. IOException
StringSelection ,
- .
public void lostOwnership(Clipboard clipboard, Transferable contents) (
) ClipboardOwner (
). -
(shared) . , (-
cut). , StringSelection
.


. ImageSelection

( 13_10_DesktopApplication2), clipboardsupport,
ImageSelection, StringSelection,
, ( 13.20).

13.20. ImageSelection,

/*
* ImageSelection.java
*
* Created on 01.09.2007, 14:33:32
*/
516 13

package clipboardsupport;
/**
* @author Vadim Monakhov
*/

import java.awt.Image;
import java.awt.datatransfer.*;

/**
*
* A <code>Transferable</code> which implements the capability required
* to transfer an <code>Image</code>.
*
* This <code>Transferable</code> supports
* <code>DataFlavor.imageFlavor</code>
*
* @see java.awt.datatransfer.DataFlavor#imageFlavor
* @see java.awt.datatransfer.Transferable
*/
public class ImageSelection implements Transferable, ClipboardOwner {
private Image image;

/**
* Creates a <code>Transferable</code> capable of transferring
* the specified <code>Image</code>.
*/
public ImageSelection(Image image) {
this.image = image;
}

private static final DataFlavor[] flavors = {


DataFlavor.imageFlavor
}

/**
* Returns an array of flavors in which this
* <code>Transferable</code>
* can provide the data. <code>DataFlavor.imageFlavor</code>
* is the single properly supported flavor.
*
* @return an array of length one, whose element is
* <code>DataFlavor.imageFlavor</code>
*/
public DataFlavor[] getTransferDataFlavors() {
return flavors.clone();
}

/**
* Returns whether the requested flavor is supported
* @return <b>true</b> if <code>flavor</code> is equal to
* <code>DataFlavor.imageFlavor</code> otherwise <b>false</b>
* @throws NullPointerException if flavor is <code>null</code>
*/
DesktopApplication 517

public boolean isDataFlavorSupported(DataFlavor flavor) {


return flavor.equals(DataFlavor.imageFlavor);
}

/**
* Transfers image to the <code>Transferable</code>'s data format
* if the requested <code>flavor</code> is
* <code>DataFlavor.Image</code>.
* @param flavor the requested flavor for the data
* @return the data in the requested <code>DataFlavor.Image</code>
* flavor
* @throws UnsupportedFlavorException if the requested data flavor is
* not equivalent to <code>DataFlavor.Image</code>
* @throws NullPointerException if flavor is <code>null</code>
* @see java.awt.datatransfer.DataFlavor
*/
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException {
if (!flavor.equals(DataFlavor.imageFlavor)) {
throw new UnsupportedFlavorException(flavor);
}
return image;
}

/**
*Implements the only method of
* the <code>ClipboardOwner</code> interface.
*/
public void lostOwnership(Clipboard clipboard,Transferable contents){
}

,
JDK 6.

StringSelection, , .
getTransferDataFlavors() isDataFlavorSupported
(DataFlavor flavor).
getTransferDataFlavors() (static) flavors,
, :
private static final DataFlavor[] flavors = {
DataFlavor.imageFlavor
}

flavors (private) (final).

public DataFlavor[] getTransferDataFlavors() {


return flavors.clone();
}

.
518 13

. . , clone() .
.
, (-
):
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{DataFlavor.imageFlavor};
}

DataFlavor[].
?
-, ,
, , .
.
, .
:
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(DataFlavor.imageFlavor);
}

, : flavor.equals(DataFlavor.imageFlavor),
.
flavor==DataFlavor.imageFlavor,
flavor.equals(DataFlavor.imageFlavor)?
-.
flavor DataFlavor.imageFlavor, . -
-
equals.
, equals ?
, flavor.equals(DataFlavor.imageFlavor),
DataFlavor.imageFlavor.equals(flavor)? -
, -
flavor null. -
NullPointerException, false.
, , , -
isDataFlavorSupported StringSelection, -
. getTransferData.
, , -
. 13.6 , -
, null.
FileSelection -
, .
DesktopApplication1View copyImageToClipboard,
copyStringToClipboard ( 13.21).
DesktopApplication 519

13.21.

public void copyImageToClipboard(Image img) {


System.out.println("copyImageToClipboard");
if (img == null) {
return;
}
clipboardsupport.ImageSelection clipData =
new clipboardsupport.ImageSelection(img);
clipboard.setContents(clipData, clipData);
}

, jLabel1
( 13.22).

13.22.

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {


icon = (ImageIcon)jLabel1.getIcon();
img = icon.getImage();
copyImageToClipboard(img);
}

13.11.

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

.
-
.
ThreadedCalc, (-
13.23).

13.23. ThreadedCalc,

package desktopapplication1;

public class ThreadedCalc extends Thread{


520 13

double r=0;
Thread indicationThread =null;

/** Creates a new instance of ThreadedCalc */


public ThreadedCalc() {
super();
}

public void setIndicationThread(Thread indicationThread){


this.indicationThread=indicationThread;
System.out.println("indicationThread: "+indicationThread);
}

@Override
public void run(){
System.out.println("calcThread.run();");
for(int i=1;i<=10000000;i++)
r=Math.sin(r+1);
System.out.println("calcThread finished");
if (indicationThread!=null)
indicationThread.interrupt();
}
}

ThreadedCalc :
double r ;
Thread indicationThread -
, ( -
,
).
setIndicationThread(Thread indicationThread) ,
( ) ( -
). -
!

: "-
". ! , -
" ", . . -
-
.
. -
. , , Clipboard
Image, . Clipboard -
Transferable. Transferable DataFlavor
. .

run .
. 20 (
DesktopApplication 521

, ). 2
4 , , (
).
.
indicationThread.interrupt() .
indicationThread. - -
, , -
.
DesktopApplication1View. -
ActionPerformed (Paste) -
. ,
, .
( 13.24). , ,
ActionPerformed .
DesktopApplication1View calcThread ( , -
,
doInBackground).

13.24. ActionPerformed (Paste)


ThreadedCalc calcThread;

private void jButton3ActionPerformed (java.awt.event.ActionEvent evt) {


System.out.println("pasteToolBarButtonActionPerformed");
calcThread=new ThreadedCalc();
calcThread.start();
System.out.println("after calcThread.start()");
doPaste();
}

, -
calcThread. , -
. , -
.
.
doPaste(); , ,
(
, calcThread).
paste , -
ThreadedCalc .
PasteTask ( 13.25) SaveTask (. 13.8), -
. ,
.
522 13

13.25. PasteTask,

private class PasteTask extends Task<Object, Void> {

PasteTask(org.jdesktop.application.Application app) {
// Runs on the EDT. Copy GUI state that
// doInBackground() depends on from parameters
// to PasteTask fields, here.
super(app);
}

@Override
protected Object doInBackground() {
System.out.println("paste doInBackground");
calcThread.setIndicationThread(Thread.currentThread());
try {
for(int i = 0; i < 10; i++) {
setMessage(resourceMap.getString("StatusBar.Working") +
"... [" + i + "]");
Thread.sleep(350L);
setProgress(i, 0, 9);
}
Thread.sleep(150L);
} catch(InterruptedException e) {
System.out.println("catch InterruptedException");
}
return null;
}
protected void finished() {
setMessage(resourceMap.getString("StatusBar.Done"));
}

@Override
protected void succeeded(Object result) {
// Runs on the EDT. Update the GUI based on
// the result computed by doInBackground().
}
}

calcThread.setIndicationThread,
. ,
Thread.currentThread(). , -
, . . ,
doInBackground.
Thread.sleep(350L)
150 350 . ,
, .
DesktopApplication 523

, , InterruptedException,
,
interrupt(). , , -
. ,
. -
InterruptedException for, -
, null.

13_11_DesktopApplication1 DVD. ,
, -
, ,
.


NetBeans 6.5 DesktopApplication -
.
(statusBar)
, -
.
(progressBar) , -
"" , .
- , -
.
ApplicationContext -
getInstance().
" " -
. , getApplication()
-, getClipboard() -
, getFocusOwner() , .
(shared objects) ,
.
Java ,
(.), ,
, .
"-" (properties),
. (locale).
-
.
@Action , -
Action, . .
actionPerformed - action (). -
.
actionPerformed, .
524 13

Task -
, NetBeans.
Task () , -
doInBackground. -
done. done
,
:
succeeded ( ) ;
( ) -
cancelled
cancel(true);
interrupted () ;
failed () ;
() ,
finished
.
java.awt.datatransfer , , Clipboard
DataFlavor,
Transferable -
.

StringSelection, Transferable ClipboardOwner.
JDK , ,
. -
.
,
ImageSelection,
StringSelection, , .
-
, , .


-,
Application.getInstance(DesktopApplication1.class) getApplication(), -
, getContext().
, DesktopApplication getResourceMap
, , -
, ,
,
.

, .
( default, -
), , , .
DesktopApplication 525

obj1.equals(obj2) obj2.equals(obj1) -
.

13_08 _DesktopApplication1.
( cancelled)
13_09_DesktopApplication1.
copyStringToClipboard -
, . 13.10.
,
jLabel1.
14


NetBeans 6.5
Java ME (Java Micro Edition) , -
.

14.1. Java Micro Edition.


.
Java Micro Edition JDK , Java
Standard Edition Java Enterprise Edition. Java
Specification Request (JSR), (Configuration)
(Profile).
, :
;
;
, .
-
.
,
, .
Connected Limited Device Configuration (CLDC) -
(PDA) (512 -
) , , 16- . -
Java- Kilobyte Virtual Machine (KVM), -
, Java Native Interface (JNI),
Reflection, JIT-.
.
:
Mobile Information Device Profile (MIDP) -
. 160 , 96 54 ,
WWW HTTP 1.1;
527

PDA Profile (PDAP) PDA ( );


Information Module Profile 2.0 (IMP) .
Connected Device Configuration (CDC)
, - , 2 -
( ) 32- . Java-
Compact Virtual Machine (CVM),
JVM / javax.microedition.io.
:
Foundation Profile ;
Personal Basis Profile ;
Personal Profile ;
RMI Profile (Remote Methods Invocation Profile)
;
Game Profile .
MIDP ,
(MIDlets MID -
applet). ,
javax.microedition.midlet.MIDlet. jar- (
) jad (Java application
descriptor).
, -
.

14.2.

,
File/New Project..., Java ME (. 14.1).
:
Mobile Application MIDP;
Mobile Class Library ;
Mobile Project with Existing MIDP Sources
MIDP Java;
Import Wireless Toolkit Project NetBeans , -
Wireless Toolkit;
CDC Application CDC ;
CDC Class Library CDC;
Import CDC Pack 5.5 Project NetBeans , -
CDC Pack NetBeans 5.5;
528 14

. 14.1. ( 1)

Import CDC Toolkit Project ,


CDC Toolkit;
Mobile Designer Components Java
ME Netbeans.
(Mobile Application), Next >.
, (. 14.2). -
, Create Hello MIDlet
, : Hello,
World! (, !).

. 14.2. ( 2)
529

Finish, , -
. ,
. Java ME
Clean and Build, .
Next >, (. 14.3):
, ;
, ;
.

. 14.3.

NetBeans
(Toolkit) Sun Java(TM) Wireless Toolkit 2.5.2 ( -
Sun Java, 2.5.2).
(Device) :
DefaultColorPhone ;
DefaultGrayPhone - ;
MediaControlSkin ,
;
QwertyDevice / (,
).
, CLDC-1.1
MIDP-2.1.
NetBeans 5.5 , , ,
,
. -
NetBeans 6.0, .
Finish .
Flow (), -
530 14

. -
( Source, . 14.4, 14_2_MobileApplication1
DVD).
Screen () (. 14.5).

. 14.4. , Source

(. 14.6), -
:
Select one to launch: ( ).
, -
: HelloMIDlet.
Select (. 14.7) -
, Launch (), ,
:
Hello Hello, World!
Hello , "Hello,
World!" (. 14.8).
, Exit
(), .

( ),
.
dist, , ,
. jad- jar-. jad
Java Application Descriptor ( Java).
531

. 14.5. , Screen

. 14.6. , . 14.7.

532 14

. 14.8.

Select

jad-, NetBeans -
, 14.1.

14.1. jad-

MIDlet-1: HelloMIDlet, ,hello.HelloMIDlet


MIDlet-Jar-Size: 2066
MIDlet-Jar-URL: MobileApplication1.jar
MIDlet-Name: MobileApplication1
MIDlet-Vendor: Vendor
MIDlet-Version: 1.0
MicroEdition-Configuration: CLDC-1.1
MicroEdition-Profile: MIDP-2.1

, Vendor ,
MIDlet-Vendor: Vendor

:
MIDlet-Vendor: V.V.Monakhov

Application Descriptor (
jad-).
jad- ,
. Sony Ericsson jad-
, jar-.
533

14.3.

, , -
. -
, . ,
,
. ,
.
Source ( ) Screen ( )
Flow () Analyzer
() ,
, MIDP 1.0. Flow
Analyzer .

Source. , , -
, , ,
.
, . .
,
Screen ( ) (. 14.9).

. 14.9.
534 14

Hello, World! !, -
. , , ,
.
. -
-
. !, -
, .
Hello .
-
helloForm .
(. . 14.5):
Ticker . .
: Ticker, -
Add Ticker String
;
Title . Welcome. ;
Instance name . form.
;
Is Lazy Initialized ( ).
true ( ). , -
, , , ,
, .
,
. . -
, , . -

.
. -
Projects ,
Properties ( ),
Abilities () (. 14.10).
ScreenHeight ( ) ScreenWidth ( ) -
. , "-
", . 240 320 -
( -
, ).
.

, , .
Properties -
. , Application Descriptor , -
jad-, Build/Creating JAR jar- jad-
. .
535

. 14.10.

. 14.1 -
.

14.1.



( )
Alcatel OT E220, OT E225 80 102
Sony Ericsson J100i 96 64
Nokia 2310 96 68
Sagem My100x 101 64
Sagem MyC2-3, My201x 101 80
Voxtel RX11 120 64
Alcatel OT E801 128 128
Motorola W220
Nec E1101
Nokia 2610, 2626, 6020
Philips Xenium 9@9a,
Sagem My200C
Samsung GT-E1117, GT-E1410
Sony Ericsson J230i
536 14

14.1 ()



( )

Alcatel OT C560 128 160


Nokia 2330, 2605, 2608, 5200, 6060i, 6070, 6080, 6085, 6111, 6125, 7360
Philips Xenium 9@9d, Xenium 9@9f, 588
Sagem My401C
Samsung C240, C300, E250, E2510, X160, X210, X300, X510, X520,
X530, X630, X640, X680
Sony Ericsson K310i, K320i, K510i, W300i, Z310i, Z530i
Voxtel V350, 1iD

BenQ-Siemens C81 132 176


Siemens C75

Nokia N70, N72, N91, 3250 176 208

BenQ-Siemens S88 176 220


Motorola MOTOKRZR K1, MOTORAZR V3i, MOTORIZR Z3, MOTOSLVR L7e
Nec E949
Sagem My700x
Samsung E390, E500, E570, E780, U100, X820
Sony Ericsson F305, K550i, K610i, K750i, S302, W700i, W710i, W810i, Z550i,
Z610i, Z710i
Voxtel BD50, V700, VS600, VS800, RX600, 2iD, 3iD, W210

Nokia 5500, 6230i, 8800 208 208

BenQ-Siemens E71, EL71, EF81 240 320


Nokia E50, E61i, E63, E65, N71, N73, N85, N93, N93i, 5130, 5300, 6131,
6208c, 6233, 6280, 6288, 6290, 7100, 7373, 7390, 8800
Samsung D600, D830, D840, D900, E900, P310, U810
Sony Ericsson C510, G705, K790i, M600i, P990i, TM506, T700, W508, W705,
W715, W850i, W880i, W902, W950i
Voxtel W420, W740
Samsung A867 240 400
Samsung i770 320 320
Nokia 6260 320 480
Nokia N80 352 416
Nokia N97, 5800 360 640

, , .
(. 14.2).
537

14.2.


1 DataBinding DataSet ;
( IndexableDataSet ;

) ContactsDataSet

2 Dispayables Alert ;
(, ) Form ;
List ;
TextBox / ;
Login Screen ;
Splash Screen -;
Wait Screen ;
File Browser ;
PIM Browser
(PIM Personal Information Manager);
SMS Composer SMS-
3 Commands Back Command "";
() Cancel Command "";
Exit Command "";
Help Command "";
Item Command "" (, );
OK Command "OK";
Screen Command ;
Stop Command ""
4 Elements Choice Element (CheckBox);
() List Element ""
5 Items Choice Group ;
( ) Date Field ;
Gauge ( );
ImageItem ;
Spacer ;
String Item ();
Text Field ;
Table Item ""
6 Flow Entry Point ;
( If ;
)
Call Point ;
List Action ;
Previous Screen Action ;
Switch Case ;
Switch
538 14

14.2 ()


7 Resources Font ;
() Image ;
Ticker , ;
Simple Table Model ;
Simple Cancellable Task ,

8 SVG components SVG Menu Element ;


( SVG Menu Action SVG-;

) SVG Image ;
SVG Form ;
SVG Menu (SVG-);
SVG Player ;
SVG Splash Screen -
;
SVG Wait Screen
9 Custom ,
(, (, )

)

14.4. Hello, World!



.
. Hello, World!,
14.2 ( 14_4_MobileApplication1 ). -
, , -
. ,
(collapsed) , .
, , javax.microedition.
midlet.MIDlet. (Users Interface UI) -
javax.microedition.lcdui. lcdui
Liquid Cristal Device Users Interface ( -
).

14.2. Hello, World!

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
539

package hello;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
* @author V.V.Monakhov
*/
public class HelloMIDlet extends MIDlet implements CommandListener {

private boolean midletPaused = false;

//<editor-fold defaultstate="collapsed" desc=" Generated Fields ">


private Command exitCommand;
private Form form;
private StringItem stringItem;
//</editor-fold>

/**
* The HelloMIDlet constructor.
*/
public HelloMIDlet() {
}

//<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">


/**
* Initilizes the application.
* It is called only once when the MIDlet is started. The method
* is called before the <code>startMIDlet</code> method.
*/
private void initialize() {
// write pre-initialize user code here

// write post-initialize user code here


}
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">


/**
* Performs an action assigned to the Mobile Device MIDlet Started
* point.
*/
public void startMIDlet() {
// write pre-action user code here
switchDisplayable(null, getForm());
// write post-action user code here
}
//</editor-fold>
540 14

//<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">


/**
* Performs an action assigned to the Mobile Device
*/
public void resumeMIDlet() {
// write pre-action user code here

// write post-action user code here


}
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">


/**
* Switches a current displayable in a display. The <code>display</code> instance
is taken from <code>getDisplay</code> method. This method is used by all actions in the
design for switching displayable.
* @param alert the Alert which is temporarily set to the display; if
<code>null</code>, then <code>nextDisplayable</code> is set immediately
* @param nextDisplayable the Displayable to be set
*/
public void switchDisplayable(Alert alert,
Displayable nextDisplayable) {
// write pre-switch user code here
Display display = getDisplay();
if (alert == null) {
display.setCurrent(nextDisplayable);
} else {
display.setCurrent(alert, nextDisplayable);
}
// write post-switch user code here
}
//</editor-fold>

//<editor-fold defaultstate="collapsed"
desc=" Generated Method: commandAction for Displayables ">
/**
* Called by a system to indicated that a command has been invoked on a particular
displayable.
* @param command the Command that was invoked
* @param displayable the Displayable where the command was invoked
*/
public void commandAction(Command command, Displayable displayable) {
// write pre-action user code here
if (displayable == form) {
if (command == exitCommand) {
// write pre-action user code here
exitMIDlet();
// write post-action user code here
}
}
541

// write post-action user code here


}
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">


/**
* Returns an initiliazed instance of exitCommand component.
* @return the initialized component instance
*/
public Command getExitCommand() {
if (exitCommand == null) {
// write pre-init user code here
exitCommand = new Command("Exit", Command.EXIT, 0);
// write post-init user code here
}
return exitCommand;
}
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: form ">


/**
* Returns an initiliazed instance of form component.
* @return the initialized component instance
*/
public Form getForm() {
if (form == null) {
// write pre-init user code here
form = new Form("Welcome", new Item[] { getStringItem() });
form.addCommand(getExitCommand());
form.setCommandListener(this);
// write post-init user code here
}
return form;
}
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: stringItem ">


/**
* Returns an initiliazed instance of stringItem component.
* @return the initialized component instance
*/
public StringItem getStringItem() {
if (stringItem == null) {
// write pre-init user code here
stringItem = new StringItem("Hello", "Hello, World!");
// write post-init user code here
}
return stringItem;
}
//</editor-fold>
542 14

/**
* Returns a display instance.
* @return the display instance.
*/
public Display getDisplay () {
return Display.getDisplay(this);
}

/**
* Exits MIDlet.
*/
public void exitMIDlet() {
switchDisplayable (null, null);
destroyApp(true);
notifyDestroyed();
}

/**
* Called when MIDlet is started.
* Checks whether the MIDlet have been already started and
* initialize/starts or resumes the MIDlet.
*/
public void startApp() {
if (midletPaused) {
resumeMIDlet ();
} else {
initialize ();
startMIDlet ();
}
midletPaused = false;
}

/**
* Called when MIDlet is paused.
*/
public void pauseApp() {
midletPaused = true;
}

/**
* Called to signal the MIDlet to terminate.
* @param unconditional if true, then the MIDlet has to be unconditionally terminated
and all resources has to be released.
*/
public void destroyApp(boolean unconditional) {
}
}

, , -
.
543

:
public HelloMIDlet() {
}

, . ,
, (-
).
initialize() . -
( 14.3).

14.3. initialize()

private void initialize() {


//write pre-initialize user code here

//write post-initialize user code here


}

//write ... user code here ( )


, (
).
:
pre-initialize code , ;
post-initialize code , ;
pre-action code , , . .

startMIDlet()
( 14.4).

14.4. startMIDlet()

public void startMIDlet() {


// write pre-action user code here
switchDisplayable(null, getForm());
// write post-action user code here
}

getForm() . -
.
switchDisplayable(Alert alert, Displayable displayable) -
, displayable.
Alert() , -
( setTimeout) -
. alert null,
544 14

. witchDisplayable
.
resumeMIDlet() ( ) -
, (
). (-
14.5).

14.5. resumeMIDlet()

public void resumeMIDlet() {


// write pre-action user code here

// write post-action user code here


}

switchDisplayable ( ) -
display.setCurrent. -
, (pre-switch code), , -
(post-switch code) ( 14.6).

14.6. switchDisplayable

public void switchDisplayable(Alert alert, Displayable nextDisplayable) {


// write pre-switch user code here
Display display = getDisplay();
if (alert == null) {
display.setCurrent(nextDisplayable);
} else {
display.setCurrent(alert, nextDisplayable);
}
// write post-switch user code here
}

commandAction . -
, -
. helloForm,
exitCommand, (-
14.7).

14.7. commandAction

public void commandAction(Command command, Displayable displayable) {


// write global pre-action user code here
if (displayable == form) {
if (command == exitCommand) {
// write pre-action user code here
exitMIDlet();
545

// write post-action user code here


}
}
// write global post-action user code here
}

, , // write (),
, (
):
, (global pre-action code),
;
, (pre-action code);
, (post-action code);
, (global post-action code), -
.
exitCommand, exitMIDlet() ( ) -
. ,
, , 14.8.

14.8. ,

if (command == exitCommand) {
// write pre-action user code here
exitMIDlet();
// write post-action user code here
} else
if (command == 2) {
// write pre-action user code here
2;
// write post-action user code here
} else
if (command == 3) {
// write pre-action user code here
3;
// write post-action user code here
}

getExitCommand() getStringItem() . -
, .
Java, "" jn ++, , -

( !). -
. "" ,
,
, . ,
-
new.
546 14

getForm , -
( 14.9).

14.9. getForm

public Form getForm() {


if (form == null) {
// write pre-init user code here
form = new Form("Welcome", new Item[] { getStringItem() });
form.addCommand(getExitCommand());
form.setCommandListener(this);
// write post-init user code here
}
return form;
}

( form == null) -,
,
. ,
. ,
( -
).
getDisplay()
Display.getDisplay(this).
exitMIDlet ( 14.10).

14.10. exitMIDlet

public void exitMIDlet() {


switchDisplayable (null, null);
destroyApp(true);
notifyDestroyed();
}

(switchDisplayable(null, null);) -
null, , -
.
destroyApp(true); ,
, . , -
, , -
(. . ).
, . . -
.
, notifyDestroyed(); , -
.
( ), -
( 14.11). startApp -
547

( ), pauseApp , destroyApp
, .

14.11. ,

public void startApp() {


if (midletPaused) {
resumeMIDlet ();
} else {
initialize ();
startMIDlet ();
}
midletPaused = false;
}

public void pauseApp() {


midletPaused = true;
}

public void destroyApp(boolean unconditional) {


}

14.5. "-"
, .
, Hello, World!,
CrossesZeros.
HelloMidlet
CrossesZeros.
stringItem, -
Hello, World!.
Delete, .
Properties Title () -
<Enter> ( -
). -
<Enter>. .
Items (
form) TableItem () .
tableItem1 -
.
, <o table model
specified> ( ),
( ) .
(. 14.11)
<None>, . . , , . -
, Add, OK Cancel, , Rows
548 14

( ) Columns ( ) .
Add () .
(Add Row) (Add Column).

. 14.11.

, Use Header (
) .
10 ( ,
). -
<Enter> . -
<Enter>. , -
, -
.
exitCommand ( ) Assigned
Commands ( ) (. . 14.9), -
Commands Navigator ( . 14.5).
exitCommand,
Label () Exit (. 14.12).
.
(. 14.13), ,
Select.
.
14.12
549

,
. , -
.

. 14.12. exitCommand

14.12.

package hello;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import org.netbeans.microedition.lcdui.SimpleTableModel;
import org.netbeans.microedition.lcdui.TableItem;

public class CrossesZeros extends MIDlet implements CommandListener {

private boolean midletPaused = false;

private Command exitCommand;


private Form form;
private TableItem tableItem;
private SimpleTableModel tableModel1;
550 14

public CrossesZeros() {
}

private void initialize() {


// write pre-initialize user code here

// write post-initialize user code here


}

public void startMIDlet() {


// write pre-action user code here
switchDisplayable(null, getForm());
// write post-action user code here
}

public void resumeMIDlet() {


// write pre-action user code here

// write post-action user code here


}

public void switchDisplayable(Alert alert,


Displayable nextDisplayable) {
// write pre-switch user code here
Display display = getDisplay();
if (alert == null) {
display.setCurrent(nextDisplayable);
} else {
display.setCurrent(alert, nextDisplayable);
}
// write post-switch user code here
}

public void commandAction(Command command, Displayable displayable) {


// write pre-action user code here
if (displayable == form) {
if (command == exitCommand) {
// write pre-action user code here
exitMIDlet();
// write post-action user code here
}
}
// write post-action user code here
}

public Command getExitCommand() {


if (exitCommand == null) {
// write pre-init user code here
exitCommand = new
Command("\u0412\u044B\u0445\u043E\u0434", Command.EXIT, 0);
551

// write post-init user code here


}
return exitCommand;
}

public Form getForm() {


if (form == null) {
// write pre-init user code here
form = new Form("\u041F\u0440\u0438\u043C\u0435\u0440
\u043C\u0438\u0434\u043B\u0435\u0442\u0430",
new Item[] { getTableItem() });
form.addCommand(getExitCommand());
form.setCommandListener(this);
// write post-init user code here
}
return form;
}

public TableItem getTableItem() {


if (tableItem == null) {
// write pre-init user code here
tableItem = new TableItem(getDisplay(),
"\u041A\u0440\u0435\u0441\u0442\u0438\u043A\u0438-\u043D\u043E\u043B\u0438\u043A\u0438");
tableItem.setModel(getTableModel1());
// write post-init user code here
}
return tableItem;
}

public SimpleTableModel getTableModel1() {


if (tableModel1 == null) {
// write pre-init user code here
tableModel1 = new SimpleTableModel(new java.lang.String[][] {
new java.lang.String[] { " ", " ",
" " },
new java.lang.String[] { " ", " ",
" " },
new java.lang.String[] { " ", " ",
" " }}, null);
// write post-init user code here
}
return tableModel1;
}

public Display getDisplay() {


return Display.getDisplay(this);
}

public void exitMIDlet() {


switchDisplayable (null, null);
552 14

destroyApp(true);
notifyDestroyed();
}

public void startApp() {


if (midletPaused) {
resumeMIDlet ();
} else {
initialize ();
startMIDlet ();
}
midletPaused = false;
}

public void pauseApp() {


midletPaused = true;
}

public void destroyApp(boolean unconditional) {


}

. 14.13.


553

, -
TableItem, -
Unicode form
tableItem.
getTableItem() getForm()
getStringItem(). ,
.
( getTableModel1()).
.
,
.
.
getTableModel1()
getForm() getStringItem().
null, SimpleTableModel(),
. -
, .
new, -
, -
( ) ( 14.13).

14.13.

new String[][] {
new java.lang.String[] { " "," "," "},
new java.lang.String[] { " "," "," "},
new java.lang.String[] { " "," "," "}
}

, -
. , ,
null. -
, null,
NullPointerException.
.
,
( )
Select (. . 14.7). , , -
. .
setCrossAndZero ( ) -
. -
, ,
( ) :
public void setCrossAndZero() {

}
554 14

- setCrossAndZero ,
, ,
destroyApp (, , !). , -
DVD 14_5_CrossesZeros1.
, , -
,
.
, . -
Screen, -
Commands Item Command .
New/Add,
Navigator Assigned commands
. Navigator (. 14.14)
itemCommand.

. 14.14. itemCommand
Navigator

,
( form), -
Assigned Commands (-
) .
.
New/Add
.
(Assigned
Resources) Assigned Item Commands (
555

), itemCommand[tableItem] ( itemCommand
tableItem) (. 14.15).

. 14.15. Assigned
Resources

itemCommand ,
Label Item .
itemCommand -
Go to Source ( ), -
getItemCommand() (-
14.14).

14.14. getItemCommand()

public Command getItemCommand() {


if (itemCommand == null) {
// write pre-init user code here
itemCommand = new Command("\u0425\u043E\u0434\u0438\u0442\u044C",
Command.ITEM, 0);
// write post-init user code here
}
return itemCommand;
}

Java ME , (. . ,
) , , -
.
getItemCommand() -, TableItem,
.

.
, Select (. . 14.7) -
. (Screen), -
Default Command
( ) itemCommand1.
556 14

, ,
, , . . setCrossAndZero()
( ) , , -
. DVD 14_5_CrossesZeros2.

14.6. -
-
.
setCrossAndZero() -
( 14.15). -
.

14.15. commandAction

public void commandAction(Command command, Item item) {


// write pre-action user code here
if (item == tableItem) {
if (command == itemCommand) {
// write pre-action user code here

// write post-action user code here


setCrossAndZero();
}
}
// write post-action user code here
}

,
.
. CROSS (), ZERO
() EMPTY (), -
:
public String CROSS=" X ";
public String ZERO =" 0 ";
public String EMPTY=" ";
public int count=3;

count ( -)
. -
. ,
3 ( 2 count1) -
.
-, -
.
-,
4 4 5 5,
557

, ( -
, , ,
).
, -
-
. ,
private.
cellIsEmpty(int col, int row), ,
col row ( 14.16).

14.16. cellIsEmpty

public boolean cellIsEmpty(int col, int row) {


String s = (String) tableModel1.getValue(col, row);
if (s == EMPTY) {
return true;
} else {
return false;
}
}

, ,
, .
getValue(col, row),
( simpleTableModel1). Object, -
.
, .
. -
? NetBeans -


(. 14.16).

. 14.16. NetBeans

,
: Comparing Strings using == or != (
== !=). ,
558 14

, -.
if(s==EMPTY), if(s.equals(EMPTY)).
, . . Java , -
.
, - -
NetBeans .
tableIsFilled() , ,
( 14.17).

14.17. tableIsFilled()

public boolean tableIsFilled() {


String s;
boolean result = true;
check:
for (int col = 0; col < count; col++) {
for (int row = 0; row < count; row++) {
if (cellIsEmpty(col, row)) {
result = false;
break check;
}
}
}
return result;
}

( ) ,
- . , , -
check, , false. -
, true.
setZero() ( 14.18) -
. , .
, Java C- ,
void , .

14.18. setZero()

public void setZero() {


if (tableIsFilled()) {
return;
}
java.util.Random r = new java.util.Random();
int col = Math.abs(r.nextInt()) % 3;
int row = Math.abs(r.nextInt()) % 3;
if (cellIsEmpty(col, row)) {
tableModel1.setValue(col, row, ZERO);
return;
559

} else {
setZero();
}
}

, -
setZero(). , -
, . ,
, , .
, . -
,
. , 3 -
count. -
! , -
3 , .
setCross(int col, int row) ( 14.19) , -
, , , ,
.

14.19. setCross()

public void setCross(int col, int row) {


if (tableIsFilled()) {
return;
}
if (cellIsEmpty(col, row)) {
tableModel1.setValue(col, row, CROSS);
return;
}
}

rowIsFilled ( ) columnIsFilled ( )
( 14.20), mainDiagonalIsFilled ( )
auxiliaryDiagonalIsFilled ( ) ( 14.21)
. , , -
, ,
.

14.20. rowIsFilled columnIsFilled

public boolean rowIsFilled(int row, String symbol) {


String sCell;
for (int col = 0; col < count; col++) {
sCell = (String) tableModel1.getValue(col, row);
if (!sCell.equals(symbol)) {
return false;
}
}
560 14

return true;
}

public boolean columnIsFilled(int col, String symbol) {


String sCell;
for (int row = 0; row < count; row++) {
sCell = (String) tableModel1.getValue(col, row);
if (!sCell.equals(symbol)) {
return false;
}
}
return true;
}

anyRowIsFilled anyColumnIsFilled ( 14.21)


, , , -
() . ,
true, false.
mainDiagonalIsFilled auxiliaryDiagonalIsFilled ( 14.21) -
, (
) ( -
).
, , ,
, , .

14.21. anyRowIsFilled, anyColumnIsFilled,


mainDiagonalIsFilled auxiliaryDiagonalIsFilled

public boolean anyRowIsFilled(String symbol) {


for (int row = 0; row < count; row++) {
if (rowIsFilled(row, symbol)) {
return true;
}
}
return false;
}

public boolean anyColumnIsFilled(String symbol) {


for (int column = 0; column < count; column++) {
if (columnIsFilled(column, symbol)) {
return true;
}
}
return false;
}

public boolean mainDiagonalIsFilled(String symbol) {


String sCell;
for (int i = 0; i < count; i++) {
sCell = (String) tableModel1.getValue(i, i);
561

if (!sCell.equals(symbol)) {
return false;
}
}
return true;
}

public boolean auxiliaryDiagonalIsFilled(String symbol) {


String sCell;
for (int i = 0; i < count; i++) {
sCell = (String) tableModel1.getValue(i,count-1-i);
if (!sCell.equals(symbol)) {
return false;
}
}
return true;
}

winning ( 14.22) , , -
( CROSS ZERO) .

14.22. winning

public boolean winning(String symbol) {


if ( anyRowIsFilled(symbol) ||
anyColumnIsFilled(symbol) ||
mainDiagonalIsFilled(symbol) ||
auxiliaryDiagonalIsFilled(symbol)) {
return true;
}
return false;
}

"" setCrossAndZero -
. setCrossAndZero ( 14.23) setCross
, ( ,
), setZero
( , ).
.

14.23. setCrossAndZero()

public void setCrossAndZero() {


if (winning(CROSS) || winning(ZERO)) {
return;
}
int row = tableItem.getSelectedCellRow();
int col = tableItem.getSelectedCellColumn();
String s = (String) tableModel1.getValue(col, row);
562 14

if (cellIsEmpty(col, row)) {
setCross(col, row);
} else {
return;
}
if (winning(CROSS)) {
tableItem.setLabel(" !");
return;
}
setZero();
if (winning(ZERO)) {
tableItem.setLabel(" !");
}
}

, -
14_6_CrossesZeros1 DVD, .
, , ,
.
.
.
, . , TableItem repaint(), -
,
(protected).
. -
, repaint , , -
setBorders TableItem ( 14.24).

14.24. setBorders

public void setBorders(boolean showBorders) {


if (this.borders != showBorders) {
this.borders = showBorders;
repaint();
}
}

setBorders :
true, , false, -
.
repaint(). , , -
14.25. .

14.25. setZero()

public void setZero() {


if (tableIsFilled()) {
return;
}
563

java.util.Random r = new java.util.Random();


int col = Math.abs(r.nextInt()) % 3;
int row = Math.abs(r.nextInt()) % 3;
if (cellIsEmpty(col, row)) {
tableModel1.setValue(col, row, ZERO);
tableItem.setBorders(false);
tableItem.setBorders(true);

return;
} else {
setZero();
}
}

,
. . -
setBorders.
, , 14_6_CrossesZeros2.
, " ", -
.
- , .
, , -
, .

14.7. ,
TableItem,
.
" ", -
, TableItem. -
,
NetBeans Java Micro Edition.
, , ,
.
( )
.
TableItem. ,
, TableItem Java Micro Edition.
, , . . ,
. , -
, .
: File/ New
Project.../, Java ME, Mobile Class Library, -
Next >
MobileItemsLibrary.
564 14

Finish ,
.
itemspackage:
Default Package, New/Java Package... ,
itemspackage.
TableItemVM (
itemspackage, New/Java Class... -
, TableItemVM, Finish). -
VM Vadim Monakhov.
14.26.

14.26.

/*
* vmTableItem.java
*
*/

package itemspackage;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import org.netbeans.microedition.lcdui.*;

/**
*
* @author Vadim Monakhov
*/
public class TableItemVM extends TableItem {

public TableItemVM (Display display, String title, TableModel model) {


super(display, title, model);
}

public void repaintTable(){


super.repaint();
}
}

.
-, :
javax.microedition.midlet,
javax.microedition.lcdui
org.netbeans.microedition.lcdui,

TableItem -
(
).
565

, repaintTable(),
repaint(). repaint()
javax.microedition.lcdui.CustomItem , final
protected, . . ,
. - protected -
-.
(. . -
) - final. -
, ,
repaintTable().
, ,
(. 14.17).

. 14.17. -

, org.netbeans.
microedition.lcdui NetBeans, -
. , - , -
, , jar-, , -
.
Resources (-
), (. 14.18), Add
Library... ( ). NetBeans
MIDP Components Add Library (. 14.19).
, .
566 14

. 14.18. . 14.19.
1 2

, NetBeans, -
jar-, Add Jar/Zip...
.
, , -
NetBeans Tools/Libraries
. jar- -
Classpath, zip-
( ) Sources.
NetBeansProjects\MobileItemsLibrary\dist -
MobileItemsLibrary.jar, -
.
.
:
NetBeans , .
(
NetBeans )
NetBeans Tools/Libraries, New library...
(. 14.20) (MobileItemsLibrary).
, , Class Libraries,
OK. Library Manager
(. 14.21) MobileItemsLibrary, jar- -
.
Classpath Add JAR/Folder ( JAR/-
) jar- (,
C:\ Documents and Settings \User \ \NetBeansProjects \MobileItemsLibrary
\dist \MobileItemsLibrary.jar). Classpath,
OK, Library Manager.
( )
. -
.
567

. 14.20. NetBeans 1

. 14.21. NetBeans 2

.
NetBeans Tools/Palette/MIDP Visual Mobile
Designer. (. 14.22) ,
, Custom ( ).

!
Add to Palette... ( ), Add to
Palette wizard (. 14.23) ( Select
Project) MobileItemsLibrary Next >.
Add to Palette wizard
itempackage.TableItemVM (. 14.24).
Finish .

itemspackage
CrossesZeros (, ,
14_7_CrossesZeros1).
568 14

. 14.22. MIDP 1

. 14.23. MIDP 2

. 14.24. MIDP 3
569

,
Palette Manager Reset Palette ( ).
, Palette Manager
Tools/Palette/ Mobility Components.
(, )
Java ME (, MobileApplication1
14_7_CrossesZeros1)
Remove (. 14.25), .

. 14.25. MIDP

Palette Manager ( )
Custom TableItemVM (. 14.25). ,
Custom. -

( -
MobileItemsLibrary).
"-", .
, -
Hello "-
-" . - -
tableItem tableItemVM repaintTable()
setZero() ( 14.27).

14.27. setZero()

public void setZero() {


if (tableIsFilled()) {
return;
}
java.util.Random r = new java.util.Random();
570 14

int col = Math.abs(r.nextInt()) % 3;


int row = Math.abs(r.nextInt()) % 3;
if (cellIsEmpty(col, row)) {
tableModel1.setValue(col, row, ZERO);
tableItemVM.repaintTable();
return;
} else {
setZero();
}
}

, -,
tableItem tableItemVM, .
tableItem
-
tableItem tableItemVM. , -
, .
, , -
display parameter cannot be null. ,

getTableItemVM() new TableItemVM
getDisplay() null. display -
. . -
( ), -
( 14.28).

14.28.

public TableItemVM getTableItemVM() {


if (tableItemVM == null) {
// write pre-init user code here
/*
tableItemVM = new TableItemVM(null, null, null);
tableItemVM.addCommand(getItemCommand());
tableItemVM.setItemCommandListener(this);
tableItemVM.setDefaultCommand(getItemCommand());
tableItemVM.setLabel( "\u041A\u0440\u0435\u0441\u0442\u0438\u043A\u0438-
\u043D\u043E\u043B\u0438\u043A\u0438");
tableItemVM.setModel(getTableModel1());
// write post-init user code here
*/
tableItemVM = new TableItemVM(getDisplay(),
"\u041A\u0440\u0435\u0441\u0442\u0438\u043A\u0438-
\u043D\u043E\u043B\u0438\u043A\u0438",null);
tableItemVM.addCommand(getItemCommand());
tableItemVM.setItemCommandListener(this);
tableItemVM.setDefaultCommand(getItemCommand());
571

// tableItemVM.setLabel
tableItemVM.setModel(getTableModel1());
}
return tableItemVM;
}

, -
, . . -
. TableItemVM -
, null, .
, -
repaintTable() ( DVD 14_7_CrossesZeros2).
, . , -
,
( ,
).

14.8. "-"

Sony Ericsson. -
Java jar-, -
(jad- ).
Bluetooth
,
(. 14.26, ).
(. 14.26, ). "-" -
(. 14.26, ).
(
)
(. 14.27). -
. ( ).
, -
Bluetooth
. .
. 14.26 14.27 Java
Sony Ericsson K710i.
Samsung jad-
jar- , jad-
. jad- . ,
, flash-. ,
jad- : MIDlet-Jar-Size MIDlet-
Jar-URL, :
MIDlet-Jar-Size: 47592
MIDlet-Jar-URL: Applic1.jar
572 14


. 14.26. Sony Ericsson Bluetooth -

. 14.27.
Sony Ericsson

jad-.
Application Descriptor (
jad-).
, Java, -
WAP- , jad-, -
.
573

14.9.

Hello, World!. Screen, Navigator
Displayables ,
New/Add/List (. 14.28).

. 14.28. . 14.29.

list[List]
Elements List Element.
Screen Command ( )
(. 14.29).
Assigned Commands form[Form] Screen
Command[Command]. (Properties)
Action .
, .
Do Nothing ( ).
Switch to Displayable ( ),
list OK (. 14.30).
Assigned Commands list[List] Back Command (
),
form Do Nothing Switch to Displayable ( ).
. , Screen
Screen Command[Command] , -
( DVD 14_9_MobileApplication).
574 14

. 14.30.

14.10.
,
NetBeans
NetBeans 6.5
CLDC MIDP, (
) CDC.
NetBeans 6.5 Java ME .
File/New Project.../ (. 14.31) -
Samples/Java ME.
, , -
. .
Visual Designer Custom Components (
), (. 14.32):
Login Screen Example , -
;
SMS Composer Example SMS- ;

File Browser Example -


;
PIM Browser Example
( , ) . , PIM Personal Information
Manager.
.
Simple Game created with Game Builder ,
(. 14.33).
575

. 14.31.

. 14.32. . 14.33. Simple Game created


Visual Designer Custom Components with Game Builder
576 14

( GameDesign.java).
Game Builder -
, ( , -
).
Sun Samples Demos , -
Sun (. 14.34). , -
(. 14.35).
Audio Samples -
( -
!).
Advanced Multimedia Supplements .
, -
. 14.36
, , , -
" ", , ,
-
(. 14.37).

. 14.34. . 14.35. Properties


Sun Samples Demos Sun Samples Demos

, Java ME (. . 14.31),
Samples/Java ME (Rico SDK/J) Samples/Java ME (BD-J),
CDC- (SDK ). ,
NetBeans,
.
. ,
NetBeans 6.5 ,
.
577

. 14.36. . 14.37. Music Effects


Advanced Multimedia Supplements

NetBeans -
. . ,
, ! NetBeans
. ,
. ! ,
.


Java Micro Edition JDK -
Java Specification Request (JSR),
(Configuration) (Profile).
, :
;
;
, .
-
.
,
, :
Connected Limited Device Configuration (CLDC)
(PDA) (512
) . Mobile Information Device
Profile (MIDP) ;
578 14

Connected Device Configuration (CDC) "" -


, - ,
2 ( ) 32- .
MIDP -
, . , -
javax.microedition.midlet.MIDlet. jar-
( ) jad (Java
application descriptor).
, -
.
jad- jar-. jad Java
Application Descriptor ( Java).
commandAction . , -
.
//write ... user code here ( )
, ( -
).
- , ,
, jar-, , -
.
Sony Ericsson -
jar-, (jad-
).
Samsung
jad- jar- , jad-
. jad- -
: MIDlet-Jar-Size MIDlet-Jar-URL.
NetBeans 6.5 ,
.


,
, CDC.
, Java -
( ,
Java ""
).

.

14_9_MobileApplication: -
( Alert
).
15

,
(
).
-
, , -
, ,
.
JavaBeans -
Java. , Beans - -
"" ( Java
). JavaBeans
Beans.

15.1.
JavaBeans
JavaBeans Java .
JavaBeans Java
.
.
(Properties) ,

(Property Editor), ( , -
, ) . (
).
(Events) .
-
, (),
().
-
(serialization) Java
580 15

. -
.
JavaBeans () -
, , , , . -
.
JavaBeans -
. , -
(bean design patterns).
,
(. . 15.2).
,
(palette) (toolbox).

Design () ,
, ,
. .
NetBeans JavaBeans.
, -
.
BeanInfo,
.
BeanInfo, -
. , MyComponent MyComponentBeanInfo.
- SimpleBeanInfo BeanInfo.
, . NetBeans
.

(Property Editor). NetBeans
.

15.2.
NetBeans 6.5
NetBeans 6.5
(, Desktop Application),
File/New File.../JavaBeans Objects/JavaBeans Component Next >
(. 15.1).
(. 15.2) Class Name -
. MyBean.
(Package), -
(desktopapplication). Finish.
15.1 ( 15_2_DesktopApplication1
DVD).
581

. 15.1. JavaBeans ( 1)

. 15.2. JavaBeans ( 2)

15.1. NetBeans

package desktopapplication;

import java.beans.*;
import java.io.Serializable;
582 15

public class MyBean extends Object implements Serializable {

public static final String PROP_SAMPLE_PROPERTY = "sampleProperty";


private String sampleProperty;
private PropertyChangeSupport propertySupport;

public MyBean() {
propertySupport = new PropertyChangeSupport(this);
}

public String getSampleProperty() {


return sampleProperty;
}

public void setSampleProperty(String value) {


String oldValue = sampleProperty;
sampleProperty = value;
propertySupport.firePropertyChange(PROP_SAMPLE_PROPERTY,
oldValue, sampleProperty);
}
public void addPropertyChangeListener(
PropertyChangeListener listener) {
propertySupport.addPropertyChangeListener(listener);
}

public void removePropertyChangeListener(


PropertyChangeListener listener) {
propertySupport.removePropertyChangeListener(listener);
}
}

,
public class MyBean implements Serializable {

:
public class MyBean extends Object implements Serializable {

, , -
Object. , , Object
, , , JPanel.
sampleProperty.
public String getSampleProperty() , -
public void setSampleProperty(String value) .
private PropertyChangeSupport propertySupport -
PropertyChange. , "property change" -
" ".
.
, ,
( PropertyChange), -
583

(listeners). . -
fire (fire , "" ) -
-
, .
propertySupport.firePropertyChange. -
( ),
.
:
public void addPropertyChangeListener(PropertyChangeListener listener)

public void removePropertyChangeListener(PropertyChangeListener listener)

--
Property Change.

()
, . NetBeans 5.5
, NetBeans 6.0
, NetBeans 6.5 : -
, .


MyBean.java, Navigator
Members View ( )
Bean Patterns (Pattern ) . 15.3.

. 15.3. Navigator

BeanInfo, -

FeatureDescriptor ( ) ,
. NetBeans 6.5 BeanInfo -
Projects MyBean.java
BeanInfo Editor. (. 15.4)
, BeanInfo.
MyBeanBeanInfo.
Designer -
(. 15.5) 15_1_DesktopApplication2 -
DVD.
584 15

. 15.4. BeanInfo . 15.5.


BeanInfo

- , -
- ,
PropertyEditor ( ), -
. File/New File.../JavaBeans
Objects/Property Editor.
, , . . -
Sourse Design, -
Customizer.
File/New File.../JavaBeans Objects/ Customizer.

15.3.
NetBeans 6.5
,
(title). javax.swing.JPanel.
:
import javax.swing.*;

JPanel.
myBean JTitledPanel, sampleProperty
title, PROP_SAMPLE_PROPERTY ,
title firePropertyChange. getSampleProperty setSampleProperty -
getTitle setTitle.
, ,
@Override addPropertyChangeListener removePropertyChangeListener.
title, -
. title :
private String title;

, title, -
:
private String title = "";
585

java.awt.Graphics,
java.awt.geom.Rectangle2D (. ) JTitledPanel
paint ( 15.2).

15.2. paint

@Override
public void paint(Graphics g){
super.paint(g);
FontMetrics fontMetrics=g.getFontMetrics();
Rectangle2D rect = fontMetrics.getStringBounds(title, g);
g.drawString(title,
(int)Math.round((this.getWidth()-rect.getWidth())/2),
10);
}

Graphics, FontMetrics Rectangle2D, -


:
import java.awt.*;
import java.awt.geom.Rectangle2D;

, fontMetrics rect,
drawString :
g.drawString(title,
(int)Math.round( ( this.getWidth() -
g.getFontMetrics().getStringBounds(title,g).getWidth() )/2 ),
10);

,
.
repaint() -
setTitle. , -
.
, 15.3.

15.3. JTitledPanel

/*
* JTitledPanel.java8

*/

package desktopapplication;

import java.beans.*;
import java.io.Serializable;
import javax.swing.*; //
import java.awt.*; //
import java.awt.geom.Rectangle2D; //
586 15

/**
* @author .
*/
public class JTitledPanel extends JPanel implements Serializable {

private String title=""; //


private PropertyChangeSupport propertySupport;

public JTitledPanel() {
super();//
propertySupport = new PropertyChangeSupport(this);
}

public String getTitle() {


return title;
}

public void setTitle(String value) {


String oldValue = title;
title = value;
propertySupport.firePropertyChange("title", oldValue, title);
repaint(); //
}

@Override
public void addPropertyChangeListener(
PropertyChangeListener listener) {
propertySupport.addPropertyChangeListener(listener);
}

@Override
public void removePropertyChangeListener(
PropertyChangeListener listener){
propertySupport.removePropertyChangeListener(listener);
}

@Override
public void paint(Graphics g){ //
super.paint(g);
FontMetrics fontMetrics=g.getFontMetrics();
Rectangle2D rect = fontMetrics.getStringBounds(title, g);
g.drawString(title,(int)Math.round((this.getWidth() -
rect.getWidth())/2), 10);
}
}

, .
, JTitledPanel.java
, Tools Add to Palette.
, Projects JTitledPanel
Tools/Add to Palette...
587

,
( Beans, -
) (. 15.6). OK
.
(. 15.7),
15_3_DesktopApplication DVD.

. 15.6. , . 15.7.

, ,
. , -
"" ( , , java.awt.*
java.awt.geom.Rectangle2D) ( 15.4).

15.4. JTitledPanel

Graphics g=jTitledPanel1.getGraphics();
FontMetrics fontMetrics=g.getFontMetrics();
Rectangle2D rect = fontMetrics.getStringBounds("", g);
g.drawString("",10,30 );

, "", , "",
, -
"" -
, "" . , -
paint, .
-

( Build main project
<F11>), , -
( DesktopView), (-
, Projects).
NetBeans , -
<Shift>+<Ctrl>+<R>,
.
588 15

, ,
, -
. , , -
.
JTitledPanel.java ( -
Compile File), .

15.4.
JavaBeans : Bound (-
) Constrained ( ).
Bound ,
propertyChangeEvent.
Constrained -
. , -
.
VetoableChangeEvent. Vetoable Veto able
, .
, ( -
).
. titleShift
int, -
. , 15.5.

15.5. , titleShift

/**
* Holds value of property titleShift.
*/
private int titleShift;

/**
* Getter for property titleShift.
* @return Value of property titleShift.
*/
public int getTitleShift() {
return this.titleShift;
}

/**
* Setter for property titleShift.
* @param titleShift New value of property titleShift.
*/
public void setTitleShift(int titleShift) {
int oldTitleShift = this.titleShift;
this.titleShift = titleShift;
589

propertySupport.firePropertyChange ("titleShift",
new Integer (oldTitleShift),
new Integer (titleShift));
repaint();//
}

, ,
repaint().

Properties, ,
, ( DesktopView),
(, Projects).
15_4_DesktopApplication DVD
JTitledPanel titleShift.
, -
15.6.

15.6. ,

/**
* Holds value of property arr.
*/
private double[] arr;

/**
* Indexed getter for property arr.
* @param index Index of the property.
* @return Value of the property at <CODE>index</CODE>.
*/
public double getArr(int index) {
return this.arr[index];
}

/**
* Getter for property arr.
* @return Value of property arr.
*/
public double[] getArr() {
return this.arr;
}

/**
* Indexed setter for property arr.
* @param index Index of the property.
* @param arr New value of the property at <CODE>index</CODE>.
*/
public void setArr(int index, double arr) {
this.arr[index] = arr;
590 15

propertySupport.firePropertyChange ("arr", null, null );


}

/**
* Setter for property arr.
* @param arr New value of property arr.
*/
public void setArr(double[] arr) {
double[] oldArr = this.arr;
this.arr = arr;
propertySupport.firePropertyChange ("arr", oldArr, arr);
}

15.5.

JPanel,
.
, .
, , java.awt.event.TextEvent,
. JPanel , -
, , .
java.awt.event.TextListener textValueChanged(TextEvent e),
.

.
Java :
Unicast Event Source , -
-. Cast , Unit -
, Unicast Unit Cast , Source .
,
.
Multicast Event Source ,
-. Multi , Multicast
. -
.
, -
, Unicast Event Source . -
, .
, java.awt.event.TextEvent. -
java.awt.event.TextListener Unicast--
. 15.7.
591

15.7. TextListener Unicast-

/**
* Utility field holding the TextListener.
*/
private transient java.awt.event.TextListener textListener = null;

/**
* Registers TextListener to receive events.
* @param listener The listener to register.
*/
public synchronized void addTextListener(
java.awt.event.TextListener listener) throws
java.util.TooManyListenersException {
if (textListener != null) {
throw new java.util.TooManyListenersException ();
}
textListener = listener;
}

/**
* Removes TextListener from the list of listeners.
* @param listener The listener to remove.
*/
public synchronized void removeTextListener(
java.awt.event.TextListener listener) {
textListener = null;
}

fire- fireTextListenerTextValueChanged ,
15.7, ( 15.8).

15.8. , fire-

/**
* Notifies the registered listener about the event.
*
* @param object Parameter #1 of the <CODE>TextEvent<CODE> constructor.
* @param i Parameter #2 of the <CODE>TextEvent<CODE> constructor.
*/
private void fireTextListenerTextValueChanged(java.lang.Object object,int i){
if (textListener == null) return;
java.awt.event.TextEvent e = new java.awt.event.TextEvent (object, i);
textListener.textValueChanged (e);
}

, -
setTitle.
592 15

repaint() :
fireTextListenerTextValueChanged(this, java.awt.event.TextEvent.TEXT_VALUE_CHANGED);

fire- - ,
. , -
, java.awt.event.TextEvent,
<Ctrl>, -
.
:
java.awt.event.TextEvent e = new java.awt.event.TextEvent (object, i);

fireTextListenerTextValueChanged, , ,
- .
textValueChanged ,
jTitledPanel1[JTitledPanel]-Properties/Events (
) ,
DesktopView.java .
15_5_DesktopApplication1 .

textValueChanged , -
.
, .
jTitledPanel1 jTitledPanel1[JTitledPanel]-Properties
Events, textValueChanged (. 15.8). ,
,
. , . . .
, Add... (...) . 15.9. , -
: - ,
.
(event handler) myHandler
OK (. 15.9). Handlers- Handlers for
textValueChanged myHandler.
OK ( !) :
private void myHandler(java.awt.event.TextEvent evt) {
// TODO add your handling code here:
}

// TODO add your handling code here:, ,


, , :
javax.swing.JOptionPane.showMessageDialog( null,"Text="+
jTitledPanel1.getTitle() );

15_5_DesktopApplication2 .
593

. 15.8. . 15.9.

( 1) ( 2)


, -
(
).
.
, -
, , , -
.
JavaBeans Java :
JavaBeans
Java . -
.
(Properties) JavaBeans
,
(Property Editor), (-
, , ) . -
( ).
(Events) . -
-
, (-
), ().
594 15


NetBeans.
fire (fire , "-
" )
, .
addListener removeListener -
- -
.
NetBeans 6.5
, NetBeans 5.5, -
.
, -
, Tools Add to Palette..., -

Tools/Add to Palette... , -
( Beans,
).
-
Properties, ,
, (
DesktopApplivationView1), (,
Projects).
Bound . -
PropertyChange. Constrained -
.
, -
. VetoableChangeEvent.
. (
).
Java :
Unicast Event Source ,
-. -
, .
Multicast Event Source , -
-. -
.
fire-
.


-
java.awt.Graphics, java.awt.FontMetrics java.awt.geom.Rectangle2D.
595


repaint(), -
.
, -
, fire-,
.

JTitledPane, .
, titleColor.
:
Graphics g
g.setColor(Color.red).
,
TitleShiftEvent,
.
.
, titleFont
, .
16

-
C/C++ Pack
Java
.
, -
. Java , -
native (). ,
(. . -) -
, - -, .
JNI Java
Native Interface.
- Java,
C C++, -
(DLL Dynamic Link Library Windows,
Shared Objects UNIX- ).
, C C++, NetBeans C/C++
Pack.

16.1. .
- (native)

- Java :
native ( );

- -
,
:
System.loadLibrary();

, UNIX- -
lib. ,
Windows MyLib.dll, :
System.loadLibrary("MyLib");
- C/C++ Pack 597

UNIX Linux System.loadLibrary("MyLib")


libMyLib.so.
,
UnsatisfiedLinkError.
,
System.load ();

loadLibrary.
, -
- -
.
, -
, ++. JDK javah.exe, -
C++ Java. ,
ClassWithNativeMethod.
. ( 16.1).

16.1. native-

package java_example_pkg;
public class ClassWithNativeMethod {

/** Creates a new instance of ClassWithNativeMethod */


public ClassWithNativeMethod() {
}

public native void myNativeMethod();


}

16.2. JNI (Java Native Interface)


Java C/C++.
Java C++
JNI :
Java ( );
Java;
;
;
.

C++. Java -
.
598 16

C++ , Java,
C.
C/C++ -
( ). -
# -
( /* ).
:
#include (include ) ,

( , ).
#define (define )
-
. ,
( ).
#ifdef, #ifndef, #else, #endif (: , , -
, ifdef) . -

. ,
#ifdef __cplusplus
extern "C" {
#endif


extern "C" {

, __cplusplus. -
, . -
include-
, , .
, -
-
.

C++. ,
, #include, -
, , -
,
, .
C/C++ Java -
C C++ .
C/C++ * ( , !).
,
JNIEnv* env;

- env, , JNIEnv.
JNIEnv*. , ,
- C/C++ Pack 599

*, *env.
- dereferencing ( ),
"".
C++ C , -

JNIEnv *env;

, *env JNIEnv. -
, , ! -
, C++, C, -
C++, C.
C++ , Java,
new, . ,
, , .
* .
-, , -
, Java,
->, . , p->GetArrayLength().
, (,
, ).
, C C++
Java, . , -
; , . .
,
-
.
, C++ (header files, h-).
C++, -
( ).
cc cpp.
C++ ( -
) C++ -
Java.
javah.exe,
build\classes,
java_example_pkg META-INF.
. -
- (Far, Total Commander . .), -
Windows,
//
. Far ( ) -
<Ctrl>+<O>,
.
600 16

:
javah.exe java_example_pkg.ClassWithNativeMethod

, . .
. javah.exe , -
.
java_example_pkg_ClassWithNativeMethod.h -
( 16.2).

16.2. h-

/* DO NOT EDIT THIS FILE it is machine generated */


#include <jni.h>
/* Header for class java_example_pkg_ClassWithNativeMethod */

#ifndef _Included_java_example_pkg_ClassWithNativeMethod
#define _Included_java_example_pkg_ClassWithNativeMethod
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: java_example_pkg_ClassWithNativeMethod
* Method: myNativeMethod
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_java_1example_1pkg_ClassWithNativeMethod_myNativeMethod
(JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

Java_java_1example_1pkg_ClassWithNativeMethod_myNativeMethod(JNIEnv *, jobject),
C++, myNativeMethod()
Java.
C++ :
Java;
_;
( _ _1), -
java_1example_1pkg;
_;
, ClassWithNativeMethod;
_;
- , myNativeMethod.
- C/C++ Pack 601

JNIEnv * -
- , C++ Java
( , ).
, , jobject
, - . -
( ), -
jclass , -
- .
C++ , Java -
, C++ -
Java.
- , -
C++ . ,
public native int myNativeMethod(int i);

C++ :
(JNIEnv *, jobject, jint)

jint void.
. 16.1 Java C/C++.
C/C++ jdk1.6.0_11\include\jni.h.

16.1. Java C++

Java JNI (C++) JNI


boolean jboolean 1 ,
byte jbyte 1
char jchar 2 ,
short jshort 2
int jint 4
long jlong 8
float jfloat 4
double jdouble 8
void void
Object jobject
Class jclass Java
String jstring Java
jarray
Object[] jobjectArray
boolean[] jbooleanArray
byte[] jbyteArray ( 1 )
602 16

16.1 ()

Java JNI (C++) JNI


char[] jcharArray

short[] jshortArray

int[] jintArray

long[] jlongArray

float[] jfloatArray float

double[] jdoubleArray double

Throwable jthrowable

. 16.3 -
++, -
( ).

16.3. ++,

#include "java_example_pkg_ClassWithNativeMethod.h"
JNIEXPORT jint JNICALL Java_java_1example_1pkg_ClassWithNativeMethod_myNativeMethod
(JNIEnv *env, jobject obj, jint i ){
return i*i
};

, -
env ( . environment ). -
JNIEnv ( JNI) C++, -
, JNI . ,
, jintArray intArr,
:
jsize length=(*env)->GetArrayLength(env, intArr);

:
jint *intArrRef=(*env)->GetIntArrayElements(env, intArr,0);

intArr C++.
- :
(*env)->ReleaseIntArrayElements(env, intArr, intArrRef ,0);


:
GetBooleanArrayElements, GetByteArrayElements, GetDoubleArrayElements .
Java , -
C++. -
- C/C++ Pack 603

GetObjectArrayElement,
SetObjectArrayElement -
.
Java jstring s C++ :
const char *sRef=(*env)->GetStringUTFChars(env,s,0);

:
int s_len=strlen(sRef);

:
(*env)->ReleaseStringUTFChars(env,s,sRef);

.
native-
. ,
. -
Java.
native- , .
, native-, -
, .
JNI . -
, ,
, .
. , ,
( , ,
).

16.3. C/C++ Pack.


C++, C
NetBeans 6.5 C/C++ Pack, -
C/C++.
, Java.
C/C++:
;
;
;
.
C/C++ : File/New Project/
(. 16.1).
C/C++: NetBeans C/C++
, . -
NetBeans g++
GCC (GNU Compilers Collection).
604 16

. 16.1. C/C++

NetBeans , , -
-
(make.exe, gdb.exe, gcc.exe, g++.exe).
GCC Windows , . .
Linux. Cygwin (http://cygwin.com/) MinGW (http://mingw.org/),
GNU, GCC Windows
, -
.
Cygwin http://cygwin.com/
setup.exe, Download Without Installing (
), , -
( , setup.exe, -
). .
Use IE5 Settings ( -
Internet Explorer 5 ).
, ( , ).
. -
Devel ( Development ) :
gcc-g++:C++ Compiler;
gdb: The GNU Debugger;
make:The GNU version of the 'make' utility.
( gcc-
core:C Compiler) !
25 , .
, Fortran,
gcc-g77:Fortran Compiler;
- C/C++ Pack 605

NetBeans 6.5 ,
.
-
setup.exe
Install from Local Directory ( ), -
.
Cygwin C:\Cygwin,
, Cygwin
C:\Program files. , Cygwin
, -
(, ) . Mingw.
cygwin1.dll
C:\cygwin\bin WINDOWS\system32 ( , Windows XP).
, C:\cygwin\bin
( /, , ,
Path ;C:\cygwin\bin).
, http://www.
netbeans.org/community/releases/65/cpp-setup-instructions.html, NetBeans 6.5
:
Cygwin 1.5.21
Cygwin gcc-core (C compiler) 3.4.4
Cygwin gcc-c++ (C++ compiler) 3.4.4
Cygwin gdb (GNU Debugger) 6.8
Cygwin make 3.81
http://cygwin.com/
Cygwin
(1.5.25-14), NetBeans 6.5 . -
.
Cygwin ( ,
) (, Far)

gcc --version
g++ --version
make --version
gdb --version

, Far , -
<Ctrl>+<O>, .
MinGW ,
. http://sourceforge.net/project/showfiles.php?group_id=2435,
MinGW,
(Automated MinGW Installer).
MinGW-5.1.4.exe.
606 16

, -
(MinGW Base Tools), g++ compiler MinGW
Make. , Fortran, g77
Compiler.
18 . , MinGW -
gdb , http://sourceforge.net/project/
showfiles.php?group_id=2435
MinGW.
NetBeans Cygwin MinGW.
make Cygwin, g++
MinGW. : Cygwin,
MinGW.
Cygwin / MinGW -
NetBeans C/C++.
, Tools/Options, C/C++ (. 16.2).

. 16.2. C/C++

Build Tools Tool Collection ( )


. -
Add... ().
, -
Remove (), NetBeans, ,
- C/C++ Pack 607

. NetBeans 6.5 ,
Tool Collection . -
Cygwin.
. -
,
<Not Found> ( ). -
, .

Edit... -
(local host).
,
. , ,
, NetBeans
Cygwin. , NetBeans -
, : -
, Cygwin (
), dist\Release\MinGW-Windows,
dist\Release\ Cygwin-Windows. , . .
dist\Release .
, -
make.exe gdb.exe. , , Cygwin -
g++ MinGW. MinGW
make.exe Cygwin ( NetBeans) gdb
CygWin. .

. Code Assistance
C C++.
C++, C -
. , -
C++, include- -
.
, native-,
include include\win32 JDK (. 16.3).
:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
Cygwin : Cygwin\usr\include (
C:\Cygwin\usr\include). MinGW MinGW\include.

#include <iostream>

:
Cygwin\lib\gcc\i686-pc-cygwin\3.4.4\include\c++ ( MinGW MinGW\include\c++\3.4.5).
608 16

. 16.3. C/C++

iostream . -
iostream.h ( ), -
. -
, h.
,
#include <stdarg.h>
Cygwin\lib\gcc\i686-pc-cygwin\3.4.4\include.
, NetBeans
.
(. 16.4). Reset
Settings ( ) , -
.
.
,
C:\cygwin\usr\include

C:\cygwin\usr\include\w32api
: Up ()
Down ().
- C/C++ Pack 609

. 16.4. C/C++

C/C++ Pack: -
Build Clean ,
*** multiple target patterns.Stop.
build dist -
.

. - , NetBeans
include-, . ,
include- JDK, -
JNI. -
.
, -
++
Properties. ,
(. 16.5): ,
(Development Host), (Tool
Collection), / C, C++ Fortran (C Compiler
Requied ) . .
C/C++:
General ()
. ( UTF-8).
610 16

. 16.5. C/C++

Build, C++ Compiler (. 16.6), :


Include Directories include, ;
Preprocessor Definitions ;
Development Mode ( ) , . .
;
Warning Level ( ) -
;

. 16.6. C/C++ C/C++


- C/C++ Pack 611

Architecture () , 32- 64--


;
Tool () g++, -
;
Command Line ( ) .
Build, Linker () (. 16.7), :
Output () ( -
). lib (
library) dll ( Windows). (, -
) , -
, ,
Output;
Additional Options ( ) .
DLL, native-
, -Xlinker --add-stdcall-alias,

sdtcall.
Build, Packaging (tar, zip .),
, .
Run ; , -
; ; -
( ) .
Debug gdb.

. 16.7. C/C++ Linker


612 16

, ( Debug)
( Release)
,
( -
). -
( Development Mode, . 16.6) -
:
Fast Build ( );
Debug ( );
Performance Debug ( -
O);
Test Coverage ( );
Diagnosable Release ( O2);
Release ( O2);
Performance Release ( O3).
C/C++
include-, ,
. . Properties
, .
, .
( heap) NetBeans 128 .
100 -
. (. -
NetBeans C and C++ Development/Getting Started/Memory
Requirements).
, , C, C++, Fortran
, ,
Java.

16.4. C++ C
C++ -
make-, -
C/C++ . make-
make.exe,
. C/C++ NetBeans,
make.exe NetBeans
.
New
(. 16.8).
16.4 .
- C/C++ Pack 613

. 16.8. h- ()

16.4. NetBeans

/*
* File: newfile.h
* Author: V.V.Monakhov
*
* Created on 23 2009 ., 23:53
*/
#ifndef _NEWFILE_H
#define _NEWFILE_H
#endif
/* _NEWFILE_H */

(
Java ).
C/C++.
, , .
File/New Project/Samples/
"C/C++".
, C, File/New
Project.../Samples/ "C/C++"/Arguments.
, .
( )
( 16.5).

16.5. C/C++

/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
614 16

*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/

:
, GPL 2 (-
) CDDL ( -
) ;
, -
, Portions Copyrighted ( );
, NetBeans,
NetBeans Sun Microsystems.

, .
- C/C++ Pack 615

args.c
16.6.

16.6. args.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char**argv) {


int i;

// Prints arguments
printf("Arguments:\n");
for (i = 0; i < argc; i++) {
printf("%i: %s\n", i, argv[i]);
}

return 0;
}

File/New Project/Samples/ "C/C++"/ .


, Subproject Application (
). Hello, World!, C++. -
,
hello1lib, hello2lib, hello3lib hello4lib,
16.7.

16.7. Hello, World! DLL

#include <iostream >

#include "../hello1lib/hello1.h"
#include "../hello2lib/hello2.h"
#include "../hello3lib/hello3.h"
#include "../hello4lib/hello4.h"

int main(int argc, char**argv) {


// Print welcome messages...
cout << "Hello from main...\n";
cout << hello1();
cout << hello2();
cout << hello3();
cout << hello4();

// Prints arguments...
if (argc > 1) {
cout << "\nArguments:\n";
616 16

for (int i = 1; i < argc; i++) {


cout << i << ": " << argv[i] << "\n";
}
}

return 0;
}

.
16.8 hello1.h, 16.9
hello1.cc.

16.8. hello1.h

#ifndef _hello1_H
#define _hello1_H

extern char *hello1();

#endif /* _hello1_H */

16.9. hello1.cc

#include "hello1.h"

char *hello1() {
return (char*)"Hello from hello1...\n";
}

NetBeans 6.5 Samples | C/C++


, C C++. , ,
Java,
, C C++.
C/C++
, -
NetBeans Fortran, NetBeans
.

16.5. native-
native-. -
:
1. Java native-.
2. h- C++, .
3. C++ , -
h-.
4. C++ (DLL).
- C/C++ Pack 617

5. DLL NetBeans.
6. DLL.
native-, -
double. , native-
.
DesktopApplication, -
native-.
<build-classes>
classes, -
, :
C:\Documents and Settings\User\ \NetBeansProjects\16_5_JNI_example1\
build\classes.

. Java
native-
Source Packages jnipackage,
Multiply ( 16.10).

16.10. Multiply native-

package jnipackage;
public class Multiply {

static {
System.loadLibrary("CPP_MultiplyLibrary");
}

public static native double getJniProduct(double a, double b);


}

CPP_MultiplyLibrary.dll , . . -
. Native- getJniProduct -
, , C++,
DLL.
DVD 16_5_JNI_example1.

. h- C++,

javah.exe, -
<build-classes>.
Far.
Windows,
( <Ctrl>+<O> -
618 16

). -
(Total Commander, Windows Commander . .).
<build-classes> -
jniexample, jnipackage,
native-, META-INF.

"C:\Program Files\Java\jdk1.6.0_11\bin\javah.exe" jnipackage.Multiply

C:\Program Files\Java\jdk1.6.0_11\bin
javah.exe ( java.exe jar-),
. : -
/// / , -
Path () :
C:\Program Files\Java\jdk1.6.0_11\bin

h- :
javah jnipackage.Multiply

javah.exe jnipackage.Multiply classes


jnipackage_Multiply.h. , NetBeans -
( ).
:
classes, (
jnipackage), class (
Multiply.class);
/ \ :
jnipackage.Multiply ( jnipackage/Multiply jnipackage\Multiply).
javah.exe h-
C++ ( 16.11).

16.11. jnipackage_Multiply.h

/* DO NOT EDIT THIS FILE it is machine generated */


#include <jni.h>
/* Header for class jnipackage_Multiply */

#ifndef _Included_jnipackage_Multiply
#define _Included_jnipackage_Multiply
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: jnipackage_Multiply
* Method: getJniProduct
* Signature: (DD)D
*/
- C/C++ Pack 619

JNIEXPORT jdouble JNICALL Java_jnipackage_Multiply_getJniProduct


(JNIEnv *, jclass, jdouble, jdouble);

#ifdef __cplusplus
}
#endif
#endif

. C++ ,

jnipackage_JniMultiply.h
, .
File/New Project...,
C/C++, Projects C/C++ Dynamic
Library ( C/C++). Next>, -
CPP_MultiplyLibrary Finish.
CPP_MultiplyLibrary Header Files -
, Add Existing Item...
( ).
h- ( ). -

, Select
.
, .
Source Files
( C/C++) New/Empty C++ File... (/
C++). : jnipackage_Multiply.
C++ ,
( 16.12).

16.12. jnipackage_Multiply.cc

#include "jnipackage_Multiply.h"
JNIEXPORT jdouble JNICALL Java_jnipackage_Multiply_getJniProduct (
JNIEnv * env, jclass cls, jdouble a, jdouble b) {
return a*b;
}

DVD 16_5_CPP_ex1_Cygwin 16_5_CPP_


ex1_MinGW. Cygwin, -
MinGW ( make.exe
Cygwin).
620 16

. C++
(DLL)
DLL NetBeans, -
(. . 16.3).
Build/C++ Compiler include-.
Cygwin:
C:/Program Files/Java/jdk1.6.0_11/include/win32
C:/Program Files/Java/jdk1.6.0_11/include
C:/cygwin/usr/include/mingw
MinGW:
C:/Program Files/Java/jdk1.6.0_11/include/win32
C:/Program Files/Java/jdk1.6.0_11/include
-Xlinker --add-stdcall-alias Additional Options
(Linker) .

Debug Release: .
NetBeans DLL :
Cygwin:
dist\Release\Cygwin-Windows Release,
dist\Debug\Cygwin-Windows Debug;
MinGW:
dist\Release\ MinGW-Windows Release,
dist\Debug\ MinGW-Windows Debug.
, , ,
, .
. ,
NetBeans,
, -
.
Java.
DLL DLL:
, . -
Dependency Walker ( -
), http://www.dependencywalker.com/.
Win32 GCC MinGW
:
C:\MinGW\bin\g++ -I"C:\Program Files\Java\jdk1.6.0_11\include" -I"C:\Program
Files\Java\jdk1.6.0_11\include\win32" -O3 jnipackage_Multiply.cc -shared -o
CPP_MultiplyLibrary.dll -Xlinker --add-stdcall-alias
- C/C++ Pack 621

Cygwin DLL
.
C++-
CPP_MultiplyLibrary.dll.

.
DLL NetBeans
DLL (NetBeansProjects\16.5_JNI_example1). -
16.5_JNI_example1, -
, ( -
).

.
DLL
DLL dist (, jar- ),
NetBeansProjects\16.5_JNI_example1\dist.
dist , -
.
jar- . , ,
JRE (, JDK).
Windows
DLL, system32.
C:\WINDOWS\system32. DLL
jar- .
16.5_JNI_example2 DVD
native-. .
Main 16.13.

16.13. example.Main

package example;

public class Main {

public static String matrixToString(double[][] M) {


String s = "";
for (int i = 0; i < M.length; i++) {
for (int j = 0; j < M[0].length; j++) {
s = s + M[i][j] + "\t";
}
s = s + "\n";
}
return s;
}
622 16

/**
* @param args the command line arguments
*/
public static void main(String[] args) {

System.out.println("Product of 2.5 and 4 is: " +


Multiply.getProduct(2.5, 4) + "\n");

double A[][] = {{1, 2, 3}, {4, 5, 6}};


double B[][] = {{1, 2}, {3, 4}, {5, 6}};
double C[][] = Multiply.getProduct(A, B);
System.out.println("Matrix A: \n" + matrixToString(A));
System.out.println("Matrix B: \n" + matrixToString(B));
if (C != null) {
System.out.println("Product of A and B is:\n" +
matrixToString(C));
} else {
System.out.println("Cannot multiply A and B!\n");
}
}
}

matrixToString :
, . -
,
.

16.14 Multiply, native-.

16.14. Multiply native-

package example;
public class Multiply {
static {System.loadLibrary("CPP_MultiplyLibrary2");}
public static native double getProduct(double A, double B);
public static native double[][] getProduct(double[][] A,double[][] B);
}

h- , classes, , :
D:\Util\Java\jdk1.6.0_11\bin\javah.exe example.Multiply
example_Multiply.h 16.15.

16.15. example_Multiply.h

/* DO NOT EDIT THIS FILE it is machine generated */


#include <jni.h>
/* Header for class example_Multiply */
- C/C++ Pack 623

#ifndef _Included_example_Multiply
#define _Included_example_Multiply
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: example_Multiply
* Method: getProduct
* Signature: (DD)D
*/
JNIEXPORT jdouble JNICALL Java_example_Multiply_getProduct__DD
(JNIEnv *, jclass, jdouble, jdouble);

/*
* Class: example_Multiply
* Method: getProduct
* Signature: ([[D[[D)[[D
*/
JNIEXPORT jobjectArray JNICALL
Java_example_Multiply_getProduct___3_3D_3_3D
( JNIEnv *, jclass, jobjectArray, jobjectArray);

#ifdef __cplusplus
}
#endif
#endif

example_Multiply.cc,
C++ ( 16.16), 16_5_CPP_ex2_Cygwin
16_5_CPP_ex2_MinGW DVD.

16.16. example_Multiply.cc

#include "example_Multiply.h"

JNIEXPORT jdouble JNICALL Java_example_Multiply_getProduct__DD


(JNIEnv * env, jclass cls, jdouble a, jdouble b)
{
return a*b;
}

// Java C++
void jMatrix2cMatrix(JNIEnv * env, jobjectArray jM, int r, int c, double* M){
double* X = M;
for (int i = 0;i < r;i++){
jdoubleArray jrow =
reinterpret_cast<jdoubleArray>(env->GetObjectArrayElement(jM,i));
env->GetDoubleArrayRegion(jrow, 0, c, X);
X+=c;
}
}
624 16

// Java c rows cols


// C++
jobjectArray cMatrix2jMatrix(JNIEnv* env, double* C, int rows, int cols)
{
jdoubleArray row = env->NewDoubleArray(cols);
jclass cls = env->GetObjectClass(row);
jobjectArray jC = (jobjectArray)env->NewObjectArray(rows, cls, row);
for (int i = 0;i < rows;i++){
row = env->NewDoubleArray(cols);
env->SetDoubleArrayRegion(row, 0, cols, C);
env->SetObjectArrayElement(jC, i, row);
C += cols;
}
return jC;
}

JNIEXPORT jobjectArray JNICALL


Java_example_Multiply_getProduct___3_3D_3_3D
(JNIEnv * env, jclass cls, jobjectArray jA, jobjectArray jB) {
// jA jB ,
// . Java
// .
// jobjectArray, //jdoubleArray

// A
int rowsA = env->GetArrayLength(jA);
if (rowsA < 1) return NULL;

// A
jdoubleArray jrow =
reinterpret_cast<jdoubleArray>(env->GetObjectArrayElement(jA,0));
int colsA = env->GetArrayLength(jrow);
if (colsA < 1) return NULL;

// B
int rowsB = env->GetArrayLength(jB);
if (rowsB < 1) return NULL;

// B
jrow = reinterpret_cast<jdoubleArray>(env->GetObjectArrayElement(jB,0));
int colsB = env->GetArrayLength(jrow);
if (colsB < 1) return NULL;

//
if (colsA != rowsB) return NULL;

// ( )
// C++ ,
//
double* A = new double[rowsA*colsA];
- C/C++ Pack 625

jMatrix2cMatrix(env, jA, rowsA, colsA, A);


double* B = new double[rowsB*colsB];
jMatrix2cMatrix(env, jB, rowsB, colsB, B);
double* C = new double[rowsA*colsB];

//
for (int i = 0;i < rowsA;i++){
for (int j = 0;j < colsB;j++){
double d = 0;
for (int k = 0;k < colsA;k++)
d += A[i*colsA + k]*B[k*colsB + j]; C[i*colsB + j] = d;
}
}
jobjectArray jC = cMatrix2jMatrix(env, C, rowsA, colsB);
delete []A;
delete []B;
delete []C;

return jC;
}

-
C++ , native-.
env->GetArrayLength(jA) Java-
native- .
C C++ jC Java.
A, B C, -
jC.
null.


, -
, Java , native (-
-).
, - -,
.
- Java,
C++ C, -
.
Java- -
JNI (Java Native Interface).
NetBeans 6.5 ,
C C++.
.
626 16

native- Linux GCC,


Windows Cygwin MinGW.
include- <JDK>/include/
win32 ( Windows), <JDK>/include -Xlinker --add-
stdcall-alias. Cygwin include-
<Cygwin>/usr/include/mingw.
NetBeans Debug Release .
,
, , -
. Java-
.


h- javah
classes, ( jnipackage),
class ( Multiply.class).
h- javah / \
: jnipackage.Multiply,
jnipackage/Multiply jnipackage\Multiply.
DLL include-.
include- . -
, .
include- , -
, -
.
DLL -Xlinker --add-
stdcall-alias Additional Options (Linker), -
native- -
( C-call, stdcall)
.
, Build Clean ,
*** multiple target patterns.Stop,
build dist ( - ).

NetBeans C C++.
C++ , NetBeans.
.
native-.
17

,


. , -
, .

(debugger).

, JUnit.
, -
,
- .
,
,
. , -
, -
(profiler).
,
.

17.1.
NetBeans
,
, . . -
. NetBeans (
) , -
.
,
. , . .
, -
. , , ,
, .
628 17

17_1_DesktopApplication, -
, . 5.7. . 17.1 () -
n. . 17.1, , n=10 -

n. , , .
?
- -
, -
, .
-.
, . -
-.

. 17.1. : n = 8; n = 9; n = 10 ( );
n = 11
, 629

-
debugger, . . (bugs). -
,
. -
.
, .
,
,
( . 17.2 ).

. 17.2.

,
. -
. , NetBeans, -
:
, , -
, -
.
, , (breakpoints)
.
(
),
(. 17.3). ,
.

. 17.3.

, , .

Projects Debugging () (. 17.4). -
,
, .
630 17

. 17.4. Debug

, , -
, . -
, , sum, -
, , -
(. 17.5).

. 17.5.

-
( )
( ).
, -
, (. 17.6), . .
, . <F8> (Step
Over ) ( -
).
.
, -
h (. 17.7).
,
<F5> (Continue ).
, 631

. 17.6. (Step Over)

. 17.7.

17.2.


(. 17.8).

. 17.8.

, . -
.
<Shift>+<F5> Finish Debugger Session ( ). -
. -
.
Pause (). -
( ).
. -
, -
.
<F5> Continue ().

(breakpoint).
<F8> Step Over ( ).
632 17

<Shift>+<F8> Step Over Expression (


). ,
. , -
, Step Over.
, -
, .
,
,
-
( -
).

<F7> Step Into ( " "


). Step Over.
,
.
<Ctrl>+<F7> Step Out ( ). ,
, "
" Step Into.
, , -
, (. 17.9).
<F4> Run to Cursor ( ). ,
, .
, -
, - .

. 17.9. sum <Ctrl>+<F7>

Apply Code Changes ( ). -


,
, . .
-,
. , -
, . . -
-.
<Ctrl>+<Shift>+<F7> New Watch... ( ).
, -
, View/Toolbar/Customize....
(. 17.10). -
, .
, 633

. 17.10. Watches

Watches
. , , -
,
(. 17.11).

. 17.11. Watches

Watches ( )
(. 17.12).

. 17.12. Watches
634 17

, -
( , . 17.10).
" " (
, ,
).
Local Variables ( ) (. 17.13)
,
,
. -
, .

. 17.13. Local Variables

( this
) . -
-
(. 17.14).

. 17.14. Local Variables,

Call Stack ( ) (. 17.15) ,


. -
, . -
,
.
, -
NetBeans Window/Debugging/Call Stack (. 17.16).
Debugging, -
, Projects
, 635

(. 17.17). Call Stack Debugging,


.

. 17.15. Call Stack

. 17.16. Call Stack

. 17.17. Debugging

Breakpoints (. 17.18) . -
-
.
, , -
.
636 17

,
Breakpoints , -
.
.
Breakpoint/Enabled.

. 17.18. Breakpoints

(Watches, Local Variables, Breakpoints .)


.
. Watches
. 17.19.

. 17.19.
Watches

Output (), ,
Debugger Console ( ). -
, -
, , . -
17.1.

17.1. ,

Listening on 1343
User program running
LineBreakpoint DesktopApplication1View.java : 202 successfully submitted.
Not able to submit breakpoint LineBreakpoint DesktopApplication1View.java : 191, reason:
No executable location available at line 191.
Invalid LineBreakpoint DesktopApplication1View.java : 191
Breakpoint hit at line 202 in class desktopapplication1.DesktopApplication1View by thread
AWT-EventQueue-0.
Thread AWT-EventQueue-0 stopped at DesktopApplication1View.java:202.
User program running
, 637

Thread AWT-EventQueue-0 stopped at DesktopApplication1View.java:207.


User program running
User program finished


, . -
,
Clear () .
-
, Window/Debugging.
. -
.
, , -
. 05_8_effectiveCalc
05_9_effectiveCalc -
. ,
, -
NetBeans 6.5, JDK 6,
,
, (
).
-
. - -
.
, , :
if (a>b)
1;
else
2;


( a b), , -
( 1 2).
, . , else,
,
if. else, -
, .
:
if (a>b)1; else 2;

, .
:
if (a>b)1;
else 2;
638 17

17.3.

, ,
.
: , -
sum, . -
17_1_DesktopApplication , n=10
.
(. 17.20).

. 17.20.

, <F8>, , n -
10. sum a, b n .
s .
h, 0,1. .
.
: x -
0, a=0.0, b=1.0.
. : s=0, x=0.
(x=0.1).
Watches f(x)*h , -
s . , 0.001.
s=0.0010000000000000002 ,
.
. -
, x=0.30000000000000004.
10 ,
10 000. ,
, 639

, .
-
. , -
.
, -
.
return s;, .
Run to Cursor ( ).
, x
x, ,
. -
for, , .

. -
( !) ,
for,
( ).

.

for (double x = a; x < b; x = x + h) {

double x;
for (x = a; x < b; x = x + h) {
.
17_1_DesktopApplication
(. . 17.1) n=10, . -
sum , x=1.0999999999999999. -
!
<F5> .
n, 10 (. . n = 9 n = 11).
n=9, .
sum , x=1.0000000000000002. .
<F5> .
n=11, . -
sum , x=1.0000000000000002. .
, n=10 x -
1.0,
double. , x=b+h, . . -
, , - ,
23 . , -
.
640 17

,
.
( 17_3_DesktopApplication) (-
17.2).

17.2.

public void calc100(ActionEvent e) {


int i;
for(i=1;i<=100;i++){
double s = sum(0d, 1d, i);
System.out.println("n="+i+" s="+s);
}
}


( ).
17.3 for .

17.3.

for (x = a; x < b; x = x + h) {
s = s + f(x) * h;
if(x>=b-2*h){
System.out.println("n="+n);
System.out.println("a="+b);
System.out.println("b="+b);
System.out.println("h="+h);
System.out.println("x="+x);
System.out.println("f(x)="+f(x));
System.out.println("s="+s);
System.out.println();
}
}

-
( 17.4).

17.4.

n=9:
n=9
a=1.0
b=1.0
h=0.1111111111111111
x=0.7777777777777779
f(x)=0.6049382716049385
s=0.19204389574759947
, 641

n=9
a=1.0
b=1.0
h=0.1111111111111111
x=0.8888888888888891
f(x)=0.7901234567901237
s=0.2798353909465021

n=10:
n=10
a=1.0
b=1.0
h=0.1
x=0.8999999999999999
f(x)=0.8099999999999998
s=0.2849999999999999

n=10
a=1.0
b=1.0
h=0.1
x=0.9999999999999999
f(x)=0.9999999999999998
s=0.3849999999999999

n=11:
n=11
a=1.0
b=1.0
h=0.09090909090909091
x=0.8181818181818183
f(x)=0.669421487603306
s=0.21412471825694973

n=11
a=1.0
b=1.0
h=0.09090909090909091
x=0.9090909090909093
f(x)=0.8264462809917359
s=0.28925619834710753

, n=10 -
x=0.9999999999999999. ! , "
", x b h.
x < b.
x=0.9999999999999999 b=1.0 , , -
0.9999999999999999<1.0.
642 17

, ? .
,
1.0000000000000001 < 1.0 ( ).
, , -
, -
. ,
,
Breakpoint/Properties ( ), -
, :
Condition () , -
. Java,
,
;
Break when hit count
Condition.
, , -
.
.

17.4. " "



, , ,
,
.
. , , -
- .
" ":
, , ,
. , -
, , . . -
().
-
, -
( ). -
,
"". , -
() ( )
, -
() , -
, . -
- .
: , -
( , ).
, 643

,
, . ,
. , , -
, .
-
.
NetBeans -
(Test Libraries),
. ,
,
(a, b, n, f(x)).
, .
, -

( , -
).
, , -
.
: " -
?". , ,
. ,
, . -
. -
.
, ,
,
-
. -
, . , ,
. -

, ,
, .
NetBeans
(. 17.21), 17_4_tests_1 DVD.
pkg Location (""),
( 17.5) (-
17.6).

17.5. Location

public class Location {

private int x = 0;
private int y = 0;
644 17

public Location(int x, int y) {


this.x = x;
this.y = y;
}

/**
* @return the x
*/
public int getX() {
return x;
}

/**
* @param x the x to set
*/
public void setX(int x) {
this.x = x;
}

/**
* @return the y
*/
public int getY() {
return y;
}

/**
* @param y the y to set
*/
public void setY(int y) {
this.y = y;
}
}

17.6. Main

public class Main {

public static void main(String[] args) {


int x = (int) Math.round(Math.random() * 100);
int y = (int) Math.round(Math.random() * 100);
Location location = new Location(x, y);
System.out.println("x=" + x + " y=" + y);
}
}

. 17.21 , NetBeans 6.5 Test Packages, -


<default
package>, Test Libraries, ,
JUnit 3.8.2 JUnit 4.5. NetBeans
, 645

. Test Packages -
, -
.

. 17.21. ,

Tools/Create JUnit Tests


(. 17.22): -
Java (JUnit 4.x), JDK 5 JDK 6, -
(JUnit 3.x, JUnit 3.8.2), -
JDK.

. 17.22.
, 1

, JUnit 4.x ( JUnit 4.5,


2009 ).
646 17

JUnit NetBeans, -
JUnit ( http://JUnit.org) Java-
. , NetBeans 6.5 JUnit -

NetBeans.

Select () , . 17.22, -
(. 17.23).

. 17.23. , 2

(Class Name)
. (Location) ,
. -
, . -
. , -
. OK
(. 17.24).
17_4_tests_1
17_4_tests_2 ( 17.7).

17.7. , Location

package pkg;

import org.junit.After;
import org.junit.AfterClass;
, 647

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

public class LocationTest {

public LocationTest() {
}

@BeforeClass
public static void setUpClass() throws Exception {
}

@AfterClass
public static void tearDownClass() throws Exception {
}

@Before
public void setUp() {
}

@After
public void tearDown() {
}

JUnit ,
TestCase JUnit,
test. JUnit 4 .
, @Test.
org.junit.Assert :
assertEquals(int1,int2) ;
assertEquals(double1, double2,delta) ,
delta;
assertEquals(obj1, obj2) ( equals,
null; , null);
assertArrayEquals(arr1,arr2) ;
assertFalse(condition) , false;
assertTrue(condition) , true;
assertNull(obj) , null;
assertNotNull(obj) , null;
assertSame(obj1, obj2) , .
648 17

. 17.24. ,

assert "", "". , -


,
(test failed).
, assertTrue , -
. " ,
true". (. . false),
, , .
, -
,
.
:
fail() , ,
. -
.
( 17_4_tests_3) -
( 17_4_tests_2), .
, -
x y, 1 100, , -
main.
, 649

17.8.

17.8. test1() Location

@Test
public void test1() throws Exception {
int x = (int) (Math.random() * 100);
int y = (int) (Math.random() * 100);
Location location = new Location(x, y);
assertTrue(", location.x==" + location.getX(),
0 < location.getX() && location.getX() < 100);
assertTrue(", location.y==" + location.getY(),
0 < location.getY() && location.getY() < 100);
}

Run/Test Project,
<Alt>+<F6>
Projects Test (. 17.25).

. 17.25.

, ,
(. 17.26).
, ( ).
, JUnit 3 -.
JUnit 4 , , -
(passed), "" (failed).
650 17

. 17.26.

, ( 50 -
x==0 y==0 random).
, test1() -
test2 ( 17.9), -
(. 17.27).

17.9. test2() Location

@Test
public void test2() throws Exception {
for (int i = 0; i < 1000; i++) {
test1();
}
}

. 17.27.

JUnit Test Results (. 17.27) , -


test2, "" (. 17.28).

. 17.28. ,
, 651

, . -
, @Test, .
, -
.
Location,
setX SetY ( 17.10).

17.10. Location

public void setX(int x) throws IndexOutOfBoundsException {


if (0 < x && x < 100) {
this.x = x;
} else {
throw new IndexOutOfBoundsException("location.x==" + x);
}
}
public void setY(int y) throws IndexOutOfBoundsException {
if (0 < y && y < 100) {
this.y = y;
} else {
throw new IndexOutOfBoundsException("location.y==" + y);
}
}

(. . , @Test),
17.11 ( 17_4_tests_4).

17.11. Location

@Test
public void test3() throws Exception {
String[] sa = new String[0];
for (int i = 0; i < 100; i++) {
Main.main(sa);
}
}

, , ,
(failed), (passed) . 17.29.

. 17.29.
652 17

,
, -
, - location
test1().
( 17.12).

17.12. Location

public Location(int x, int y) {


// this.x=x;
setX(x);
// this.y=y;
setY(y);
}

,
. test1() -
location.x location.y assertTrue, (-
17_4_tests_5).
, ,
, . . , , -
.
-
, (
this.x this.y). ,
, .
.
.
, , -
,
, -
.
.
, , , ,
(. 17.30).
,
(failed). ,
.
. ,
@Test expected:
@Test(expected=IndexOutOfBoundsException.class)

17_4_tests_6, 17_4_tests_5
test3(), ,
(. 17.31).
, 653

. 17.30.

. 17.31.

. .
Location,
. ,
. -
, -
, , -
:
, -
. .
, ,
,
( f(x)=1, f(x)=x, f(x)=x2 . .).
,
.
f(x)=sin(x), f(x)=a1*exp(b1*x) . . a b, a b
.
,
.
f(x)=a1*exp(b1*x), f(x)=sqrt(x) . . a1
b1, a b
. ,
x=0, , ,
. . , -
, ,
null. . .
654 17

, JUnit, -, . . -
( ), -
:
@Test(timeout=10)

- , . , -
test3
@Test(expected = IndexOutOfBoundsException.class, timeout = 1)

( , -
), . . test3 16 (. 17.31),
, . -
, -
.
test2
@Test(timeout = 1)

(. 17.32).

. 17.32. -

@Ignore
. -
, -
, :
@Ignore (" ")

@BeforeClass
@AfterClass
@Before
@After

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

, 655

. , -
, , ,
, , , -
.
JUnit 3 . JUnit 4
, NetBeans
, JUnit 3.
@BeforeClass ,
, LocationTest:
@BeforeClass
public static void setUpClass() throws Exception {
}

before class " ", setup class -


" ".
@Before
:
@Before
public void setUp() {
}

setup " ", -


, .
@After -
:
@After
public void tearDown() {
}

tear down " ()", " ",


.
@AfterClass ,
:
@AfterClass
public static void tearDownClass() throws Exception {
}

after class " ".


17_4_tests_7 DVD .
, System.out.println -
JUnit Test Results , LocationTest
. ,
@BeforeClass @AfterClass, . ,
, NetBeans,
Output. , , ,
.
656 17

JUnit 4 @RunWith, . -
-
. NetBeans 6.5 , -
org.junit.runner.
JUnit - -
.
,
- , ,
.
- Java AspectJ. ,
, , , ,
.

17.5.
, ,
, , .
, -
.
"" (hot spots), -
,
.
, ,
. , , , -
.
, -
20%
( ).
, , , -
"".
( ,
), , -
USB- -,
( ) .
( Kaspersky
Internet Security) .

1 700 000 . 1 700 000
,
, .
, -
, . ,
,
!
!
, 657

, , , -
,
.
NetBeans
Profile/Profile Main Project..., -
. 17_5_DesktopApplication
DVD (
).

, , (script)
(. 17.33).
, ,

Profile/Advanced Commsnds/Unintegrate Profiler. -
, OK.

. 17.33.

, (. 17.34).
(Analyze Performance
CPU). ( Entire
application).
Overhead ( )
( ), -
. 5%. , -
.

. .
Run
, .
, (. 17.35).

-
, ( -
Java-).
658 17

. 17.34. CPU ()

. 17.35.


. -
, -
.
-
(, Intel Centrino).
, ,
.
.
, -
, -
, 659

. , -
. -
( !),
Wi-Fi.
OK ( ),
(. 17.36).
,
Profile/Advanced Commsnds/Run Profiler Calibration.
Show Details ( ).
Intel CoreTM 2 Duo T5300 1,73 -
" / " :
(timestamp): 4,41
(1 = 106 );
(thread) :
1,43 ;
: 5,36 .

. 17.36.

" -
/ " 0,27 .
, 5%
(. 17.37).
, Intel CoreTM 2 Quad Q8200 -
2,33 .
" / " :
(timestamp): 0,653 ;
(thread) :
0,969 ;
: 1,45 .
" -
/ " 0,19 .
660 17

. 17.37.

, , , -
, . 17.38.

. 17.38.

, Yes. -
, Do not show this
message again ( ).

. 17.39. ( )

CPU ( " ") Call


Tree Method ( ) -
(. 17.39). Time [%] -
, 661

,
. Time
( ). , Invocations -
.

(. 17.40).

. 17.40.

, , , -
/
.
Go to Source .
, -
, (,
). , n=8 (
17_3_DesktopApplication) (invocations) f 8, n=9 9,
n=10 11, n=11 11. ,
- .
.
Save Snapshot to Project ( ) -
,
, . Snapshot -
, . . -
.
Save Snapshot to Custom File ( -
) .
662 17

Saves current view to image (


) ( !) -
png.
Hot Spots ( )
"" (hot spots) (. 17.41). -
, (
- ). -
Call Tree
.

. 17.41. "" (hot spots)

Combined () -
: , "" (. 17.42).
, 17_3_DesktopApplication -
, ,
n .
, .
.
Profiler () (. 17.43).
Take Snapshot ( ,
) , .
Live Results ( )
. ,
, . . ,

Invocations .
, 663

. 17.42. Combined

. 17.43. Profiler

. 17.44.

,
, Reset Collected Results Buffer (
) (. 17.43),
Take Snapshort . -
664 17

, ,
(. 17.44).

17.6.
.
sum
( 17.13, 17_6_DesktopApplication
DVD).

17.13. sum

double sum(double a, double b, long n) {


double s = 0;
double h = (b a) / n;
double x;
for (x = a; x < b; x = x + h) {
s = s + f(x) * h;
if(x>=b-2*h){
System.out.println("n="+n);
System.out.println("a="+b);
System.out.println("b="+b);
System.out.println("h="+h);
System.out.println("x="+x);
System.out.println("f(x)="+f(x));
System.out.println("s="+s);
System.out.println();
}
}
return s;
}

, , -
(Entire
application) (Part of application)
(. 17.45), 2%.
, Part of
application, No root methods, define... ( , -
...), . . , .
(root), , -
, -
.
define... Specify Root Methods (
) (. 17.46) Add From Project... ( ...).
, -
jButton1ActionPerformed (. 17.47).
, 665

. 17.45.

. 17.46.

.
OK ,
desktopapplication1.DesktopApplication1View.jButton1ActionPerformed.

Profiling/Set As Profiling Root Method....
OK, ,
. Part of
application 1 root method, Edit... (1 , ).
.
-
(. 17.48).
"" , ,
. 17.49.
666 17

. 17.47. ,

. 17.48.

. 17.49. ""
, 667

"" .
sum (68%).
(24%).
f (1,4%),
10 ( , 2,43 -
sum). ,
.
. -
,
.
Profile Only Project Classes ( -
). Profile All Classes
( ), (overheads) 2
7%.
sum, ""
jButton1ActionPerformed.
(. 17.50),
java.io.PrintStream.println. ?

. 17.50.

sum , 17.13.
, java.io.PrintStream.println -
System.out.println.
668 17

, java.lang.StringBuilder.append - -
System.out.println.

,
NetBeans.
, , StringBuilder.
- , NetBeans -
, , , Intel VTuneTM. VTune
, NetBeans .
NetBeans. NetBeans -
, , NetBeans
.

.
: -
-
(. 17.51). 11,7 sum 0,111 (. . -
!). f
33 (0,033 ) (. . sum!).
,
( !).

. 17.51.

-, , 81, 80 ( !).
-, , sum f, 10 .
sum 0,113 , 0,696 ( 6,2 ).
f 0,033 , 0,25 ( 7,6 ).
, sum n=8 .
n=80 85% ,
15% (. 17.52).
,
( 17.14).
, 669

. 17.52. 80

17.14.

double sum(double a, double b, long n) {


double s = 0;
double h = (b a) / n;
double x;
int i;
for (i = 0; i < n; i++) {
s = s + f(a + i * h) * h;
}
return s;
}

sum n=8 0,107 , 0,113


.
n=80 80 f. , !
81 80. sum -
0,475 0,696 . , -
.
, ,
. h,
. 17.15 .

17.15.

double sum(double a, double b, long n) {


double s = 0;
double h = (b a) / n;
int i;
for (i = 0; i < n; i++) {
s = s + f(a + i * h);
}
return s*h;
}
670 17

n=8 0,102 , n=80 0,643 .


, , -
8%. , -
. , , -
, , -

"".
, .
, -
.
, "" .
, 0,1% ,
( 0,1%).
10% , 90%
, 9%.
"" , ,
.
, .
, f :
double f(double x) {
double r = x * x;
return r;
}

:
double f(double x) {
return x * x ;
}

n=8 . n=80 -
f sum 20% , -
.

17.7. " ".



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

. -
, . -
, .
, (, -
). , -
.
(memory leakage).
, Java , -
. -
, .
5 " " [11].

, .
.
Java ,
, . ,
, .
-
, .
jTextArea1
jTextField1 jTextField2. , ,
jTextField1, , jTextField2. -
, ,
(,
), , (-
, ).
replaceSubS ( 17.16, 17_7_DesktopApplication1
DVD) . s, -
, subS -
, newSubS , .

17.16. replaceSubS

String replaceSubS(String s, String subS, String newSubS) {


String newS = "";
int i = 0;
int old_i = 0;
i = s.indexOf(subS, i);
while (i > -1) {
newS = newS + s.substring(old_i, i) + newSubS;
old_i = i + subS.length();
i = s.indexOf(subS, old_i);
}
newS = newS + s.substring(old_i, s.length());
return newS;
}
672 17

. -
(i > -1),
(, ),
newSubS .
,
. , ,
subS. ( -
) s -
s.
17.17 replaceSubS
jTextArea1 , jTextField1,
, jTextField2, ,
(
jTextField1) ( jTextField2).

17.17. replaceSubS
jButton1ActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {


String s = jTextArea1.getText();
String subS = jTextField1.getText();
String newSubS = jTextField2.getText();
jTextArea1.setText(replaceSubS(s, subS, newSubS));
}

, , . , ,
a=a+... a+=..., . -
replaceSubS , -
jButton2 ( 17.18).
1000 , 10 000
, . -
, !

17.18.
jButton2ActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {


int i = 0;
int COUNT = 1000;
String s = "";
for (i = 1; i <= COUNT; i++) {
s = s + " 1," + i;
}
jTextArea1.setText(s);
}

replaceSubS Profile All Classes.


. 17.53 , , -
, 673

StringBuilder.append. StringBuilder.toString,
s.substring(old_i, i).

. 17.53. replaceSubS

replaceSubS, -
,
. .
, " " (on
fly) : Profiler Modify Profiling Session...
(<Alt>+<Shift>+<F2>) ( ) ( . 17.54
).

. 17.54. " "



674 17

,
. Profile only Project
Classes ( ) Exclude Java core Classes (-
Java).
(Reset Collected Results) . ,
-
replaceSubS. , ,
. - -
, " " . -
Profiling points.
, -
, .

replaceSubS:
i = s.indexOf(subS, i);

,
Profiling/Insert Profiling Point..., ,
(. 17.55).

:
Reset Results .
, ,
;

. 17.55. ( 1)
, 675

Stopwatch . -
System.getCurrentTimeMillis();
Take Snapshot .
.
;
Timed Take Snapshot , ,
, ,
;
Triggered Take Snapshot , ,
,
, , , -
(heap),
(generations). -
, . -
, -
, . .
-
, .
, Triggered Take Snapshot
, -
. Watches
.
, .
, Take Snapshot Next >.
Reset results after taking snapshot ( -
) , -
,
(. 17.56). -
, .
(line), -
. End, , -
. ,
,
Begin.
Reset Results,
Take Snapshot, . Reset Results
Begin.
Finish
( )
(. 17.57).
Output Profiling Points (. 17.58), -
.
676 17

. 17.56. ( 2)

. 17.57.

. 17.58. Profiling Points

:
Add Profiling Point ;
Remove Profiling Point(s) ( );
, 677

Edit Profiling Point ;


Enable/Disable Profiling Point(s) ( ) -
.
, -
. - -
, , -
. ,
.
Results -
report ()
(. 17.59).

. 17.59. Profiling Points

report . Reset -

1 . (snapshot)
, open snapshot
(. 17.60). -
(. 17.61).

. 17.60.

, NetBeans 6.5 -
. -
,
678 17

( ), , NetBeans
. , -
.

. 17.61.

17.8.

, , .
. -
JTextArea, generatedS,
.
, 10 000 , (
17_8_DesktopApplication1, 17.19).

17.19.
generatedS

String generatedS = "";

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {


String subS = jTextField1.getText();
String newSubS = jTextField2.getText();
replaceSubS(generatedS, subS, newSubS);
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {


int i = 0;
int COUNT = 10000;
String s = "";
for (i = 1; i <= COUNT; i++) {
s = s + " 1," + i;
}
generatedS = s;
}
, 679

Monitor (), CPU,


. -
.
Profiler Telemetry
Overview ( ) ( . 17.62 -
).

. 17.62.

Output VM Telemetry Overview, -


(. 17.63):
( heap);
(Garbage Collector GC);
.

. 17.63.

NetBeans,
Profiler View () VM
Telemetry ( ) (. 17.64).

. 17.64. View

, , -
. , -


, . ,
680 17

, ,
. (Surviving
Generations).
? !
s = s + " 1," + i;

-, 10 000 !
,
. . - , -
. 10 000
, (
, ).
,
.
,

(. 17.65). , .

. 17.65.

-. -
, , , -
, ( 17_8_DesktopApplication2, 17.20).

17.20.

int generatedI = 0;

int generateSum() {
int i;
int COUNT = 10000;
int sum = 0;
for (i = 1; i <= COUNT; i++) {
sum = sum + 1;
}
return sum;
}
, 681

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {


generatedI = generateSum();
}

,
, , -
(. 17.66).

. 17.66.

, , -
. 12 ,
, ,
( ,
). NetBeans 6.5
, -
, (-) -
( ).
10 000 -
0,59 . ,
20 000 !

17.9.

-
. Memory (). -
, -
.
: Reset Results
Take Snapshot .
Reset Collected Results,
. -
, .
-
. (-
682 17

Take Snapshot Profiler Profiling Results),


.
, -
. :
Create Custom... ( )
(. 17.67). (. 17.68),
New Memory Analysis.
OK -
(. 17.67), Advanced settings (-
), .
, -
Run garbage collection when getting memory results (
).

. 17.67. ( 1)

. 17.68. ( 2)
, 683


Reset Results Take Snapshot (. 17.69).

. 17.69.

.
.
(. 17.70).
-
,
,
.

. 17.70.

,
41 000 , 284 !
char[] . ? -
(. 17.71).
684 17

. 17.71.


Output Profiling Points -
No results available ( )

( ). report ()
NetBeans (. 17.72).

. 17.72.

open snapshot,
, (. 17.73).
, ,
,
.
.
Reset Results Take Snapshot.
Reset Results:
Enable/Disable Profiling
Point(s) Output/Profiling Points (. . 17.58).
, -
, . -

.
, 685

. 17.73.

(. 17.74). -
, -
.

. 17.74.

Computes the
difference between two comparable memory snapshorts (
686 17

). ,
(. 17.75), ,
(. 17.76). ,
,
.
, , -
- Java.
,
.
char[], String, , Java -
, .
-
.
StringBuffer . , -
17.21 ( 17_9_DesktopApplication,
StringBuffer), (0,48 )
( 74 ).

. 17.75.

17.21.

int i = 0;
int COUNT = 10000;
StringBuffer s = new StringBuffer("");
for (i = 1; i <= COUNT; i++) {
s.append(" 1,").append(i);
}
generatedS = s.toString();

, " "
,
.
, -
30 4000 .
, 687

. 17.76.


(debugger) (bugs).
: (breakpoints) -
.
, ,
, -
.
Watches
.
" ": -
, , ,
.
,
,
"" (hot spots), -
, .
NetBeans :
;
(CPU) "" ;
.
:
;
;
.
688 17


-
(<F8> Step Over) (<F7> Step Into)
.
NetBeans , -
, <Shift>+<F8>
Step Over Expression ( )
<Ctrl>+<F7> Step Out ( ).
, Java .
, Java "" ,
. . "" .

(
String ).
-
""
, .
,
, . -
"" - , -
.

replaceSubS.
setText JTextArea , -
10 000 ,
. , , -
.

Java NetBeans , -
Java. , -
, , -
Java-, , , -

. " ", "-
", "", " ", " ",
"", "", " " " ".
, , -
-
, , ,
, , -
, .
, Java NetBeans
, ,
, !
. ,
, .
, ,
, -
, !
690 17

DVD

DVD Sun Microsystems


(Oracle) JDK 6u22
NetBeans 6.9.1; JDK 6;
; ,
, JDK 6u11 NetBeans 6.5, -
.
, -
( 15 , -
- ).
1.jdk-6u11 JDK 6, 11 -
:
jdk-6u11-windows-i586-p.exe 32- i586-
(Pentium 4, Celeron, Core 2 Duo . .)
Windows. 64- ;
jdk-6u11-linux-i586.bin 32- i586-
Linux. 64-
.
2.jdk-6-doc zip- JDK 6 ( jdk-6u10-
docs.zip).
3.netbeans-6.5 NetBeans 6.5
Windows ( netbeans-6.5-ml-windows.exe) Linux ( netbeans-6.5-ml-linux.sh),
uml6.zip UML-.
4.netbeans-6.9 NetBeans 6.9.1
Windows ( netbeans-6.9.1-ml-windows.exe) Linux ( netbeans-6.9.1-
ml-linux.sh), "NetBeans IDE 6.9.1
Installation Instructions.html" ( Linux),
uml.zip UML- NetBeans ( -
NetBeans uml.zip uml -
NetBeans, , Windows C:\Program Files\NetBeans 6.9).
5.jdk-6u22 JDK 6, 22 -
:
692

jdk-6u22-windows-i586.exe 32- i586--


(Pentium 4, Celeron, Core 2 Duo . .) -
Windows;
jdk-6u22-windows-x64.exe 64- -
Windows ( 64- -
);
jdk-6u22-linux-i586-rpm.bin 32- i586-
Linux, jdk-6u22-linux-
i586.bin ;
jdk-6u22-linux-x64-rpm.bin 64- -
Linux ( 64- -
), jdk-6u22-linux-x64.bin .
NetBeansProjects NetBeans,
. . .
(. 1) ,
NetBeansProjects , (Chapter02, Chapter04, Chap-
ter07 . .).
,
, . 9 ,
, , (01, 02 . .).
.
( -
), 1, 2, 3 . . (,
02_09_LookAndFeel_1, 02_09_LookAndFeel_2 . .).
, , NetBeansProjects\Chapter16\16_6_
JNI_example1 NetBeansProjects\Chapter16\16_6_JNI_example2
CPP_MultiplyLibrary.dll DLL,
Java c native-
NetBeans.
, NetBeansProjects , -
(, 02_11_GUI_example3).
( -
) .

UML-. -
, . .
UML- NetBeans .

1.


02_03_JavaApplication1 Java
"!"
02_04_console Java
"!"
<Enter>
DVD 693

1 ()


02_06_GUI_example Java

02_07_GUI_example1 Java
()
02_07_GUI_example2 Java
( HTML- )
02_07_GUI_example3 Java
(
)
02_09_LookAndFeel_1 Java -
( Metal)
02_09_LookAndFeel_2 Java -
( System
)
02_09_LookAndFeel_3 Java -
( Motif
)
02_09_LookAndFeel_4 Java
( Metal)
02_09_LookAndFeel_5 Java -

( System)
02_09_LookAndFeel_6 Java -

( Motif)
02_11_GUI_example1 ( ).
.
<S> ( <Ctrl>+<S>)
02_11_GUI_example2 ( -
-
)
02_11_GUI_example3 ( -
)

02_11_GUI_example4 ,
02_12_GUI_example1

02_12_GUI_example2
Figure
02_13_EnumExample

02_14_OptionPane
02_15_Layout1_Free Free Design
694

1 ()


02_15_Layout2_Absolute Absolute
02_15_Layout3_GridBag GridBag
02_15_Layout4_Null Null
02_16_DesktopApplication1 Java
DesktopApplication
04_1_integerCalc , -

05_5_consol_example ,
( )
05_7_integral ,

05_8_effectiveCalc -

05_9_effectiveCalc -

07_1_UMLProject1 UML- Figure Dot
07_3_UML_Figures0 UML-

07_3_UML_Figures1 UML-

07_3_UML_Figures2 Hierarchical
Layout
07_4_1_UML_Figures
07_4_2_UML_Figures
( )
07_4_3_UML_Figures , Java-
07_4_3_JavaLibrary1
07_4_3_JavaLibrary1 Java,
07_4_3_UML_Figures
07_5_JavaLibrary_Figure Java,
07_5_JavaLibrary_Figure-Model
07_5_JavaLibrary_Figure- , Java-
Model 07_5_JavaLibrary_Figure
07_6_refactoring1 ,
07_6_refactoring2
08_3_for_each for...each
08_5_JavaEnumExample
08_6_DateTime ,
08_7_Graphics1
DVD 695

1 ()


08_7_Graphics2
( paint())
08_9_File1
08_9_File2

08_9_File3 ,
,
08_9_File4_Stream

08_9_File5_Stream ,

08_9_File6_Zip gzip zip,
Files

10_6_Threads
10_7_Lock FIFOMutex
11_2_applets HTML-,

11_2_Applet1
11_3_ServletsExamples_1
11_3_ServletsExamples_2
11_4_JSPExamples JSP
11_5_JSTL_Examples JSTL
13_01_DesktopApplication1 DesktopApplication
13_06_DesktopApplication1 DesktopApplication
doInBackground()
13_07_DesktopApplication1 DesktopApplication (
)
13_07_DesktopApplication2 DesktopApplication Save Save
save. save
. doInBackground()
13_07_DesktopApplication3 DesktopApplication
13_08_DesktopApplication1 DesktopApplication
13_08_DesktopApplication2
DesktopApplication
13_09_DesktopApplication1
DesktopApplication
13_10_DesktopApplication1

696

1 ()

13_10_DesktopApplication2

13_11_DesktopApplication1
DesktopApplication
14_2_MobileApplication1 "Hello, World!"
14_4_MobileApplication1 ", !"
14_5_CrossesZeros1 "-"
14_5_CrossesZeros2 "-" (
)
14_6_CrossesZeros1 "-" ( -)
14_6_CrossesZeros2 "-"
( )
14_7_MobileItemsLibrary Java ME
14_7_CrossesZeros1
"-" ()
14_7_CrossesZeros2
"-"
14_9_MobileApplication
15_2_DesktopApplication1
15_2_DesktopApplication2
BeanInfo
15_3_DesktopApplication JTitledPanel title

15_4_DesktopApplication JTitledPanel
titleShift

15_5_DesktopApplication1 JTitledPanel
TextValueChanged title

15_5_DesktopApplication2
TextValueChanged

16_5_JNI_example1 ,
native-
16_5_CPP_ex1_Cygwin C++, DLL
native- 16_5_JNI_example1.
Cygwin
16_5_CPP_ex1_MinGW C++, DLL
native- 16_5_JNI_example1.
MinGW

16_5_JNI_example2 , native-,


DVD 697

1 ()


16_5_CPP_ ex2_Cygwin C++, DLL
native- 16_5_JNI_example2.
Cygwin
16_5_CPP_ ex2_ MinGW C++, DLL
native- 16_5_JNI_example2.
MinGW
17_1_DesktopApplication
( )
17_3_DesktopApplication -
( )
17_4_tests_1 ,
17_4_tests_2
17_4_tests_3
17_4_tests_4
17_4_tests_5
( )
17_4_tests_6
17_4_tests_7
17_5_DesktopApplication
17_6_DesktopApplication
17_7_DesktopApplication1

17_7_DesktopApplication2 -

17_8_DesktopApplication1
( )
17_8_DesktopApplication2

17_9_DesktopApplication

( )
1. http://java.sun.com/ Sun Java .
2. http://www.netbeans.org/ NetBeans ( -
).
3. http://barsic.spbu.ru/www/comlan/java_r.html/ , -
Java. "
Java NetBeans".
4. Ken Arnold, James Gosling, David Holmes, The Java Programming Language, Fourth
Edition, Addison-Wesley Professional, 2005. 928 p.
5. http://java.sun.com/docs/books/jls/index.html -
(!) : James Gosling, Bill
Joy, Guy Steele, Gilad Bracha. The Java Language Specification, Third Edition. Addison
Wesley, 2005. 688 p.
6. . , . , . . Java, 3- /
. . .: , 2002. 624 .
7. . . Java. / . . .:
, 1996. 448 .
8. . . . Java 2: . .: " ", 2000. 320 .
9. . . Java, 4- / . . .: , 2009.
640 .

( )
10. . . : / . . .:
-, 2003. 432 .
11. . JavaTM. / . . .: -
"", 2002. 224 .

J N
Java Class Library NetBeans Module
25, 71 NetBeans 25, 71
JIT- 23


105 20
383 417
473 108
123 465
280 (anonimous) 466
@Action 491, 523 (nested) 465
490 (inner) 465
(applet) 24, 427 (local) 465
175, 211,
214
94
383
40 251, 287, 288, 305, 582
418
417
417
122
224
223, 267 100
30, 171
- 23
JSTL 460
30, 170 377
180 200
346 97
150 260
700

43
40
253 627
173
388

183
308
553 312
91 308
183 313
311
311
309
505 312
35 311
223
314
486, 501
311
201
38, 39, 223 313
200, 240 311
75 314
18 314
345 310
20 309, 373
315 229
397
171
188
657 144
40, 42 90, 132
- 245 43
- 245 218
255 40
41, 90
- 338 579
338 202
420 41
18 205
383 (midlet) 24, 71, 527, 578
56, 100, 579, 593 519
NetBeans 58 396
326 375, 380
/ 91 42, 48, 232
154 native 596
40, 91, 256 90
96, 101, 128
248, 380 private 235
526, 577 protected 235
379 public 236
391 96
701

58 () 419
47 281
267

258
38, 223, 267 248

188 234
419 240
419 (hiding) 248
186 36
43, 233
42
43
162 42
104, 108, 472, 476 40, 237
271 42
40, 42 116
- lock 408 - 596
- 100 180
- 481, 523 172, 182
- 491 40, 226
233 593
110, 282 39
- 39
for 318 - 39
switch 198 - 19
do...while 217 (threads) 387
for 200, 201 91
while 215 38, 223, 252
347 224, 375
217 40
151 183
176 478
169
493 521
(debugger) 629 522
520
(threads) 387, 414
(descendants) 223
251 (ancestor) 223
47 266
48 190, 265
164
282 39
105 - 19
494
20
90 - 38
234 18
234 18
702

120
352
476 169
GlassFish 25 169
486 169
228 170
206 169
(namespaces) 47 170
656 169, 177
389 96
526, 577 (listeners) 472
387 472, 579
271 160
444
193, 195
226
523 41, 233
488 this 267
171 172
229 43
253
437 523
121 423
NetBeans 98
125 (subclass) 224
125 (superclass) 224
629 201
630
298
375

map 488
488
47 397
579 479
105 418
280
24, 71 420
(servlet) 24, 442 233
- 443 201
251, 287, 288, 305, 582 643
643
248
261 ASP 59
- 487 JSP 59
627 PHP 59
JSP 456
389
389 boolean 36, 37
391 byte 37
389 char 37
703

double 37
float 36, 37 JPEG 283
int 36, 37 PNG 283
long 37 SVG 284
object 36 (floating point) 183
short 37 434
36
36
37
37 - 243, 325
- 333
590
18
177
201

375
32
if 194 () 100


267 452
522 30
267

Вам также может понравиться