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

Java

1.

C ore Java
Volume I - Fundamentals
Ninth Edition

Cay S . Horstmann
Gary Cornell

PRENTICE
HALL

Upper Saddle River, NJ Boston Indianapolis San Francisco


New York Toronto Montreal London Munich Paris Madrid
Capetown Sydney Tokyo Singapore Mexico City

Java"

1.

-
2014

32.973.26-018.2.75
82
681.3.07
""
. ..
..
"" :
info@williamspubUshing.com, http://www.williamspublishing.com
, ., , .
82 Java. , 1. . 9- . : . . . :
".. ", 2014. 864 . : . . . .
ISBN 978-5-8459-1869-7 (., 1)
ISBN 978-5-8459-1886-4 (., .)

32.973.26-018.2.75

.

, ,
, Prentice Hall, Inc.
Authorized translation from the English language edition published by Prentice Hall, Inc., Copyright 2013
Oracle and/or its affiliates.
All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, elec
tronic or mechanical, including photocopying, recording or by any information storage retrieval system, without
permission from the Publisher.
Russian language edition published by Williams Publishing House according to the Agreement with R&I
Enterprises International, Copyright 2014

-
. ,

Java. , 1.
9-

..
..
..
..

22.11.2013. 70x100/16.
Tim es. .
. . . 69,66. .-. . 47,67.
1500 . 3968.
" "
199034, - , 9- , 12/28
" . . ", 127055, . , . , . 43, . 1
ISBN 978-5-8459-1869-7 (., 1)
ISBN 978-5-8459-1886-4 (., .)
ISBN 978-0-13-708189-9 (.)

" ", 2014


O racle and/or its affiliates, 2013

13

19

1. Java

21

2. Java

37

3. Java

57

4.

131

5.

197

6.

271

7.

313

8.

359

9. Swing

397

10.

525

11. , ,

579

12.

645

13.

683

14.

753

. Java

849

651


13

15
17
17

19

20

1. Java

21

Java
Java


Java
Java

21
22
23
23
24
24
25
26
26
27
27
27
28
28
30
32

2. Java

37

Java Development Kit


JDK










38
38
39
41
42
43
44
44
46
47
50
51
53

3. Java

57

Java




char
boolean

58
51
62
62
63
64
66
66
68
68





API String
API










switch


*

for each





69
70
71
72
72
74
75
75
76
77
77
77
78
79
80
80
81
83
86
88
88
90
95
96
97
97
100
105
108
111
113
116
117
118
119
120
121
124
127

131





GregorianCalendar Java


Employee

Employee







132
133
134
134
135
137
137
140
142
148
149
151
152
153
154
155
157
158
158
159
159




main ()







finalize ()

160
160
161
162
164
170
170
171
172
172
173
174
174
179
179
180
181
182
185
186
188
189
190
190
191
192
192
193
194
194

5.

197


:



Object
equals ()

hashCode ()
toString ()





Class





198
204
205
206
209
210
212
217
218
219
220
224
226
232
235
238
239
243
244
246
246
249
250
256
260
264
267

6.

271








,




-
-

272
278
279
280
286
289
291
294
295
298
298
301
304
307
311

7.

313

Swing








314
319
322
324
324
329
334
343
346
354

8.

359


AWT

359
361
366
368
370
373
377
385
392
392

9. Swing

397

Swing " - -

"--"
Swing --"









398
398
399
403
405
408
410
414
414
416
418
418
419
421
422
424
427
432
435

10



-






-









441
442
444
445
446
448
450
454
457
458
460
470
480
480
484
485
486
496
501
507
518

10.

525

JAR

JAR-


Java Web Start
""

JNLP API


HTML- <applet>
<object>

)



API

526
527
528
529
532
533
537
538
540
549
549
554
557
557
563
564
567
567
572

11. , ,

579








finally
try





580
582
583
586
587
588
591
592
596
597
600
603
604
605
606
608
608
608


""


AWT

11

611
612
613
615
616
617
626
- 631
634
639

12.

645








Class<T>

646
647
648
650
651
653
655
655
657
658
658
658
659
660
661
662

13.

683



Collection Iterator Java



-



665
666
668

670
672
673
675
676
676
683
684
686

692
693
702
702
706
707
713
715
716
720
725
729
736
737
737
739
741
743

12



Hashtable


" "

744
746
746
746
747
748
749
750

753


,


synchronized


volatile
final




/
, stop () suspend ()


,


Callable Future


Swing

SwingWorker

754
759
765
767
768
768
768
769
771
771
772
772
774
774
778
780
783
788
792
793
794
796
796
796
799
800
802
803
805
813
813
815
815
816
821
821
826
826
828
831
831
832
832
833
833
833
835
839
846

. Java

849
851

1995 Java
. Java
, ,
-, ,
, .
, Java , .
,
Microsoft.
, Java.
Java ,
,
.
1995 Java Development
Kit. 17 (API)
200 3 . API
, ,
, ,
XML.
, , .
, ,
Java Development Kit, , ,
, Java.
, Java
Standard Edition (SE) 7.
, -
, Java
. , , , ,
, Java,
, ,
"
". .
Java ,
.
,
.
, .
" ".
.

14

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

Swing.
.
.
.
.
Java
Java,
. . ,
,
Java, .

.
.
-.
.
.
.
.
XML.
.
.
.
JavaBeans.
.
.
. , , .
,
h tt p : / /horstm ann.com / core ja v a ,
.

15


1 Java,
.
, Java
. Java
, , .
2 , JDK,
.
Java ( ,
) JDK, ,
Java,
Java.
3 Java.
: , .
C++,
, , ,
Java. , ,
Visual Basic, .
- ()
, Java. 4

, , Java:
. Java
- . , ,
j avadoc,
* - .
C++, .
, -
, ,
Java .
, 5
.

.
Java. Java
C++. C++ Moiyr
.
6 , Java .
; 5.
-
Java.
Java, .
.
7 .
Java
, .
, , ,

16

,
.
8 AWT
. , ,
, .
,
.
9
Swing. Swing
.
, , , , ,
.
.
10 , ,
. , ,
JAR
Java Web Start . , , ,
Java
.
11 Java,
,
.
.

- .

. , ,
.
12
Java SE 5.0.
. ,
,

Java.
13 Java. ,
, ,
,
, .
, ,
.
14
, .
( .)
, .

Java SE 5.0, .
Java.

17


,
.
! .

. .

! .

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

Java
(API). -
API
. , , ,
, ,
API.
, .
, JDK,
, .
1.2
,
.
1.1. InputTest/InputTest.java


, ,
- http://horstmann.com/corejava.

j, Java Development
Kit (JDK). JDK 2.

,
, Java.
,
, ,
.
Prentice Hall
, .
. ,
Prentice Hall (Greg Doench)
, ,

. (Julie Nahil)
,
.
(Gary Cornell),
.
,

. ,
,
.

(Chuck Allison), C/C++ Users Journal,
(Lance Anderson, Oracle), (Alec Beaton, PointBase, Inc.),
(Cliff Berg), (Joshua Bloch), (David Brown),
(Corky Cartwright), (Frank Cohen, PushToTest),
(Chris Crane, devXsolution), . (Dr. Nicholas
J. De Lillo) , (Rakesh Dhoopar, Oracle),
David Geary (David Geary, Sabreware), (Oracle), (Brian
Goetz) Oracle, (Angela Gordon), (Dan
Gordon), (Rob Gordon), (John Gray)
, (Cameron Gregory, olabs.com), (Marty
Hall)
, (Vincent Hardy) Adobe Systems, (Dan
Harkey) -, (William
Higgins, IBM), (Vladimir Ivanovic) PointBase,
(Jerry Jackson) Technologies, (Tim Kimmet) Walmart,
(Chris Laffra), (Charlie Lai) Apple,
(Angelika Langer), (Doug Langston), (Hang Lau)
, (Mark Lawrence), (Doug Lea)

20

SUNY Oswego, (Gregory Longshore), (Bob Lynch)


Lynch Associates, (Philip Milne, ),
(Mark Morrissey) - , (Mahesh Neelakanta) ,
( Pham), (Paul Philion), (Blake Ragsdell),
(Stuart Reges) , (Rich
Rosen) Interactive Data Corporation, (Peter Sanders)
(ESSI), . , , (Dr. Paul Sanghera)
- , (Paul Sevinc) Teamup AG, (Devang Shah) Oracle, .
(Bradley A. Smith), (Steven Stelting) Oracle,
(Christopher Taylor), (Luke Taylor) Valtech, (George Thiruvathukal), (Kim Topley) StreamingEdge,
(Janet Traub), (Paul , ),
(Peter van der Linden) Motorola Mobile Devices^ (Burt Walsh),
(Dan Xu) Oracle (John Zavgren) Oracle.
,
-, 2012 .


, , .
, ,
.
, .
.
-
. , ,
, ,
.
, ,
.
.
:
E-mail:
info@williamspublishing.com
WWW:
http: //www.williamspublishing.com
:
: 127055, . , . , .43, . 1
: 03150, , / 152

Java
...
Java
Java
Java
Java
Java

Java 1996
,
, The New York Times, The Washington Post Business Week. Java
,
.

100 . . .
Java .

Java
Java : "
, Java . Java
. , ,
. Java ,
, , , .
,
".

Sun Microsystems. , ,

22

1 Java

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

(.. C++). , Java,
.
" ", .
,
. Java
,
.
Java.

Java
Java ,
.
Java.
;
-;
;
;
;
;
;
;
;
;
.

Java,
;

Java, .

Java

23

! , , www.oracle.com/
technetwork/java/langenv-140151 .html. Java.

" ; ,

. C++ ,
, Java
C++. ;
C++, , , , ".
Java, ,
C++. , (
) , , , ,
.. ( Java C++
.) Java
C++. , sw itch Java
. C++, Java.
(, Visual Basic),
Java .
, . : Java,
.
Visual Basic,
.
Java,
. , , ()
, .
" . Java
,
.
40 ;
, , 175 ".
. ,
.
Java Micro Edition ,
.

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

24

1 Java

-
,
. , Java, ,
C++.
, Java
, Java ( 5).
! - ,
4-6. -
, -
, Basic.
.


" Java
TCP/IP, HTTP FTP. Java
,
, URL ".
Java .
, -
, , Java
, . (
.)
Java (
).

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

".
. Java
,
. , ,
, - ,
, Java
.
Visual Basic
, ,
, .
, , .

Java

25

Visual Basic ,
.
, , ,
. Java . ,
, .
, , ,
. Java ,
,
, .

" Java .
. Java
, ".
: " ",
. Java Development Kit

Java 1.0. Sun Microsystems
Java. ,
, .
. , Java
.
.
,
Java.

, "".
,
, .
.
Java . , Java 1.1
(
). , .
,
.
! , Microsoft,
ActiveX,
. ,
Microsoft ,
, .
Java , ActiveX,
-
.

26

1 Java


" ,,
.
, Java. ,
Java, -.
,
".
.
(Niclaus Wirth) Pascal.
UCSD Pascal.
, -, ,
, ,
. -

.
Microsoft .NET,
.

.
,
. -
, .

" C++, Java


.
".
, int Java 32- . C++
int 16-, 32- .
, int
short int long int.
,
.
, ,
.
Unicode.
", ,
. , Java Window
Unix, Windows Macintosh".
, - ,
Windows, Macintosh
Unix, , .
Java 1.0 ,
,
. , ,

Java

27

,
. (
.) .

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

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

" - ,
, .
-
, ".
Java
, " ".
( JIT-) ,
,
,
. , , ,
,
. , .
,
, ,
, .

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

28

1 Java

. ,
, Java ,
. ,
. ,
Java
! .

" Java , C++.


,
. ,
, . Java
".
,
. ,
. Java 1.0
, Java
, .
, .

, ,
.
! Java Microsoft
J++, ,
Java. Microsoft J++
, C# - Java,
. J#,
J++ , #. J++, C# J#
.

- Java
. Java,
-, .
-, Java -.
Java Oracle,
, ,
Java ,
Java. -, ,
. :

, .

29

- ,
. ,
. , , . ,
, ,
, .
. 1.1 -,

. ,
, .
-, . (
http://jmol.sourceforge.net.)

. 1.1. Jmol
, . ,
,
Java. .
Netscape Internet Explorer
Java, .
,
Java.
- JavaScript
Flash,
. , Java
, -
.

30

1 Java

Java
Java.
( ,
Java SunWorld
1995 .).
Java 1991 , Sun
Microsystems (Patrick Naughton)
( ) (James Gosling)
,
, ,
.
,
. ,
,
.
"Green".
,
,
Pascal . ,
Pascal, ,
.
, ]ava (JVM).
, .
, "Green",
, .
Sun Microsystems
Unix,
C++, Pascal. , -,
-. : "
, ". Oak (). (
, ,
Sim Microsystems.) , "Oak"
,
Java. .
1992 . "Green"
"*7". .
( 6x4x4 , SPARC.)
, -
.
, ,
, .
. , , -
, (Jim Clark) Netscape,
Java.
1993 1994
, "Green",
"First Person, Inc.". , ,

Java

31

, 300 ,
. "First Person, Inc."
1994 .

World Wide Web ( ).
, .
1994 -
Mosaic,
1993 . (Mark Andreessen),
6,85 .
, . (
Netscape.)
Sun World , 1994 .
: " .
,
"-", , :
, , ,
, .
".
(Johnatan
Payne). Hotjava.
Java, .
, ,
-. ,
, 23 1995
SunWorld '95 Java, .
Sun Microsystems Java 1996 .
, Java 1.0
. ,
-, , ,
"" , Java 1.0 .
. , Java 1.0 .
, Java 1.1, ,

. , .
Java 1.2 JavaOne 1998 .

.
, "Write Once, Run Anywhere" ("
"),
. 1998 (!)
Java 2 Standard Edition Software Development Kit Version 1.2
(
Java 2, 1.2).
Standard Edition, : Micro Edition
("") ,
, Enterprise Edition ( ).
Standard Edition.

32

1 Java

1.3 1.4 Standard Edition



Java 2. , ,
, . Java
. , ,
Java .
5.0 Java
1.1. ( 5.0 1.5,
JavaOne 2004 . .)
(
C++),
. , , f o r
each, , "" #.
6 ( .0) 2006 .
, ,
, .

,
Sun Microsystems ,
Oracle 2009 . Java
. 2011 Oracle
Java 7 .
Java 8, 2013 .
. 1.1 Java. ,
API .
1.1. Java

1.0

1996

211

1.1

1997

477

1.2

1998

1524

1.3

2000

1840

1.4

2002

2723

5.0

2004

, for each,
, ,
, ,

3279

2006

3793

2011

switch ,
, ,

4024

Java

, Java.

Java

33

Java HTML.
Java , a HTML
-. , HTML, - , Java.
XML, Java.
Java , a XML . ,
XML, ,
,
API Java .
, Java ,
XML-.
.
Java .
,
Java, .
, .
, Java
. ,
, . ,
,
, Java .
Java .
.
, Microsoft. ,
,
. ,
! ,
- .
.
, -. ,
C++, ,
Java.
Java .
Java .
, , C++ #.
,
, , , C++ Visual
Basic, .
?
, .
, ,
?
?
? Java ,

34

1 Java

,
, ,
. , Java ,
, .
. .
C# Java .
C# ,
Java, ,
" ". C# Java,
.
C# . Windows,
, , #.
, Java -
.
Java ,
.
Java Sun Microsystems
.
Sun Microsystems Java,
.
,
,
. Java " ,
".
2007 , Sun Microsystems
, Java General Public
License (GPL) ,
Linux. Oracle
Java, .
Java GPL,
. , Java
, , ,
, . ,
, Java
.
Java , ,
.
Java
. , ""
, , .
,
C++, .
Java
. , ,
Java, , ,
- .

Java

35

Java.
, ,
. Java ,
"" C++.
,
"" Java.
Java -.
, Java, -.
Java ,
-. Java
- -.
Java .

Java. Java .

Java,
. .
, , , , ^
.
,
Windows Word,
. .
, ActiveX Internet Explorer ,
,
.

Java , , ,
, ActiveX ,
Word, .
15 Java -
, .
JavaScript Java.
JavaScript , -
. Netscape LiveScript.
JavaScript Java,
( , ). JavaScript
-262. JavaScript
, Java. , JavaScript
,
.
I

Java,
.
Java, , .
, Java,

36

1 Java

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


Java
...
Java Development Kit




,
Java Development Kit (JDK),
: ,
. JDK,
.
, ().
,
, Java. ,

,
. , ,
,
3, , , Java.

38

2 Java

Java Development Kit


Java Development Kit (JDK)
Oracle Solaris, Linux, Mac OS X Windows.
, ,
.

JDK
Java Development Kit
- www.oracle.com/technetwork/java/javase/downloads,
,
. ,
. 2.1.
2.1. Java

Java Development Kit

JDK

,
Java

Java Runtime Environment

JRE

,
Java

Standard Edition

SE

Java

Enterprise Edition

EE

Java

Micro Edition

ME

Java

Java 2

J2

Java,
1998-2006 .

Software Development Kit

SDK

JDK,
1998-2006 .

Update

, Oracle

NetBeans

Oracle

JDK . , , Java
Development Kit, ..
Java. , 1.2-1.4
Java SDK (Software Development Kit).
. Java Runtime Environment (JRE),
, . , , .
JRE Java,
. Java SE.
Java Standard Edition, .. Java, Java
(Enterprise Edition) Java ME (Micro Edition) .
Java 2, 1998 .,
Sun Microsystems ,
JDK 1.2

Java Development Kit

39

.
JDK, , 1.2 .
JDK 1.3, 1.4 5.0.
Java Java 2. ,
Java 2 Standard Edition Software Development Kit Version 5.0, J2SE SDK 5.0.
, , ,
, .
. , 2006 . .
Java 2 , Java Standard Edition Java SE
6. 1.5 1.6
5.0 6.
, , Oracle ,
, . ,
Java SE 7
JDK 7ul, , 1.7.0_01.
.
JDK .
Oracle , ,
JDK.
Forte, Sun ONE Studio, Sun Java Studio Netbeans. ,
,
- Oracle.
JDK. ,
h t t p :/ /netbeans.org.
! JDK.
, jdk1.7.0.
, JDK,
.
Windows, .
c:\Program FilesXjdkl.7.0. Program Files
.
j d k , JDK. ,
j d k / bin, /usr/local/jdkl .7.0/bin
c:\jdkl.7.0\bin.


JDK :
jd k / bin ,
. -.

Unix ( Solaris, Mac OS X Linux)



. , Bourne Again ( Linux
), ~ / .bashrc
~ / .bash_profile.

export PATH=jdk/bin:$PAT

40

2 Java

Windows .
, System (). Windows
. Vista Windows 7
Advanced System Settings (
), . 2.1.
Advanced (), Environment
( ). System Variables
( ) ,
Path. Edit (), . 2.2.
jdk\bin .
, :
jd k \ bin;

, jd k Java,
: \ j d k l .7.0 02.
Program Files ,
: "c:\Program FilesXjdkl.7.0_02\bin";
.
.
.

. 2 .1 . W indows Vista

Java Development Kit

41

. 2.2. Path W indows Vista

.
. , .
:
java -version

<Enter>. :
javac 1.7.0_02

" j a v a :c o m m a n d not found"


(java:command ) "The name specified is nor recognized as an
internal or external command, operable program or batch file" (
,
), ,
.
! Windows
. Windows , Run () S ta rt ()
cmd Open () .
Vista Windows 7 cmd S ta rt S earch ( )
S tart. <Enter>, .
,
, , ,
www.horstmann.com/bigj/help/windows/tutorial.html.

JDK ,
src. zip. ,
. ,
.

42

2 Java

1. , JDK , jd k /b in
.
2. .
3. jd k ( cd /usr/local/jdkl . 7 . 0
cd :/jdkl .7.0).

4. src , :
mkdir src
cd src

5. :
jar xvf ../src.jar

Windows,
jar xvf ..\src.zip

. src.sip .
(, ,
), - http://jdk7.
java.net.

JDK .
www.oracle.com/technetwork/java/javase/downloads.
.
1. , JDK , jdk/bin
.
2. . zip, ,
jdk. jdk-
- doc.zip, ,
7.
3. .
4. jdk.
5. :
jar xvf jdk- -apidocs.zip


, ,
. -
http://horstmann.com/corejava.
corejava.zip, (
CoreJavaBook). .

Java Development Kit

43

1. , JDK , jd k /
bin .
2. CoreJavaBook.
3. corejava.zip .
4. .
5. CoreJavaBook.
6. :
jar xvf corejava.zip


Java
Java. ,
. . 2.3
JDK.

jd k

( , jdkl.7.0_02)

b in

demo

docs HTM L ( j2sdk<Bepciw>-doc.zip)


include (. )

Java

lib

( src.zip)

. 2 .3 . JDK

, Java,
docs sr c . docs
Java HTML. -,
Firefox.
. docs/api/index,
html. Java .

src ,
Java. , ,
, ,
. .
,
. , , System,
src/java/lang/System.java.

44

2 Java


Microsoft Visual Studio, ,
, ,
, . JDK
,
(). .
Java ,
.
Java , ,
.
,
.

Java, , ,
.
, .
Eclipse NetBeans. ,
Eclipse, ,
NetBeans, NetBeans .
, ,
.

Emacs, JEdit TextPad.
,
. ,
JDK,
, .


,
. .
1. .
2. CoreJavaBook/vlch02/Welcome. (,
Core JavaBook
, "
".)
3. :
javac Welcome.java
java Welcome

, . 2.4.

45

cd CoreJavaBook/vlchQ2/Welcome
~/CoreJavaBook/vlchQ2/Welcome$ javac Welcome.java
~/CoreJavaBook/vlchG2/Welcome$ java Welcome
Welcome to Core Java
by Cay Horstmann
and Gary Cornell
~/CoreJavaBook/vlchG2/Welcome$ |

. 2.4. Welcome, java

!
Java.
? ( ) javac
Java. Welcome .java
-, Welcome.class. java
Java. -,
. class.
! , ,
, Java.
for

(String g : greeting)

Java,
:
for (int i = 0; i < greeting.length;
System.out.printIn(greeting[i]);

i++)

Welcome .
2.1, , ,
.
2.1. Welcome .java
----------------------------------------------------------

1
2
3
4
5

/**
*
* (Aversion 1.20 2004-02-28
* @author Cay Horstmann
*/

46

2 Java

6 public class Welcome


7 {
8
public static void main(String[] args)
9
{
10
String[] greeting = new String[3];
11
greeting[0] = "Welcome to Core Java";
12
greeting[1] = "by Cay Hortsmann";
13
greeting[2] = "and Gary Cornell";
14
15
for (String g : greeting)
16
System.out.println(g);
17
}
18 }

no

.
. , ,
.

,
. ,
Welcome, welcome WELCOME.

( Welcome.java).
( Welcome)
.java .class.

"Bad command or file name" (


) " javac : command not
found", , Java
.

javac "cannot read: W e l c o m e .java"


( Welcome, java), ,
.
Unix, ,
Welcome.java. Windows
dir,
Windows. ( , Notepad)
. txt.
Welcome, java,
Welcome.java.txt. Windows
. txt, .
, ,
, , "Welcome, java".

java.
lang.NoClassDefFoundError, , .
welcome,
java Welcome,

47

W. , Java .
Welcome/java,
, java Welcome .java. java
Welcome.

Welcome,
, , -
CLASSPATH . ( ,
, ,
Windows .)
CLASSPATH
,
set CLASSPATH

Windows, Unix/Linux
shell. Unix/Linux
Boume/bash, :
export CLASSPATH
. http://docs.oracle.com/javase/
tutorial/getStarted/cupojava. ,
Java.


, Eclipse.
,
http://eclipse.org. Eclipse Java,
- .
Eclipse Linux, Mac OS X,
Solaris Windows.
, Eclipse
. ,
.
1. Eclipse File=>New Project (=>
).
2. Java Project ( Java)
(. 2.5).
Eclipse 3.2. Eclipse
.
3. Next (), W e lc o m e
, Welcome, java (. 2.6).
4. - Create project from existing source (
).
5. Finish (). .

48

2 Java

J\v I'I.jI I

""

S e le c t a w iz a rd
C re a te a Java project

Hazards:
| ty p e filte r te x t

41

I: . *

t-ave Project

& Java P roject fro m Existing A nt Buildfile

0 Plug-in Project
^ (? G e n e ra l

> {^CVS
> Eclipse M od elin g F ra m e w o rk
_____________________________________

? ** **

i|

Cancel

. 2.5. Eclipse

N.
C re a te a ja v a p ro je c t
C re a te a Java pro ject in th e w o rksp ace or in an e x te rn a l location.

project nam e: W e lco m e


(C o n ten ts------; C reate new project inaforkspace
: $ C reate project fro m e x is tin g to u rs *
.
,

'..r-TT-n-n'r^ -rr.T-r-n-^ r,^ J

; Q jrectp ry: |/h o m e /c a y /C o re J a v a B o o k /v lc h 0 2 /W e lc o m e

m :

.'sa.

j'Fit M
_urrent';-

'

J ] B tfflw e ..

.6

Lk is p.<a.a..L tpeeihs; jfiE:


}11-(\:

---

'

| .*. yp&.p'oiftit'Mder as iO.sc far spiPciss ahd'aa?sfi!tis.


j

'

/ a its? sap-a/jla source ftr-d ouU>-.-. feeders

The specified external location already exists, tf a project is created in this

Cancel

. 2 .6 . Eclipse

49

6.
, (default package), ..
. Welcome .ja v a .
, . 2.7.
! 1. I -

I I .

I11

">I -I

#& ..

0 Edit Source Rafactw fterigat*


If

Q~

i V *

\8<*[ |1
v %j %

9 1|

;A
ir

!*(
K it r J

MJ

{ A Package ... 3

I
|
1^ W
I
| 7

Outline \

4.
-i A ;
l 8 main(String!])
* i

* This program displays a greeting from the authors.

W elcom e

* e v e r s io n 1 .2 0 2 0 0 4 0 2 2 8

(default package)

* gauthor Cay Horstmann


*/

f i

p u b lic c la s s Welcome
JRE System Library [jd k l.e .O jii

4i
iiI

p u b lic s t a t i c v o id m a in ( S t r in g [ ] e rg s )

S t r i n g ! ] g r e e t in g = new S t r i n g [ 3 ] ;
g r e e t in g [ 0 ] = 'W elcom e t o C o re J a v a " ;
g r e e t i n g t l ] = "by Cay H o rstm an n ";
g r e e t in g [ 2 ] = "and G ary C o r n e ll" ;
f o r ( S t r i n g g : g r e e t in g )
S y s te m . out. p r i n t l n ( g ) ;

* \
i

3r *I

If$%

$
a

?ii< I
f# Tl
. 2 .7 . Eclipse

7. (Welcome)
. Run*=>Run A s^Java
Application ( ^ 1^ Java).
(. 2.8).

. 2 .8 . Eclipse

50

2 Java



. ,
, , String
:
String[] greeting = new string[3];

.
, ,
string (. 2.9). .
,
.

. 2.9. , Eclipse
. Eclipse
. ,
.

,
Eclipse. Eclipse 11.

51


Welcome .
.
, . ,
.
1. .
2. CoreJavaBook/vlch02/ImageViewer.
3. :
javac ImageViewer.java
java ImageViewer

ImageViewer (. 2.10).
f* lm.
Bl*

<-r

_ X

. 2 .10 . ImageViewer

File^Open (=>)
, . (
.) ,
Close ()
File^Exit (^).
.
, , , ,
C++ ,
. , Visual
Basic.
, . JDK
,
, 2.2.
7-9.

52

2 Java

2.2. Im a g e V ie w e r /Im a g e V ie w e r . j a v a
1
2
3
4
5

import
import
import
import

java.awt.EventQueue;
java.awt.event.*;
java.io.*;
javax.swing.*;

6 /**
7
*
8
* version 1.22 2007-05-21
9
* author Cay Horstmann
10 */
11 public class ImageViewer

12 {
13
14
15
16
17
18
19

public static void main(String[] args)


{
EventQueue.invokeLater(new Runnable()
public void run()
JFrame frame = new ImageViewerFrame ();
frame.setTitle("ImageViewer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

}) ;
}
}
/**
* .
*/
class ImageViewerFrame extends JFrame
{
private JLabel label;
private JFileChooser chooser;
private static final int DEFAULT_WIDTH= 300;
private static final int DEFAULT_HEIGHT = 400;
public ImageViewerFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
//
label = new JLabel();
add(label);
//
chooser = new JFileChooser();
chooser.setCurrentDirectory(new File( ."));
//
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);

v
JMenu menu = new JMenu("File");
menuBar.add(menu);


56
57
58
59
60
61
62
63
64
65
66
67
68

53

JMenuItem openltem = new JMenuItem("Open");


menu.add(openltem);
openltem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
//
int result = chooser.showOpenDialog(null);
// ,
if (result == JFileChooser.APPROVE_OPTION)

{
String name = chooser.getSelectedFile().getPath ();
label.setlcon(new Imagelcon(name));

69
70
71
}
72
}) ;
73
74
JMenuItem exitltem = new JMenuItem("Exit);
75
menu.add(exitltem);
76
exitltem.addActionListener(new ActionListener()
77
{
78
public void actionPerformed(ActionEvent event)
79
{
80
System.exit(0);
81
}
82
});
83
}
84 }


, , ,
Java, .. ,
. ,
Java
-.
.
( appletviewer), JDK.
-.
,
CoreJavaBook/vlch2/WelcomeApplet, :
javac WelcomeApplet. java
appletviewer WelcomeApplet.html

. 2.11.
Java.
WelcomeApplet.java
-, WelcomeApplet .class.
java appletviewer.
JDK.
appletviewer HTML, .
WelcomeApplet.html 23.

54

2 Java
. | >| I t*I V 1w <*I : W t*| ( <>11111 | >| >11 (. <

--- ......... ____ sJi

. 2 .1 1 . WelcomeApplet,
Applet Viewer
2.3. WelcomeApplet.html
1 <html>
2
<head>
3
<title>WelcomeApplet</title>
4
</head>
5
<body>
6
<hr/>
7
<p>
8
This applet is from the book
9
<a href="http://www.horstmann.com/corejava.html">Core Java</a>
10
by <em>Cay Horstmann</em> and <em>Gary Cornell</em>.
11
</p>
12
<applet code="WelcomeApplet.class"width="400" height="200">
13
<param name="greeting" value ="Welcome to Core Java!"/>
14
</applet>
15
<hr/>
16
<p><a href="WelcomeApplet.java">Thesource.</a></p>
17
</body>
18 </html>

HTML,
<applet>, appletviewer,
, WelcomeApplet .class.
appletviewer HTML, <applet>.
, . ,
Java . -
http://java.com/ru/download/help/enable_browser.xml ,
Java.
, .
.
1. /
2. File^Open File ( ^ )
.

55

3. CoreJavaBook/vlch2/WelcomeApplet/
WelcomeApplet.html .
4. , . -
, . 2.12.
*M*km*fb lodf

,Q

f e file :///bo m e/cay/C oreJavaB o o ^ Ic h o I/W e lc o m e A p plef /W elcorneAppret , ]7

This applet Is from the book Core lava by Cay Horstmann and Gary Cornell,

Welcome to Core Java!

The source.

. 2 .12 . WelcomeApplet

,
. Cay Horstmann,
. Gary Cornell.
,
.
,
appletviewer.
-,
.
.
.
. . Eclipse,
R u n^R un as^ Java A pplet (^ <=> Java).

Welcome 2.4.
. 10.
2.6. WelcomeApplet/WelcomeApplet .java1
3
2
1
2
3

import java.awt.*;
import java.awt.event.*;
import java.net.*;

56
4
5
6
7
8

2 Java

import javax.swing.*;
/**
*
* (Aversion 1.22 2007-04-08
* Oauthor Cay Horstmann

9 */

10 public class WelcomeApplet extends JApplet


11 {
12
public void init()
13
{
14
EventQueue.invokeLater(new Runnable()
15
{
16
public void run()
17
{
18
setLayout(new BorderLayout());
19
20
JLabel label =
21
new JLabel(getParameter("greeting), SwingConstants.CENTER);
22
label.setFont(new Font("Serif, Font.BOLD, 18));
23
add(label, BorderLayout.CENTER);
24
25
JPanel panel = new JPanelO;
26
27
JButton cayButton = new JButton("Cay Horstmann");
28
cayButton.addActionListener(makeAction("http://www.horstmann.com"));
29
panel.add(cayButton);
30
31
JButton garyButton = new JButton("Gary Cornell");
32
garyButton.addActionListener(makeAction("mailto:gary_cornell@apress.com"))
33
panel.add(garyButton);
34
35
add(panel, BorderLayout.SOUTH);
36
}
37
});
38
}
39
40
private ActionListener makeAction(final String urlString)
41
{
42
return new ActionListener ()
43
{
%
44
public void actionPerformed(ActionEvent event)
45
{
46
try
47
{
48
getAppletContext().showDocument(new URL(urlString));
49
}
50
catch (MalformedURLException e)
51
{
52
e.printStackTrace();
53
}
54
}
55
};
56
}
57 }

,
, Java. 3,
Java.


Java
...
Java



I

, JDK
, 2.
. ,
Java ,
, .
, Java ,
, , ,
.
,

58

3 Java

,
.
.
, C/C++,
, C/C++,
. ,
, Visual Basic, ,

. .

Java
, Java.
.
public class FirstSample

{
public static void main(String[] args)

{
System.out.println("We will not use 'Hello, World!'");

, ,

Java, .
, Java .
(, Main main),
.
.
public .
.
5. class ,
Java .
, ,
, .
, ,
Java. , Java, .
class .
. ,
.
. Java
(, public class). (
.)
,
( FirstSample).
, . (
" " CamelCase.)
, , ,
(public) , .java. ,

Java

59

FirstSample. java. ( ,
, f irstsample .java
.)

, , -
. Java FirstSample.class
, .
Java, :
java FirstSample

( .class !)
"We will not use * Hello, W o r l d ' ! " (
, !).

:
java

Java main ()
( Java .)
,
main (). ,
main (). ( , , .)
! Java (Java Language Specification!
main () public. ( Java
. http://docs.oracle.com/javase/specs.
Java , main()
public. ,
http://bugs.sun.com/bugdatabase/index.jsp,
4252539. .
Sun Microsystems , Java
, main () (. - http://docs.
oracle.com/javase/specs/jvms/se7/html),
. , .
Java Java SE 1.4 , main () (public).
. , -
, , ,
Java,
. , ,
Sun Microsystems
-, .
. " . ,
, JDK.

1
. Java, , C/C++,
. Java
({) (}).

3 Java

.
, .
Java,
. ,
, .
s t a t i c void,
Java. 4
. ,
Java main (),
.
public class

{
public static void main(String [] args)

}
}
C++! C++, , , , .
Java C++, . , Java
. ( Java
- C++.) , Java ,
main (). , - C++.
-, .
main () Java . , C/C++,
void , . C/C++, main ()
.
, 0.
, System.exit ().

:
{
System.out.println("We will not use 'Hello, World!'");

}
,
.
, Java
. Java .
, ,
, .
main ()
. System,
out println (). ,
. Java
, :
. ()

println ()
. ,
. Java, C/C++,

61

. (
.)
Java, ,

, 2.
, . ,
p r in t In () .
:
System.out.println();

! System .out print ( ) ,


, . ,
System, out .print ("Hello") "Hello" .
.

Java, ,
. ,
, , . Java
.
(//),
/ / . ,
, / / ,
.
System.out.println("We will not use 'Hello, World!'");
// ", !".
// , ?

,
/ * * / . ,
, ^
/ * * * / , 3.1.

4.
3.1. FirstSample/FirstSample. java 1
1
2
3
4
5
6
7
8
9
10

/**
* 3
* @version 1.01 1997-03-22
* Oauthor Gary Cornell
*/
public class FirstSample
{
public static void main(String[] args)
{
System.out.println("We will not use 'Hello, World!'");

11

12 }

62

3 Java

! Java , / * * / , .
, ,
/ * * / , , ,
/ * * /


Java . ,
. Java
. ,
, (
" char"), .
! Java
. " " Java
. , .


,
. Java
. . 3.1.
3.1. Java

()

()

int

-2 1 4 7 4 8 3 6 4 8 2 1 4 7 4 8 3 6 4 7 (.. 2 .)

short

-3 2 7 6 8

long

-9 2 2 3 3 7 2 0 3 6 8 5 4 7 7 5 8 0 8 -9 2 2 3 3 7 2 0 3 6 8 5 4 7 7 5 8 0 7

byte

- 1 2 8

3 2 7 6 7

127

, in t. ,
,
lo n g . byte sh o rt , ,
, ,
,
.
Java
, .
.
C++,
. ,
32- ,
16- . Java
,
.

63

L (, 4000000000L),
(, OxCAFE),
0. , 010 8 .
,
.
Java 7
0. , 0 001 9 . ,
, , ,
1_000_000 ( 01111_ 0100_ 0010_ 0100_ 0000) .

, Java .
C++! C++ , int long,
. , 8086 16-
int 2 , 32- ,
Pentium SPARC, 4 . long
32- 4 , 64-
8 . .
Java .
, Java unsigned.


. Java
. . 3.2.
3.2. Java

()

()

float

3,40282347E+38F (6-7
)

double

1,7976931348623157E+308F (15
)

double ,
f l o a t . ( .)
double ,
f l o a t .
() , , ,
,
. , f l o a t ,
( f l o a t ),
(
).
f l o a t F, 3.14F.
, F (
, 3.14), double.
( ) D, 3 . 14D.

64

3 Java

!
. , 0 ,1 2 5 = 2 '3 0 1 .0 -3 .
,
, . ,
, ,
2, 10.


IEEE 754. , Java :

POSITIVE INFINITY ( );

NEGATIVE INFINITY ( );

NaN ( ).

, 0
. 0 /0
NaN.
! Java Double. POSITIVE_INFINITY, Double.NEGATIVE_
INFINITY Double.NaN ( float).
. , , ,
Double.NaN, .
if

( == Double.NAN)

//

, ", .
Double.isNaN (), .
if (Double.isNaN()) // ,

! ,
. , System.out.
println(2.0 - 1.1) 0.8999999999999999, 0.9,
.
. 1 /3 ,
1 /1 0 .
, BigDecimal,
.

c h a r
char .
. , 1',
65. ,* "",
. (Unicode)
\u0000 \uFFFF. ,
\u2122 (), \u03C0
71.

65

Xu, ,
,
. 3.3.
, 1\u2122' "11\".
, \ ( ),
, .
, \u005B
\u005D [ ].
public static void main(String\u005B\u005D args)

3.3.

\u0008

\t

\u0009

\u000a

\u000d

\"

\u0022

\u0027

\\

\u005c

char,
.
.
: ASCII, ISO 8859-1, KOI-8,
GB18030, BIG-5 .. . -,
. -,
:
, ,
.
.
, 1980- , ,
,
.
. 1991 Unicode 1.0,
65536 . Java
16- ,
, 8- .
:
65536.
, .
16- char
.
,
Java, Java SE 5.0, . ,
, .

66

3 Java

,
U+. ,
U + 0 0 4 1 . 17 .
, , "
" U+0000 U+FFFF.
U+10000 U+10FFFF
.

UTF-16
.
16- , .
.
2048
.
U+D800 U+DBFF
U+DC00 U+DFFF .
,
. , ,
, U+1D546
U+D835 U+DD46 ( UTF-16
, http://ru.wikipedia.org/wiki/UTF-16).
Java char UTF-16.
Java UTF-16
.
( , "
").

b o o le a n
boolean : false true.
. boolean
.
C++! C++
. , false,
true. Java
. , Java ,
:
if

( = 0) // == 0 = !

C++ ,
false. Java
, = 0 .

Java .
, .
.

67

double salary;
int vacationDays;
long earthPopulation;
char yesChar;
boolean done;

.
, Java .

. Java ,
. ' A f ' Z',
, a f- , z ,/ 1_ ' , .
,
' 1, 1 '.
, 10 1- 19 1, ,
. ' + 1
'', .
, .
.
! ,
Java, isJavaldentif ierStart ()
isJavaldentifierPart () Character.

! $ Java,
.
, Java .

Java.
(
.)
:
int i, j; //

.
, ,
.
! , Java . ,
hireday hireDay . ,
, , .
.
, , .
:
Box box;

// Box - ,

a box -

:
Box ;

68

3 Java



/ ,
, . ,
.
int vacationDays;
System.out.println(vacationDays); // !

- ,
, (=),
Java , :
int vacationDays;
vacationDays = 12;

.
:
int vacationDays = 12;

Java ; ,
.
double salary = 65000.0;
System.out.println(salary) ;
int vacationDays = 1 2 ; //

Java
, .
C++! C++
.

int i = 10;

:
extern int i;

Java .

Java f i n a l ,
.
public class Constants
{
public static void main(String[] args)

{
final double CM_PER_INCH = 2.54;
double paperWidth = 8.5;
double PaperHeight = 1 1 ;
System.out.println("Paper size in centimeters: "
+ paperWidth * CM_PER_INCH + "by" + paperheight * CM_PER_INCH);

69

final , -
, .
,
.
Java ,
. .
static final.
.
public class Constants2

{
public static final double CM_PER_INCH = 2.54;
public static void main(String [] args)

{
double paperWidth = 8.5;
double paperHeight = 11;
System.out.println("Paper size in centimeters: "
+ paperWidth * CM_PER_INCH + " by " + paperHeight * CM_PER_INCH);

,
main (), . ,
public,
.
Constants2.CM PER INCH.

C++! Java const ,


. final.

, ,
Java : + - * /
. / ,
.
. %.
, 15/2 7, 15%2 1, 15.0/2 7.5.
,
,
NaN.
Java
(.. , ). ,
X += 4;


= + 4;

( , * %,
, * = %=.)

70

3 Java

! Java .
, ,
.
.
double 64 , 80-
. *
. :
double w = * / z;

Intel *
80- , z , ,
64 . ,
. ,
64- .
Java , .
. .
,
. Java ,

.
. ,
strictfp, ,
. , main () :
public static strictfp void main(String[] args)

main ()

. s t r i c t f p ,
.

Intel.
,
. ( Intel
.) ,
, .
, .
, , . ,
, strictfp .


, , ,
. Java,
C++,
. , ++
,
.
13.
int * 12;
++;

71

++ ,
. , 4++ .
.
,
. : ++.
. ,
.
, ,
,
, .
int
int
int
int

m
n
a
b

=
=
=
=

7;
7;
2 * ++m; // 16, a m 8
2 * n++; // b 14, a n 8


,
.
( ++ C++,
. ,
: " ++,
".)


Java .
= . , 3 == 7
false. ! =. , 3 ! =
7 true. , Java
: < (), > (), <= ( ) =>
( ).
Java, C++, 66
, | | . ,
(!) . 66 | |
:
, .
, 66.
_ 1 && _ 2

, .
. ,
, .
! = 0 & & 1 / > + / /

, .
1 I I _2 ,
. Bjopoe .
Java ?:,
. .
? _1 : _ 2

72

3 Java

, ,
. , < ? :
.


, ,
, ,
. ,
. Java : 6
(), | (), ( ), - (). , ,
,
.
int fourthBitFromRight = (n & 8) / 8 ;

& 2,
, .
! & |
boolean . &&
11, , , ..
.

Java ,
. ,
:
int fourthBitFromRight = (n & (1

3) )

3;

> , ,
.
, < , Java .
!
32 ( long,
64). , 1 3 5 1 3
8.

! C/C++ , :
( ) (
). ,
. , C/C++
. Java .


Math ,
. ,
, sqrt ():

73

double = 4;
double = Math.sqrt(x) ;
System.out.println () ; // 2.0

! println () sqrt () , .
println () System.out, System,
sqrt() Math, . .
.

Java .
pow () Math.
, .
pow (), double.
double = Math.pow(, );

Math
.
Math.sin()
Math.cos()
Math.tan()
Math.atan()
Math.atan2(>

,
( ):
Math.exp()
Math.log()
Math.loglO()


71 .
Math.PI ()
Math. ()

. Math
, :
import static java.lang.Math.*;

, .
System.out.println("The square root of \u03C0 is " + sqrt(PI));

! Math
, .
, , StrictMath.
fdlibm
, . ,
, http://www.netlib.org/fdlibm/index.html.
( fdlibm ,
IEEE 75 StrictMath "".)

74

3 Java


.
. 3.1 .

. 3 .1 .

. 3.1 ,
,
, . ,
123456789 ,
f l o a t . , f l o a t ,
, :
int = 123456789;
float f = n; // f 1.2345678928

(, n+f,
, a f ),

.

double,
double.

, f l o a t ,
f l o a t .

, long,
long.

in t.

75


, int ,
, double. ,
double .
Java , , , .
.
, ,
:
double = 9.997;
int nx = (int)x;


9,
.
( ),
M a t h . round (), .
double = 9.997;
int nx = (int)Math.r o u n d ();

nx 10.
round () - (int). ,
, round (), long,
int .
.
!
. . ,
(byte) 300 44.

C++! .
. ,
,
b ? 1 : 0.


. 3.4 .
, . ,
, ,
, , . 3.4. ,
&& | |, && b I |
( && b) I | . += ,
, += b += += ( += ).
b += (.. b
) .

76

3 Java

3.4.

[ ] . () ( )

! ~ ++ + () - () () () new

* /%

+-

>

< < = > > = instanceof

= !=
&.

&&

II

= + = - = * = / = % = | = = = = > =

C++, Java -.
for , .



. , : ,
, . ,
(1, 2, 3 4) (S, X). .

, 0 .
.
. :
enum Size { SMALL, MEDIUM, LARGE, EXTRA_LARGE };

, .
Size s = Size.MEDIUM;

Size .
n u ll, ,
.
5.

77


, Java
. , " Java\u2122" : J, a, v,
. Java .
Java String. ,
, String:
String = "; //
String greeting = "Hello";

substring () String
. ,
" I:
String greeting = "Hello";
String s = greeting.substring(0, 3);

substring () ,
.
0 ,1 2 (.. 0 2 ),
s u b s tr in g () 0 3,
0 2 , 3.
substring ()
:
. s .substring (, ) b - . ,
" 1" 3 - 0 = 3.

Java, ,
, + .
String expletive = "Expletive";
String PG13 = "deleted";
String message = expletive + PG13;

message
"Expletivedeleted", . (
. +
,
.)
, ,
. ( 5,
Java .)
rating "PG13",
,
.
int aqe = 13;
String rating = "PG" + age;

78

3 Java

. ,

, .. :
System.out.println("The answer is " + answer);


String ,
. ,
greeting "10* " H e l p ! ",
. , ,
. " ?" . Java
, ,
, , .
greeting = greeting.substring(0, 3) + ! ;

greeting "Help! ".


Java, ,
S t r i n g , .. .
3 3, "Hello"
' ', 1 1, 11 *, 11' 1. . ,
,
greeting ,
, 3, 4.
? ,
, . , .
,
"1" " ! ". :
.
, ,
.
.
.
,
. , Java ,

.
. ,
, . , ,
.
,
, .
Java StringBuffer,
" ", ,
String.

C++!
Java, ,
:

79

char greeting[] = "Hello";

: Java
char*:
char* greeting = "Hello";

greeting Java
:
char* temp = malloc(6);
strncpy(temp, greeting, 4);
strncpy(temp + 4, "!", 2);
greeting = temp;

, greeting "Help!".
, Java ,
strncpy (). , greeting
, ?
greeting = "Howdy";

? , Java
". , .
C++ string, ANSI
C++, string Java. string
C++ .
,
. C++ , ,
.


,
equals (). , s.equals (t) true,
t , false.
, t
. , :
"Hello!".equals(greeting);

,
, equalsIgnoreCase (), .
"Hello".equalsIgnoreCase("hello");

==.
, .
, , .
,
. .
String greeting = "Hello"; // greeting
if (greeting = "Hello") ...
// ,
if (greeting.substring(0, 3) == "Hel") ...
// ,

80

3 Java


,
= . ,
, ,
s u b s t r i n g (). ,
= ,
,
.
C++! string C++,
. string ==
. ,
Java ,
.
Java , , = ,
+. , .
= ,
strcmp (). compareTo () Java
strcmp (). , :
if

(greeting.compareTo("Help")

== 0)

...

, , equals () .


"" .
, ,
if (str. length () == 0) if (str .equals ( " " ) ) .
Java , (.. 0)
. String
null, ,
. (
null 4.) ,
, .. null, if (str =
= null).

, ,
. if (str != null && str. length () != 0). Ho
, str .
4, null .


Java
char. " char",
char ,
UTF-16.
, .

81

length ()
UTF-16. .
String greeting = "Hello";
int n = greeting.length(); // n 5

, ,
:
int cpCount = greeting.codePointCount (0, greeting.length());

s .char At (n) ,
0 s . length () - 1.
.
char first = greeting.charAt(0); // - * 1
char last = greeting.charAt(4); // - 'o'

i- .
int index = greeting.offsetByCodePoints(0, i) ;
int cp = greeting.codePointAt(index);

! Java, C/C++,
.

?
:
is the set of octonions

UTF16. ,
:
char ch = sentence.charAt(1)

, char,
.
, ..
, ,
.
int cp = sentence.codePointAt(i);
if (Character.isSupplementaryCodePoint(cp)) i += 2;
else i++;


:
i ;
if (Character.isSurrogate(sentence.charAt(i))) i ;
int cp = sentence.codePointAt(i);

API S t r i n g
Java String 50 .
.
API .

82

3 Java

!
API Java.
, java.lang.string, java,
lang ( 4).
.
,
.
, .
, , .
, .

ja v a .la n g .S tr in g

1 . 0 *

char charAt(int index)

, .
, .

int codePointAt(int in d ex)

5.0

, .

int offsetByCodePoints(int s t a r t l n d e x ,

int cpCount)

5.0

, cpC ount
s t a r t l n d e x .

int compareTo(String o th e r)

,
o th e r, o t h e r ,
.

boolean endsWith(String s u f f i x )

true, s u f f i x .

boolean equals(Object o th e r)

true, o th er.

boolean equalsIgnoreCase(String o th e r)

true, o t h e r
.

int indexOf(String s t r )

int indexOf(String s t r ,

int indexOf(int cp)

int indexOf (int cp,

int from ln dex)

int from ln dex)

, s t r ,

0 fo rm ln d a x .

, , -1 .

int lastlndexOf(String str)

83

int LastindexOf (String s t r ,

int lastindexOf(int cp)

int lastindexOf (int cp ,

int from ln dex)

int from ln dex)

, s t r ,
. form lndex.
, , -1 .

int length()

int codePointCount(int
sta r tln d e x ,
i

int en dln dex)

5.0

s t a r t l n d e x e n d ln d e x
.

String replace(CharSequence o l d S t r in g ,

1.

CharSequence n ew Strin g)

, ,
o l d S t r i n g , n e w S trin g . CharSequence
String StringBuilder.

boolean startWith(String p r e f i x )

true, p r e f i x .

String substring(int b e g in ln d e x )

String substring(int b e g in ln d e x ,

int endln dex)

, , b e g in ln d e x
en d ln d ex

1.

String toLowerCase()

, .
,
.

String toUpperCase()

, .
,
.

String trim()

, .

API
/ S t r i n g . ,
/
. .

API,
.

84

3 Java

JDK. HTML.
docs/api/index.html,
, JDK. ,
. 3.2.

. 3.2.
API

.
.
. ,
(. 3.3). ,
String,
, String,
.
,
.
(. 3.4). ,
(. 3.5). , compareToIgnoreCase,
.


S tu n u

P la tfo r m

85

7 )-

FHe Edit View History Bookmarks Tools Help

S3
SB

R ie:///data/apps/jdk-7-d ocs/api/index.htm l

';

1' '

PJatfonn

StandardEd 7

1'/
-- .. ,

AS? C lasse s

java,applet

rm

!
J~

iv
li
j

->
--. --4J ' ,

javaJang

Class String

StraamFHter
java.fang.QbJect
javaJangString

StreamHandler
Sbeam PnntService
StreamPrlntServiceFact
StreamReaderDelegate
StreamResuit
Sbeam Source
StreanVfoKenizer
SfrictMath

All implemented Interface s :


Serializable, CharSequence, Com parabie<Stn ng>
;

public final class S trin g


extends Object
iapleeents Serializable, Co#parable<String>, CharSequence

iS......trtn
o.'/i
...V

StringBuffer
SbingBuffertnputSbearr
StdngSuiider
(
StnngCharactertferator
StringCenten r 11
String Holder
-~
StringlndexGutCHBound
Stnng Monitor

The St n n g class represents character strings. string literals in Java program s, such as "abc",
im plem ented as Instances o f tois d ass.
Strings are constant; their values cannot be changed alter they are created. String butters support
m utabie strings. B ecause Stong objects are im m utable toey can be shared For exam ple:
String str = "abc

SfringMonltorMBean
StringNameHelper

r?m !
1

v.v.-.

< Previous > n e x t

Find: ! String

. HaghUghtiU Q M atch case

. 3 .3 . String
I

, ) M \;r r', 'j

I ! ,i F i n d o x

Fite Edit View History Bookmarks Toots |4eip

<$

G ; ffle:///data/ppps/jdk-7"docs/api/index.htm l

Java v P-atfon
Standard Fd

Method Summary

! int

S tr & a m F iite r

Sbeam Handler
Sbeam PrlntService
SfreamPrintServtceFacf
Stream ReaderDeiegate
StreamResuit
Sbeam Source
Sbeam totenizer
StoctMato

<{
;|

SbingBuffer
String BuffertnputStrearr
SbingBuilder
jj
StringC haracter iterator j~_ tj
SbingContent
{- ij
SfrlngHoider
M i
SbmgtndexOutQffiound
StringMonitor
S trin g M o n ito r M B e a n

j jj

StringNam eHelper

0 j

Find: [s tring

iU,

c o d e P o in tA tlirrt in d e x )
Returns tee character (U nicode code point) a t toe specified in d ex

irrt

irrt

codeP ointC ounrt ( ir r t b e g in In d e x , in t e n d ln d e x )


j
Returns toe num ber o f Unicode code points In the specified text range j
o ftd s S tr in g .
1

{ in t
irrt

conpareToIgnoreCaselString st r)
Com pares two strings lexicographically, ignoring case differences

' IS trin g
! ) bo o lean

cent a im ! CharSequence s)

Retom s true it and only If tris sbing contains toe spedfled sequence o f j
char values.
j

.. I. ...
nilHkiftlttiil lilnjfl lii'llrltr't

< Erevious > M ext

H ig h lig h t# M atch case

. .. String

~RTvijaueA

86

3 Java
St t j. i v , , I ,I' ; ;

ZI

jFile Edit View H istory Bookmarks Tools Help


^

G ; fite:///d ata/ap p s/jd k-7-d o cs/ap i/( ndex.htm l

J 3 v ^ " Pl a t ?C-l!Ti

H i

S t a m i a r r i 3 7

All C la s s e s

Packages

J a v a .a p p le t .........._
4/
l

p./Fr*rTM
/|-4TW
r*<;pW
fJ. ... ......

!<3 > L

1 ^nj c a iiio v ! i UjJl!MJCAU?^;,ull,.i

Str&amFlitsr
SfreamHandier
StreamPrintService
SlreamPrintServiceFad
StreamReaderDeiegate
StreamResult
SireamSource
StreamloKenizer
StrictMath
Siring
StringBufler
SfringBufterfnputStrearr;
StringBuilder
:
StringCharactertterator j
StringContenl
]
StnngHoider
!
StringindexOutGfBound
S&ingMonitor
StringM om torM Bem

SfeingNameHelper

0i

T~

i idiet**

r-

ir
(/

"4ftm

iI public char charAt(int index)


ii

R eturns tie c h a value a t the specified In d e x An index ranges from G to 1 en g t h 1 1 - l . Trie


first cha r value o f the sequence Is at Index G, 9w next a t index l , and so on, as fo r array
Indexing,
tf trie c h a r valu e specified by Hie index Is a surrogate, d ie surrogate valu e is returned.

Specified b y :
c h arA t In interface CbarSequence
P a ra m e te rs :
in d e x - trie index o f the ch ar valu e.

Returns:
the ch ar value a t the specified index o f this sfiin g . Trie first c h a r value is a t Index G.

Throws:
in d exQ u tO fB o u n d sE xcep tio n - i f the in d e x argum ent is negative or not less Rian Hie
length o f this sfring.

L public int cpdePpintAt(int irif|exJ

l._:

Find:

String

< Erevfous

> tie x t

^ Highlight i l l M atch case

. 3.5. charAt () String


. . docs/api/index.html.



, ,
. .

String, . ,
StringBuilder.

,
. -,
:
StringBuilder builder = new StringBuilder();

( new 4.)
, ,
append (), .
builder.append(ch); //
builder.append(str); //

87

, t o S t r i n g ().
, S trin g , ,
:
String completedString = builder.toString();

! StringBuilder JDK 5.0. ,


StringBuffer, ,
. (
), , , StringBuilder.
API .

API
StringBuilder.
ja v a . la n g . S tr in g B u ild e r 5 . 0

StringBuilder()

int length()

StringBuilder append(String s t r )

this .

StringBuilder append(char )

this
.

StringBuilder appendCodePoint(int )

, ,
this .

void setCharAt(int i, int c)

/- .

StringBuilder insert(int o f f s e t , String s t r )

o f f s e t this
.

StringBuilder insert(int o f f s e t ,

char c)

o f f s e t this
.

StringBuilder delete(int s t a r t l n d e x ,

int endln dex)

s t a r t l n d e x e n d ln d e x -

this .

String toString()

, ,
.

3 Java


"" ,
, .
, ,

, .
Java,
-.
7-9.


,
(.. ), System, out .printIn ( ) .
System, in (.. )
- . Scanner
System, in, .
Scanner in = new Scanner(System.in);

( new 4.)
,
Scanner, . ,
nextLine () , .
System.out.print("What is your name? ");
String name = i n .nextLine();

nextLine () ,
. ,
, :
String firstName = in.nextO;

nextlnt ():
System.out .print ("How old are you? ");
int age = i n .nextlnt () ;

, next Double ()
.
, 3.2,
, :
Hello, Cay. Next year, you'll be 52
(, . 52)

:
import java.util.*;

Scanner java.util.
, ja v a .lang,
import.
import 4.

89

3.2. I n p u t T e s t / I n p u t T e s t .j a v a
1

import java.util.*
*;

3
4
5
6
7
8
9
10

/**
*
* (Aversion 1.10 2004-02-10
* @author Cay Horstmann
*/
public class InputTest
{
public static void main(String[] args)
11
{
12
Scanner in = new Scanner(System.in);
13
14
//
15
System.out.print("What is your name? ");
16
String name = in.nextLine ();
17
18
//
19
System.out.print("How old are you? ");
20
int age = in.nextlnt ();
21
22
//
23
System.out.println(
24
"Hello, " + name + ". Next year, you'll be " + (age + 1) );
25
}
26 }

! Scanner ,
. Java SE 6 Console,
. ,
:
Console cons = System.console();
String username = cons.readLine("User name: ");
chart] passwd = cons.readPassword("Password: ");

,
.
. ( .)
Console ,
Scanner. .
Console .

ja v a .u til.S c a n n e r 5 .0

Scanner(InputStream in )

Scanner .

String nextLine()

90

3 Java

String next()

, .

int nextlnt()

double nextDouble()

,
, .

boolean hasNextO
/

, .

boolean hasNextlntO

boolean hasNextDouble()

, ,
.

j a v a . l a n g . S y s te m 1 . 0

static Console console()

Console ,
, null. Console
, .
.

ja v a .io .C o n s o le

6
readPassword(String prom pt,

static chart]

static String readLine(String prom pt,

Object...

Object...

arg s)

arg s)

,
. a r g s
, .


System,
out . p r i n t l n ( ) .
, . ,

3 3 3 3 .3 3 3 3 3 3 3 3 3 3 3 3 5 .
double = 10000.0 / 3.0;
System.out.print(x);

. ,
, .

91

Java
. , Java SE 5.0
printf () , .
,
, 8 ,
. ( .)
System.out.printf("%8.2f", ) ;

, .
3333.33
p r i n t f () .
.
System.out.printf("Hello, %s. Next year, y o u ll be %d", name, age);

, %,
. ,
, : f ;
s ; d .
. 3.5.
3.5. p r intf ()

159

9f

15.9

1.59+01

(
f, ,
)

0x1.fccdp3

Hello

tx

true
426282
. . 3.7
%

,
. . 3.6.
, , , . ,

3 ,3 3 3 .3 3 .
System.out.printf ("%,.2f", 10000.0 / 3.0);

92

3 Java

,
, "% , ( . 2 f " ,
, .
! s
. Formattable, formatTo().

toString (). toString () 5, 6.

3.6. prin t f ()

+3333.33

| 3333.331

003333.33

13333.33 |

(3333.33)

3,333.33

# ( f)

3,333

# ( )

Oxcafe

,
. , %l$d %1$
,
,

159 9F

<

159 9F
,
. ,
%d %< ,
,


String.format (), .
String message =
String.format("Hello, %s. Next year, you'll be %d", name, age);

Date 4,
printf ,
.
, t,
, . 3.7. .
System, out .printf ("%tc", new D a t e O ) ;

:
Mon Feb 09 18:05:19 PST 2012

93

. 3.7,
.
, .
, ,
. %
$, .
System.out.printf("%l$s %2$tB %2$te, %2$tY", "Due date:", new D a t e O ) ;

:
Due date: February 9, 2012

<, ,
, .
, ,
.
3.7.

ISO 8601

Mon Feb 04 18:05:19


PST 2012
2012-02-04

, (//)

02/04/2012

24-

18:05:19

12-

06:05:19 pm

24- ( )

18:05

( ,
)

2012

( ,
)

12

( ,
)

20

February

b h

Feb

( ,
)

02

( ,
)

09

( )

Mon

001 366 (
, )

035

00 23 (
, )
0 23 (
)

18

Monday

94

3 Java
. 3 .7

01 12 (
, )

06

01 12
( )

( ,
)

05

( ,
)

19

( ,
)

047

( ,
)

047000000

AM

am pm

(GMT)
RFC 822

-0800

PST (

)
S

1970-01-01
00:00:00 GMT

197001-01 00:00:00 GMT

1078884319
1078884319047

! , . , %1$
. ,
.

, p r i n t f (). . 3.6
-,
.

%]

. 3 .6 .

95


,
S c a n n e r:
Scanner in = new Scanner(Paths.get("myfile.txt")) ;

,
, , : " : \ \
mydirectoryWmyfi l e . t x t " . ,
Scanner.
,
PrintWriter, , .

PrintWriter out = new PrintWriter("myfile.txt");

, .
print (), println () printf () ,
( System, out).
! Scanner ,
, . ,
:
Scanner in = new Scanner("myfile.txt"); // ?

Scanner 1m', ' ,


' f ' .. , .

! , "myfile.txt",
"mydirectory/myfile.txt" " . ./myfile.txt",
, Java.
:

java Prog
.
, .
, :
String dir = System.getProperty("user.dir");

,
": WmydirectoryWmyfile.txt" "/home/me/mydirectory/
myfile.txt".

, ,
System, in System.out . ,
: Scanner ,
, PrintWriter ,
, . Java
, , ,
. 11 .
,

96

3 Java

" ". main () throws:


public static void main (String [] args) throws FileNotFoundException

{
Scanner in = new Scanner(new File("myfile.txt"));

}
, .
-,
, , ,
1 .
! ,
- ,
System.in System.out, .
java MyProg < myfile.txt > output.txt

FileNot
FoundException.

ja v a .u til.S c a n n e r 5 .0

Scanner (File f)

Scanner, .

Scanner(String d a ta )

Scanner, .

ja v a .io .P r in tW r ite r

1 .1

PrintWriter(String fileN am e)

PrintWriter,
.

ja v a .n io .file .P a th s

static Path get(String pathnam e)

Path .


Java, ,
.

97

, .
sw itch,
.
C++! Java , C++,
. goto,
break ,
( goto). , Java
for, C++.
foreach #.



, . , ,
Java,
. .
. ,
main ().
public static void main(String [] args)

{
int n;

{
int k;

} // k

}
Java
. ,
.
public static void main(String[] args)

{
int n;

int k;
int n; // : n

}
C++! C++ .
. , Java
.


i f Java .
.
i f ( )

98

3 Java

Java, ,

. , .
{
1 ;
0 2 ;

}
:
if (yourSales >= target)

{
performance = "Satisfactory";
bonus = 100;

}
, ,
, yourSales
target (. 3.7).

. 3 .7 . -,
i f

! (

99


() Java,
() .

i f Java.
. 3.8.
if ( ) ! else 2

. 3.8. -,
i f / e l s e

if/else .
if (yourSales >= target)

{
performance = "Satisfactory";
bonus = 100 + 0.01 * (yourSales - target);

}
else

{
performance = "Unsatisfactory";
bonus = 0;

3 Java

e l s e .
i f . ,
e l s e i f :
if ( <= 0) if ( == 0) sign = 0; else sign = -1;

,
, .
if ( <= 0) { if ( == 0) sign = 0; else sign = -1; }

Java
i f . . . e l s e i f . . . (. 3.9).
.
if (yourSales >= 2 * target)

{
performance = "Excellent";
bonus = 1000;

}
else if (yourSales >= 1.5 * target)

{
performance = "Fine";
bonus = 500;

}
else if (yourSales >= target)

{
performance = "Satisfactory";
bonus = 100;


w h ile ( ,
) , , ..
tru e. .
while ( )

w hile , , ..
f a l s e (. 3.10).
3.3 , ,
,
. ,
.
, . ,
:
while (balance < goal)

{
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
years++;

}
System.out.println(years + " years.");

101

. 3 .9 . -,
i f / e l s e i f

( .
,
.)
w hile . ,
, , , ,
. , ,
. do-w hile,
:
do while ( );

102

3 Java

. 3 .1 0 . -,
w h ile

,
, . , ..
, , 3.4,
, ,
:
do

{
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
year++;

103

//

//

}
while (input.equals("N"));

, "Y"
(. 3.11). ,
,
, ,
.

. 3 .1 1 . -, d o - w h ile

104

3 Java

3.3. Retirement/Retirement.j ava


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

import java.util.*;
/**
*
* (Aversion 1.20 2004-02-10.
* author Cay Horstmann
*/
public class Retirement
{
public static void main(String[] args)

while

{
//
Scanner in = new Scanner(System.in);
System.out .print ("How much money do you need to retire? ");
double goal = in.nextDouble ();
System.out.print ("How much money will you contribute every year? ");
double payment = in.nextDouble ();
System.out.print("Interest rate in %: ");
double interestRate = in.nextDouble ();
doublebalance = 0;
intyears = 0;
// ,
while (balance < goal)
{
//
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
years++;
}
System.out .println ("You can retire in " + years + " years.");
}
}

3.4. R e t ir e m e n t 2 /R e t ir e m e n t2 . j a v a 1
1
2
3
4
5
6
7
8
9
10
11
12

import java.util.*;
/**
* do-while
* (Aversion 1.20 2004-02-10
* author Cay Horstmann
*/
public class Retirement2
{
public static void main(String[] args)

{
Scanner in = new Scanner(System.in);

105

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

System.out.print ("How much money will you contribute every year? ");
double payment = in.nextDouble ();
System.out.print("Interest rate in %: ");
double interestRate = in.nextDouble();
double balance
int year = 0;

= 0;

String input;
// ,
do
{
//
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
year++;
//

System.out.printf(
"After year %d, your balance is %,.2f%n", year, balance);
//
System.out.print("Ready to retire? (Y/N) ");
input = in.nextO;
}
while (input.equals("N"));


f o r .
,
.
fo r 1 10.
. 3.12.
for (int i = 1; i <= 10; i++)
System.out.printIn (i);

fo r ,
,
.
Java, C++,
f o r , ,
f o r
, .
, ,
.

106

3 Java

. 3 .1 2 . -, fo r

.
, f o r ,
, :
for (int i = 1 0 ; i > 0 ; i )
System.out.println("Counting down . . . " + i) ;
System.out.printIn("Blastoff!");

! , .
, .
for

(double = 0; != 10; += 0.1)

...

107

- . ,
9 .9 9 9 9 9 9 9 9 9 9 9 9 9 9 8 1 0 .0 9 9 9 9 9 9 9 9 9 9 9 9 9 8 ,
0 .1 .

fo r
, .
for (int i = 1; i <= 10; i++)

}
// i

, fo r,
. ,
fo r,
! , .
int i;
for (i = 1; i <= 10; i++)

} // i -

, ,
fo r, .
for (int i = 1; i <= 10; i++)

{
a a a

for (int i = 11; i <= 20; i++) // i


{

}
f o r w h ile.
, :
for (int i = 10; i > 0; i )
System.out.println("Counting down . . . " + i) ;

, . .
int i = 10;
while (i > 0)

System.out.println("Counting down . . . " + i);

i ;

}
f o r
3.5. . ,
6 50,
(50x49x48x47x46x45) / (12456), 1
15890700. ! , ,
:
( (-1)

( - 2)

. . .

( - + 1) / (1

. . .

108

3 Java


fo r:
int lotteryOdds = 1;
for (int i = 1; i <= k; i++)
lotteryOdds = lotteryOdds * (n - i + 1) / i;

! fo r ,
f o r each. Java SE 5.0.

3.5. LotteryOdds/LotteryOdds .java


1

import java.util.*;

2 /**
3
4
5

*
* (Aversion 1.20 2004-02-10
* @author Cay Horstmann

for

6 */
7

public class LotteryOdds

8 {
9

public static void main(String[] args)

10

11
Scanner in = new Scanner(System.in);
12
13
System, out .print ("How many numbers do you need to draw? ");
14
int k = in.nextlnt();
15
16
System.out.print ("What is the highest number you can draw? ");
17
int n = in.nextlnt ();
18
/*
19
* :
20
* *(-1)* (-2)*...*(n-k+1)/(1*2*3*...*k)
21
*/
22
int lotteryOdds = 1;
23
for (int i = 1; i <= k; i++)
24
lotteryOdds = lotteryOdds * (n - i + 1) / i;
25
26
System.out.println(
27
"Your odds are 1 in " + lotteryOdds + ". Good luck!");
28
}
29 }

s w it c h
if/else ^,
. Java
switch, C++. ,
(. 3.13),
:
Scanner in = new Scanner(System.in);
System, out .print ("Select an option (1, 2, 3, 4) ") ;
int choice = i n .nextlnt ();

109

switch (choice)

{
case 1:

break;
case 2:
#

break;
case 3:
#

break;
case 4:
#

break;
default:
//
# # #
break;

}
case, 1
choice, break
switch. case ,
default ( ).
! break case,
case. , ,
switch .
switch ,
-Xlint:fallthrough, .
javac -Xlint:fallthrough Test.java

,
break.
case,
@SuppressWarnings ("fallthrough").
. (
,
Java .
13 .)

case .

char, byte, short, int (


- Character, Byte, Short Integer,
4).

, Java SE 7.

no

3 Java

. 3 .1 3 . -,

s w itc h

1 11

, case.
String input = . . .;
' switch (input.toLowerCase ())

{
case "yes": // , Java SE 7

break;

}
sw itch ,
,
sw itch. :
Size sz * . . .;
switch (sz)

{
case SMALL: / / Size.SMALL

break;


Java goto,
. go to
.
, goto
(., , "
go to " (Structured Programming with goto statements; h ttp : / /
p p la b .sn u .a c .k r/c o u rse s/a d v _ _ p l0 5 /p a p e rs/p 2 6 1 -k n u th .p d f)). ,
goto .
. Java

. break .
b re a k .
break, sw itch.
break .
while (years <= 100)

{
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
if (balance >= goal) break;
years++;

}

: y e a rs > 100 b a la n ce >= g o a l .
, y e ars
break, .
while (years <= 100 && balance < goal)

{
balance += payment;

112

3 Java

double interest = balance * interestRate / 100;


balance += interest;
if (balance < goal)
years++;
1

}
, , , b a la n c e < g o a l
. break.
C++, Java break ,
.
.

.
, break
. ,
, . ,
.
Scanner in = new Scanner(System.in);
int n;
read^data:
while (. . .) //

for (. . .) //
{
System.out.print("Enter a number >= 0 : ");
n = i n .nextlnt ();
if (n < 0) //
break read_data;
//

}
}
//
// break
if ( < 0) //
{
//

}
else

{
//

}
, break
. ,
,
break.
! , -
if , .
:
{


if

() break ;

//

}
/ / break

, goto, ,
, , ,
break! , .
, , .

continue, , break,
. continue
.
.
Scanner in = new Scanner(System.in);
while (sum < goal)

{
System.out.print("Enter a number: ");
n = in.nextlnt();
if (n < 0) continue;
sum += n; / / , n < 0

}
n < 0, continue ,
. continue
for, .
:
for (count = 1; count <= 100; count++)

{
System.out.print("Enter a number, -1 to quit: ");
n = i n .nextlnt();
if (n < 0) continue;
sum += n; / / , n < 0

}
n < 0, continue count ++.
Java continue ,
, .
. Java ,

break continue

. ,
, . break
continue , , .



, Biglnteger
BigDecimal java.math.
, .

114

3 Java

Biglnteger BigDecimal

.
(
) valueOf ():
Biglnteger = Biglnteger.valueof(100) ;

,
+ * add () multiply ()
,
.
Biglnteger = a.add(b) ; // = + b
Biglnteger d = .multiply (b. add (Biglnteger. value. Of (2))); // d = c * (b + 2)

C++! C++, Java .


Biglnteger + *
add() multiply (), Biglnteger
. Java
+ .
Java .

3.6 3.5
.
. , ,
60 4 9 0 , ,
1 7 1 6 3 9 5 8 4 3 4 6 1 9 9 5 5 5 7 4 1 5 1 1 6 2 2 2 5 4 0 0 9 2 9 3 3 4 1 1 7 1 7 6 1 2 7 8 9 2 6 3 4
9 3 4 9 3 3 5 1 0 1 3 4 5 9 4 8 1 1 0 4 6 6 8 8 4 8 . !
3.5 :
lotteryOdds = lottery * (n - i + 1) / i;


:
lotteryOdds =
lotteryOdds.multiply(Biglnteger.valueOf(n-i+1).divide(Biglnteger.valueOf(i));

3.6. BiglntegerTest/BiglntegerTest.java 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

import java.math.*;
import java.util.*;
/**
*
* '
* (Aversion 1.20 2004-02-10
* @author Cay Horstmann
*/
public class BiglntegerTest

{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);

115

16
System, out .print ("How many numbers do you need to draw? ");
17
int = in.nextlnt ();
18
19
System.out.print ("What is the highest number you can draw? ");
20
int n = in.nextlnt ();
21
22
/*
23
* :
25
* *(-1)* (-2)*...*(n-k+1)/(1*2*3*...*k)
25
*
26
*/
27
28
Biglnteger lotteryOdds = Biglnteger.valueOf (1);
29
30
for (int i = 1; i <= k; i++)
31
lotteryOdds = lotteryOdds.multiply(Biglnteger.valueOf (
32
n - i + 1)).divide(Biglnteger.valueOf(i));
33
34
System.out.println("Your odds are 1 in " +
35
lotteryOdds + ". Good luck!");
36
}
37 }

java .math.Biglnteger 1.1

Biglnteger subtract(Biglnteger o th e r)

'"Biglnteger multiply (Biglnteger o th e r)

Biglnteger divide(Biglnteger o th e r)

Biglnteger mod(Biglnteger o th e r)

, , , ,

other.

int compareTo(Biglnteger o th e r)

0, o th er,
, o th er,
.

static Biglnteger valueOf(long x)

, .________________________________

java.math.BigDacimal 1.1

BigDecimal add(BigDecimal o th e r)

BigDecimal subtract(BigDecimal o th e r)

BigDecimal multiply(BigDecimal o th e r)

116

3 Java

BigDecimal divide(BigDecimal o t h e r , int roundingM ode)

5.0

, , ,
o th e r .
, . roundingMode.ROUND_HALF_UP
0-4 5-9.
.
.

int compareTo(BigDecimal o th e r)

0, BigDecimal o th e r ,
, o t h e r ,
.

static BigDecimal valueOf(long )

static BigDecimal valueOf(long x ,

int s c a l e )

,
x/10scale.

, .
.
, , a [i] i-e .
: , .. ,
, ,
. , .
int[] ;

, .
, new, .
int[] = new int [100];

, 100 .
. , new in t []
.
! :
int[]

int [];

Java ,
.

117

0 99 ( 1
100). .
, , .
int [] = new int[100];
for (int i = 0; i < 100; i++)
a[i] = i; // 0 99

.
boolean false,
null, ,
. .
, ,
, .. null.
String[] names = new String[10];

,
, .
for (int i = 0; i < 10; i++) names [i] = ,,H;

! , , 100 ,
[100] ( , 0
99), ,
.

_.
length. , length
:
for (int i = 0; i < a. length; i++)
System.out.printIn(a[i]);

( , ,
).
,
, . (
5.)

f o r e a ch
Java ,
( ), .
for :
for ( : )


, ( ).
,
Iterable, ArrayList. ArrayList
5, Iterable 1
.

118

3 Java


.
for (int element : )
System.out.println(element);


. Java
fo re a c h in .
Java,

, , ,
, System .in .
, , ,
fo r:
for (int i = 0; i < a. length; i++)
System.out.println(a[i]);

fo r each ,

. .
! for each
.

fo r each,
, fo r
. , , ,
, , ,
.
.
toStringO Arrays. , Arrays .toString ()
, ,
, : " [ 2 , 3, 5, 7 , 11, 1 3 ]" . ,
, System, out .println (Arrays .toString ());.


Java
. .
int[] smallPrimes = { 2, 3, 5, 7, 11, 13};

, new .
,
, .
new int[] {16, 19, 23, 29, 31, 37}

,
, .

119

.

. ,
smallPrimes = new int{ 17, 19, 23, 29, 31, 37 };

:
int[] anonymous = { 17, 19, 23, 29, 31, 37 };
smallPrimes = anonymous;

! .
, ,
. :
new _ [0 ]

, , ,
null. ( 4.)


,
mom :
int[] luckyNumbers = smallPrimes;
luckyNuimbers[5] = 12; // smallPrimes [5] 12

. 3.14.

,
Arrays.
:
int [] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers, luckyNumbers.length);

.
:
luckyNumbers = Arrays.copyOf(luckyNumbers, 2 * luckyNumbers.length);

, ,
false, boolean.
, ,
.

120

3 Java

C++! Java C++,


.
. , Java
int[]

= new int[100];

//Java

C++:
.int* = new int[100];

// C++

.
int [100];

// C++

Java [] . ,
Java . ,
, .


Java
main () String [ ] args. , main ()
, ,
. :
public class Message
{
public static void main(String[] args)

{
if (args[0].equals ("-h"))
System.out.print("Hello,");
else if (args[0].equals("-g"))
System.out.print("Goodbye,");
//
for (int i = 1; i < args. length; i++)
System.out.print(" " + args[i]);
System.o u t .println("!");

}
}
:
java Message -g cruel world

args :
args[0]: "-g"
args[l]: "cruel"
args[2]: "world


:
Goodbye, cruel world!
(, !)

C++! Java a rg s ,
m a i n ( ) . , Massage
java Message -h world args[0] "-h",
"Message" "java".

121


,
sort () Arrays:
int[] = new int [10000];

Arrays.sort(a);


,
. Arrays ,
. .
, 3.7,
. ,
49, :
Bet the following combination. It'll make you rich!
( , !)
4
7

8
19
30
44

numbers
1, 2,..., , .
int [] numbers = new int[n];
for (int i = 0; i < numbers.length; i++)
numbers[i] = i + 1;

:
int [] result = new int[k];

. M a t h .random ()
, 0 () 1 (
). ,
0 -1, :
int = (int) (Math, random () * n) ;

i-e i- .
+1, , , number
.
result[i] =numbers[r];

, , ..
. , number []
, , ,
.
numbers[] = numbers [ - 1];
;

,
, . , ,

122

3 Java

.
r e s u l t , :
Arrays.sort(result);
for (int i = 0; i < result.length; i++)
System.out.printIn(result[i]);

3.7. LotteryDrawing/LotteryDrawing. java 1


1 import java.util.*;
2
3 /**
4
*
5
* version 1.20 2004-02-10
6
* author Cay Horstmann
7
*/
8
public class LotteryDrawing
9
{
10
public static void main(String[] args)
11
{
12
Scanner in = new Scanner(System.in);
13
System, out .print ("How many numbers do you need to draw? ");
14
int k = in.nextlnt ();
15
16
System.out.print ("What is the highest number you can draw? ");
17
int n = in.nextlnt ();
18
19
// 1 2 3 . . . n
20
int[] numbers = new int[n];
21
for (int i = 0; i < numbers.length; i++)
22
numbers[i] = i + 1;
23
24
// k
25
int[] result = new int[k];
26
for (int i = 0; i < result.length; i++)
27
28
// 0 - 1
29
int = (int) (Math.random() * n);
30
31
//
32
result[i] = numbers[];
33
34
//
35
numbers[r] = numbers[n - 1];
36
37
n;
38
39
//
40
Arrays.sort(result);
41
System.out.println(
42
"Bet the following combination. Itll make you rich!");
43
for (int r : result)
44
System.out.println();
45
46

47 }

j a v a . u t i l .A rra y s

123

1 .2

static String toString ( [] a) 5.0

,
.
:

int, long, short, char, byte, boolean,


float double

static type copyOf ( []

a,

int le n g th )

static type copyOf([]

a, int s t a r t ,

6
int end)

, , le n g t h end -

s t a r t

.
:

int, long, short, char, byte, boolean,

float double

sta rt

()

end

(). ,
a. len gth ,
false
. le n g th , a . le n g th ,

le n g th

false. le n g th

static void sort( [] ) 6

, (Quicksort).
:

int, long, short, char, byte, boolean,

float double

static int binarySearch ( [] ,

v)

static int binarySearch ([] a ,

int s t a r t ,

6
int end,

v)

v.
.
; - - 1 , ,
.
:

int, long,

short, char, byte, float double

Start

()

end

()

static void fill([]

vbo

v)

.
int, long, short, char, byte, boolean,

float double
v

124

3 Java

static boolean equals([]

[] b )

true ,
.
:

int, long, short, char, byte, boolean,

float double


.

.
, .
, , ,
10
, .
. 3.8.
3.8.

10%

11%

12%

13%

H%

15%

10000,00

10000,00

10000,00

10000,00

10000,00

10000,00

11100,00

11200,00

11300,00

11600,00

11500,00

12100,00

12321,00

12566,00

12769,00

12996,00

13225,00

13310,00

13676,31

16069,28

16628,97

16815,66

15208,75

16661,00

15180,70

15735,19

16306,76

16889,60

17690,06

16105,10

16850,58

17623,62

18626,35

19256,15

20113,57

17715,61

18706,15

19738,23

20819,52

21969,73

23130,61

19687,17

20761,60

22106,81

23526,05

25022,69

26600,20

21635,89

23065,38

26759,63

26586,66

28525,86

30590,23

23579,68

25580,37

27730,79

30060,62

32519,69

35178,76

11000,00

, (
), , balan ce. Java .
, , :
doublet] [] balances;

, ,
new.
:
balances = new double[NYEARS][NRATES];

125

, ,
, new.
.
i n t [][] magicSquare =

{
{16, 3, 2, 13},
{5, 10, 11, 8},
{9, 6, 7, 12},
{4, 15, 14, 1}

};
,
, b a la n c e s [i] [ j ].
,
in t e r e s t ,
b alan ce.
:
for (int j = 0; j < balances [0] .length; j++)
balances [0] [j] = 10000;

, .
for (int i = 1; i < balances.length; i++)

{
for (int j = 0; j < balances[i].length; j++)
double oldBalance = balances[i - 1] [j];
double interest = . . .;
balances[i] [j] = oldBalance + interest;

}
}
3.8.
! for each
. , , ,
. ,
:
for (double [] row : )
for (double value : row)
value

. ,
System.out.println(Arrays.deepToString(a)) ; .
:
[[16. 3, 2.13], [5,10.11. 8], [9. 6, 7,12]. 15, , 1]]

126

3 Java

3.8. Compoundlnterest/Compoundlnterest.java

1 /**
2
3
4
5

*
*
*
*



(aversion 1.40 2004-02-10
Qauthor Cay Horstmann

6 */
7

public class Compoundlnterest

8 {
9
public static void main(String[] args)
10
{
11
final doiible STARTRATE = 10;
12
final int NRATES = 6;
13
final int NYEARS = 10;
14
15
// 10 . . . 15%
16
doublet] interestRate = new double[NRATES];
17
for (int j = 0; j < interestRate.length; j++)
18
interestRate[j] = (STARTRATE + j) / 100.0;
19
20
doublet][] balances = new double[NYEARS][NRATES];
21
22
// 10000
23
for (int j = 0; j < balances [0]. length; j++)
24
balances[0][j] = 10000;
25
26
//
27
for (int i = 1; i < balances.length; i++)
28
{
29
for (int j = 0; j < balances [i] .length; j++)
30
{
31
//
32
double oldBalance = balances[i - 1] [j];
33
34
//
35
double interest = oldBalance * interestRate[j];
36
37
//
38
balances[i] [j] = oldBalance + interest;
39
}
40
}
41
42
//
43
for (int j = 0;
j < interestRate.length; j++)
44
System.out.printf ("%9.0f%%", 100 * interestRate[j]);
45
46
System.out .pryitln ();
47
//
48
for (doublet] row
:balances)
49
{
50
//
51
for (double b : row)
52
System, out .printf ("%1.0.2f", b) ;
53
54
System.out.println() ;
55
}
56
}
57 }

127



.
Java , .
, .
" ".
, b a la n c e s
, 10 ,
, (. 3.15).

b a la n c e [ i] z- , .. i- .
, b alan ce [i] [ j ]
. . , ,
, !
double [] temp = balances [i];
balances[i] = balances[i + 1];
balances[i + 1] = temp;

128

3 Java

, Java , "", , ..
, .
, , , /- /-
, j i .
1
1 1

12 1
13
1 4
1 5
1 6

3 1
6 4 1
10 10 5 1
15 20 15 6 1

j i, - .
i- i+1 . ( 0
, .) ,
, :
int[] [] odds = new int[NMAX+l] [];

:
for (int n=0; n<=NMAX; n++)
odds[n] = new int[n+l];

, ,
, , ,
. , .
for (int n=0; n<odds.length; n++)
for (int k=0; k<odds [n] .length; k++)

{
//

odds[n][k] = lotteryOdds;

}
,
, 3.9.
3.9. LotteryArray/LotteryArray. java 1

1 /**
2
*
3
* (Aversion 1.20 2004-02-10
4
* Oauthor Cay Horstmann
5 */
6 public class LotteryArray
7 {
8
public static void main(String[] args)
9
{
10
final int NMAX = 10;
11
//
12
13
int [] [] odds = new int [NMAX + 1][];
14
for (int n = 0; n <= NMAX; n++)
15
odds[n] = new int[n + 1];
16
17


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

129

//
for (int n = 0; n < odds.length; n++)
for (int k = 0; k < odds[n].length; k++)
{
/*
* :
* n*(n-1)* (n-2)*...*(n-k+1)/ (1*2*3*...*k)
*/
int lotteryOdds = 1;
for (int i = 1; i <= k; i++)
lotteryOdds = lotteryOdds * ( n - i + 1 ) /i;

odds[n][k] = lotteryOdds;
}
//
for (int[] row : odds)
{
for (int odd : row)
System.out.printf("%4d", odd);
System.out.println ();
}

C++! Java
doublet] [] balance = new double[10][6];

// Java

:
double balance[10] [6]; // C++

.
double

(*balance) [6] = new double[10] [6]; // C++

, . C++
:
double** balance = new double*[10]; // C++

, 6 ,
.
for (i = 0; i < 10; i++)
balance[i] = new double[6];

,
new double [10] [6]. ,
.

, Java.
-
Java.


...
-








.
__

- .

Java.

-
, . -

, - .
, .
Java -
.

132

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

-
- ()
, "",
- , 1970- . Java
- ,
.
- .
,
, .
,
.
. , , ,
, ,
.

( ) .
, .
Pascal (Niklaus Wirth)
+ = (Algorithms +
Data Structures = Programs; Prentice Hall, 1975 ).
, ,
. .
, ,
, .
,
, .

. .
-. 2000
, .
100 ,
20 (. 4.1).
. . ,
. ,
20 , ,
2000 .

133

----------------------------- S

. 4.1. -


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

. , ,
, . , ..
, .
.
.
,

.
. ,

134

. ,
.
, , .
Java:
. ,
, . Java, ,
", O bject.
. .
,
. ,
.
.
.

-
.

,
.

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


,
.. main (). -
"" ,
, . :
, .

135

,
.
, , . ,

.

.
4

Item, Order ..
. .
. . ,
, . , ,
Order (),

. , Order add () ,
Item () .
,
.
,
.

(" -").

(" -").

(" -").

. ,
Order Account, Order
Account, .
Item Account, Item
. , ,
- .
.
, !
( ,
.)
, . ,
Order Item. ,
.

136

!
, . .
, .
:
, (. 4.1).


. , RushOrder Order.
RushOrder
, ,
, , Order.
, , ,
, . (
.)
UML (U nified M odeling
Language )
, .
. 4.2. ,
. . 4.1 ,
UML.
V i . I <-1 I ir-ll [ i lit

. 6 .2 .

137

4.1. UML

UML


Java ,
, . Java
, .
Math. ,
Math, M a t h .random (), ,
.
( ). , ,
, . Math ;
, , .
,
, Math !
Date.
, .


,
. . Java
. ,
.
Date, Java.
,
"December 31, 1999, 23:59:59 GMP".
! :
, , ?
, , Visual Basic, #6/1/1995#.
.
?
//, //.
? ,
, .

. ,
. ( , Java
, ; . http://jcp.org/en/jsr/detail?id=310.)

138

. ,
D a t e D a t e . D a t e ,
n e w , .
new Date ()

,
.
:
System.out.println (new Date ());

, .
D a t e t o S t r i n g O ,
. :
String = new Date() .toStringO;

. ,
, .
, , ,
, .
Date birthday = new Date ();

. 4.3 ,
.

b ir th d a y

.
,
d e a d l i n e , D a t e .
Date deadline; // deadline

, d e a d l i n e
.
D a t e .
.
s = deadline.toString(); // !

139

d e a d lin e .
. ,
:
deadline * new Date();

, ,
.
deadline * birthday;

d e a d lin e b ir th d a y
(. 4.4).

. 4.4. ,

,
. . Java
, . n e w
. ,
: n e w D a t e () D a t e ,
.
Date deadline = new Date ;


, :

n u ll,

deadline = null;

if(deadline != null)
System.out.println(deadline);

n u

, ,
l l , :
birthday = null;
String s = birthday.toString(); // !


n u l l . ,
n e w n u l l .

140

C++! , Java
C++. C++ .
Java . ,
Date birthday;

// Java

:
Date* birthday;

// C++

. , Date*
, new. C++
Java .
Date* birthday = new Date();

// C++


. C++ null Java NULL.
Java , "".
,
, .
C++ , .
. Java
. ,
, ,
. ,
" " .
C++
. ,
, , , .
, ,
. Java clone ().

G re g o ria n C a le n d a r Java
Date,
Java. Date ,
.
Date ,
, (
), ,
, .. 00:00:00 UTC, 1 1970 . UTC
Universal Coordinated Time ( )
. UTC
GMT (Greenwich Mean Time ).
Date .
Java , , "December 31, 1999, 23:59:59",
.
,
.
, ,
.

141

!
. ,
. , , ,
(Nachum Dershowitz) . (Edward . Reingold)
C a le n d r ic a l C a lc u la tio n s ( Cambridge University Press, 2nd ed., 2001 .).
,
.

Java ,
, . ,
Java : Date,
, GregorianCalendar, Calendar,
. ,
Java .
,
. Date
, . ,
b e f o r e () a f t e r () ,
, .
if

(today.before(birthday))
System.out.println("Still time to shop for a gift.");

! Date , getDay (), getMonth ()


getYear (), .
, ,
.
Date , Java ,
, , . ,
Date .
, ,
,
.

G r e g o r i a n C a l e n d a r , Date.
, . ,
, ,
.
new GregorianCalendar()

, , //,
:
new GregorianCalendar(1999, 11, 31)

, . , 11
. C a l e n d a r .DECEMBER
:
new GregorianCalendar(1999, Calendar.DECEMBER,

31)

142

, GregorianCalendar , .
new GregorianCalendar(1999, Calendar.DECEMBER,

31, 23, 59, 59)


:
GregorianCalendar deadline = new GregorianCalendar(...);

GregorianCalendar ,
. , ,
.
. :
.


GregorianCalendar
: , , ,
, ?
,
API.
.
,
, , , , .
, get () GregorianCalendar.
, , Calendar,
Calendar .MONTH Calendar.DAY_OF_WEEK, :
GregorianCalendar now = new GregorianCalendar();
int month = now.get(Calendar.MONTH);
int weekday = now.get(Calendar.DAY_OF_WEEK);

,
GregorianCalendar.
set () :

deadline.set(Calendar.YEAR, 2001);
deadline.set(Calendar.MONTH, Calendar.APRIL);
deadline.set(Calendar.DAY_OF_WEEK, 15);

, :
deadline.s e t (2001, Calendar.APRIL,

15);

,
, ..
deadline.add(Calendar.MONTH,

3); // 3

, ,
, .
get (), , set () add (), ,
. get ()
, set () add () . ,
, , ,
, , .

143

C++! C++ c o n s t. ,

const, . Java
,
.

qmt,
e a t. , GregorianCalendar
, ,
getTime () setTime ():
Date time = calendar.getTime();
calendar.setTime(time);


GregorianCalendar Date, . , ,
Date,
. Date ,
GregorianCalendar, getTime ()
:
GregorianCalendar calendar = new GregorianCalendar(year, month, day);
Date hireDay * calendar.getTime();

, , ,
Date, GregorianCalendar,
, get (), .
GregorianCalendar calendar * new GregorianCalendar();
calendar.setTime(hireDay);
int year = calendar.get(Calendar.YEAR);

,
GregorianCalendar.
:
Sun Mon Wad Thu Fri Sat
1
7
8
6
4
5
2
3
9 10 11 12 13 14 15
16 17 18 19* 20 21 22
23 24 25 26 27 28 29
30 31

. , ,
.
. GregorianCalendar,
.
GregorianCalendar d = new GregorianCalendar();

,
g e t ().
int today = d.get(Calendar.DAY_OF_MONTH);
int month = d.get(Calendar.MONTH);

weekday Calendar.SUNDAY,
, Calendar .MONDAY , .. (

144

1, 2, ..., 7,
, .)
, ,
.
, .
,
.
Java
.
, .
.
, main () , :
Locale.setDefault(Locale.ITALY);

g e t F i r s t D a y O f W e e k ()
. ,
1 , , ,
:
int firstDayOfWeek = d.getFirstDayOfWeek();
int indent = 0;
while (weekday != firstDayOfWeek)

{
inderit++;
d.add(Calendar.DAY_OF_MONTH, -1);
weekday = d.get(Calendar.DAY_OF_WEEK);

}
.
DateFormatSymbols :
String

[] weekdayNames = new DateFormatSymbols().getShortWeekdays();

getShortWeekdays ()
( "Sun", " M o n
..). . ,
, .
do

{
System.out.printf("%4s", weekdayNames[weekday]);
d.add(Calendar.DAY_OF_MONTH, 1);
weekday = d.get(Calendar.DAY_OF_WEEK);

}
while (weekday != firstDayOfWeek);
System.out.println() ;

.
. ,
d .
. d , * .
, .
d , .

145

d.add(Calendar.DAY_OF_MONTH, 1);

? , : 3 1 ,
3 0 , 2 9 2 8 . , d
.
do

}
while (d.get(Calendar.MONTH) == month);

d ,
. 4.1.
, GregorianCalendar
, ,
.
, GregorianCalendar
. , get () ,
set () add (). ,
,
.
4.1. CalendarTest/CalendarTest.java 1
1
2
3
4
5

import java.text.DateFormatSymbols;
import java.util.*;
/**
* (Aversion 1.4 2007-04-07
* Oauthor Cay Horstmann

6 */
7
8 public class CalendarTest
9 {
10
public static void main(String[] args)
11
{
12
// d
13
GregorianCalendar d = new GregorianCalendar();
14
15
int today = d.get(Calendar.DAY_OF_MONTH);
16
int month = d.get(Calendar.MONTH);
17
18
// d
19
d.set(Calendar.DAY_OF_MONTH, 1);
20

21

int weekday = d.get(Calendar.DAY_OF_WEEK);

22

23
24
25
26
27
28
29
30
31

// ( )
int firstDayOfWeek = d.getFirstDayOfWeek();
// ,
int indent = 0 ;
while (weekday != firstDayOfWeek)
{
indent++;
d.add(Calendar.DAY OF MONTH, -1) ;

146

32
33
34
35
36
37
38
39
40
41
42
43
44
45
4 6
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
}
73 }

weekday = d.get(Calendar.DAY_OF_WEEK);
}
//
String[] weekdayNames = new DateFormatSymbols().getShortWeekdays();
do
{
System.out.printf C%4s", weekdayNames[weekday]);
d.add(Calendar.DAY_OF_MONTH, 1);
weekday = d.get(Calendar.DAY_OF_WEEK);
}
while (weekday != firstDayOfWeek);
System.out.println();
for (int i = 1; i <= indent; i++)
System.out.print(" ");
d.set(Calendar.DAY_OF_MONTH, 1);
do
{
//
int day = d.get(Calendar.DAY_OF_MONTH);
System.out.printf("%3d", day);
// *
if (day == today) System.out.print ("*");
else System.out.print(" ");
// d
d.add(Calendar.DAY_OF_MONTH, 1);
weekday = d.get(Calendar.DAY_OF_WEEK);
//
if (weekday == firstDayOfWeek) System.out.println ();
}
while (d.get(Calendar.MONTH) == month);
// , d
//
// ,
if (weekday != firstDayOfWeek) System.out.println ();

ja v a .u til.G r e g o r ia n C a le n d a r 1 .1

GregorianCalendar()

GregorianCalendar,
.

GregorianCalendar (int year, int m o n t h , int day)

GregorianCalendar (int y e a r , int m o n t h , int day, int hour, int m i n u t e s , int


seconds)

GregorianCalendar, .
:

year

month

( , ..
0 )

day

h our

( 0 23)

m in u te s

( 0 59)

se c o n d s

( 0 59)

int get (int f i e l d )

.
:

fie ld


: Calendar.ERA,
Calendar.YEAR, Calendar.MONTH,
Calendar.WEEK_OF_YEAR,
Calendar.DAY_OF_YEAR,
Calendar.DAY_OF_WEEK,
Calendar.DAY_OF_WEEK_IN_MONTH,~
Calendar.AM PM, Calendar.HOUR,
Calendar.HOUR_OF_DAY,
Calendar.MINUTE,

Calendar.SECOND,

Calendar.MILLISECOND,
Calendar.ZONEJDFFSET
Calendar.DST OFFSET

void set(int f i e l d ,

int v a lu e )

.
:

fie ld

, get ()

v a lu e

void set (int y e a r , int month, int day)

void set (int y e a r , int month, int day, int h ou r, int m in u te s, int se co n d s)

.
* :

year

month

( , .. 0 )

day

h our

( 0 23)

m in u te s

( 0 59)

se c o n d s

( 0 59)

147

148

void add(int f i e l d , int amount)

. .
, 7 , . add (Calendar.
DAY_0 F_MONT H, 7).
:

fie ld

, get ())
amount

,
( )

int getFirstDayOfWeek()

.
, Calendar.SUNDAY.
void setTime (Date tim e)

.
:

tim e

Date getTime()

,
.

j a v a . t e x t . D a te F o rm a tS y m b o ls 1 . 1
String[] getShortWeekDays()
String[] getShortMonths()
String[] getWeekDays()

String[] getMonths()

.
Calendar .


3
. main ().
, "" .
, main () .
. ,
, main ().

149

E m p lo ye e
Java :
class

{
_1
_2
_ 1
_2

_1
2

}
, E m p lo y e e ,
:
class Employee

{
//
private
private
private

String name;
double salary;
Date hireDay;

//
public Employee(String n, double s, int year,

int month,

int day)

{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1,
day) ;
hireDay = calendar.getTime();

}
//
public String getN a m e O

{
return name;

}
//

}

. 4.2
E m p lo y e e .
4.2. E m p lo y e e T e s t /E m p lo y e e T e s t . j a v a 1
1
2
3
4
5

import java.util.*;
/**
*
* version 1.11 2004-02-19

'

Employee

150

6
* Qauthor Cay Horstmann
7 */
8 public class EmployeeTest
9 {
10
public static void main(String[] args)

11

// staff 1
Employee!] staff - new Employee[3];
staff[0] - new Employee("Carl Cracker", 75000, 1987, 12, 15);
staff[l] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);

12
13
14
15
16
17
18
19
20

//
for (Employee e : staff)
e .raiseSalary(5);

5%

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

// 1
for (Employee : staff)
System, out. print In ("name-" + e.getNameO + ", salary-" +
e.getSalary() + ",hireDay-" + e.getHireDay());
}
}
class Employee
{
private String name;
private double salary;
private DatehireDay;
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar - new GregorianCalendar(year, month - 1, day)
// GregorianCalendar
hireDay = calendar.getTime ();
}
public String getNameO
{
return name;
}
public double getSalaryO
{
return salary;
}
public Date getHireDayO
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;

}
}

151

Employee,
:
Employee[]
staff[0] *
staff[1] =
staff[2] *

staff = new Employee[3];


new Employee("Carl Cracker", . . .);
new Employee("Harry Hacker", . . .);
new Employee("Tony Tester", . . .);

raiseSalary () Employee,
5%, .
for (Employee : staff)
.raiseSalary(5);

, getName () , getSalary () getHireDay ()


.
for (Employee : staff)
System.out.println("name*" + e.getName()
+ ", salary*" + e.getSalary()
+ ",hireDay=" + e.getHireDay());

, :
Employee EmployeeTest,
public. main ()
EmployeeTest. EmployeeTest.
j ava, .
, public,
, .

: EmployeeTest .class Employee, class.
, - ,
main () :
java EnployaaTaat

main() EmployeeTest.
Employee
.


4.2
. Java
. , Employee
Employee .java, EmployeeTest EmployeeTest .java.
,
. ,
:
javac Employee*.java

,
, . ,
.
javac BnployeeTeet.java

152

, Employee, java . ,
EmployeeTest.java Employee, Java
E m p l o y e e .class. ,
Employee.java. , Employee, java
, Employee.class, Java

.
! make, Unix
, . ,
Java .

E m p lo ye e
Employee, . ,
, Employee
, .
public
public
public
public
public

Employee(String n, double s,int year, int month,


String getName()
double getSalaryO
Date getHireDayO
void raiseSalary(double byPercent)

int day)

public, ..
. (
. .)
,
, Employee, .
private String name;
private double salary;
private Date hireDay;

private ,
Employee.
.
! public,
. ( )
, , ,
- ,
.
private.

, ,
. , name hireDay
String Date. :
.

153


Employee.
public Employee(String n, double s, int year, int month,

int day)

{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1,
day);
hireDay = calendar.getTime();

}
, .
Employee,
. , Employee

new Employee("James Bond, 100000,

1950,

1, 1);

:
name = "James Bond";
salary = 100000;
hireDay = January 1, 1950;

:
new.
, . ,
.
james.Employee("James Bond", 250000,

1950,

1, 1); // !

. .

new.
C++! Java C++ . ,
Java
new. , C++, :
Employee number007("James Bond", 10000,
// C++, Java

1950,

1, 1)

C++ , Java .

! ,
, . ,
.

154

4
public Employee(String n, double s,

...)

{
String name = n; // !
double salary = s; // !

}
name salary.
. .
,
. .
, .


. :
public void raiseSalary(double byPercent)

{
double raise = salary * byPercent / 100;
salary += raise;

}
s a la r y ,
. , :
007.raiseSalary (5);

5% number007. s a la r y number007.
,
:
double raise = number007.salary * 5 / 100;
number007.salary += raise;

r a i s e S a l a r y () . ,
, E m p lo y e e ,

. ,
, .
, ,
d o u b le b y P e r c e n t .
. t h i s .
r a i s e S a l a r y () :
public void raiseSalary(double byPercent)

{
double raise = this.salary * byPercent / 100;
this.salary += raise;

}
,
.
C++! C++ , .
void Employee::raiseSalary(double byPercent) // C++, Java
{

155

}
, .
class Employee

int getName()

{ return name; } // C++

}
Java , .
Java , ,
, . ,
, ,
.


getName () , getSalary () getHireDay ()
Employee. .
public String getName()

{
return name;

}
public double getSalary()

{
return salary;

}
public Date getHireDay()

{
return hireDay;

}
.
,
. name, salary hireDay
(.. public) ?
, name .
, .
, , , .
salary , ,
raiseSalary (). ,
, .
salary , .
.
.
(private) .
(public) .
(public) .

156

, ,
. . -,
.
, :
String firstName;
String lastName;

getName ()
:
firstName + " " + lastName

'
. ,
, .
: ,

. , s e tS a la r y () ,
.
! ,
. Emloyee, : getHireDay ()
Date, .
class Employee
{
private Date hireDay;
public Date getHireO;

{
return hireDay;

}
}
! :
Employee harry = ...;
Date d = harry.getHireDay();
double tenYearsInMilliSeconds = 10 * 365.25 * 24 * 60 * 60 * 1000;
d .setTime(d.getTime() - (long) tenYearsInMilliSeconds);
//

: , d harry.hireDay,
(. 4.5). d
Employee!
, . -
, .
6. .
class Employee
{
public Date getHireDay()

157

{
return hireDay.clone();

}
}
clone (),
.

. 4 .5 .


,
, .
! equals ,
Employee.
class Employee
{
public boolean equals(Employee other)

{
return name.equals(other.name);

}
}
:
if (harry.equals(boss)) ...

harry, .
boss. ,
boss Employee, , Employee,
.

158

C++! C++ .
.


,
.
? .
. ,
,
public .
private, .. . ,
public private .
,
. , ,
, , , , .
: , (private),
, ,
, , .
(public), ,
.


final.
, .. ,
.
. , name Employee
,
, setName () .
class Employee

private final String name;

}
final
, .
, .
, String. ,
final .
:
private final Date hiredate;

, hiredate .
, , ,
. setTime ().

159


main ()
static.
.


static
. , .
,
. Employee id
next Id, .
class Employee

{
private int id;
private static int nextld = 1;

}
Employee id,
nextld, .
, Employee,
id: .
nextld.
Employee, nextld . ,
.
1 -
. C++.

:
public void setld()

{
id = nextld;
nextld++;

}
, harry
:
harry.s e t l d ();

id harry,
nextld , .
harry, id = Bnployaa. nextld;
Bnployaa.nextId++;

160


.
. , ,
, Math :
public class Math
{
public static final double PI = 3.14159265358979323846;

}
M a t h .
PI. static , PI
Math. ,
Math,
PI.
System, out.
System :
public class System

public static final PrintStream out = ...;


}
, ,
.
(.. , final) .
, out final, :
System.out = new PrintStream(...); // :

out !

! System,
setOut (), System.out .
, final? , setOut ()
, .. , Java.
, Java.
, .


, . ,
pow() Math . M a t h . p o w (, )
.
Math. , this. ,
this. (
this ; .
" " ).
,
.
. .

161

public static int getNextldO


{
return nextld; //

}
, :
int n = Employee.getNextld();

static ?
, Employee.
! . ,
harry Employee, Employee.getNextldO
harry.getNextld (). ,
getNextldO harry.
, .

,
(, M a t h .pow ()).

(,
Employee.getNextld ()).
C++! Java C++, ,
. C++ ,
, : Math: :1.
. static
, .
: ,
.
, .
static , . , C++
, .
, ,
. static Java.


. NumberFormat
,
, .
NumberFormat currencyFormatter = NumberFormat.getCurrencylnstance();
NumberFormat percentFormatter = NumberFormat.getPercentlnstance();
double x = 0.1;
System.out.println(currencyFormatter.format( x ) ) ; / / $ 0 .1 0
System.out.println(percentFormatter.format( x ) ) ; / / 10%

? .

162

.
. , Number Format
.

.
, DecimalFormat,
Number Format. (
5.)

m a in ()
, ,
. , M a t h . pow (),
Math . main () :
public class Application
{
public static void main(String []

args)

{
//

main () .
. main ()
, .
. , main().
. , main() Employee
:
class Employee
{
public Employee (String n, double s, int year,

int month,

int day)

{
name = n;
salary = s;
GregorianCalendar calendar =
new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();

public static void main(String[] args)

//

{
Employee e = new Employee ("Romeo", 50000, 2003, 3, 31);
e.raiseSalary(10);
System.out.println(e.getName() + " " + e.getSalary());

}
}
Employee,
ja v a E np loyee. Employee ,
ja v a A p p lic a tio n . main ()
Employee .

163

, 4.3,
Employee nextld g e t N e x t l d O .
Employee,
. ,
.
, Employee main ()
. main () ja v a
Employee ja v a S t a t ic T e s t .
6.3. StaticTest/StaticTest.java1
1

/**

2
3
4
5

*
* version 1.01 2004-02-19
* author Cay Horstmann
*/
6 public class StaticTest
7 {
8
public static void main(String[] args)
9
{
10
// staff Employee
11
Employee [] staff = new Employee [3*] ;

12
13
staff[0] = new Employee ("Tom", 40000);
14
staff[1] = new Employee("Dick", 60000);
15
staff[2] = new Employee("Harry", 65000);
16
17
// . Employee
18
for (Employee :staff)
19
{
20
e.setldO ;
21
System.out.println("name=" + e.getNameO + ",id=" +
22
e.getldO + ",salary=" + e .getSalary () );
23
}
24
25
int n = Employee.getNextld(); //
26
System.out.println("Next available id=" + n) ;
27
}
28 }
29
30 class Employee
31 {
32
private static int nextld = 1 ;
33
34
private String name;
35
private double salary;
36
private int id;
37
38
public Employee(String n, double s)
39
{
40
name = n;
41
salary = s;
42
id = 0;
43
} .
44
public String getNameO
45
{

164

46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

return ;

public static int getNextldO

66

}
public double getSalaryO
{
return salary;
}
public int getld()
{
return id;
}
public void setld()
{
id = nextld; //
nextld++;
}

67
68

return nextld; //

69
70
public static void main(String [] args) //
71
{
72
Employee e = new Employee("Harry, 50000);
73
System.out.println(e.getName() + " " + e.getSalary());
74
}
75 }


,
( ) .
, ,
. , ,
. ,
, , ,
. " ..."
,
, Java. (
,
, Algol,
.)
Java . ,
.
,
.
:
double percent = 10;
harry.raiseSalary (p e rc e n t) ;

165

,
p ercen t 10.
. ,
, .
public static void tripleValue(double x ) ; // !

{
x = 3 * x;

}
V

:
'

double percent = 1 0 ;
tripleValue(percent);

. p e rc e n t
- 10. .
1. p ercen t (..
10).
2. , 30.
p ercen t - 10 (. 4.6).
3. ,
.

. 4 .6 .
,

166

(.. ).

,
. . ,
, :
public static void tripleSalary(Employee x) // !

{
x .raiseSalary(200);

}

.
harry = new Employee(...);
tripleSalary(harry);

1. x harry, ..
.
2. raiseSalary () . ,
Employee, harry,
, 200%.
3. , .
, harry ,
(. 4.7).

. U1. ,

167

, , ,
, .
: ,
.
( , C++ Pascal)
: .
(, , ) , Java
. .
,
. , Employee.
public static'void swap(Employee x, Employee ) // !

{
Employee temp = x;
x = y;
= temp;

}
Java
, :
i
Employee = new Employee("Alice, . . .);
Employee b = new Employee("Bob", . . .);
swap(a, b ) ;
// Bob,

b Alice?

,
. swap () , ,
.
// Alice, Bob
Employee temp = ;
= ;
= temp;
// Bob,

Alice

, , .
, b
(. 4.8).
, Java .
. ,
.

(..
).
, .

4.4.

.
Testing tripleValue:

{ t r ip le V a lu e )

168

Before: percent=l .

( )
End of method: =30.0

( )
After: percent=10.0

( )

/^ 3 ^

11
. 4 .8 .

.
Testing tripleSalary:

( t r i p l e S a l a r y ())
Before: salary=50000.
End of method: salary=150000.0
After: salary=150000.0

,
harry, . ,
. ,
swap ().
Testing swap:

( sw apO)
Before: a=Alice
Before: b=Bob
End of method: x=Bob
End of method: y=Alice
After: a=Alice
After: b=Bob

, ,
b .


4.4. ParamTest/ParamTest .java
1

2
3
4
5
6

7
8

/** ,
* Java
* version 1.00 2000-01-27
* Oauthor Cay Horstmann
*/
public class ParamTest
{
i
public static void main(String[] args)
{

10

/*

11

* 1:

12

*/

13
14
15
16
17
18
19
20

System.out.println("Testing tripleValue:");
double percent = 10;
System.out.println("Before: percent=" + percent);
tripleValue(percent);
System.out.println("After: percent=" + percent);
/*
* 2: ,
*

21

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

*/

System.out.println("\nTesting tripleSalary:");
Employee harry = new Employee("Harry", 50000);
System.out.println("Before: salary=" + harry.getSalary());
tripleSalary(harry);
System.out.println("After: salary=" + harry.getSalary());
/*
* 3:

*
*/
System.out.println("\nTesting swap:");
Employee a = new Employee("Alice", 70000);
Employee b = new Employee("Bob", 60000);
System.out.println("Before: a=" + a .getName());
System.out.println("Before: b=" + b.getName());
swap(a, b);
System.out.println("After: a=" + a .getName());
System.out.println("After: b=" + b.getName());
}
public static void tripleValue(double x) // !
{
x = 3 * x;
System.out.println("End of method: x=" + x) ;
}
public static void tripleSalary(Employee x) // !

50
51
52

53
54
55

x.raiseSalary(200);
System.out.println("End of method: salary=" + x.getSalary());

public static void swap(Employee x, Employee )

169

170

D iaia 4

56
57
Employee temp = ;
58
= ;
59
= temp;
60
System.out .println ("End of method: x=" + x .getName());
61
System.out.println ("End of method: y=" + .getName ());
62
63 }
64 class Employee // Employee
65 {
66
private String name;
67
private double salary;
68

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

public Employee(String n, double s)


{
name = n;
salary = s;
}
public String getName()
{
return name;
}
.
public double getSalaryO
{
return salary;
}
public void raiseSalary(double byPercent)

87

double raise = salary * byPercent / 100;


salary += raise;

88

89
}
90 }

C++! C++ , .
, void tripleValue (doubles ) void
swap (Employees x , Emloyees ). .


, ,
. ,
Java .
.

, G r e g o r i a n C a l e n d a r
. :
GregorianCalendar today = new GregorianCalendar();

171

GregorianCalendar deadline =
new GregorianCalendar(2099, Calendar,

DECEMBER,

31);

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

, . (
.)
! Java , . ,
, .
. , String
indexOf (). :
*

indexOf(int)
indexOf(int, int)
indexOf(String)
indexOf(String, int)

. ,
,
.


,
: ,
false, null.
. ,
.
! .
.
, ,
(0, false null).

Employee. ,
. salary
, name hireDay null.
getName () getHireDay () null
, .
Date h = harry.getHireDay() ;
calendar.setTime(h); // h = null,

172


, ,
.
Employee.
public Employee()

{
name = "";
salary = 0 ;
hireDay = new Date();

}
,
.
, . , ,
, ,
false, null.

, , , . ,
Employee 4.2 :
Employee(String name, double salary,

int y, int m, int d)

,
. , :
= new Employee();

! ,
, .

, .
new ()

, ,
:
public ()
{


, ,
,
.
.

, .
class Employee

private String name = "";

173

.
, ,
.
. ,
.
class Employee
{
private static int nextld;
private int id = assignld();

private static int assignld()

{
int r = nextld;
nextld++;
return r;

}
C++! C++
. . C++
, , .
Employee::Employee (String n, double s, int y, int m, int d) // C++
: name(n),
salary(s),
hireDay(y, m, d)

{
}
C++ .
Java ,
, .


(
), .
, .
public Employee(String

n, double s)

{
name = n;
salary = s;

}
, , ,
, s.
"".
public Employee (String

{
name = aName;
salary = aSalary

aName, double aSalary)

174

. ,
.
. , ,
. , salary,
salary , .
t his.salary. ,
this , .. .
:
public Employee(String name, double salary)

{
this.name = name;
this.salary = salary;

}
C++! C++ ,
( m ). ,
, , _salary, mSalary xSalary.
Java, , .


this .
.
this ( . . . ) , .
.
public Employee(double s)

{
// Employee(String,
.this("Employee " + nextld, s) ;
nextld++;

double)

}
n e w E m p l o y e e (60 0 0 0 ),
Employee (double) Employee (String, double).
this
.
C++! this Java this C++. C++
.
C++, .

Java :
. ,
. :
class Employee
{
private static int nextld;
private int id;
private String name;
private double salary;
//
{
id = nextld;
nextld++;

}
public Employee(String n, double s)
{
name = n;
salary = s;

}
I
public Employee()

{
name = "";
salary = 0 ;

}
id
, ,
. ,
. .

.
1 ,
. ,
, ,
. 8.3.2.3 Java ( (h t t p : / / d o c s .
o r a c le .c o m /ja v a s e /s p e c s ). ,
. ,
. .


.
, .
1. ,
(, f a l s e n u ll).

176

2.
.
3.
, .
4. .
, , ,
, . , ,
.
.
,
.
, .
static int nextld = 1 ;

,
.
s t a t i c . ,
,
10000.
:
//

static

{
Random generator = new R a n d o m O ;
nextld = generator.nextlnt(1 0 0 0 0 );

}
,
. , 0,
f a l s e n u ll, . ,
,
.
! , ,
"Hello, World", m a i n (), .
public class Hello
{
static

{
System.out.println("Hello,

World!");

}
}
java Hello Hello,
"Hello, World! " ,
main () . , System.exit (0 )
.

177

, 4.5,
Java, , .

t h i s ( . . . ) .

4.5. ConstructorTest/ConstructorTest.ja v a 1
1

import java.util.*;

2 /**
3
4
5

*
* (Aversion 1.01 2004-02-19
* @author Cay Horstmann

*/

public class ConstructorTest

8 {
9

public static void main(String[] args)

10

11

//

staff finployee

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

35
36
37
38
39

40
41

Employee[] staff = new Employee[3];


staff[0] = new Employee("Harry, 40000);
staff[1] = new Employee(60000) ;
staff [2] = new Employee ();
// Enployee
for (Employee : staff)
System, out .print In ("name=" + e.getNameO + ",id=" +
e.getldO + ", salary="+ e.getSalary () );
}
}
class Employee
{
private static int nextld;
private int id;
private String name =
private double salary;

//

//
static
{
Random generator = new Random ();
// 0-999
nextld = generator.nextlnt(10000);

nextld

/8
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

//
{
id = nextld;
nextld++;
}
//
public Employee(String n, double s)
{
name = n;
salary = s;
}
public Employee(double s)
{
// Employee(String, double)
this("Employee #" +nextld, s);
}
//

66

public Employee ()
{
// "" - .
// salary ,
// id
}
public String getNameO
{
return
name;
}

67
68

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

public double getSalaryO


{
return
salary;
}
public int getldO
{
return id;
}

86

j a v a . u t i l . Random 1 . 0

Random()

int nextlnt(int )

1.2

0 - 1 .

179

f i n a l i z e ()
- ,
, C++ , .
, . Java
" ",
, .
, ,
, , , ,
. ,
. f i n a l i z e (),
, " " .
,
, f i n a l i z e (), ,
.
! System. runFinalizerOnExit (true), ,
finalize () , .
.
Runtime.addShutdownHook().
API.

,
.
c lo s e ,
, , . "
t r y " ,
.

Java , .
,
, , . Java
, ja v a .la n g , j a v a . u t i l , ja v a .n e t ..
Java .
, .
j ava j avax.
.
, Employee.
, .
,
( ),
.
. ,
horstmann.com. ,
com.horstmann.
,. com. hors tmann. core j ava.

180

.
.
, java.util java.util.jar .
.



.
. -,
, .
java.util.Date today = new java.util.D a t e ();

, . ,
import.
.
, .
import (
package). , java.util
:
import java.util.*;

, .
Date today = new Date();

:
import java.u t i l .Date;

.
. ,
, .
. Eclipse, S o u rc e ^ O rg a n ize Im p o rts (
^ ). import java. util. * ;
,
:
import java.util.ArrayList;
import java.util.Date;

, , , import
. import
j a v a . * import j a v a . * . *, ,
jav a . ,
. ,
, . , , java.util java.sql,
Date. , ,
:
import java.util.*;
import java.sql.*;

181

Date,
:
Date today; // : , : java.util.Date java.sql.date?

, Date
. ,
import :
import java.util.*;
import java.sql.*;
import java.u t i l .Date;

, Date?
, .
java.util.Date deadline = new java.util.Date();
java.sql.Date today = new java.s q l .D a t e ();

. -,
, .
C++! C++ , import
#include. . C++ #include
, C++
, , , #include.
Java , , .
Java , , java,
util.Date. C++ #include .
import .
, . , import
java.util.* ( import java.util.Date) java.util.Date
Date.
C++ namespace.
package import Java namespace using C++.


import,
, . ,
:
import static java.lang.System . * 7

,
System, , :
out.println("Goodbye, World!");
exit (0) ; // System.exit

//

System.out

:
import static java.lang.System.out;

182

Java , System.out
System.exit, .
. , :
sqrt(pow(, 2) + p o w (, 2))

, :
Math.sqrt(Math.pow(x,

2) + Math.pow(, 2))


,
. , Employee, java
4.7 :
package com.horstmann.corejava;
public class Employee

}
package , ,
, . .
.
,
. , com. hors tmann. core java
com/horstmann/corejava ( com\horstmann\
core java Windows).
.
4.6 4.7 :
PackageTest , Employee .
horstmann. core java. , Employee, class
com/horstmann/corejava. ,
:
. ( )
__ PackageTest.java
_ PackageTest.class
_ com/
|
__ horstmann/
|
__ corejava/
Employee.java
mployee. class

41

4.6, ,
PackageTest .java, :
javac Package.java

c o m / h o r s t m a n n / c o r e ja v a / E m p l o y e e .
j a v a .
.
. (.
horstmann. core java .), .

183

. ( )
|
__ /
_ horstmann/
| corejava/
__ Employee.java
___ Employee.class
___ mycompany/
PayrollApp java
t
PayrollApp.class
.

,
.. , , .
javac //PayrollApp.java
java com.mycompany.PayrollApp

He , (
. j ava).
( ).
4.6. PackageTest/PackageTest.java
1
2
3
4
5
6
7
8
9
10

import com.horstmann.corejava.*;
// Employee
import static java.lang.System.*;
/**
*
* Qversion 1.11 2004-02-19
* eauthor Cay Horstmann
*/
public class PackageTest

11 {
12
public static void main(String[] args)
13
{
14
// com.horstmann. corejava.Employee
15
// import
16
Employee harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);
17
18
harry.raiseSalary(5);
19
20
// System.out,
21
// static import
22
out.println("name=" + harry.getName() + ",salary=" + harry.getSalary());
23
}
24 }

4.7. PackageTest/com/horstmann/corejava/Employee. java1


1
2

package com.horstmann.corejava;
//

3
4
5
6
7

import java.util.*;
// import
/**

package

184

8
* 0version 1.10 1999-12-18
9
* @author Cay Horstmann
10 */
11 public class Employee
12

13
14
15
16

private String name;


private double salary;
private DatehireDay;

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

public Employee(String n, double s, int year, int month, int day)


{
name = n;
salary = s;
GregorianCalendar calendar =
new GregorianCalendar(year, month - 1, day);
// GregorianCalendar
hireDay = calendar.getTime();
}
public String getNameO
{
return name;
}
public double getSalaryO
{
return salary;
}
public Date getHireDayO
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}

.
. ,
.

! . ,
:
package com.mycompany;

, com/mycompany.
, ,
.

185



public private. , public,
. ,
private, ,
. ,
(, )
.
4.2. Employee
. ,
( , ),
EmployeeTest, .
.
. private,
, , ,
.
private. Window,
ja v a .awt, JDK.
public class Window extends Container

{
String warningstring;

}
, warningstring
private! , java.awt
, ,
"Trust m e !" ( !). ,
Warningstring, Window,
. , , ,
private. (
, ,
.)
! , ,
. , ,
. , Window ,
private.

, ?
. , ,
. ,
, ,
. , Java
ja v a .awt.
:
package java.awt;

186

ja v a \a w t.
j a v a . awt .
,
(. 4.9).

. 4 .9 .

1.2 JDK ,
, " j a v a . "! ,
.
, .
, . 10
, JAR, .


,
. . ,
j a r ,
JAR ( Java JAR-).
,
.
,
JAR- . JDK JAR-, ,
, j r e / l i b / r t . ja r , . 10
, JAR-.
. JAR-
ZIP. r t . j a r JAR- ,
ZIP.

187

,
.
1. ,
/home/user/classdir. ,
. .
horstmann. core java. Employee,
/home/user/classdir/com/horstmann/corejava.
2. JAR- , /home/user/archives.
3. .
, .
Unix :
/home/user/classdir:.:/home/user/archives/archive.jar

Windows :
c:\clasdir;.;c:\archives\archive.jar

.
:

/home/user/classdir c:\classes;

(.);

JAR- / h o m e / u s e r / a r c h i v e s / a r c h i v e .jar c : \ a r c h i v e s \
archive .jar.

Java SE 6 JAR-
:
/home/user/classdir:.:/home/user/archives/'*'

c:\classdir;.;:\archives\*

UNIX * ,
. JAR- (
.class), archives, .
(rt. jar JAR
jre/lib jre/lib/ext) ,
.
! javac ,
java ,
I .). ,
(.).
, , .

188

,
.
:
/home/user/classdir:.:/home/user/archives/archive.jar

, , .
horstmann. core java. Employee. ,
, jre/lib jre/lib/ext.
, ,
:

/home/user/classdir/com/horstmann/corejava/Employee.class;

c o m .horstmann/corejava/Employee.class, ;

com.horstmann/corejava/Employee.class /home/user/archives/
archive .jar.

,
. , , ,
, .
,
import. ,
, , Employee.
import java.util.*
import c o m .horstmann.corej a v a .*;

j a v a .lang . E m p l o y e e (
java.lang ), java.util .Employee, com.
horstmann.core java .Employee Employee .
, .
, . (
, import .)
. ,
, , .
, . ,
.
, ,
. , ,
, .
, (.. public).
.
, ,
.


-classpath ( -)
:
java -classpath /home/user/classdir:.:/home/user/archives/archive, jar MyProg

java -classpath c :\classdir;.;c :\archives\archive.jar MyProg.java

189

.
.
-classpath
. CLASSPATH.
. , Bourne
Again (bash) :
export CLASSPATH=/home/user/classdir:.:/home/user/archives/archive.jar

C shell :
setenv CLASSPATH /home/user/classdir:.:/home/user/archives/archive, jar

Windows
set CLASSPATH=c:\classdir;.;c:\archives\archive.jar

.
! c l a s s p a t h
. .
, , .
QuickTime Apple Windows.
CLASSPATH ,
JAR-, .
Java ,
, .

! ,
JAR j r e / l i b / e x t . . ,
, ,
( 9
). , ,
. ,
,
.


JDK javadoc,
HTML .
API
javadoc Java.
,
/ * * , , .
, ,
. ,
.
, javadoc,
.

190

/
jav ad o c .

, p u b lic .

, p u b lic p ro te cte d .

, p u b lic p ro te cte d .

,
p ro te c te d , 5, 6.
, ( )
.
, .
/ * * * / . / * * . . . * /
, . 0,
author @param.
.
ja v a d o c ,
. HTML-, ,
< >.. .</> , < c o d e > .. .</cod e>
, < stro n g > . . .< /s tr o n g >
<img . . .> . , ,
(<hl> <h6>) (<hr>),
.
! , (
),
doc-files, . javadoc
,
. doc-files,
<img src="doc-files/uml.png" alt="UML diagram"/>.


im port,
. .
j --

^ Card ,
* .
*(1=, 2...10, 11=, 12=, 13=).

*/

public class Card


{

191

! . ,
:

I
Card ,
, .
( 1=, 2...10, 11=, 12=, 13=).

*/

.


,
. ,
.

@param
.
. ,
HTML-. , ,
,

return
.

HTML-.

throws
, .
11.

.
/
*
*
*
*
*


param byPercent
,
(, 10 = 10%).
return ,

*/
public double raiseSalary(double byPercent)

{
double raise = salary &* byPercent / 100;
salary += raise;
return raise;

192


. , ,
. .
I if-

*
*/
public static final int HEARTS = 1;

0auth or
.
.

version .

.
.
,
, .

since
.
, .
, since v e rsio n 1 .7 .1 .

deprecated
, ,
. , deprecated
. :
deprecated Use setVisible(true)

instead

see link
,
javadoc.
see ". ".
.
:
, # _
< href="... > < />
" "

. ,
, javadoc
. ,
raiseSalary (double) com. horstmann. core java. Employee.

193

,
.
@see com.horstmann.corejava.Employee#raiseSalary(double)

,
#, . j avac
, , , ,
, . ja v a d o c
, .
@see <,
. - URL,
.
@see < href="www.horstmann.com/corejava.html'^Web- Core
Java</a>


,
. ,
URL.
@see ",
". ", .
@see "Core Java volume 2"


@ see, .

.
{ lin k . _}.
, @see.


, , ,
/ * * . . . * / .

. .
1. HTML- package.h tm l. ,
<body> . . . </body>, javadoc.
2. p a c k a g e - in fo . ja v a .
Javadoc, / * * * / ,
package, .
, .
overview .h tm l,
. ,
<body> . . . </body>, jav a d o c .
, Overview ()
.

194


, d o cD irecto ry ,
HTML-. .
1. ,
. , .
horstmann. core jav a, , . (
overview .htm l.)
2. :
javadoc -d d o c D ir e c to r y _

3. :
javadoc -d d o c D ir e c to r y __1 __2 ...

4. , ,
:
javadoc -d d o c D ir e c to r y * .java

-d d o c D i r e c t o r y , HTML-
, . .
jav ad o c . ,
@author (Aversion,
-au th o r - v e r sio n ( ). - lin k
. ,
,
- Oracle.
javadoc -link http://doc8.oracle.eom/java8e/7/docs/api *.java

- lin k s o u r c e ,
HTML ( , ),
.
jav ad o c, h t t p : / / d o c s .
o ra c le .c o m /j a v a s e / 1 . 5 . /d o c s/g u id e /ja v a d o c .
! , ,
, HTML,
, .
- http://docs.oracle.eom/javase/l.5.0/
docs/guide/j avadoc/doclet/overview.html.


,
.

195

1. , private.
:
. *
, .
, ,
. ,
, .
2. .
Java ,
. ,
.
3. .

. , ,
. , Customer
Address:
private
private
private
private

String street;
String city;
String state;
int zip;

, , ,
, .
4. .
,
, ,
.
, . , ,
. ,
, Address.
5. .
, , : , "
" , .

, . ( .
, .)
.
public class CardDeck //
{
private i n t [] value;
private int[] suit;
public
public
public
public
public

CardDeck() { . . . }
void shuffle () { . . . }
int getTopValue() { . . . }
int getTopSuitO { . . . }
void draw ()' { . . . }

196

: -,
shuffle () () draw() () , -
, .
Card,
. , ,
.
public class CardDeck
{
private Card[] cards;
public CardDeck() { . . .
public void shuffle() { .
public Card g e t T o p O { .
public void draw()
{. .

}
. . }
.. }
.}

}
public class Card
{
private int value;
private int suit;
public Card(int aValue, int aSuit)
public int getValue() { . . . }
public int getSuitO { . . . }

{ . . . }

}
6. ,
.
, , ,
. ( ,
, , Date , .)
:
(Order) ,
(RushOrder)
(BillingAddress). ,
get, (getSalary),
set, (setSalary).
, Java
. -
,
. Java .

...
,
O b j e c t





4 .
-
(). ,
.
() ,

. Java .
,
. ,
.
, ,
,
.

198

,
Employee, .
, ,
, . ,
.
,
. .
? , Manager,
. -
, Employee, ,
. , Manager Employee
"":
. .
, Manager, Employee.
Java extends.
class Manager

extends Employee

}
C++! Java C++ . Java :
extends. Java
, .. ,
C++.

extends ,
. , ,
, .
Java ,

, .
Employee . ,

. :
, . , Manager
, Employee.
! - - .
. ,

. ,
.

Manager , ,
, , .
class Manager extends Employee
{

199

private double bonus;

public void setBonus(double b)

{
bonus = b;

. Manager,
setBonus () :
Manager boss = . . .;
b o s s .setBonus(5000);

, Employee setBonus () ,
, Employee.
g e t N a m e O getH i r e D a y O Manager,
Employee, Manager.
name, salary hireDay . ,
Manager : name, salary, hireDay bonus.
,
. ,
, .

.
Manager.
, getSaiary () .
, , .. ,
:
class Manager extends Employee

{
public double getSalaryO
{

}
}
? ,
salary bonus :
public double getSalaryO

{
return salary + bonus; / / !

}
, . g e t S a l a r y O
Manager . ,
g e t S a l a r y O Manager
salary, , Manager
. Employee
. Manager ,
, :
( getSaiary () Employee).

200

, .
salary getSalary (), .
public double getSalary()

{
double baseSalary = getSalary(); // - !
return baseSalary + bonus;

}
, getSalary () , Manager
( ).
,
.
, getSalary ()
Employee, .
super.
getSalary () Employee.
super.getSalary()

getSalary () Manager:
public double getSalary()

{
double baseSalary = super.getSalary();
return baseSalary + bonus;

}
! super this.
super . ,
.
, .

, ,
.
.
C++! Java super.
C++ : : . ,
getSalary () Manager C++ :
Employee::getSalary (), super . getSalary ().

, Manager , .
public Manager(String n, double s, int year, int month,

int day)

{
super(n, s, year, month, day);
bonus = 0;

}
super .
Employee n, s, year,
month day.
super(n,

s, year, month, day);

201

Manager Employee,
,
super. , super,
.

,
. ,
, Java
.
! , this :
.
super :
. this super
.
.
(this) (super).

C++! super C++ .


. C++ Manager
:

Manager::Manager (String n, double s, int year, int month, int day) // C++
: Employee(n, s, year, month, day)

{
bonus = 0;

}
getSalary () Manager
.
, Manager
, .
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
boss.setBonus(5000);
\

, Employee:
EmployeeU

staff = new Employee[3];

Manager Employee:
staff[0] = boss;
staff[1] = new Employee("tfarry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);

, :
for (Employee : staff)
System.out.println(.getName() + " " + e.getSalary());

:
Carl Cracker 85000.0
Harry Hacker 50000.0
Tommy Tester 40000.0

202

staff [1] staff [2]


, Employee.
staff [0] Manager,
getSalaryO .
:
.getSalary()

getSalary (),
. ,
Employee, ,
, Employee, Manager.
Employee,
.getSalary () getSalary () Employee.
Manager, getSalary ()
Manager. ,
, .
(, ) ,
, .
.
.
C++! Java .
. , ,
f i n a l (
).

5.1 ,
Employee ( 5.2) Manager ( 5.3).
5.1. inheritance/ManagerTest. java1
1 package inheritance;
2

3 /**
4
*
5
* 0version 1.21 2004-02-21
6
* Oauthor Cay Horstmann
7 */
8 public class ManagerTest
9
{
10
public static void main(String[] args)
11

12
13
14
15
16
17
18
19
20
21
22

// Manager
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
boss.setBonus (5000) ;
Employee[] staff = newEmployee[3];
// staff Manager Enployee
staff[0] = boss;
staff [1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);

203

23
// Enploye*
24
for (Employee : staff)
25
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
26
}
27 }

5.2. in h e r it a n c e /E m p lo y e e . ja v a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

21

package inheritance;
import java.util.Date;
import java.util.GregorianCalendar;
public class Employee
{
private String name;
private double salary;
private DatehireDay;
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month-1, day);
hireDay = calendar.getTime();
1
}
public String getNameO

22
return name;
23
}
24
public double getSalaryO
25
{
26
return salary;
27
}
28
29
public Date getHireDayO
30
{
31
return hireDay;
32
}
33
34
public void raiseSalary(double byPercent)
35
{
36
double raise = salary * byPercent / 100;
37
salary += raise;
38
}
39 }

5.3.
1
2
3
4
5
6

i n h e r i t a n c e / M a n a g e r . j a v a 123456

package inheritance;
public class Manager extends Employee
{
private double bonus;
/**

204
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 }

5
* @param
* @param
* @param
* @param
* @param


s
year
month
day

*/

public Manager(String n, double s, int year, int month, int day)


{
super(n, s, year, month, day);
bonus = 0;
}
public double getSalaryO
{
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
public void setBonus(double b)
{
bonus = b;
}


. ,
Manager Executive.
, , .
. 5.1.
.

. 5.1. Employee

205

.
Employee , , Programmer
Secretary ,
Manager , .
.
C++! Java . ,
, Java
( ).

, ,
.
"", .
, . ,
Manager , Employee. ,
.
"" -,
. ,
. ,
:
Employee ;
= new Employee (...); // Employee.
= new Manager (...); // Manager

Java . Employee
Employee, ,
Employee (, Manager, Executive, Secretary ..).
5.1
:
Manager boss = new manager (...);
Employee[] staff = new Employee[3];
staff[0] = boss;

staff [0] boss .


staff [0] Employee.
, :
boss.setBonus(5000); // !

.
staff[0].setBonus(5000); // !

, staff [0] Employee,


setBonus () .
. ,
:
Manager m = staff[i]; // !

206

: .
m Employee,
,
m. setBonus ( . . . ) , .
! Java
. .
Manager:
Manager[] managers = new Manager[10];

Employee [ ], .
Employee[] staff = managers;

// !

, , Manager
, Employee. ,
managers staff ,
. :
staff[0] = new Employee("Harry Hacker",

...);

. staff [0] manager [0]


, , ,
, , .
managers [0] .setBonus (1000),
.
,
. ,
new Manager [10],
Manager, Employee
ArrayStoreException, .


, ,
. .

1. , .
, x . f (param),
. ,
f, (,
f (int) f (String)). f
f ,
. ( .) ,
f .
2. ,
. f ,
,
. . ,
. f ("Hello" ) f (String), f (int).
(int double,

207

Manager Employee ..).


, ,
. , ,
.
! ,
. , f (int) f (String) , .
,
, , .
.
.
. , Employee getBuddy ()
:
public Employee getBuddy() { ...

, .
, Manager getBuddy ()
:
public Manager getBuddy() { ... } // !

, getBuddy ()

3. (private), (static),
(final) , , . (
final .)
.
,
.
f (String)
.
4.
, ,
, .
, D ,
. D f (String), .
f (String)
..
,
,

.
.
D f (String).
D.f (String) X.f (String), X
D. .
super.f (param), ,
super.

208

e . g e t S a l a r y () 5.1.
Employee. getSalary (),
. ,
.
getSalary () private,
static final, .
Employee Manager. Employee
, , .
Employee:
g etN a m e O -> Employee.getName ()
getSalary() -> Employee.getSalary()
getHireDayO -> Employee.getHireDay()
raiseSalary(double) -> Employee.raiseSalary(double)

. , Employee
Object, .
.
Manager .
, ,
.
Manager:
getNameO -> Employee.getName ()
getSalary() -> Manager.getSalary()
getHireDayO -> Employee.getHireDay()
raiseSalary(double) -> Employee.raiseSalary(double)
setBonus(double) -> Manager.setBonus(double)

.getSalary ()
.
1. ,
.
Employee, Manager , Employee.
2. ,
getSalary () .
.
3. , .
:
.
. ,
Executive, . ,
e.getSalary (), .
Executive,
Executive.getSalary().

!
. ,
public, public.
, public .
, .

209

:
. ,
, .
final. ,
, Executive. Executive
:
final class Executive extends Manager

}
.
. (
.) .
class Employee

{
public final String getNameO
{
return name;

}
}
! , final
, . .
final, ,
.

1 final
: . ,
g e t T i m e O s e t T i m e O Calendar.
,
Date
. .
String. ,
, . ,
String, , ,
- .
, final
.
,
. , C++ C#
. ,
, :
.
Java
final , ,
. ,
,

210

. , e . g e t N a m e O e.name.
,
, . ,
getName () ,
. ,
.
, ,
, ,
. , ,
, .
, ,
. ,
, ?
.
, .


3
, . Java
. ,
:
double = 3.405;
int nx = (int) x;


,
.
, .
,
. .
Manager boss = (Manager)

staff[0];

:
,
. , Manage Test staff
Employee. ,
.
Manager, ,
staff Manager. ( ,
, ,
. , boss
Manager, .
,
.)
, Java .
,
, . ,
staff [1 ] Employee,
Manager.

211

,
, . ,
, ,
.
, ,
, .
,
.
,

, ?
Manager boss = (Manager) staff[1]; // !


ClassCastException. ,
. ,
.
instanceof, .
if (staff[1] instanceof Manager)

{
boss = (Manager) staff[1];

}
, ,
. ,
,
Date , Employee.
Date = (Date) staff[1];

,
.

,
instanceof.
!

null,
, false.

instanceof
. n u l l ,
, .

.
Employee
Manager . g e t S a l a r y O
,
.

212

, ,
, ,
Manager, setBonus (). -
setBonus () Employee,
: ? ,
setBonus ().
,
ClassCastException.

instanceof.

C++! Java ,
dynamic_cast
C++. , , ,
.
Manager boss = (Manager)staff[1]; // Java
Manager* boss = dynamic_cast<Manager*>(staff[1]); // C++

. ,
. Java
C++. Java. C++
:
Manager* boss = dynamic_cast<Manager*>(staff[1]); // C++
if (boss != NULL) ...

Java in s ta n c e o f ,
.
if

(staff[1] instanceof Manager)

// Java

{
Manager boss =

(Manager)staff[1];


,
. ,
, ,
, ,
. , ,
. , Employee,
Person Student.
. 5.2.
?
, , .
,
getName ()
.

213

. 5.2. -,
Person

getDescription (),
, :
an employee with a salary of $50,000.00
( 50 . )
a student majoring in computer science
(, )

Employee Student .
Person? ,
. , Person.getDescription (),
. .
Person ,
abstract, .
public abstract String getDescription ();
//

,
, :
abstract class Person
{

public abstract String getDescription ();

}
,
. , Person
, , .
abstract class Person
{
private String name;
public Person(String n)

{
name = n;

214

public abstract String getDescription();


public String getName()

{
return name;

. ,
. ( )
, : .

,
. ,
. .
, .
, , Student, Person
getDescription (). Student
,
. , ,
.
. ,
. .
new Person("Vince V u " );

,
, .
:
Person = new Student("Vince Vu",

"Economics");

p Person,
Student.
C++! C++ .
=0, .
class Person // C++

{
public;
virtual string getDescription() = 0;

C++ , .
C++ .

Student,
Person, :
class Student extends Person
{
private String major;

215

public Student(String n, String m)

{
super(n);
major = m;

)
public String getDescription()

{
return "a student majoring in " + major;

getDescription ().
Student , ,
.
5.4
Person ( 5.5) Employee ( 5.6)
Student ( 5.7). Person
Employee Student:
Person[] people = new Person[2];
p e o p l e [0] = new Employee(. . .);
p e o p l e [1] = new Student(. . .);

, ,
:
for (Person : people)
System.out.println(.getName() + ", " + p .getDescription());

. getDescription () .
? ,
Person,
.
, Employee Student.
getDescriprion () .
Person
getDescription () Employee Student? ,
getDescription () .
, ,
.
,
Java.
, 6.
5.4. abstractClasses/PersonTest.java1
1
2
3
4
5

package abstractClasses;

*/

/ * *

*
* (Aversion 1.01 2004-02-21
* @author Cay Horstmann

public class PersonTest

public static void main(String[] args)

216

11

Person[] people = new Person[2];

12
13
14
15
16
17
18
19
20
21
}
22 }

// people Student Enployee


people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
people[l] = new Student("Maria Morris", "computer science");
// ,
// Person
for (Person : people)
System.out.println(p.getName() + ", " + p.getDescription ());

5.5. abstractClasses/Person. java


1 package abstractClasses;
2
3 public abstract class Person
4 {
5
public abstract String getDescription();
6
private String name;
7
8
public Person(String n)
9
{
10
name = n;
11

12
13
public String getName()
14
{
15
return name;
16
}
17 }

5.6. abstractClasses/Employee. java 1


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

package abstractClasses;
import java.util.Date;
import java.util.GregorianCalendar;
public class Employee extends Person
{.
private double salary;
private Date hireDay;
public Employee(String n, double s, int year, int month, int day)

{
super(n);
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month-1, day);
hireDay = calendar.getTime ();
}
public double getSalaryO
{

,
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 }

217

return salary;

}
public Date getHireDayO
{
return hireDay;
}
public String getDescription ()
{
return String.format("an employee with a salary of $%.2f", salary);
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}

5.7. abstractClasses/Student .java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

package abstractClasses;
public class Student extends Person
{
private String major;
/**
* @param n
* @param m
*/

public Student(String n, String m)

{
//
super();
major = m;

}
public String getDescription()
{
return "a studentmajoring in

" + major;

}
}


, p r iv a te ,
p u b lic . (.. p r iv a te )
. :
.

.
.

218

protected. , hireDay
Employee , ,
Manager .
Manager hireDay,
Manager, Employee.

, ,
.
.
, , ,
. ,
, .
,
. ,
.
.
, . ,
, ,
, .
clone () Object,
6.
C++! Java ,
. Java C++,
protected . , Java
, C++.

, Java ,
.
1. p r iv a t e .
2. p u b lic .
3. p r o t e c t e d
.
4.
( ) .

O b je c t
Object ,
Java Object. ,
, .
class Employee extends Object

, Object.
Java Object, ,
Object.

Object

219

, Object ,
. (
Object ,
14.)
Object
:
Object obj = new Employee("Harry Hacker",

35000);

,
. - ,
, ,
. Java : ,
.
Employee = (Employee)

obj;

,
Object, ,
.
Employee[] staff = new Employee[10];
obj = staff; // !
obj = new int[10]; // !

C++! C++ ,
, , void*.

e q u a ls ()
equals () Object , .
equals () Object,
: .
:
. . , -
PrintStream ,
-.
, .
, . ,
, ,
. ( ,
.
equals () , .)
class Employee

{
public boolean equals(Object otherObject)

{
//
if (this == otherObject) return true;

// false,
//
if (otherObject == null) return false;

null

220

// ,
if (getClass() != otherObject.getClass())
return false;
// , otherObject
/ / Employee
Employee other = (Employee) otherObject;
// ,
return n a m e .equals(other.name)
&& salary = other.salary
&& hireDay.equals(other.hireDay) ;

getClass () .
. ,
.
. name hireDay null,
Objects .equals (). Objects.equals (, b)
true, null;
false, null;
a.equals (b).
Employee.equals () :
return Objects.equals(name, other.name)
&& salary == other.salary
&& Object.equals(hireDay, other.hireDay);

equals () ,
. ,
. ,
, .
class Manager extends Employee
{

public boolean equals(Object otherObject)

{
if (!super.equals(otherObject)) return false;
// super.equals() ,
// otherObject
Manager other = (Manager) otherObject;
return bonus == other.bonus;

}
}


equals (),
? .
equals () false,

________________________________________________________________ Object

.
:
if (!(otherObject instanceof Employee))

return false;

, otherObject
. .
Java , equals ()
.
1. . . equals ()
true.
2. . . equals ()
true ,
. equals () true.
3. . . equals () . equals (z)
, z true,
. equals (z) true.
4. . , ,
, . equals ()
.
5. . equals (null)
false.
. ,
, ,
. equals () . equals ().
,
. :
.equals(m)

Employee, m Manager,
, .
.equals (m) instanceof,
true. ,
m.equals () true,
false
.
Manager . equals ()
Employee
, !
instanceof .
, getClass ()
, .
equals () AbstractSet,
,
. AbstractSet
TreeSet HashSet, .
.

222

,
, .
, , ,
. AbstractSet .equals ()
,
. ( final .

.)
, .

,
getClass ().

,
instanceof. ,
.
4


, . , Manager
, ,
, .
getClass (). ,
.
.
instanceof Employee.equals () final.
! Java 150
equals (). instanceof,
getClass () ,
ClassCastException, .
java.sql.Timestamp,
. , Timestamp java,
util.Date, equals () instanceof,
.


equals ().

1. otherObject.
other.
2. , this otheObject, :
if

(this == otherObject)

return true;

.
, .
3. , otherObject (null), .
, false.
.
if (otherObject == null)

return false;

Object

223

4. this otheObject.
, getClass () :
if (getClass() != otherObject.getClass()) return false;

,
ins tan of :
if (!(otherObject instanceof ClassName)) return false;

5. otherObj e c t ,
.
other = {) otherObject;

6. , .
= , Objects . equals ().
, true,
false.
return 1 == other.!
&& 2 . equals(other.2)
Sc &

...;

equals (),
super .equals (other).
. ,
Arrays.equals ().

! equals ( ) , .
,
?
public class Employee
{
public boolean equals(Employee other)

{
return name.equals(other.name)
&& salary == other.salary
&& hireDay.equals(other.hireDay);

}
}
Employee.
equals () Object, .
, ,
, Override, .
Override public boolean equals(Object other)

,
. , Employee :
Override public boolean equals(Employee other)

Object,
.

224

j a v a . u t i l .A r r a y s

1 .2

static boolean equals(t y p e []

a,

ty p e []

b)

5.0

true,
. Object,
int, long, short, char, byte, boolean, float double.

ja v a .u til.O b je c ts

static boolean equals(Object a ,

Object b)

true, , , null;
false, null;
a.equals (b).

hashC ode ()
- , . -
: ,
. hashCode ()
. hashCode (). . 5.1 -,
hashCode () String.
5.1. -, h a s h C o d e ( )

Hello

69609650

Harry

699648

Hacker

-2141031506

- String :
int hash = 0;
for (int i = 0; i < leng t h O ; i++)
hash = 31 * hash + charAt(i);

hashCode () Object.
-, . -
, . :
String s = "Ok";
StringBuilder sb = new StringBuilder(s);
System.out.println(s.hashCode() + " " + s b .hashCode());
String t = new String("Ok);
StringBuilder tb = new StringBuilder(t);
Sys tem. out .print In (t. hashCode () + " " + tb. hashCode ()) ;

. 5.2.

Object

225

5.2. - String StringBuf fer

2556

sb

20526976

2556

tb

20527

, s t
-,
. sb tb - . ,
StringBuilder hashCode () , Object
hashCode (), - ,
.
equals (),
hashCode () , -.
( - 13.)
hashCode () ,
. - ,
- .
hashCode Employee.
class Employee
{
public int hashCode()
{
return 7 * name.hashCode()
+ 11 * new Double(salary).hashCode()
+ 13 * hireDay.hashCode();

}
}
Java 7 . -,
Objects .hashCode (),
. , , 1
null, hashCode () .
.
public int hashCode()
{
return 7 * Objects.hashCode(name)
+ 1 1 * new Double(salary).hashCode()
+ 13 * Objects.hashCode(hireDay) ;

}
-, Objects .hash (),
-, . Objects.hashCode ()

-. Employee .hashCode () ,
.

226

public int hashCode()

{
return Objects.hash(name,

salary, hireDay);

}
equals () h a s h C o d e O :
. equals () true,
.hashCode () .hashCode () . , Employee.
equals () ,
- hashCode () ,
, .
. , -, -
, Arrays.hashCode ().

ja v a .la n g .O b je c t 1 .0

int hashCodeO

- . -
. -.

ja v a .la n g .O b je c ts

int hash(Object... )

-, - .

static int hashCode(Object a)

, null,
a.hashCode().

j a v a . u t i l .A rra y s

1 .2

static int hashCode(t y p e [] a)

5.0

- , Object, int, long,


short, char, byte, boolean, float double.

t o S t r i n g ()
Object toString (),
.
toString () Point, ,
.
java.awt.Point[=10,=20]

Object

227

( ) t o S t r i n g O ,
,
. toString () Employee.
public String toStringO

{
return "Employee[name=" + name
+ ",salary=" + salary
+ ",hireDay=" + hireDay
+

}
.
toString () getClass () .getName ()
, , .
public String toStringO

{
return getClass().getName()
+ " [name=" + name
+ ",salary=" + salary
+ ",hireDay=" + hireDay
+

}
t o S t r i n g O . ,
toString ()
. , getClass () .getName (),
super .ToString ().
toString () Manager.
class Manager extends Employee

public String toStringO

{
return super.toStringO
+ " [bonus=" + bonus
+

Manager :
Manager [name=..., salary=..., hireDay=... ] [bonus=... ]

toString () .
:
+, Java toString (),
:
Point = new Point (10, 20);
String message = "The current position is " + p;
// p.toStringO

. . toString "" + .

.toStringO. ,
.

228

:
System.out.println () ;

println () x . t o S t r i n g O
. toStringO, Object,
. :
System.out.println(System.out);

println () . :
java.io.PrintStream@2f6684

, PrintStream
toString ().
! , toStringO Object,
. ,
[10146", [ I
.
int[] luckyNumbers = { 2, 3, 5, 7, 11,
String s = "" + luckyNumbers;

13 };


Arrays. toString (). ,
[2, 3, 5, 7, 11,

13]":

String s = Arrays.toString(luckyNumbers);

A r r a y s .
deepToString().

toString () .
,
. , ,
:
System.out.println("Current position = + position);

11 , :
Logger :
Logger.global.info("Current position = " + position);

. toStringO
. , , .

5.8
equals (), hashCode () toStringO, Employee (
5.9) Manager ( 5.10).
5.8. equals/EqualsTest .java
1
2

package equals;

Object

3 /**
4
* equals()
5
* (Aversion 1.12 2012-01-26
6
* author Cay Horstmann
7 */
8 public class EqualsTest
9 {
10
public static void main(String[] args)
11
{
12
Employee alicel = new Employee("Alice Adams", 75000, 1987, 12, 15);
13
Employee alice2 = alicel;
14
Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15);
15
Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);
16
17
System.out.println ("alicel == alice2: " + (alicel == alice2));
18
19
System.out.println("alicel == alice3: " + (alicel == alice3));

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
}
37 }

System.out.println("alicel.equals (alice3): " + alicel.equals(alice3));


System.out.println("alicel.equals (bob) : " + alicel.equals(bob));
System.out.println("bob.toString (): " + bob);
Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
boss.setBonus(5000);
System.out.println("boss.toString(): " + boss);
System.out.println("carl.equals(boss): " + carl.equals(boss));
System.out.println("alicel.hashCode(): " + alicel.hashCode());
System.out.println("alice3.hashCode (): " + alice3.hashCode());
System.out.println("bob.hashCode(): " + bob.hashCode());
System.out.println("carl.hashCode (): " + carl.hashCode());

5.9. equals/Employee .java1


1 package equals;
2

3
4
5

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Objects;

7 public class Employee


8

9 private String name;


10
private double salary;
11
private Date hireDay;
12

13
14
15
16
17
18

public Employee(String n, double s, int year, int month, int day)


{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month-1, day);
hireDay = calendar.getTime ();

229

230
19

5
}

20

21
public String getNameO
22
{
23
return name;
24
}
25
26
public double getSalaryO
27
{
28
return salary;
29
}
30
31
public Date getHireDayO
32
{
33
return hireDay;
34
}
35
36
public void raiseSalary(double byPercent)
37
{
38
double raise = salary* byPercent / 100;
39
salary += raise;
40
}
41
42
public boolean equals(Object otherObject)
43
{
44
//
45
if (this == otherObject) returntrue;
46
47
// null,
48
// false
49
if (otherObject == null) return false;
50
// ,
51
if (getClassO != otherObject.getClass () ) return false;
52
53
// , otherObject Employee
54
Employee other = (Employee) otherObject;
55
56
// ,
57
return Objects.equals(name, other.name) && salary == other.salary &&
58
Objects.equals(hireDay, other.hireDay);
59
}
60
61
public int hashCodeO
62
{
63
return Objects.hash(name, salary, hireDay);
64
}
65
66
public String toStringO
67
{
68
return getClass().getName () + "[name=" + name +
69
,,,salary=" + salary + ", hireDay=H + hireDay + "]";
70
}
71 }

Object

231

5.10. equals/Manager.java
1
2
3
4
5

package equals;
public class Manager extends Employee
{
private double bonus;

7
8
9
10
11

public Manager(String n, double s, int year, int month, int day)

{
super(n, s, year, month, day);
bonus = 0;

12
13
public double getSalaryO
14
{
15
double baseSalary = super.getSalary();
16
return baseSalary + bonus;
17
}
18
19
public void setBonus(double b)
20
{
21
bonus = b;
22
}
23
public boolean equals(Object otherObject)
24
{
25
if (!super.equals(otherObject)) return false;
26
Manager other = (Manager) otherObject;
27
// super.equals() , ,
28
// this other,
29
return bonus == other.bonus;
30
}
31
32
public int hashCodeO
33
{
34
return super.hashCode() + 17 * new Double(bonus).hashCode();
35
}
36
37
public String toStringO
38
{
39
return super.toString () + " [bonus=" + bonus + ]";
40
}
41 }

ja v a . la n g . O b je c t 1 .0

Class getClassO

, .
, Java ,
Class.

232

----------- -

1 1

------ ----- ---------------------------------------------------------- ___________________________________

boolean equals(Object o th e rO b je c t)

true,
, false.
.

String toStringO

, .
.

ja v a .la n g .C la s s

1 .0

. String getNameO

Class getSuperclass()

Class.


, , ,
.
.
? 100 . , - ,
150 ,
10 ? 90% !
Java
, .
int actualSize = ...;
Employee[] staff = new Employee[actualSize];

,
. , .
, .
, A r r a y L i s t .
,
.
.
A r r a y L i s t .
: A r r a y L i s t < E m p l o y e e > .
13,
A r r a y L i s t ,
.
, ,
E m p l o y e e .
ArrayList<Employee> staff = new ArrayList<Employee>();

233


. , Java 7,
:
ArrayList<Employee> staff = new A r r a y L i s t o () ;

, , ,
.
n e w . , .
, ,
, ,
. n e w
A r r a y L i s t o () A r r a y L i s t < E m p l o y e e > .
, E m p l o y e e .
!

Java SE 5.0 .
ArrayList, Object.
Java, ArrayList
( < . . .>). ArrayList < . . . > .
ArrayList , " .

Java ,
, Vector. ArrayList
. Vector.

add ().
,
E m p l o y e e . ^
staff.add(new Employee("Harry Hacker", . . .));
staff.add(new Employee("Tony Tester", . . .));

.
.
. , add ()
,
, .
, ,
e n s u r e C a p a c i t y () :
staff.ensureCapacity(100);

,
100 . a d d (),
.
A r r a y L i s t :
ArrayList<Employee> staff = new ArrayList<Employee>(100);

-.

, .
new ArrayList<Employee>(100) // 100
new Employee[100] // 100

234


. 100 ,
. .
( ),
.

size ()
. ,
staff.
staff.s i z e ()


:
.lenght

, ,
trimToSize ().
, .
" " ,
.
trimToSize ()
, ,
. ,
,
.
C++! ArrayList , vector C++. ,
ArrayList vector . vector
[ ] , . Java
, . ,
vector C++ . b , =
b , . b
. Java
b .

j a v a . u t i l . A r r a y L i s t < T > 1 . 2 *

ArrayList<T>()

ArrayList<T>(int i n i t i a l C a p a c i t y )

.
:

in itia lC a p a c ity

235

boolean add(T o b j)

. true.
:

obj

int size ()

, . (
.)

void ensureCapacity(int c a p a c it y )

,
,
.
:

c a p a c ity

void trimToSizeO


, . ,
1 ,
, .
, A rra y L ist Java,
, .

g e t () s e t (). , i-ro
:
staff.set(i, harry);

i-ro
. ,
.
a[i] = harry;

! list.set (i, ) ,
i. , :
ArrayList<Employee> list = new ArrayList<Employee>(100); // 100, 0
list.set (0, x); // 0

add() set ,
.

g e t (),
.
Employee = staff.get(i);

236

"

Employee = [i ] ;

! ,
get () ArrayList Object.
, :
Employee =

(Employee)

staff.get(i);

ArrayList ,
, add() set () . ,
.
staff.set(i,

new Date());

,
Employee.
ArrayList<Employee>, .

,
.
:
ArrayList<X> list = new ArrayList<X>();
while (...)

{
x = . . .;
list.add(x);

}
, toA rray (),
:
X [] = new X [list.s i z e ()];
list.toArray();

,
:
int n = staff.size()
staff.add(n, e) ;

/ 2;

,
.
, .

:
Employee = staff.remove(n);

, , ,
.
. , ,
.
,
.
13.

237


for each :
for (Employee : staff)

, !
for (int i = 0; i < staff.size (); i++)

{
Employee e = staff.get(i);

}
5.11
EmployeeTest 4. Employee [ ]
ArrayList<Employee>.
.

add () .

length
size ().

[ i ]
a.get(i).

5.11. arrayList/ArrayListTest.java1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

package arrayList;
import java.util.*;
/**
*
* (Aversion 1.11 2012-01-26
* Oauthor Cay Horstmann
*/
public class ArrayListTest

ArrayList

{
public static void main(String[] args)
{
// staff Eknployaa
ArrayList<Employee> staff = new A r r a y L i s t o ();
staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15));
staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 1));
staff.add(new Employee("Tony Tester", 40000, 1990, 3, 15));
// 5%
for (Employee : staff)
.raiseSalary(5);
// Bnployaa
for (Employee : staff)
System.out .println ("name=" + e.getNameO + ",salary=" +
e.getSalary() + ",hireDay=" + e.getHireDay());
}
}

238

ja v a .u til.A r r a y L is t< T >

1 .2

void set(int in d e x , T o b j)

,
.
:

in d e x
obj

( 0 size () - 1)

get(int in d ex)

, .
:

in d e x

,
( 0 size () - 1)

void add(int in d e x , o b j)

.
:

in d e x
obj

( 0 size () - 1)

remove(int in d ex)

.
.
:

in d e x

( 0 size () - 1)



. ,
, .
, ,
:
public class EmployeeDB

{
public void update(ArrayList list) { ... }
public ArrayList find(String query) { ... }

}
u pdate ()
, .
ArrayList<Employee> staff = ...;
employeeDB.update(staff) ;

s t a f f update ().
!
,
. u p d a te ,

239

Employee. , ,
Java.
Java , ,
.

,
A rra y L ist , ,
.
ArrayList<Employee> result = employeeDB.find(query);
//

! ,
-Xlint: unchecked.

, .
.
.
ArrayList<Employee> result = (ArrayList<Employee>)
//

employeeDB.find(query);

- ,
Java.
ArrayList ,
, .
:
. (ArrayList) (ArrayList<Employee>)
.
.
, ,
.
,
, ,
SuppressWarnings ("unchecked"), .
@SuppressWarnings("unchecked) ArrayList<Employee> result =
(ArrayList<Employee>) employeeDB.find(query);
//


int
. . ,
Integer, int.
. : Integer, Long, Float,
Double, Short, Byte, Character, Void Boolean. (
Number.) .
, ,
, .

240

, . ,
,
, ArrayList<int> .
Integer. , ,
Integer, :
ArrayList<Integer> list = new ArrayList<Integer> () ;

! ArrayList<Integer>
, int[]. :
,
. ,
,
.

Java SE 5.0
. :
list.add(3);

.
.
list.add(new Integer(3));

!
, #.

, Integer int,
, .. .
, :
int n = list.get(i);

.
int n = list.get(i).intValue();


. ,
, Integer,
.
Integer = 3;
++;

,
.
,
.
. ,
= ,
, . , ,
, , ,
.

241

Integer = 1000;
Integer b = 1000;
if ( == b) . . .

Java , ,
,
. .
e q u a ls ()
-.
! , boolean, byte, char
127, short int -1 2 8 127
. , b
100, .

, ,
, . ,
-.

. Java ,

. ,
, .
'1

int = Integer .parselnt (s) ;

, Integer
, parselnt () .
Integer .
Integer.

.
! ,
, . . 4,
Java , ,
, .
public static void triple(int x) // !
{
x++;

//

}
, , , int Integer?
public static void triple(Integer x) // !

{
}
, Integer .
, , ,
.

242

- , ,
, org.omg.CORBA.
intHolder, BooleanHolder .
(!) value, , .
public static void triple(IntHolder x)

{
x.value++;

ja v a .la n g .In t e g e r 1 .0

int intValueO

Integer int
( intValue () Number).

static String toString(int i)

String,
.

static String toString(int i, int r a d ix )

String, ,
r a d ix .

static int parselnt(String s)

static int parselnt(String s ,

int r a d ix )

. , String
, (
) , r a d i x (
).

static Integer valueOf(String s)

static Integer valueOf(String s , int r a d ix )

Integer, ,
. , String
, (
) , r a d i x (
).

ja v a .t a x t .N u m b a r F o z in a t 1 . 1

Number parse(String s)

, .
, String ,
.

243


Java SE 5.0 , Java,
. ,
.
, p r in t f (), . .
System.out.printf("%d", n ) ;
System.out.printf("%d %s", n, "widgets");

,
,
. p r in t f () :
public class PrintStream

{
public PrintStream printf(String fmt, Object... args)
{ return format(fmt, args); }

}
( . . . ) Java. ,
fmt .
, printf () :
Object [ ], . (
,
.)
fmt
args[i]. , printf ()
Object . . . , Object [ ].

p r in t f (), , ,
:
System.out.printf("%d %s", new Object[] { new Integer(n),

"widgets"

} );


, , .
,
.
public static double max(double... values)

{
double largest = Double.MIN_VALUE;
for (double v : values) if (v > largest)
return largest;

largest = v;

}
:
double m - m a x (3.1, 40.4, -5);

max ()
: new doublet] { 3. 1, 40. 4, -5 }.
! ,
, :

244

System.out.printf("%d %s", new Object[]

{ new Integer(1),

"widgets"

} ); 1

, , ,
, .
Java SE 5.0 MessageFormat.format ().
main () :
public static void main(String... args)


3, Java SE 5.0 Java
.
.
public enum Size { SMALL, MEDIUM,

LARGE, EXTRA_LARGE };

, , .

. .
,
equals ().
= . ,
. ,
. .
public enum Size

{
SMALL("S"), MEDIUM("M"), L A R G E ("L "), EXTRA_LARGE("XL");
private String abbreviation;
private Size(String abbreviation) { this.abbreviation = abbreviation;
public String getAbbreviation() { return abbreviation; }

}
,
Enum. .
toStringO, . ,
S i z e .SMALL.toString() "SMALL".
valueOf() ,
toString (). ,
s Size.SMALL.
Size s = (Size) Enum.valueOf(Size.class,

"SMALL");

values (),
:
Size[] values = Size.values();

ordinal ()
enum, . , Size.MEDIUM.ordinal ()
1.
, 5.12.

245

! Enum ,
. , Size Enum<Size>,
. ,
compareTo (). ( compareTo () 6,
12.)

5.12. e n u m s /E n u m T e s t . j a v a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

package enums;
import java.util.*
*;
/**
*
* (Aversion 1.0 2004-05-24
* @author Cay Horstmann
*/
public class EnumTest

{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a size: (SMALL, MEDIUM, LARGE, EXTRA_LARGE) ");
String input = in.next().toUpperCase();
Size size = Enum.valueOf(Size.class, input);
System.out.println("size=" + size);
System.out.println("abbreviation^' + size.getAbbreviation());
if (size == Size.EXTRA_LARGE)
System.out.println("Good job you paid attention to the

}
}
enum Size
{
SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");
private Size(String abbreviation) { this.abbreviation = abbreviation; }
public String getAbbreviation () { return abbreviation; }
private String abbreviation;
}

ja v a .la n g .E n u n K E > 5 . 0

static Enum valueOf(Class en um C lass,

String name)

String toStringO

246

5 ai

int ordinal()

enum, .

int compareTo( o th e r)

,
o th er, 0 this==other, .
enum.


Java .
JavaBeans . ( JavaBeans
.)
, ,
Visual Basic. ,
,
.
, ,
. ,
. ,
.

, ,
toString (), .

Method,
, C++.

, .
, ,
, .

, ,
, , .

C la s s
Java
.

.
,
, : Class. getClass () Object
Class, .

247

Employee ;

Class cl = e.getClass ();

, Employee
, Class . ,
Class getName (),
. , :
System.out.println(e.getClass().getName() + " " + e .getName());


Employee Harry Hacker

e Employee,
Manager Harry Hacker

Manager.
,
:
Date d = new D a t e ();
Class cl = d.getClass();
String name = c l .getName(); // name
// " j a v a . u t i l . D a t e "

forName (), Class,


, .
String className = "java.util.Date";
Class cl = Class.forName(className);

, ,
.
, className .
forName () .
, "
".
. ,
main (). . , ,
.. ,
, .
, .
, , main (), .
.
, Class.forName ().

Class .
, .class . :
Class ell = Date.class; // java.util.*;
Class 12 = int.class;
Class cl3 = Double[].class;

248

, Class ,
. , int , ,
, int .class Class.
! Java SE 5.0, Class .
, Employee.class Class<Employee>.
, .

Class. 13.

! , getNameO
.

Double [ ] .class.getName () "[Ljava.


lang.Double;".

int [] .class.getName ( ) "[I".

Java C l a s s
. ,
= , .
if (.getClass() == Employee.class)

. . .


. , , newlnstance ().
:
.getClass().newlnstance();


, .
new l n s t a n c e () .
, .
f o r N a m e O n e w l n s t a n c e (),
, :
String s = "java.util.Date";
Object m = Class.forName(s).newlnstance();

!
- , .
newlnstance () Constructor.

C++! newlnstance () C++.


C++ ,
. Class type_
info C++, getClass () typeid. Class Java ,
C++. type info
, .

249


11,
,
. ,
. ,
,
, -
.
,
. ,
. ,
,
.
: .
,
. .
, , ,
. ,
. ,
, .
. , ,
, ,
, ,
. , Class.forName ()
. 11
, ,
.
, ,
, try, catch
:
try

}
catch(Exception )

}
:
try

{
String name = . . .; //
Class cl = Class.forName(name); //
- cl

}
catch

(Exception )

{
.printStackTrace();

250

, try
catch. (
StackTrace () Throwable.
Exception.) try
, catch .

. , ,
. ,
, ,
.
ja v a .la n g .C la s s

1 .0

static Class forName(String classN am e)

Class, className.

Object newlnstance ()

ja v a . la n g . r e f l e c t . C o n s tru c to r 1 .1

Object newlnstance(Object[] a r g s )

.
:

args

, .
. ""

j a v a . l a n g . T h r o w a b le 1 . 0

void printStackTrace()

Throwable
.



, .
, Field, Method Constructor, java.lang.reflect
, .
getName , . Field
getType , Class,
. Method Constructor ,
, Method .

251

getModifiers (), ,
, public static.
Modifiers
java.lang.reflect. , , isPublicO,
isPrivate () isFinal (), ,
, . ,
, Modifier ,
getModifiers ().
Modifier.toString ( ) .
getFields (), getMethods () getConstructors () Class
, ,
. .
getDeclaredFields (), getDeclaredMethods () getDeclaredConstructors ()
Class , ,
, . ,
.
5.13 ,
. ,
.
, :
java.lang.Double


:
public class java.lang.Double extends java.lang.Number

{
public java.lang.Double(java.lang.String);
public java.lang.Double(double);
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public

int hashCodeO;
int compareTo(java.lang.Object);
int compareTo(java.lang.Double);
boolean equals(java.lang.Object);
java.lang.String toString();
static java.lang.String toString(double);
static java.lang.Double valueOf(java.lang.String);
static boolean isNaN(double);
boolean isNaN ();
static boolean islnfinite(double);
boolean islnfinite ();
byte byteValueO;
short shortValue();
int intValueO;
long longValueO;
float floatValue();
double doubleValue();
static double parseDouble(java.lang.String);
static native long doubleToLongBits(double);
static native long doubleToRawLongBits(double);
static native double longBitsToDouble(long);

public static final double POSITIVE_INFINITY;

252

5
public static final double NEGATIVE_INFINITY;
public static final double NaN;
public staticfinal double MAX_VALUE;
public static final double MIN_VALUE;
public static final java.lang.Class TYPE;
private double value;
private static final long serialVersionUID;

>

}
5.13. reflection/ReflectionTest.ja v a 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

package reflection;
import java.util.*;
import java.lang.reflect.*;
/**
*
* * version 1.1 2004-02-21
* author Cay Horstmann
*/

public class ReflectionTest


{

public static void main(String[] args)


{
//
//
String name;
if (args.length > 0) name = args[0];
else

{
Scanner in = new Scanner(System.in);
System.out.println("Enter class name (e.g. java.util.Date): ");
name = in.next();
}
try
{
e
// (if != Object)
Class cl = Class.forName(name);
Class supercl = cl.getSuperclass ();
String modifiers = Modifier.toString(cl.getModifiers());
if (modifiers.length() > 0) System.out.print(modifiers + " ) ;
System.out.print("class " + name);
if (supercl != null && supercl != Object.class)
System.out.print (" extends " + supercl.getName ());
i

System.out.print("\n{\n");
printConstructors (cl);
System.out.println();
printMethods(cl);
System.out.println();
printFields(cl);
System.out.println("}");
}

catch (ClassNotFoundException e)

{
.printStackTrace();

}
System.exit(0) ;

}
/*
*
* @param cl a class

V
public static void printConstructors(Class cl)

{
Constructor[] constructors = cl.getDeclaredConstructors ();
for (Constructor c : constructors)

{
String name = c.getNameO;
System.out.print( ");
String modifiers' = Modifier.toString(c.getModifiers ()) ;
if (modifiers.length()-> 0) System.out.print(modifiers + " ")
System.out.print(name + "();

66
67
68

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

//
Class [] paramTypes = c.getParameterTypes () ;
for (int j = 0; j < paramTypes.length; j++)

{
if (j >0) System.out.print (, ");
System.out.print(paramTypes[j].getName ());

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

j
*
* 0param cl a class
*/
public static void printMethods(Class cl)

{
Method[] methods = c l .getDeclaredMethods ();
for (Method m : methods)

{
Class retType = m.getReturnType ();
String name = m.getNameO;
System.out.print(" ") ;
// ,
String modifiers = Modifier.toString(m.getModifiers());
if (modifiers.length () > 0) System.out.print(modifiers + " ") ;
System.out.print(retType.getName() + " " + name +"(");
//
Class[] paramTypes = m.getParameterTypes();
for (int j = 0; j < paramTypes.length; j++)

{
if (j > 0) System.out.print (", );
System.out.print(paramTypes[j].getName());

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

^*

47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

253

254

106
}
107
}
108
109
/**
110
*
111 ' * @param cl a class
112
*/
113
public static void printFields(Class cl)
114
{
115
Field[] fields = cl.getDeclaredFields();
116
117
for (Field f : fields)
118
{
119
Class type = f.getTypeO;
120
String name = f.getNameO;
121
System.out.print(" ");
122
String modifiers = Modifier.toString(f.getModifiers());
123
if (modifiers.length () > 0) System.out.print(modifiers + " ");
124
System.out .println (type.getName () + " + name + ";");
125
}
126
}
127 }

, ,
Java, ,
. ,
Java.
ja v a .la n g .C la s s

1 .0
1 .1

Field[] getFields()

Field[] getDeclaredFields() 1 . 1

g e t F i e l d s O , Field,
.
getDeclaredFields () , Field,
. ,
Class .

Method[] getMethods() 1.1

Method[] getDeclaredMethods() 1.1

, Method,
, ( getMethods ()),
, ( getDeclaredMethods ()).

Constructor[] getConstructors() 1 . 1

Constructor[] getDeclaredConstructors() 1 . 1

, Constructor,
( getConstructors ( )) ,
Class ( getDeclaredMethods ()).

255

ja v a . la n g . r e f l e c t . F i e ld 1 .1
j a v a . l a n g . r e f l e c t .M e th o d 1 . 1
ja v a . la n g . r e f l e c t . C o n s tru c to r 1 .1

Class getDeclaringClass()

Class, ,
, .

Class [ ] getExceptionTypes () ( Constructor Method)

Class, ,
.

int getModitiers()

, ,
. Modifier.

String getName()

, , .

Class [ ] getParameterTypes () ( Constructor Method)

Class, .

Class getReturnType () ( Method)

Class, .

ja v a . la n g . r e f l e c t . M o d if ie r 1 .1

static String toString(int m o d if ie r s )

, ,
modifiers.

static boolean isAbstract(int m o d if ie r s )

static boolean isFinal(int m o d ifie r s )

static boolean islnterface(int m o d ifie r s )

static boolean isNative(int m o d ifie r s )

static boolean isPrivate(int m o d if ie r s )

static boolean isProtected(int m o d if ie r s )

static boolean isPublic(int m o d if ie r s )

static boolean isStatic(int m o d ifie r s )

static boolean isStrict(int m o d if ie r s )

static boolean isSynchronized(int m o d if ie r s )

static boolean isVolatile(int m o d ifie r s )

m o d i f i e r s ,
, .

256


,
.

Class.

getDeclaredFields () .


. , ,
.
, .
get Field.
f Field (,
getDeclaredFields ), obj ,
f, f .get (obj) ,
obj.
:
Employee harry = new Employee("Harry Hacker", 35000, 10, 1, 1989);
Class cl = harry.getClass();
// Class, Employee
Field f = cl.getDeclaredField("name");
// Employee
Object v = f.get(harry);
// name harry, .. String,
// "Harry Hacker"

, ,
. , name private,
, get () IllegalAccessException.
get () .
Java , ,
, .
,
Java. ,
. , setAccessible ()
Field, Method Constructor, , :
f.setAccessible(true); // f. get (harry);

setAccessible () AccessibleObject,
Field, Method Constructor.
,
.
toString ().
get () . name
String, , Object.
, salary.
double, Java .
, getDouble () Field
get (). ,
, Double.

257

, , . ,
f . s e t (obj, v alu e) obj v a lu e ,
f .
5.14 ,
toStringO, .
getDeclaredFields () , se tA c c e ssib le (),
. .
, 5.14
toStringO, .
class ObjectAnalyzer
{
public String toString(Object obj)

s {
Class cl = obj.getClass();

String r = cl.getName();
//
do
{

+=
F i e l d [] fields = cl.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
//
for (Field f : fields)

{
if (!Modifier.isStatic(f.getModifiers()))

{
if (!r .endsWith( [)) r +=
r += f.getName() +
try
{
Object val = f.get(obj);
r += toString(val);

}
catch

(Exception e)

{ e.printStackTrace(); }

r +=
cl = cl.getSuperclass() ;

}
while (cl != null);
return r;

}
}
5.14 .
, , ObjectAnalyzer (
5.15) , .
, ,
.
,
toString (). :
ArrayList<Integer> squares = new A r r a y L i s t o ();
for (int i = 1; i <= 5; i++) squares.add(i * i);

System.out.println(new ObjectAnalyzer().toString(squares));

258


:
java.util.ArrayList[elementData=class java.lang.Object[]{
java.lang.Integer[value=l][] [],
java.lang.Integer[value=4][] [],
java.lang.Integer[value=9][][],
java.lang.Integer[value=l6][][],
java.lang.Integer[value=25][1[],null,null,null,null,null},
size=5][modCount=5][][]
4

toString (),
t o S t r i n g () . , ,
:
public String toString()

{
return new ObjectAnalyzer().toString(this);

}
toString ()
.
5.14. o b j e c t A n a l y z e r / O b j e c t A n a l y z e r T e s t . j a v a
1 package ObjectAnalyzer;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

import java.util.ArrayList;
/**
*
* (Aversion 1.12 2012-01-26
* author Cay Horstmann
*/
public class ObjectAnalyzerTest

{
public static void main(String[] args)
{
ArrayList<Integer> squares = new ArrayListo ();
for (int i = 1; i <= 5; i++)
squares.add(i * i) ;
System.out.println(new ObjectAnalyzer().toString(squares));
}
}

5.15. objectAnalyzer/ObjedtAnalyzei?. java 1


1 package ObjectAnalyzer;
2
3
4
5
6
7

import
import
import
import
import

java.lang.reflect.AccessibleObject;
java.lang.reflect.Array;
java.lang.reflect.Field;
java.lang.reflect.Modifier;
java.util.ArrayList;

9 public class ObjectAnalyzer


10 {


11

private ArrayList<Object> visited = new ArrayListo () ;

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

67

j - -

*
* 0param obj
* 0return ,
*

*/
public String toString(Object obj)

{
if (obj == null) return "null";
if (visited.contains(obj)) return
visited.add(obj);
Class cl = obj.getClass ();
if (cl == String.class) return (String) obj;
if (cl.isArray())

{
String r = cl.getComponentType () + "[]{";
for (int i = 0; i < Array.getLength (obj); i++)

{
if (i > 0) r += ",";
Object val = Array.get(obj, i);
if (cl.getComponentType().isPrimitive ()) r += val;
else r += toString(val);

}
return r + "}";

}
String r = cl.getName();
//
do

{
+= "[";

Field[] fields = cl.getDeclaredFields();


AccessibleObject.setAccessible(fields, true);
//
for (Field f : fields)

if (!Modifier.isStatic(f.getModifiers ()))

{
if (!r.endsWith("[")) r += ",";
r += f.getName() + "=";
try

{
Class t = f .getType();
Object val = f.get(obj);
if (t.isPrimitive()) r += val;
else r += toString(val);

}
catch (Exception e)

{
e.printStackTrace();

}
}
}
r += "]";
cl = cl.getSuperclass ();

259

260

68

69
while (cl != null);
70
71
return r;
72
}
73 }

ja v a .la n g .r e fle c t.A c c e s s ib le O b je c t 1 .2

void setAccessible(boolean f l a g )
. true
f l a g , Java
.

boolean isAccessible()
.

static void setAccessible(AccessibleObject[] a r r a y ,

boolean f l a g )

j a v a . l a n g . C la s s

1 .1

Field getField(String name)

Field [] getFieldsO
, .

Field getDeclaredField(String name)

Field[] getDeclaredFields()
,
.

ja v a . la n g . r e f l e c t . F ie l d 1 .1

Object get(Object o b j)
obj, Field.

void set(Object o b j,

Object newValue)

obj, Field.


A rray j a v a . l a n g . r e f l e c t
. , ,
copyOf () A rrays. ,

261

. ,
.
Employee[] = new Employee[100];

//
= Arrays.copyOf(, 2 * a.length);

? ,
Employee [ ] O b ject [ ]. . ,
:
public static O b ject[] badCopyOf(Object[] a, int newLength)

//

{
Object[] newArray = new Object[newLength];
System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength));
return newArray;

}
,
.
O bject [], :
new Object[newLength]

O b j e c t []
E m p l o y e e [ ] .
ClassCastException. ,
Java , .. ,
new. Employee [ ]
Ob ject [ ] , ,
Ob ject [ ], Employee [ ] .
, - ,
.
Array java.lang.reflect new lnstance (),
.
:
Object newArray = Array.newlnstance(componentType,

newLength);

, .
Array. g e tL e n g th ().
getLength () Array .
, .
1. , .
2. , .
3. g e t Component () C la s s (
C la ss, ),
.
*

g e t L e n g t h () A rray , g e t ComponentType () C la ss? -,


.
, .

262

.
public static Object goodCopyOf(Object a, int newLength)

{
Class cl = a .getClass();
if (!c l .isArray()) return null;
Class componentType = c l .getComponentType();
int length = A r r a y .getLength(a);
Object newArray = A r r a y .newlnstance(componentType, newLength);
System.arraycopy(a, 0, newArray, 0, Math.min(length, newLength));
return newArray;

}
, g o o d C o p y O f ()
, , .
int [] = { 1, 2, 3, 4, 5 };
= (i n t []) goodCopyOf(, 10);

g o o d C o p y O f ()
O b j e c t , (.. O b j e c t [ ]). i n t [ ]
O b j e c t , !
5.16 C o p y O f ():
b a d C o p y O f () g o o d C o p y O f ( ) . , , ,
, b a d C o p y O f (),
.
5.16. arrays/CopyOfTest.j ava1
1 package arrays;
2

'

3
4
5

import java.lang.reflect.*;
import java.util.*;

/**

7
8
9
10

*
*
*
*

11

*/



(Aversion 1.2 2012-05-04
Qauthor Cay Horstmann

12 public class CopyOfTest


13 {
14
public static void main(String[] args)
15
{
16
int [] a = { 1, 2, 3 };
17
a = (int[]) goodCopyOf(a, 10);
18
System.out.println(Arrays.toString(a));
19
20
String[] b = { "Tom", "Dick", "Harry" };
21
b = (String!]) goodCopyOf (b, 10);
22

System.out.println(Arrays.toString(b));

23

24
25
26
27
28

29
30

System.out.println("The following call will generate an exception.");

b = (String!]) badCopyOf(b, 10);


}
/**

*
*


31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61 }

*
*
*
*

263

@
0param newLength
@return ,
, Objoct[],

*/
public static Object[] badCopyOf(Object [] a, int newLength) //
{
Object [] newArray = new Object[newLength];
System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength));
return newArray;
}
/**
* ,
*
* @param .
*
* @return ,
*
*/
public static Object goodCopyOf(Object a, int newLength)
{
Class cl = a.getClass();
if (!cl.isArray()) return null;
Class componentType = cl.getComponentType();
int length = Array.getLength (a);
Object newArray = Array.newlnstance(componentType,newLength);
System.arraycopy (a, 0, newArray, 0,Math.min(length, newLength));
return newArray;
}

ja v a . la n g . r e f l e c t .A rra y 1 .1
get(Object a r r a y , int in d ex)

static Object

static x x x getXxx (Object a r r a y ,

int in d ex)

. (

boolean, byte, char, double, float, int, long, short.)

static void set(Object a r r a y ,

static setXxx(Object a r r a y ,

int in d e x ,

int in d e x ,

Object newValue)

xxx newValue)

.
( boolean, byte, char, double, float, int,
long, short.)

static int getLength(Object a r r a y )

static Object

newlnstance(Class componentType, intle n g th )

static Object

newlnstance(Class componentType, int[]

,
.

le n g th s )

264


C++ .
, Java , ..
,
. Java ,
, ,
, ,
.
.
! Java, Microsoft
J++ ( #), ,
Method, . .
, ,
, .

, get ()
Field. Method invoke (),
, , :
Object invoke(Object o b j, Object... a r g s )

,
. ,
, null. , ml
getName () Employee, :
String n = (String) m l .invoke(harry);

, invoke ()
-. , m2
g e t S a l a r y O Employee. -
Double,
double.
:
double s = (Double) m2.invoke(harry);

M e t h o d ? , ,
getDeclaredMethods ()
Method. , g e t M e t h o d O Class.
getField (),
Field.
,
. ,
. g e t M e t h o d O
:
Method getMethod(String name, Class... p a ra m e te rT y p e s )

,
getName () raiseSalary () Employee.


Method ml = Employee.class.getMethod("getName");
Method m2 = Employee.class.getMethod("raiseSalary",

265

double.class);

, Method,
. 5.17 ,
Math.sqrt Math.sin.
:
public static native double java.lang.Math.sqrt(double)
1.0000 |
1.0000
2.0000 |
1.4142
3.0000 |
1.7321
4.0000 |
2.0000
5.0000 |
2.2361
6.0000 |
2.4495
7.0000 |
2.6458
8.0000 |
2.8284
9.0000 |
3.0000
10.0000 |
3.1623

, , , , .
double dx = (to - from) / ( - 1);
for (double x = from; <= to; += dx)

{
double = (Double) f.invoke(null, x ) ;
System.out.printf("%10.4f | %10.4f%n", x, y);

}
f Method. ,
invoke () null.
M a t h .sqrt
:
Math.class.getMethod("sqrt, double.class)

getMethod () sqrt ()
Math double. 5.17
.
5.17. methods/MethodTableTest .java1
1
2
3
4
5
6
7
8
9
10

package methods;

12
13
14
15

import java.lang.refleet.*;
/**
*
* (Aversion 1.2 2012-05-04
* Qauthor Cay Horstmann
*/
public class MethodTableTest
public static void main(String[] args) throws Exception
{
// square() sqrt()
Method square = MethodTableTest.c la ss.g e tM e th o d ("sq u a re , dou ble.c l a s s ) ;

266

16
Method sqrt = Math.class.getMethod("sqrt", double.class);
17
18
// x
19
20
printTable (1, 10, 10, square);
21
printTable (1, 10, 10, sqrt);
22
}
23
j
24
25
*
26
* @param
27
* 0return
28
*/
29
public static double square(double x)
30
{
31
return x * x;
32
}
j
--
33
34
*
35
*
36
*
37
*
38
* f , double
39
*/
40
public static void printTable(double from, double to, int n, Method
41
{
42
//
43
System.out.println (f);
44
45
double dx = (to - from) / (n - 1);
46
47
for (double x = from; x <= to; x += dx)
48
{
49
try
50
{
double = (Double) f .invoke(null, x);
51
System.out.printf ("%10.4f | %10.4f%n", x, y);
52
53
}
catch (Exception e)
54
55
{
e.printStackTrace();
56
57
}
58
}
59
}
60 }

, Method ,
( #). ,
. , ,
, invoke () ?
invoke () .
, invoke ()
Object.
.
. ,
, . ,

267

,
, , ,
.
Method
. ,
. ,
Java, Method
, ,
, .
j a v a . l a n g . r e f l e c t . M e th o d 1 . 1

public Object invoke(Object i m p l i c i t P aram eter, Object[] e x p lic it P a r a m e t e r s )

, ,
, .
null.
.
.



.
1. .
Person ,
Employee Student.
2. .
, " "
,
. ,
. -,
. , ,
,
, . -, Java
, ,
, .
,
.
3. "".
,
. , Contractor.
, ,
, . ,
, . ,

268

Contractor , Employee, hourlyWage.


class Contractor extends Employee
{
private double hourlyWage;

}
. ,
, , , .

, . ,
, ,
, .
" - "
"". , ,
.
4. ,
.
, Holiday. ,
,
GregorianCalendar,
:
class Holiday extends GregorianCalendar(...)

,
. GregorianCalendar
add (), :
Holiday

C h r istm a s;

C h r is t m a s . add(Calendar.DAY_OF_MONTH,

12);

, .
5. , .
,
, .
. .
, .
, add ()
Holiday, , , ,
.
.

,
, GregorianCalendar
Holiday.
int dl = .get(Calendar.DAY_OF_MONTH);
x .add(Calendar.DAY_OF_MONTH, 1);
int d2 = x.get(Calendar.DAY_OF_MONTH);
System.out.println(d2 - dl);

269

, .
. ,
, , M anager,
e q u a ls () bonus,
E m p lo y ee.eq u als ().
. , ,
, .
6. , .
,
:
if ( 1)
1 ();
else if ( 2)
2 ();

_1 _2 ? ,
.

,
.
. ();


, ,
.
7. .

, .
,
. ,
.

.
, Java
: , .
,
Java: .



...




-

, -
Java.
.
, ,
Java.
,
, , .
.
, .
, , Kotopoe
. ,
. , , .
.
,
.
. , ,
,
- .

272

-,
. -
,
.
.

Java .
, , .
, ,
, : "
, ".
. sort () Array
: ,
Comparable.
:
public interface Comparable

{
int compareTo(Object other);

}
, , Comparable,
compareTo (), Object
.

! Java SE 5.0, Comparable ,


.
public interface Comparable<T>

{
int compareTo(T other);

//

}
, Comparable<Employee>,
:
int compareTo(Employee other);

- ( ')
Comparable,
compareTo () .

, ,
, public .
, : compareTo ()
,
.
, , ,
.
,
. ,

273

. :
. ,
, .
, ,
. ,
.
, sort () Array
Employee. Employee
Comparable.
, .
1. , .
2. , .
, ,
implements:
class Employee

implements Comparable

, compareTo (), ,
. , compareTo ()
Employee.
public int compareTo(Object otherObject)

(
Employee other = (Employee) otherObject;
return Double.compare(salary, other.salary);

}
Doul^L^,
compare (), , |$
; , , .
! compareTo () public
, .
.
, ,
,
.

Java SE 5.0, ,
Comparable<Employee>, .
class Employee implements Comparable<Employee>

{
public int compareTo (1 other)

{
return Double.compare(salary, other.salary);

}
}
, Object .

274

. () Comparable .
, .
, ,
. ,
.
id - other.id. ,
, ,
, . , , ,
,
. ,
(Integer .Max_Value - 1) / 2,
.
, .
salary - other.salary , ,
. Double.compare ( , )
-1 , < , 1, > 0.

,
(). .
- sort ()
. Employee () ,
Comparable?
, Java .
- ,
. s o r t () ,
:
if

(a[i].([j ]) > 0)

{
// [1]

}
, [ i ]
(). ,
Comparable, ,
, ,
().
! , sort () Array
Comparable [ ] ,
sort () , .
, . sort Object []
, .
// ,
//
if (((Comparable) a[i]).(a[j]) > 0)

{
// a[i] a[j]

275

a [i] , Com parable,


.

6.1 ,
Employee ( 6.2).
6.1. in te r fa c e s/E m p lo y e e S o r tT e st. ja v a
1 package interfaces;
2

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

import java.util.*;
/**
*
* Aversion 1.30 2004-02-27
* Qauthor Cay Horstmann
*/
public class EmployeeSortTest

{
public static void main(String[] args)
{
Employee[] staff * new Employee[3];
staff[0] * new Employee("Harry Hacker", 35000);
staff[1] - new Employee("Carl Cracker", 75000);
staff[2] new Employee("Tony Tester", 38000);
Arrays.sort(staff);
// Employee
for (Employee : staff)
System.out.println ("name*" + e.getNameO + ", salary*" + e.getSalary());
}
}

6.2. in te rfa c e s/E m p lo y e e .ja v a 1


1 package interfaces;
2
3 public class Employee implements Comparable<Employee>
4 {
5
private String name;
6
private double salary;
7
8
public Employee(String n, double s)
9
{
10
name = n;
11
salary * s;

12

13
14
15
16
17

public String getNameO


{
return name;

276

6
-

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

public double getSalaryO


{
return salary;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}

j
*
* @param other Employee
* @return ,
*
, ; ,
*
;
*/
public int compareTo(Employee other)
{
return Double.compare(salary, other.salary);
}

ja v a .la n g .C o n p a r a b le < T > 1 .0

int compareTo( o th e r)

o t h e r ,
, o t h e r ; , ;
.

j a v a . u t i l .A r r a y s

1 .2

static void sort(Object[] a)

.
, Comparable,
.

ja v a .la n g .In te g e r 7

static int compare (int x ,

int y)

,
.

<

277

ja v a .la n g .D o u b le

static int compare(double x ,

double y)

, <
.

! Java :
,
sgn (.compareTo ()) = -sgn ( . compareTo ()). ( ,
.compareTo () ,
. compareTo ().) sgn : sgn(n) -1 ,
; 0, ; 1, . ,
compareTo (),
( ]
.
equals (),
. , Manager Employee, ,
Comparable<Employee>, Comparable<Manager>, .
class Manager extends Employee
{
public int compareTo(Employee other)

{
Manager otherManager =

(Manager)

other;

// !

}
}
.
Employee, Manager, .compareTo ()
, Employee.
. compareTo () ClassCastException.
equals (),
5. .
, .
, compareTo () :
if

(getClass()

!= other.getClass ()) throw new ClassCastException ();

,
compareTo () final.
, ,
. , Executive
Secretary? , Employee
rank(). rank() ,
compareTo ( ) .

278


. , new
:
= new Comparable (...); // !

, , ,
:
Comparable ; // !

,
, .
= new Employee (...); // , Employee
// Comparable
9

, instanceof ,
. ,
:
if (anObject instanceof Comparable)

{ ...

,
.
. ,
Moveable:
public interface Moveable

{
void move(double x, double y);

}
Powered,
Moveable :
public interface Powered extends Moveable

{
double milesPerGallon() ;

}
,
, , .
public interface Powered extends Moveable

{
double milesPerGallon() ;
double SPEED_LIMIT = 95; //

}
,
. , (..
public static final).
! public,
public static final, .
,
. Java ,
.

279

.
, SwingConstants,
NORTH, SOUTH, HORIZONTAL .. ,
SwingContants, . ,
, NORTH,
SwingConstants.NORTH. ,
.
.
Java ,
.
. , Java
Cloneable, . ,
Cloneable,
clone () Object. ,
, .
, Clonable Comparable,
:
class Employee implements Cloneable, Comparable

, , .


5,
, :
Java
Comparable , , , ?
abstract class Comparable // ?

{
public abstract int compareTo(Object other);

}
Employee
compareTo () :
class Employee extends Comparable // ?

{
public int compareTo(Object other)

{ ...

}
, ,
.
. , Employee
- , , Person. ,
:
class Employee extends Person, Comparable // !


, .
class Employee extends Person implements Conparable // !

, , C++
.

280

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



(. 6.1). ,
:
Employee original = new Employee("John Public, 50000);
Employee copy = original;
copy.raiseSalary(10); // !

, ,
original,
, clone ()
:
Employee = original.c l o n e ();
.raiseSalary(10); // !

. clone () (protected)
Object, .. . Employee
.
. , Object
clone (). ,
.
, .
,
.
, Employee, ,
4,
. . 6.2 , , clone ()
Object Employee. ,
"" ,
.

281

|
=
=

. 6 .1 .

? .
, , ,
, . ,
, String. ,

, ,
, .
,
clone (), ,
.
hire Day Date.

282

Siring.

Employee

/
&

nam e -------------------------- salary =


hireDay =

50000.0
------------

................ ........ 11 ' s


Date

\;

li
7

-i\

'jr ~ ... .....

!
/
{

. 6 .2 .

.
1. clon e (), ?
2. clo n e ()
, ?
3. clon e () ?
.
.
1. Cloneable.
2. clone () public.
! clone () Object protected,
anObject.clone ().
, Object? ,
(. 5).
clone () .
, clone
.

Cloneable .
, clone () , Object.

, ,
, . Java
,

283

, Cloneable,
.
! Cloneable Java,
. ,
Comparable
, .
, instanceof
:
if

(obj instanceof Cloneable)

...

clone () ( )
, Cloneable,
clone () super . clone (),
:
class Employee implements Cloneable
{
// ,
public Employee clone () throws CloneNotSupportedException
{
return (Employee) super.c l o n e ();

}
}
! Java SE 5.0 clone ()
Object.
clone () .

clone ()
Object.clone (), .
,
.
clone (), .
class Employee implements Cloneable

p u b li c

Employee

c lo n e ()

throw s

C lo n e N o tS u p p o rte d E x c e p tio n

{
// Object.clone ()
Employee cloned = (Employee) super.c l o n e ();
//
cloned.hireDay = (Date) hireDay.c l o n e ();
return cloned;

}
}
c l o n e () O b j e c t
CloneNotSupportedException. , clone ()

284

, Cloneable.
Employee Date , .
, ,
:
public Employee clone ()

throws CloneNotSupportedException

He ,
?
public Employee c l o n e ()

{
try

{
return super.clone();

}
catch (CloneNotSupportedException e) { return null; }
// ,

Cloneable

}
,
final. throws.

CloneNotSupportedException,
.
, . ,
clone () Employee,
Manager. clone ()
Employee ? ,
Manager. ,
bonus . Manager
,
. ,
clone (), .
clone () Object protected. ,
clone (), " "
.
clone () ?
, , , .
, clone ()
, .
, clone () ,
, . ,
. , clone ()
5 .
, 6.3,
Employee ( 6.4),
. raiseSalary () salary,
setHireDay () hireDay.
, clone ()
.

6.3. c lo n e /C lo n e T e st. ja v a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

package clone;
/**
*
* version 1.10 2002-07-01
* author Cay Horstmann
*/
public class CloneTest
{
public static void main(String[] args)

{
try
{
Employee original = new Employee("John Q. Public", 50000);
original.setHireDay(2000, 1, 1);
Employee copy = original.clone ();
copy.raiseSalary (10);
copy.setHireDay(2002, 12, 31);
System.out.println("original=" + original);
System.out.println("copy=" + copy);

21

22
catch (CloneNotSupportedException e)
23
{
24
e.printStackTrace();
25
}
26
}
27 }

6.4. clone/Employee .java1


1
2
3
4
5

package clone;
import java.util.Date;
import java.util.GregorianCalendar;
public class Employee implements Cloneable

6 {
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

private String name;


private double salary;
private Date hireDay;
public Employee(String n, double s)

{
name = n;
salary = s;
hireDay = new Date();
}
p u b lic Employee clone

()

throws CloneNotSupportedException

{
// Object.clone ()
Employee cloned = (Employee) super.clone ();
//
cloned.hireDay = (Date)hireDay.clone ();

285

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

return cloned;
}
/**
*
* @param year
* 0param month
* @param day
*/
public void setHireDay(int year, int month, int day)
{
Date newHireDay = new GregorianCalendar(year, month - 1, day).getTime();
//
hireDay.setTime(newHireDay.getTime());
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
public String toStringO
{
return "Employee[name=" + name + ",salary=" +
salary + " ,hireDay=" + hireDay + "]";
}

! , c lo n e ().
, ,
:
int[] luckyNumbers = { 2, 3, 5, 7, 11, 13 };
int[] cloned = (int[]) luckyNumbers.clone ();
cloned[5] = 12; // luckyNumbers[5]

! 1
Java.
, .


.
, ,
. , ,

.
, , .

287

ja v a x . swing Timer,
. , ,
Timer .
,
.
, ?
,
. Java
- :
. .
, ,
.
, , .
, ActionListener
ja v a .a w t .event. :
public interface ActionListener

{
void actionPerformed(ActionEvent event);

actionPerformed().

C++! 5, Java
Method. ,
. , C++
, Java .

,
, .
, ActionListener,
, , actionPerformed ():
class TimePrinter implements ActionListener

{
public void actionPerformed(ActionEvent event)

{
Date now = new D a t e ();
System.out.println("At the tone, the time is " + now);
Toolkit.getDefaultToolkit().beep();

}
}
ActionEvent actionPerformed ().
, , (
8).
, ActionEvent .

Timer :
ActionListener listener = new TimePrinter();
Timer t = new T i m e r (10000, listener);

288

Timer
.
.
ActionListener.
, :
t .start();

,
:
At the tone, the time is Thu Apr 13 23:29:08 PDT 2000

6.5 ,
.
, ,
. .
. "Quit
program? " ( ),
.
, , ja v a x .swing.* j a v a . util.*,
ja v a x . swing.Timer.
, .
. , ja v a . util .Timer,
.
6.5. timer/TimerTest .java1
1

package timer;

2 /**
3
4
5

(Aversion 1.00 2000-04-13


@author Cay Horstmann
*/

7
8
9
10

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import ja v a x . swing.*;

11 import javax.sw ing.Tim er;


12 / /

13 / / ja v a .u til.T im e r
14
15 public class TimerTest
16 {
17
public static void main(String[] args)
18

19

A c tio n L iste n e r

li s t e n e r = new Tim ePrinter ();

20
21

//

22

//

23
24
25
26
27
28

Timer t = new Timer(10000, listener);


t .start () ;

10

JOptionPane. show M essageDialog(null, "Q u it program ?");


S y s t e m .e x it (0);


29
30
31
32
33
34
35
36
37
38
39

289

}
class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Date now = new Date();
System.out .println ("At the tone, the time is " + now);
Toolkit.getDefaultToolkit().beep();
}
}

j a v a x . s w in g . J O p tio n P a n e 1 . 2

static void showMessageDialog(Component p a r e n t ,

Object m essage)

.
parent. parent
null, .

j a v a x . s w in g . T im e r 1 . 2

Timer(int i n t e r v a l ,

ActionListener l i s t e n e r )

, listener
, i n t e r v a l .

void start()

, actionPerformed ()
.

void stop()

. actionPerformed ()
.

ja v a . a w t. T o o lk it 1 .
" static Toolkit getDefaultToolkit()

, .
.

void beep ()


, .
? .

290

,
, .

,
,
.


.
1. ,
.
2. ,
.
3. .
Moiyr .
4. ,
.
5. ,
.
6. , ,
.
C++! C++ .
. :
, , , .
class LinkedList
{
public:
class Iterator //
{
public:
void insert(int x);
int erase();

};
private:
class Link //
{
public:
Link* next;
int data;

};
, .
LinkedList Iterator Link.

291

:
. Iterator LinkedList,
LinkedList::Iterator Iterator
. Java ,
. , Link
LinkedList. .
, LinkedList
,
. Java ,
.
Java ,
, C++.
, .
. * .
Java. C++.


, , . ,
,
, - . ,
T i m e st ,
TalkingClock. " "
: ,
. .
public class TalkingClock

{
private int interval;
private boolean beep;
public TalkingClock(int interval, boolean beep)
public void s t a r t () { . . . }

{ . . . }

public class TimePrinter implements ActionListener


//
{

}
, T i m e P r i n t e r
TalkingClock. , T a l k i n g C l o c k
TimePrinter. ,
T i m e P r i n t e r T a l k i n g C l o c k .
T i m e P r i n t e r . ,
actionPerformed () beep ,
.
public class TimePrinter implements ActionListener

{
public void actionPerformed(ActionEvent event)

292

{
Date now = new D a t e ();
System.out.println("At the tone, the time is " + now);
if (beep) Toolkit.getDefaultToolkit().beep();

}
}
. , TimePrinter
beep. actionPerformed ()
TalkingClock. .
. ,
, , ..
. ,
, . 6.3.

. 6.3.
/

.
, , ou ter.
actionPerformed () :
public void actionPerformed(ActionEvent event)

{
Date now = new Date();
System.out.println("At the tone, the time is " + now);
if (outer.beep) Toolkit.getDefaultToolkit().beep();

}
.
,
. TalkingClock ,
1, ,
:
public TimePrinter

{
o u te r = clock;
}

(TalkingClock clock) //

293

, o u te r
Java. ,
.
start () TimePrinter,
this TalkingClock
:
ActionListener listener = new TimePrinter(this); //
//

6.6 ,
. TimePrinter ,
beep
TalkingClock. ,
,
- .
! TimePrinter private.
TimePrinter TalkingClock.
.
.

6.6.

in n e r C la s s /In n e r C la s s T e s t. ja v a 1

1 package innerClass;
2
3 import java.awt.*;
4 import java.awt.event.*;
5 import java.util.*;
6 import javax.swing.*;
7 import javax.swing.Timer;

8 /**
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

*
* (Aversion 1.10 2004-02-27
* @author Cay Horstmann
*/
p u b lic

c la s s

In n e rC la ssT e st

{
public static void main(String[] args)
{
T a lk in g C lo c k c lo c k = new T a lk in g C lo c k (1000, true);
clock.start ();
// ,
/ /
JOptionPane.showMessageDialog(null, "Quit program?);
S y s t e m .e x it (0);
}
}
/**
* ,
*/
c la s s

T a lk in g C lo c k

294

31 {
32
private int interval;
33
private boolean beep;
34
35
/**
36
* " "
37
* @param interval ( )
38
* @param beep ,
39
*/
40
public TalkingClock(int interval, boolean beep)
41
{
42
this.interval = interval;
43
this.beep = beep;
44
}
45
46
/**
47
*
48
*/
49
public void start ()
50
{
51
ActionListener listener = new TimePrinter ();
52
Timer t = new Timer(interval, listener);
53
t .start () ;
54
}
55
public class TimePrinter implements ActionListener
56
{
57
public void actionPerformed(ActionEvent event)
58
{
59
Date now = new Date();
60
System.out .println ("At the tone, the time is " + now);
61
if (beep) Toolkit.getDefaultToolkit().beep();
62
}
63
}


o u te r ,
, .
. ,
.
.thi s

, T i m e P r i n t e r
actionPerformed () :

public void actionPerformed(ActionEvent event)

if (TalkingClock.this.beep) Toolkit.getDefaultToolkit () .beep () ;

}
,
, :
.new ()

295

,
TimePrinter this ,
.
ActionListener listener = this.new TimePrinter();

, this ,
, .
. , TimePrinter
, " ",
.
TalkingClock jabberer = new TalkingClock(1000, true);
TalkingClock.TimePrinter listener = jabberer.new TimePrinter () ;

,
, :
.

,
Java 1.1.
,
, Java. ,
Java C++ . .
( , , ,
, .)
,
.
Java ,
, ,
, , , , ?
, ,
, .
$, .
, .
, TimePrinter, TalkingClock,
TalkingClock$TimePrinter .class. ,
, :
Ref lectionTest (. 5)
TalkingClock$TimePrinter. ,
javap :
javap -private

! UNIX, $,
. , Ref lectionTest javap
:
java reflection.ReflectionTest .TalkingClock\$TimePrinter

javap -private .TalkingClock\$TimePrinter

296

:
public class TalkingClock$TimePrinter
{
public TalkingClock$TimePrinter(TalkingClock);
public void actionPerformed(java.awt.event.ActionEvent);
final TalkingClock this$0;

}
, this$0
. ( this$0 ,
.) ,
TalkingClock. ,
? ,
TimePrinter , TalkingClock,
this , .
class TalkingClock
{
public void start ()

{
ActionListener listener = new TimePrinter(this);
Timer t = new Timer(interval, listener);
t. start () ;

class TimePrinter implements ActionListener

{
private TalkingClock outer;

public TimePrinter(TalkingClock clock)

{
outer = clock;

actionPerformed().
outer.beep :
if

(outer.beep)

. . . // !

.
, . TimePrinter
, , .
, , , ,
, .
:
, ,
? ,
ReflectionTest, TalkingClock,
:

297

class TalkingClock

{
private int interval;
private boolean beep;
public TalkingClock(int, boolean);
static boolean access$0(TalkingClock);
public void s t a r t ();

}
access $ 0,
. beep ,
. (
, access$000.)
. a c t i o n P e r f o r m e d O
TimePrinter :
if (beep)

.
if (access$100(outer));

? !
access $ 0 () beep. , access $ 0
Java. ,
,
. ,
(, ).
, ,
.
, ,
, .
, .
, ,
.
! (
, ). , TimePrinter
.
, ,
:
private TalkingClock$TimePrinter(TalkingClock);

, . ,
, .
TalkingClock$TimePrinter(TalkingClock,

TalkingClock$l);

start () TaklingClock
:
new TalkingClock$TimePrinter(this,

null)

298


TalkingClock,
, TimePrinter :
start ().
, .
public void start()

{
class TimePrinter implements ActionListener

{
public void actionPerformed (ActionEvent event)

{
Data now * new Data ();
System.out.println("At the tone, the time is " + now);
if (beep) Toolkit.getDefaultToolkitO .beep();

}
)
ActionListener listener = new TimePrinter();
Timer t = new Timer(interval, listener);
t .s tart();

}

(, public protected).
, .
:
TalkingClock. , start (),
TimePrinter.



, ,
!
final. , interval beep
TalkingClock start (), .
public void start (int interval,

final boolaan basp)

{
class TimePrinter implements ActionListener

{
public void actionPerformed(ActionEvent event)

{
Data now * naw Data();
System.out.println("At tha tons, the time is " + now);
if (beep) Toolkit.getDefaultToolkitO .beapO ;

}
}
ActionListener listener = new TimePrinter();
Timer t = new Timer(interval, listener);
t .start () ;

299

, TimePrinter
beep. ,
. , . ,
start ,
beep?
if (beep)

. . .

. ,
.
1. start ( ) .
2. TimePrinter
listener.
3. listener Timer,
start () . beep
start () .
4. i f

(beep) . . .

actionPerformed().

a c t i o n P e r f o r m e d () ,
TimePrinter beep ,
start (). .

TalkingClock$lTimePrinter. Ref lectionTest
TalkingClock$lTimePrinter, :
class TalkingClock$lTimePrinter

{
TalkingClock$lTimePrinter(TalkingClock, boolean);
public void actionPerformed(java.awt.event.ActionEvent);

final boolean val$beep;


final TalkingClock this$0;

}
, boolean,
val$beep. beep
val$beep.
, .
,
,
,
.

.
,
.
,
, final. beep
(.. final).

300

. ,
, ,
.
! ,
:
public static final double SPEED LIMIT = 55;

final , ,
. :
: .
.


. , beep
, start (). (
,
beep.) val$beep
TalkingClock$lTimePrinter :
. ,
, .
final . ,
, ,
compareTo ():
int counter = 0;
Date[] dates = new D a t e [100];
for (int i = 0; i < dates.length; i++)
dates[i] = new Date()

{
public int compareTo(Date other)

{
counter++; // !
return super.compareTo(other);

}
};
Arrays.sort(dates);
System.out.println(counter + " comparisons.);
/

counter final . ,
. Integer,
Integer .
1 , .
final int[] counter = new int[l] ;
for (int i = 0; i < dates.length; i++)
dates[i] = new Date()

{
public int compareTo(Date other)

{
counter[0]++;
return super.compareTo(other);

301

( final. ,
.
.)
,
,
.
"", final. ,
Java .


,
. ,
, .
, .
public void start (int interval,

final boolean beep)

{
ActionListener listener =

new ActionListener()

{
public void actionPerformed(ActionEvent event)

{
Date now = new Date ();
System.out.println("At the tone, the time is " + now);
if (beep) Toolkit.getDefaultToolkit().beep();

};

Timer t = new Timer(interval,


t .start ();

listener);

}
, .
:
, ActionListener,
{} actionPerformed ().
.
new ( )

}
, ActionListener,
. .
.
,
,
. , ,
. , - ,
.
:
new ()

{

}

302



, . ,
, ,
, .
Person queen = new Person("Mary");
// Person
Person count = new Person("Dracula") { . . .};
// ,

Person

Java ,
? ,
.
, , , ,

. ,
6.7 ,
" ", .
6.6, ,
,
, .
4

6.7. anonymousInnerClass/AnonymousInnerClassTest. java1


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

package anonymousInnerClass;
import
import
import
import
import

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

/**
*
* version 1.10 2004-02-27
* author Cay Horstmann
*/
public class AnonymousInnerClassTest
{
public static void main(String[] args)
{
TalkingClock clock = new TalkingClock();
clock.start (1000, true);

20

21
22
23
24
25
26
27
28
29
30
31
32

// ,
/ /
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}
/**
* ,
*/
class TalkingClock
{

33

I -it

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

*
* @ interval ( )
* @param beep ,
*/
public void start(int interval, final boolean beep)

303

{
ActionListener listener = new ActionListener ()

{
public void actionPerformed(ActionEvent event)

{
Date now = new Date ();
System.out .println ("At the tone, the time is " + now);
if (beep) Toolkit.getDefaultToolkit().beep ();

};

Timer t = new Timer(interval, listener);


t.start ();

! ,
. ,
:
ArrayList<String> friends = new ArrayListo ();
favorites.add("Harry");
favorites.add("Tony");
invite(friends);

, .
? :
invite(new ArrayList<String>() {{ add("Harry"); add("Tony");

}})

.
ArrayList,
(. 4).

! , ,
.
equals (). 5, equals ()
:
if (getClassO

!= other.getClass ()) return false;

.
, .
System.err.println("Something awful happened in " + getClass());

. getClass ,
, this.getClass (). this
. :

304

6
new Object(){}.getClass().getEnclosingClass() //
//

new Object () {} ,
Object, getEnclosingClass () , .. ,
.


,
, .
, (.. static).
, .
, :
, .
.
,
, :
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
for (double v : values)

{
if (min > v) min = v;
if (max < v) max = v;

}
. ,
Pair ,
.
class Pair
{
private double first;
private double second;
public Pair(double f, double s)

{
first = f;
second = s;

}
public double getFirstO { return first; }
public double getSecondO { return second; }

}
minmax () Pair :
class ArrayAlg
{
public static Pair minmax(double[] values)

return new Pair(min, max);

305

,
getFirst () getSecond (), .
Pair = ArrayAlg.minmax(d);
System.out .println ("min = " + p.getFirst());
System.out.printIn("max = " + p .getSecond());

, Pair ,
,
Pair , .
, Pair
ArrayAlg.
Pair, a ArrayAlg.Pair:
ArrayAlg.Pair p = ArrayAlg.minmax (d) ;

' , , ,
Pair . ,
:
class ArrayAlg

{
static class Pair

public
{

}
}
, .
,
,
. ,
,
.
public static Pair minmax(double[] d)

return new Pair(min, max);

}
Pair , ,
ArrayAlg .
! ,
.
.

! , ,
(.. static public).

6.8 ArrayAlg
Pair.

306

6.8. staticInnerClass/StaticInnerClassTest.java
1 package staticInnerClass;
2
3 /**
4
*
5
*

6
* Qversion 1.01 2004-02-27
7
* eauthor Cay Horstmann

8 */
9

public class StaticInnerClassTest

10 {
11
public static void main(String[] args)
12
{
13
doublet] d = new double[20];
14
for (int i = 0; i < d.length; i++)
15
d[i] = 100 * Math.random();
16
ArrayAlg.Pair p = ArrayAlg.minmax(d);
17
System.out.println("min = " + p.getFirst());
18
System.out.println ("max = " + p.getSecond ());
19
}
20 }
21 class ArrayAlg
22 {
23
/**
24
*
25
V
26
public static class Pair
27
{
28
private double first;
29
private double second;
30
31
/**
32
*
33
* f
34
* s
35
*/
36
public Pair(double f, double s)
37
{
38
first s f;
39
second = s;
40
}
41
42
/**
43
*
44
* @return
45
*/
46
public double getFirstO
47
{
48
return first;
49
}
50
51
/**
52
*
53
* Qreturn
54
*/
55
public double getSecondO
56
{

-
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78 }

307

return second;
}
}

j
*
* @param values
* @return ,
*
,
*/
public static Pair minmax(double[] values)
{
double min = Double.MAX VALUE;
double max = Double.MIN_VALUE;
for (double v : values)
{
if (min > v) min = v;
if (max < v) max = v;
}
return new Pair(min, max);
}

-
-,
-. ,
,
. - , ,
.
.
, -,
.
, ,
,
. , ,
. - .
new lnstance () C la s s
, .
. , .

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

, .

, O bject ( t o S t r i n g (), e q u a ls ()
..).

308


. , .. ,
InvocationHandler.
:
Object invoke(Object proxy, Method method, Object[] args)

- -
invoke () , Method
.
. - newProxylnstance ()
Proxy. .

. Java
: , ..
9 .
null,
, .

Class .

:
-? ,
,
-. , .

, ,
, .

-
.
TraceHandler,
. invoke () ,
, ,
, .
class TraceHandler implements InvocationHandler

{
private Object target;
public TraceHandler(Object t)

{
target = t;

}
public Object invoke(Object proxy, Method m, Obje c t [] args)
throws Throwable

{
//
//

-
return m.invoke(target,

309

args);

}
}
, -,
.
Object value = . . .;
//
InvocationHandler handler = new TraceHandler(value);
// -
C l a s s [] interfaces = new C l a s s [] { Comparable.class};
Object proxy = Proxy.newProxylnstance(null, interfaces, handler);

, proxy,
,
value.

, 6.9, -
. ,
- 1 1000.
binarySearch () Arrays.
, , ,
.
Object[] elements = new Obje c t [1000];
// - 1 1000
for (int i = 0; i < elements.length; i++)

{
Integer value = i + 1;
elements[i] = Proxy.newProxylnstance(. . .); // -
//

}
//
Integer key = new R a n d o m ().nextlnt(elements.length)
// key
int result = Arrays.binarySearch(elements,

+ 1;

key);

// ,
if (result >= 0) System.out.println(elements[result]);

Integer Comparable. -
, . ( $0.)
Comparable. compareTo ()
invoke () -.
! , Integer
Comparable<Integer>.
, - Comparable.

binarySearch () , :
if (elements[i].compareTo(key)

< 0)

...

-, compareTo ()
invoke () TraceHandler.

310

, compareTo ()
Integer.

, :
System.out.println(elements[result]);

println () t o S t r i n g O -,
.
.
i

500.compareTo(288)
250.compareTo(288)
375.compareTo(288)
312.compareTo(288)
281.compareTo(288)
296.compareTo(288)
288.compareTo(288)
288.toString()

, .
, toString () -,
, Comparable.
, Object -.
6.9. proxy/ProxyTest .java1
1
2
3
4
5
6
7
8
9
10

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

package proxy;
import java.lang.reflect.*;
import java.util.*;
/**
* -
* version 1.00 2000-04-13
* author Cay Horstmann
*/
public class ProxyTest
{.

public static void main(String[] args)


{
Object[] elements = new Object[1000];
// lenente - 1 1000
for (int i =-0; i < elements.length; i++)
{
Integer value = i + 1;
InvocationHandler handler = new TraceHandler(value);
Object proxy = Proxy.newProxylnstance(null,
new Class[] { Comparable.class } , handler);
elements[i] = proxy;
}
//
Integer key = new RandomO .nextlnt(elements.length) + 1;
// k*y
int result = Arrays.binarySearch(elements, key);

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

311

// ,
if (result >= 0) System.out.println(elements[result]);
}
}
/**
* , ,
*
*/
class TraceHandler implements InvocationHandler
{
private Object target;
/**
* TraceHandler
* @param t
*/
public TraceHandler(Object t)
{
target = t;
}
public Object invoke(Object proxy, Method m, Object[] args)
throws Thrbwable
{
//
System.out.print(target);
//
System.out.print (". " + m.getNameO + "(");
//
if (args != null)
{
for (int i - 0; i < args.length; i++)

{
System.out.print(args[i]);
if (i < args.length - 1) System.out.print (", ");
}
}
System.out.println(")");
//
return m.invoke(target, args);
}
}

-
, - , .
, - .
, ,
.
- Proxy.
, ,
Proxy. ,
, -, .

312

, 6.9 -,
Comparable, TraceHandler
.
- t o S t r i n g O , e q u a l s ()
hashCode () Object. invoke ()
. Object (, clone () getClass ())
. - .
, $ Proxy.

-. , ,
newProxylnstance ()
, .
getProxyClass () :
Class proxyClass = Proxy.getProxyClass(null,

interfaces);

- . ,
-, public,
. ,
public, ,
-, . isProxyClass ()
Proxy, , Class
-.
java.lang.reflect.InvocationHandler 1.3

Object invoke(Object p ro x y ,

Method method,

Object[] a r g s )

, ,
- -.

j a v a . l a n g . r e f l e c t . P r o x y 1 . 3 *

static Class getProxyClass(ClassLoader lo a d e r ,

Class[] i n t e r f a c e s )

-, .

static

Object

newProxylnstance(ClassLoader

lo a d e r,

Class!] i n t e r f a c e s ,

InvocationHandler h an d le r)

-, .
invoke () , .

static boolean isProxyClass(Class )

true, -.

Java.
. ,
-
, . , ,
,
7.

...
Swing






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

,

314

, , .
,
.
.
Java , ,
.

Swing
Java Abstract Window Toolkit (AWT),
.
(Windows, Solaris, Macintosh ..) AWT
. ,
AWT ,
.
,
, ,
Sun Microsystems: " , ".
, ,
. ,

, .
, , ,
, -. ,

. , (, Xll/M otif)
,
Windows Macintosh. , ,
. ,
AWT, Windows Macintosh
. ,
AWT .
,
: " , ".
1996 Netscape
, IFC (Internet Foundation Classes).
. ,
.

. , , IFC,
, ,
. Sun Microsystems Netscape
, Swing.
Swing
- .
Swing Java 1.1
Java SE 1.2.

Swing

315

, : "It
D o n 11 Mean a Thing If It A in f t Got That Swing" (Ax, :
), Swing -
. Swing
Java Foundation Classes (JFC). JFC
, Swing
. JFC Swing,
API ,
.
! Swing AWT.
AWT. Swing
. Swing, ,
AWT. Swing -
" , AWT
, .*

, Swing
,
AWT. , ,
. , Swing
.

,
. , ,
.

, Swing :

, ( , )
, , ..
.
Swing . ,
Swing,
. , . 7.1 7.2 ,
Windows GTK.
, Sun Microsystems
Metal (),
Java " Java".
Metal. .

316

. 7.1. W indows

. 7 .2 . GTK

Metal "". ,
JDK 5.0 (. 7.3).
Metal,
. Ocean
(). Java SE 6 Windows GTK.

317

Swing

Swing
,
.
* Svvi ncj Sf t --'

_ H X

File Look & Fee! Themes Ofitions

!ii_JLjf,

Text Buttons

;L

Text Position:

D isplay Options:

j i ~--- r

Two, [

'0 Paint Border

Tferes!

=r

b r if it f r a f it f c r f c a i

" f S l t .

E] Paint focus'
tabled

{} Contem Fitted

Image Buttons

Pad Amount:
# Default

Content Alignment:

Q0
0 10

Press SWt-Flp to activate popup menu

, 7.3. Ocean M etal


7 ,
Nimbus (; . 7.4). ,
, .
S V/ in } S e t ^

>ok&Feel jhemes

ounons | Boxes

**-* ;

**| , J

*/

x rjfiiia riitrtitttb P q ie ttfy

____ ,_____=:_______ :___ -

--------

*... -

----------

. 4*

-iWWI

^/' E t#' ft.f'&r:


K T J -T ''<* 4 ., 3 V ' 1H

--j r, "! ;

!r, -A- -

ifb .ll -

t t f l 1!

ti*

' l| - -

',

$4****/1?
1 -- . -

1 *
:f f - 7 . r 4 f r r n - - f r

]Press Shift-F10 to activate popup menu


^ ^ 2 g ij^ j-j2 ^ 2 5 iS S S ffl& i ta S S S 2 !i3 i5 S iS 3 S iS Il3 iS -fiiS

. 7.4. N im bus

318

, Java
, ,
Metal . 8,

.
! ,
. ,
,
. , ,
Swing .
Java ,
. Swing
http://www.javootoo.com.
Java SE 5.0 Synth (),
. Synth
, XML-,
.

. Napkin (; http://napkinlaf.sourceforge.net),
.
, ,
.

! Java
, Swing.
, Eclipse. Swing
SWT, , AWT,
. SWT
http://www.eclipse.org/articles/.

Oracle JavaFX,
Swing. JavaFX ,
www.oracle.com/technetwork/java/javafx/overview.

Microsoft Windows Visual


Basic #, , , ,
.

, . Java
, ,
Windows. , ,
,
, ,
.
.

319


(.. ,
) Java . AWT
Frame. Swing JFrame. JFrame
Frame
Swing, . , ,

, Swing.
! Swing J.
JButton JFrame.
AWT (, Button Frame). J
, ,
Swing AWT
.


JFrame. 7.1 ,
, . 7.5.

_ X

. 7.5.

7.1. s i m p l e f r a m e / S i m p l e F r a m e T e s t .java 1
1
2
3
4
5

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

6 /**
7
* version 1.32 2007-06-12
8
* author Cay Horstmann
9 */
10 public class SimpleFrameTest
11 {
12
public static void main(String[] args)

320

13
14
15
16
17
18
19

EventQueue.invokeLater(new Runnable()
public void run()
SimpleFrame frame = new SimpleFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

20

21

22

});

23
}
24 }
25
26 class SimpleFrame extends JFrame
27 {
28
private static final int DEFAULT_WIDTH = 300;
29
private static final int DEFAULT_HEIGHT = 200;
30
31
public SimpleFrame()
32
{
33
setSize(DEFAULT WIDTH, DEFAULT HEIGHT);
34
35

. Swing
javax. swing. ja v a x ,
Java .
Swing , Java 1.1.
Java SE, 1.2.
: 0x0 .
SimpleFrame,
300x200 .
SimpleFrame JFrame. main() SimpleFrameTest
SimpleFrame, .
,
Swing-. , Swing
, .. ,

.
:
EventQueue.invokeLater(new Runnable()

{
public void run()

}) ;
14.
" ",
Swing-.

321

! Swing-,
. ^
. , Swing
JDK .
, ,
. ,
.

,
, .
. :
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

,
,, ,
. ,
. ( , , ,
, , , Swing .)

. .
, .
main () setvisible ().
! Java SE 5.0
show (). , JFrame
Window, Window Component, show().
Java SE 1.2 Component.show () , ,
, , setvisible (true). ,
, , Java SE 1
Window.show () . show() ,
. ,
. Java SE 5.0 show()
.


main (). ,
. . ,
,
, System.exit ().
. 7.5. ,
, ,
, Swing.
Windows, GTK Mac OS -.
, , Swing.
, .
! Java SE 1.4,
, frame.setUndecorated(true).

322


JFrame ,
. , JFrame
,
. .

setLocation () setBounds (), .

disposed ),
, .

setlconlmage (), ,
, ..

setTitle (), .

setResizable (),
, .

JFrame . 7.6.
. , ^
. JFrame,
JFrame.
. ,
JDK - , . ,
toFront () JFrame,
Window, JFrame . ,
, , ,
, , .
API
.
.

API,
Component,
, Window,
Frame. , show (),
, Window, Component
setLocation (), .
,

(0,0) .
setLocation(,)

setBounds () Component
( , JFrame)
:
setBounds(, , width, height)

323

. 7 .6 . AWT Swing

,
. :
setLoationByPlatform(true);

( ) ,
.
! , setLocation ()
setBounds (), . 9,
.

324



.
Frame:
public String getTitleO
public void setTitle(String title)

.
get set
. , Frame title
String. , title .
, .
,
.
( ),
Frame. , .
, , .
private String title;

//

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

: boolean is.
, locationByPlatform.
8
.
public boolean isLocationByPlatformO
public void setLocationByPlatform(boolean b)

! , Visual Basic #,
. , Java
.


, ,
0x0 ,
,
.
,
, .
, ,
.
,
. getDefaultToolkit ()

325

Toolkit, Toolkit. ( Toolkit -

,
.) getScreenSize (),
Dimension.
(!) width height .
, .
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;


:
setSize(screenWidth / 2, screenHeight / 2);
setLocationByPlatform(true);

, .
,
Toolkit.
, .
Image img = new Imagelcon("icon.gif").getlmage();
setlconlmage(img);


-. , Windows
, ,
<Alt+Tab>.
7.2 ,
.
Core Java ( Java).
7.2. sizedFrameT/SizedFrameTest.java1
*
>

1
2
3
4
5

package sizedFrame;

/**

_____________________________________________________

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

7
* (Aversion 1.32 2007-04-14
8
* author Cay Horstmann
9 */
10 public class SizedFrameTest
11
12
public static void main(String[] args)
13
{
14 *
EventQueue.invokeLater(new Runnable()
15
{
16
public void run()
17
{
18
JFrame frame = new SizedFrame();
19
frame.setTitle("SizedFrame");
20
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
21
frame.setVisible(true);
22
}

326
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

7
});
}

}
class SizedFrame extends JFrame
{
public SizedFrame()
{
//
Toolkit kit = Toolkit.getDefaultToolkit ();
Dimension screenSize = kit.getScreenSize ();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
// ,
//
setSize(screenWidth / 2, screenHeight / 2);
setLocationByPlatform(true);
//
Image img = new Imagelcon("icon.gif").getlmage();
setlconlmage(img);
}
}


, (),
. ,
.
.
Java SE 1.4, ,
:
frame.setExtendedState(Frame.MAXIMIZED_BOTH);

,
,
. 10 ,
Preferences API.

,
, GraphicsEnvironment
GraphicsDevice .

GraphicsDevice
.

327

ja v a . a w t. Com ponent 1 .0

boolean isVisibleO

void setVisible(boolean b)

visible.
, JFrame.

void setSize(int w idth,

int h e ig h t)

1.1

void setLocation (int ,

int ) 1 . 1

. ,
,
(, JFrame).

void setBounds (int x ,

int y, int w idth,

int h e ig h t)

1.1

, w id th s h e ig h t.
1.1

Dimension getSizeO

void setSize(Dimension d) 1 . 1

size, .

j a v a . a w t . W in d o w 1 . 0

void toFrontO

void toBackO

, ,
.

boolean isLocationByPlatformO

5.0

void setLocationByPlatform(boolean b)

5.0

locationByPlatform.
, , .

ja v a .a w t.F r a m e

1 .0

boolean isResizable()

void setResizable(boolean b)

resizable. ,
.

328

String getTitle()

void setTitle(String s)

title, .

Image getlconlmage()

void setlconlmage(Image im age)

iconlmage, .
.

boolean isUndecoratedO

1.4

void setUndecorated(boolean b)

1.4

undecorated. ,
, .
.

int getExtendedState() 1.4

voidsetExtendedState(int s t a t e )

1.4

. s t a t e
:

Frame.NORMAL
Frame.ICONIFIED
Frame.MAXIMIZED_HORIZ
Frame.MAXIMI ZED_VERT
Frame.MAXIMIZED BOTH

java.awt.Toolkit 1.0

static Toolkit getDefaultToolkit()

Toolkit, .

Dimension getScreenSize()

filename.

javax. swing. Imagelcon 1.2

Imagelcon(String _)

, .

Image getlmage()

329


, . ,
3
. "Not a Hello, World program" (
", ") , . 7.7.

. 7 .7 . ,

,
. Java ,
(,
). , ,
.
, JFrame .
. 7.8. , JFrame ,
. ,
.
.
Swing .

/
:
Container contentPane = frame.getContentPane();
Component c = . . .;
contentPane.add(c) ;

Java SE 1.4 add()


JFrame "Do not use JFrame.addO . Use
JFrame.getContentPane () .add () instead" (He JFrame.add ( ) .
JFrame.getContentPane () .add ()). Java
SE 5.0 JFrame. add (),
add () . , Java SE 5.0,
:
frame.a d d ();

330

,
. ,
, JComponent,
paintComponent () . paintComponent ()
Graphics,
. , , .
Java Graphics.
, .
! Graphics Windows
11.

,
.
class MyComponent extends JComponent
{
public void paintComponent(Graphics g)

}
}
,
, .

331

paintComponent () .
paintComponent () .
,
.
? , ,
.
, , ,
. (
.) ,
, , ,
.
. , paintComponent ()
repaint (). , ,
paintComponent ()
Graphics.

, paintComponent ()
Graphics. ,
Graphics, . (0 ,0 )
, .
.
Graphics drawstring(),
:
g.drawstring(text,

, )

"Not a Hello, World Program"


,
. ,
, ,
(75, 100). , ,
75 100 .
( 100
, .) paintComponent ()
:
class NotHelloWorldComponent extends JComponent

{
public static final int MESSAGE_X = 75;
public static final int MESSAGE_Y = 100;
public void paintComponent(Graphics g)

{
g.drawstring("Not a. Hello, World program", MESSAGE_X, MESSAGE_Y);

}
}
, ,
. getPreferredSize (),
Dimension ,
.

332

class NotHelloWorldComponent extends JComponent


{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;

public Dimension getPreferredSize()


{ return new Dimension(DEFAULT_WIDTH,

DEFAULT_HEIGHT); }

}

,
setSize () pack ():
class NotHelloWorldFrame extends JFrame
{
public NotHelloWorldFrame()

{
add(new NotHelloWorldComponent());
pack () ;

7.3.
! JComponent
JPanel, ,
. .
, , .
,
super .paintComponent () paintComponen ()
:
class NotHelloWorldPanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);

7.3. notHelloWorld/NotHelloWorld. java 1


1
2
3
4
5
6
7
8
9
10
11

12

package notHelloWorld;
import javax.swing.*;
import java.awt.*;
/**

* (Aversion 1.32 2007-06-12


* @author Cay Horstmann
*/
public class NotHelloWorld

public static void main(String[] args)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

333

{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new NotHelloWorldFrame();
frame.setTitle("NotHelloWorld");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

}
});
}
}
/**
* ,
*/
class NotHelloWorldFrame extends JFrame
{
public NotHelloWorldFrame()
{
add(new NotHelloWorldComponent());
pack();
}
}
/**
* ,
*/
class NotHelloWorldComponent extends JComponent
{
public static final int MESSAGE_X = 75;
public static final int MESSAGE_Y = 100;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public void paintComponent(Graphics g)
{
g.drawstring("Not a Hello, World program", MESSAGE_X, MESSAGE_Y);
}
public Dimension getPreferredSize()
{ return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT) ; }
}

j a v a x . s w in g . J F ra m e 1 . 2

Container getContentPane()

JFrame.

Component add(Component )

. (
Java SE 5.0 .)

334

ja v a .a w t .C o m p o n e n t 1 . 0

void repaint()

. ,
, .

Dimension getPreferredSize()

j a v a x . s w in g . J C o o p o n e n t 1 . 2
void paintComponent(Graphics g)

j a v a . a w t . W in d o w 1 . 0

void pack ()

,
.


1.0 Graphics ,
, .
. ,

.
Java SE 1.2 Java 2D,
.
Java 2D,
7 .
Java 2D,
Graphics 2D. ,
Graphics. Java SB 2, , paintComponent (),
Graphics2d.
, .
public void paintComponent(Graphics g)

{
Graphics2D g2 = (Graphics2D)

g;

}
Java 2D
- . , ,

335

, ,
S h a p e .
Line2D
Rectangle2D
Ellipse2D

! Java 2D
, , , .
7 .

,
, S h a p e ,
d r a w () G r a p h i c s 2 D , :
Rectangle2D rect = . . .;
g2.draw(rect);

! Java 2D Java
Graphics, ,
drawRectangle (). .
, Java 2D, ,
,
, .

Java 2D
. Java 1.0,
, , Java 2D
, .
,
(,
), .
Java 2D .
,
.
,
. ,
,
f l o a t , d o u b l e .
f l o a t
, Java
d o u b l e f l o a t
. :
float f * 1.2; // !

, 1 .2
d o u b l e , .
F
:
float f = 1.2F; // !

336

:
rectangle2D = ...
float f = .getWidth(); // !

^ . getWidth ()
, double.
:
float f = (float) .getWidth(); // !

,
Java 2D
:
float ( ),
double ( ). ( ,
double
, .)

, .
Rectangle2D. ,
, :
Rectangle2D.Float
Rectangle2D.Double

. 7.9 - .

. 7 .9 .

,
. ,
, FloatRectangle2D DoubleRectangle2D. (
6.)
R e c t a n g l e 2 d . F l o a t
, float,
Rectangle2d. Double double,
.

337

Rectangle2D.Float floatRect =
new Rectangle2D.Float(10.0F, 25.OF, 22.5F, 20.OF);
Rectangle2D.Double doubleRect =
new Rectangle2D.Double(10.0, 25.0, 22.5, 20.0);

, Rectangle2d.Float Rectangle2D.Double,
Re tangle 2D, ,
,
. ,
Rectangle2D :
Rectangle2D floatRect = new Rectangle2D.Float (10 .OF, 25.OF, 22.5F, 20.OF);
Rectangle2D doubleRect = new Rectangle2D.Double (10.0, 25.0, 22.5, 20.0);

,
, .
,
.
! Rectangle2D. Float
setRect (float , float , float h, float w),
Rectangle2D. Rectangle2D. Float
Rectangle2D, . ,
Rectangle2D setRect () double.

, Rectangle2D,
double. , getwidth () double,
float
Rectangle2D.Float.

. float, ,
double.
, .
, float.

, Rectangle2D,
, . ,
Point2D Point2D. Float Point2D. Double.
.
Point2D = new Point2D.Double(10, 20);

. Point2D . Point2D
- ,
. ,
Point2D. ,
.*

* Rectangle2D Ellipse2D
RectangularShape. ,
, (. 7.10).

338

. 7 .1 0 . ,
RectangularShape 20 ,
. , getWidth (),
getHeight () , getCenterX () getCenterY () (, ,
getCenter (),
Point 2D).
,
Java 1.0, . , Rectangle
Point,
, Rectangle2D Point 2D.
. 7.11 ,
. Float Double . ,
,
.
Rectangle2D Ellipse2D .
:

*
, ,
, (150,
200), 100 50 .
Ellipse2D = new Ellipse2D.Double(150, 200,

100, 50);

,
.
,
. :
Rectangle2D rect =
new Rectangle2D.Double(, py, qx - px, qy - p y ) ; // !

p ,
, .
,
setFrameFromDiagonal () :
Rectangle2D rect = new Rectangle2D.Double();
rect.setFrameFromDiagonal(px, py, qx, qy) ;

339

. 7.11. ,

,
q Point2D.
:
rect.setFrameFromDiagonal(, q ) ;

,
, .
setFrameFromCenter (), ,
. , :
Ellipse2D ellipse = new Ellipse2D.Double(centerX - width / 2,
centerY - height / 2, width, height);

,
Point2D , .
Line2D line = new Line2D.Double(start,

end);

Line2D line = new Line2D.Double(startX,

startY, endX, endY);

340

, 7.4,
, , , ,
, .
. 7.12.
7.4. draw/DrawTest.j ava1
1
2
3
4
5

package draw;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

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

/**
* (Aversion 1.32 2007-04-14
* author Cay Horstmann
*/

public class DrawTest

public static void main(String[] args)


{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new DrawFrameO;
frame.setTitle("DrawTest);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
/**
* ,
*/
class DrawFrame extends JFrame
{
public DrawFrameO
{
add(new DrawComponent());
pack();
}
}
/**
* ,
*/
class DrawComponent extends JComponent
{
private static final int DEFAULT_WIDTH = 400;
private static final int DEFAULT_HEIGHT = 400;
p u b lic v o id paintComponent(Graphics

g)


50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

Graphics2D g2 = (Graphics2D) g;
//
double leftX = 100;
double topY = 100;
double width = 200;
double height = 150;
Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height)
g 2 .draw(rect);
//
Ellipse2D ellipse = new Ellipse2D.Double ();
ellipse.setFrame(rect);
g2.draw(ellipse);
//
g2.draw(new Line2D.Double(leftX, topY, leftX + width, topY + height))

66

67
68

69
70
71
72
73
74
75
76
77
78
79
80
81

//
double centerX = rect.getCenterX ();
double centerY = rect.getCenterY ();
double radius = 150;
Ellipse2D circle = new Ellipse2D.Double ();
circle.setFrameFromCenter(centerX, centerY, centerX + radius,
centerY + radius);
g2.draw(circle);

}
public Dimension getPreferredSize()
{ return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }

}
[ >i. i w

. 7 .1 2 .

341

342

j a v a . a w t . g e o m . R e c t a n g u la r S h a p e 1 . 2

double getCenterX()

double getCenterYO

double getMinX()

double getMinY()

double getMaxX()

double getMaxY()

,
.

double getWidth()

double getHeight()

double getX()

double getY()

j a v a . a w t . g e o m . R e c t a n g le 2 D . D o u b le 1 . 2

Rectangle2D. Double (double x , double y, doubles, double h)

, .

j a v a . a w t . g e o m . R e c t a n g le 2 D . F l o a t 1 . 2

Rectangle2D. Float (float x , floaty, floats, float h)

, .

j a v a . a w t . g e o m . E l l i p s e 2 D . D o u b le 1 . 2

Ellipse2D. Double (double x , double y, doubles, double h)

,
.

j a v a . a w t . g e o m . P o i n t 2 D . D o u b le 1 . 2

Point2D.Double(double x , double y)

343

j a v a .a w t . g e o m . L i n e 2 D . D o u b le 1 . 2

Line2D.Double (Point2D s t a r t , Point2D end)

Line2D. Double (double s t a r t X , double s t a r t Y , double endX, double endY)


setPaint () Graphics2D ,
.
.
g 2 .setPaint(Color.RED);
2 .drawstring("Warning!", 100, 100);


. draw ()
fill () :
Rectangle2D rect = . . .;
g 2 .setPaint(Color.RED);
g2.fill(rect); //

,
, ,
..
! fill ()
. , new Rectangle2D. Double (0, 0, 10, 20),
, = 10
= 20. ,
.

Color. java.a w t .Color


, 13 : BLACK (), BLUE (),
CYAN (), DARK_GRAY (-), GRAY (), GREEN (), LIGHT_GRAY
(-), MAGENTA (), ORANGE (), PINK (), RED (
), WHITE (), YELLOW ().
! Java SE 1.4 , ,
, Color, r e d ,
, . Java SE 1.4,
, (
).

,
, Color. Color
0 255 (.. )
:

344

Color(int redness,

int greenness,

int blueness)

.
g 2 .setPaint(new C o l o r (0, 128, 128)); // -
2 .drawstring("Welcome!", 75, 125);

! , ""
. ,
AWT, .
Graphics2D Graphics,
setColor().

, setBackground ()
Component, Jpanel:
MyComponent = new MyComponent();
.setBackground(Color.PINK);

setForeground (). ,
.
. brighter () darker () Color
. brighter (), ,
, .
brighter () .
, : .brighter () .brighter () .brighter ().

SystemColor
. ,
. ,
,
.
.setBackground(SystemColor.window)

. ,
SystemColor, , ,
, . . 7.1
.
7.1.

desktop

activeCaption

^ activeCaptionText

activeCaptionBorder

inactiveCaption

inactiveCaptionText

inactiveCaptionBorder

345

. 7.1

window

windowBorder

windowText

menu

menuText

text

textText

textlnactiveText

textHighlight

textHighlightText

control

controlText

controlLtHighlight

controlHighlight

controlShadow

controlDkShadow

scrollbar

info

infoText

ja v a .a w t.C o lo r 1 .0

Color (int r, int g, int b)

Color.
:

(0-255)

(0-255)

(0-25 5

ja v a .a w t.G r a p h ic s

1 .0

Color getColorO

void setColor(Color c )

.
.
:

346

ja v a .a w t .G r a p h i.c s 2 D

1 .2

Paint getPaintO

void setPaint(Paint p)

.
Color Paint.

void fill(Shape s)

ja v a . a w t. Com ponent 1 .0

Color getBackground()

void setBackground(Color c)

.
:

Color getForeground()

void setForeground(Color c)

.
:


, , ,
. ,
. .
(, Helvetica)
(, Bold ). , Helvetica
Helvetica Bold Helvetica.
,
, g e t A v a i l a b l e F a m i l y N a m e s ()
GraphicsEnvironment. ,
. GraphicsEnvironment,
, g e t L o c a l GraphicsEnvironment (). ,
, .
import java.awt.*;
public class ListFonts
{
public static void main(String[] args)

{
String[] fontNames = GraphicsEnvironment

347

.getLocalGraphicsEnvironment()
.getAvailableFontFamilyNames();
for (String fontName : fontNames)
System.out.println(fontName);

:
Abadi Condensed Light
Arial
Arial Black
Arial Narrow
Arioso
Baskerville
Binner Gothic

.
,
.
. , ,
. , Helvetica
Windows Arial.
AWT
:
SansSerif
Serif
Monospaced
Dialog
Dialoglnput

,
. , Windows SanSerif
Arial. , JDK Oracle
"Lucida Sans", "Lucida Bright" "Lucida Sans Typewriter".
,
Font, , .
, Font.
Font sansboldl4 = new Font("SansSerif", Font.BOLD,

14);

.
, . 72
. Font
. (.. ,
, ),
:
Font.PLAIN
Font.BOLD
Font.ITALIC
Font.BOLD + Font.ITALIC

348

!
fontconfig.properties, jre/lib Java.
http://docs.oracle.eom/javase/7/docs/
technotes/guides/intl/fontconfig.html.

TrueType, PostScript
1.
- ( -
1 ).
F o n t .CreateFont () :
URL url = new U R L ("h t t p ://www.fonts.com/Wingbats.ttf");
InputStream in = u r l .openStream();
Font fl = Font.createFont(Font.TRUETYPE_FONT, in);

1 .
, deriveFont (), .
Font df = f .deriveFont(14.OF);

! deriveFont ( ) .
( float) , ( int)
. , f .deriveFont (14) , !
( , 14
, i t a l i c , b o l d .)

Java , ,
. , Dialog 1\u2297 *,
* U.
, .
"Hello, World",
SanSerif 14 .
Font sansboldl4 = new F o n t ("SansSerif", Font.BOLD,
g 2 .setFont(sansboldl4);
String message = "Hello, World!";
g 2 .drawstring(message, 75, 100);

14);

.
.
.

( sans serif
14 ).

( "Hello, World! ").

, (
).

,
, getFontRenderContext () Graphics2D.
FontRenderContext.
getStringBounds () Font, . getStringBounds ()
, .

349

FontRenderContext context = g2.getFontRenderContext();


Rectangle2D bounds = f.getStringBounds(message, context);

, ,
, (. 7.13).
, ,
.
, , b .
, , .
/

. 7 .1 3 . ,


. ,
, .
, getStringBounds (),
. ,
.
. .
. , ,
:
double stringWidth = bounds.getWidth();
double stringHeight = bounds.getHeight();
double ascent = -bounds.getY();

, ,
getLineMetrics () Font, .
LineMetries,
.
LineMetrics metrics = f.getLineMetrics(message,
float descent = metrics.getDescent();
float leading = metrics.getLeading();

context);


.
FontRenderContext context = g2.getFontRenderContext();
Rectangle2D bounds = f.getStringBounds(message, context);
// (x, )
double = (getWidth() - bounds.getWidth()) / 2;
double = (getHeight() - bounds.getHeight()) / 2;
// ,

350

double ascent = -bounds.getY();


double baseY = + ascent;
g 2 .drawstring(message, (int) x,

(int) baseY);

,
, , g e t Width ()
. , bounds. getW idth (),
.
. ,

.
.
!
paintComponent (),
Graphics2D. getFontMetrics ()
JComponent, getFontRenderContext () :
FontRenderContext context = getFontMetrics(f).getFontRenderContext();

, ,

. . 7.14
, 7.5.
*

out - .t

_ X

. 7 .1 4 . ,

7.5. fo n t/F o n tT e st. ja v a 1


1 package font;
2
3 import java.awt.*;
4 import java.awt.font.*;
5 import java.awt.geom.*;
6 import javax.swing.*;
7
8

9
10
11

/**

* (Aversion 1.33 2007-04-14


* Oauthor Cay Horstmann
*/


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

public class FontTest


{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new FontFrameO;
frame.setTitle("FontTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
/**
*
*/
class FontFrame extends JFrame
{
public FontFrameO
{
add(new FontComponent());
pack();
}
}
/**
* , ,
*
*/
class FontComponent extends JComponent
{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
String message = "Hello, World!";
Font f = new Font("Serif", Font.BOLD, 36);
g2.setFont (f);
//
FontRenderContext context = g2.getFontRenderContext ();
Rectangle2D bounds = f.getStringBounds(message, context);
// (x, )
double = (getWidth() - bounds.getWidth ()) / 2;
double = (getHeightO - bounds .getHeight ()) / 2;
// ,
double ascent = -bounds.getY ();
double baseY = + ascent;
//
g2.drawstring(message, (int) x, (int) baseY);

351

352

72
73
g2.setPaint(Color.LIGHT_GRAY);
74
75
//
76
2.draw(new Line2D.Double(x, baseY, x + bounds.getWidth(), baseY));
77
//
78
Rectangle2D rect =
79
new Rectangle2D.Double(x, y, bounds.getWidth(), bounds.getHeight());
80
g 2 .draw(rect);
81
}
82
83
public Dimension getPreferredSize()
84
{ return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
85 }

ja v a .a w t.F o n t 1 .0

Font(String name,

int s t y l e ,

int s i z e )

Font .
:

, ..
(, Helvetica Bold)
(Serif SansSerif)

sty le

(Font.PLAIN, Font.BOLD,
Font.ITALIC Font.BOLD + Font.ITALIC)

siz e

(, 12 )

String getFontName()

(, Helvetica Bold).

String getFamilyO

(, Helvetica).

String getName()

(, SansSerif),
; *

Rectangle2D getStringBounds(String s ,

FontRenderContext c o n t e x t ) 1 . 2

, .
.
. , .
.

LineMetrics getLineMetrics(String s ,

FontRenderContext c o n te x t)

1.2

LineMetrics,
, .

Font deriveFont(int s t y l e )

Font deriveFont(float s i z e )

Font deriveFont(int s t y l e ,

1.2
1.2
float s i z e )

1.2

Font , ,
, .

j a v a . a w t . f o n t . L in e M e t r i e s

353

1 .2

float getAscent()

float getDescentO

float getLeadingO

float getHeight()

,
, .

j a v a . a w t . G r a p h ic s

1 .0

Font getFont()

void setFont(Font fo n t)

.
.
:

fo n t

void drawstring (String s t r ,

int x, int y)

, .
:

str

j a v a . a w t . G r a p h ic s 2 D

1 .2

FontRenderContext getFontRenderContext()

,
.

void drawstring(String s t r ,

float x, float y)

, .
:

str

354

! 7

j a v a x . s w in g . J C o m p o n e n t 1 . 2

FontMetrics getFontMetrics(Font f) 5.0

. FontMetrics
LineMetrics.

j a v a . a w t . F o n tM e tr ic s

1 .0

FontRenderContext getFontRenderContext() 1.2


,
.
, ,
. ( ,
.)
,
, Graphics.
. , ,
Image Icon :
Image image = new Imagelcon(filename).getlmage();

image ,
. ,
drawlmage () Graphics, .
public void paintComponent(Graphics g)

g.drawlmage(image,

x, y, null);

}
7.6 ,
.
. 7.15.
paintComponent ().
, (),
, .
for (int i = 0; i * imageWidth <= getWidthO; i++)
for (int j = 0; j * imageHeight <= getHeightO; j++)
if (i + j > 0)
g .copyArea(0, 0, imageWidth, imageHeight, i * imageWidth,
j * imageHeight);

7.6 .

. 7 .1 5 .

7.6. im a g e /Im a g e T e s t . j a v a 1
1
2
3
4
5

package image;
import java.awt.*;
import javax.s w i n g ;

6 /**
7
* Oversion 1.33 2007-04-14
8
* @author Cay Horstmann
9 */
10 public class ImageTest
11
12
public static void main(String[] args)
13
{
14
EventQueue.invokeLater(new Runnable()
15
{
16
public void run()
17
{
18
JFrame. frame = new ImageFrame ();
19
frame.setTitle("ImageTest");
20
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
21
frame.setVisible(true);

22

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

});
}
}
/**
*
*/
class ImageFrame extends JFrame
{
public ImageFrame()
{
add(new ImageComponent());
pack () ;
}
}

355

356
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

/**
* ,
*/
class ImageComponent extends JComponent
{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
private Image image;
public ImageComponent()
{
image = new Imagelcon("blue-ball.gif) .getlmage();
}
public void paintComponent(Graphics g)
{
if (image == null) return;
int imageWidth = image.getWidth(this);
int imageHeight = image.getHeight(this);
//
g.drawlmage(image, 0, 0, null);
//
for (int i = 0; i * imageWidth <= getWidthO; i++)
for (int j = 0; j * imageHeight <= getHeight (); j++)
if (i + j > 0)
g.copyArea(0, 0, imageWidth, imageHeight,
i * imageWidth, j * imageHeight);
}
public Dimension getPreferredSize()
{ return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
}

j a v a . a w t . G r a p h ic s

1 .0

boolean draw Image (Image img,

int x, int y, ImageObserver observer)

. :
, .
:

img

observer


( null)

boolean

drawlmage (Image

img,

int

x,

int

y,

int

width,

int

357

h e ight,

ImageObserver observer)

. ,
. :
, .
:

img

width

height

observer


( null)

void copyArea(int , int ,

int width,

int height,

int dx,

int dy)

.
:

width

height

dx

dy

Java .

. ,
.

Swing
...
Swing "--"






Java. , ,
.
,
.
,
Swing.
,
. ,
Swing, ,

360

9 Swing

- . ,
Java,
. ,
Swing.
Swing
, .
.
.

Swing

--
, ,
Swing. ' ,
"--",
Swing.


,
.
.

. ,
(Christopher Alexander).
Timeless Way of Building ( ; - Oxford University Press, 1979 .)
.

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

. 9 .1 .

Swing --

361

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

: , .
"--"
, AWT Swing.
.

"".

"".

"".

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

(Erich Gamma) Design PatternsElements of
Reusable Object-Oriented Software ( Addison-Wesley, 1995 ;
- .
). ,
(Frank Buschmann) System of Patterns ( ;
John Wiley & Sons, 1996 .),
.

--
, , , , ,
.
.

, , ( )
.

362

9 Swing

(, ..).

( ).

, , , ,
. ,
. Metal
Windows Motif. , :
, . ,
, . ,
.
, ,
,
. , ,
. ,
,
,
.
Swing
"--"
(Model-View-Controller MVC). ,
5, :
. , ,
. ,
. "--"
, .

, .

, .

, .

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

" T h e q u ic k b fo w n f o x

ju m p ^ o v e r t h e la jz y d o g "

. 9 .2 .

Swing --

363

,
. ,
, . ,
. , ,
.
!

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

"--"
, ,
. , HTML-
:
WYSIWYG ( , )
(. 9.3). , .
, .
, , ,

.
,
, , , ,
. ,
,
" ".
. , .
,
. ,
, . ,
. 9.4.
, Swing,
"--". -
(, J B u t t o n J T e x t F i e l d ) ,
. (, ),
- .
(, ), -
. -
.
, . (
,
.)

364

9 Swing

II
iii
i
iiL
t
L
i
L
it
ii

it
i

i!
1
i1i

L
iL
L
i

ii
i
1ll
)
?
j]
3
1

iI

<P> II l u l l . II

II </P> I

<OL>
<U>|| l u l l . Illl< / U >

< U > I |||||I bbIII</U>


< U > lllllll

IIIIH</U>

1?
7

. 9 .3 .

, "--"
, Swing
,
. ,
.
. , , ,
, ,
. ,
Swing
.
, , .
, . ,
" " ,
. Swing ,
"--".
,
. , ,
,
. ,
, . ,
, .

Swing "--

365

. 9.4. ,

Swing --
,
, ,
.
,
"--".
Swing.
,
Model. ,
ButtonModel. , ,
. , Swing
DefaultButtonModel,
. , , ,
ButtonModel (. 9.1).

366

9 Swing

9.1. B u tto n M o d e l

actionCommand

mnemonic

armed

true, ,

enabled

true,

pressed

true, ,

rollover

true,

selected

true, (
-)
,

JButton
:
JButton button - new JButton("Blue);
ButtonModel model - button.getModel();

,
, . JButton
, . (
JButton .)
B u t t o n M o d e l ,
. ,
. . (
-, ,

.)
, ( DefaultButtonModel)
, -
. ,
.
Metal, JButton
BasicButtonUI, ButtonUIListener. ,
Swing ,
UX. Swing
.
, JButton, :
JButton? -,
J C o m p o n e n t DefaultButtonModel,
, (,
), BasicButtonUI,
.

367


Swing,
-, ,
. Visual Basic, JDK ,

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

. 9 .5 .

JP an e l
. . 9.6
, , . ,
, .
, ,
(. 9.7).

. 9 .6 . ,

368

9 Swing

. 9 .7 .

,
.
,
Component. , .
,
Container Component. . 9.8
Component.

. 9 .8 . Component

369

,
. -, , JFrame, ,
Container, , Component,
. , JComponent
Container, Component,
JButton. ( .)

,
. ,
GridLayout
. , add ()
,
.
panel.setLayout(new GridLayout(4, 4));

j a v a .a w t .C o n t a in e r

1 .0

void setLayout(LayoutManager m)
.

Component add(Component )

Component add(Component c ,

Object c o n s t r a i n t s )

1.1

.
:

c o n str a in ts

j a v a .a w t.F lo w L a y o u t

1 .0

FlowLayout()

FlowLayout(int a li g n )

FlowLayout(int a l i g n ,

int h gap,

int vgap)

FlowLayout.
:

a lig n

(l e f t ),
(r i g h t ) (c e n t e r )

hgap


(
)

vgap


(
)

370

9 Swing



, J F ra m e .
, ,
.
, ,
, (. 9.9).

. 9 .9 .

:
frame.add(component, BorderLayout.SOUTH);

,
.
, ,
, .
CENTER (), NORTH (), SOUTH (), EAST
() WEST (), B o r d e r L a y o u t.
. ,
CENTER, .. .
! BorderLayout .
, BorderLayout.SOUTH "South".
,
, contentPane. add (component, "South").
, .

,
, . (
.)
, .
frame.add(yellowButton, BorderLayout.SOUTH); // He !

371

. 9.10 , ,
. ,
. ,
.

. 9 .1 0 .


. ,
. 9.11.
, , ,
.

. 9 .1 1 . ,

,
JPanel, . ,

FlowLayout. . add ()
, .
FlowLayout. ,
,
. ,
,
. ,
() .

372

9 Swing

JPanel panel = 'new JPan e l O ;


p anel.add(yellowButton);
p anel.add(blueButton) ;
p anel.add(redButton) ;
frame.add(panel, BorderLayout.SOUTH);

j a v a . a w t . B o r d e r L a y o u t 1 .0
>

BorderLayout()

BorderLayout(int hgap,

int vgap)

BorderLayout.
:

hgap


(
)

vgap


(
)


,
.
. . 9.12 ,
.
,
.


GridLayout :
panel.setLayout(new GridLayout(4, 4) ) ;

: ,
, .
9.1 ,
. .

373

,
Java. pack (),

.

, ,
( )
. ,
, .
, ,
.
9.1. calculator/CalculatorPanel.java 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21.
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

package calculator;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
*/
public class CalculatorPanel extends JPanel

{
private JButton display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
public CalculatorPanel ()
{
setLayout(new BorderLayout());
result = 0;
lastCommand = "=";
start = true;
//
display = new JButton ("0");
display.setEnabled(false);
add(display, BorderLayout.NORTH);
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction ();
// 4 x 4
panel = new JPanel ();
panel.setLayout(new GridLayout (4, 4));
addButton("7",
addButton("8",
addButton("9",
addButton ("/",

insert);
insert);
insert);
command);

addButton("4",

i n s e r t );

374
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

89
90
91
92
93
94
95
96

9 Swing
addButton("5", insert);
addButton("6", insert);
addButton(" *", command);
addButton("1",
addButton(2,
addButton("3",
addButton("-",

insert);
insert);
insert);
command);

addButton("0", insert);
addButtoninsert);
addButton("=", command);
addButton("+", command);
add(panel, BorderLayout.CENTER);

}
I

*
* Oparam label
* @param listener
*/
private void addButton(String label, ActionListener listener)

{
JButton button = new JButton(label);
button.addActionListener(listener);
panel.add(button);

}
I

*
*
*/
private class InsertAction implements ActionListener

{
public void actionPerformed(ActionEvent event)

{
String input - event.getActionCommandO;
if (start)

{
display.setText("");
start - false;

}
display.setText(display.getText () + input);

}
}
I ifit

* ,
*

*/
private class CommandAction implements ActionListener

'{
public void actionPerformed(ActionEvent event)

{
String command = event.getActionCommand();


97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119

}
/**
*
* Qparam x ,
*/
public void calculate(double x)

120

if (start)
{
if (command.equals("-))

{
display.setText(command);
start = false;
}
else lastCommand = command;
}
else
{
calculate(Double.parseDouble(display.getText()));
lastCommand = command;
start * true;

}
}

121
122
123
124
125
126
127
}
128 }

if (lastCommand.equals ("+ ")) result += x;


else if (lastCommand.equals ("-")) result -= x;
else if (lastCommand.equals("*))
result ** x;
else if (lastCommand.equals("/")) result / x;
else if (lastCommand.equals("*"7) result = x;
display.setText("" + result);

ja v a .a w t .G r id L a y o u t 1 . 0

G r id L a y o u t(in t

ro w s ,

in t

c o lu m n s )

G r id L a y o u t ( i n t

ro w s ,

in t

c o lu m n s ,


.
:

G r id L a y o u t

in t

hgap,

in t

vgap)

ro w s

c o lu m n s

hgap

'*
( )

vgap


( )

376

9 Swing


^
, Swing. ,
.
: JTextField JTextArea.
,
. JPasswordField ,
.

JTextComponent. ,
. , Java,
API ,
, JTextComponent
. ,
.
j a v a x . s w in g . t e x t . J T e x tC o m p o n e n t 1 .2

String getTextO

void setText(String t e x t )

boolean isEditableO

void setEditable(boolean b)

editable, ,
.



. , .
JPanel panel = new J P a n e l O ;
JTextField textField = new JTextField("Default input", 20);
p anel.add(textField);

,
"Default input" ( ).
.
20 . , .
. ,
, .
,
. ,
AWT .
, .
, JTextField,

377

,
. ,
,
.
,
.
, setColumns ().
. setColumns ()
revalidate () , , .
textField.setColumns (10);
panel.revalidate();

revalidate ()
. ,
.

revalidate () JComponent.
,
.
.
JFrame, validate (),
JFrame JComponent.

.
. ,
JTextField,
.
JTextField textField = new JTextField(20);

,
setText () TextComponent :
textField.setText("Hello!") ;

, ,
, getText (). ,
.
, trim() ,
getText (), . ,
, set Font ( ) .
String text = textField.getText().t r i m ();

j a v a x . s w in g . J T e x t F ie l d

1 .2

JTextField(int c o ls )

JTextField .

I 3 7 8

9 Swing

JTextField(String t e x t ,

int c o ls )

int getColumnsO

void setColumns(int c o ls )

ja v a x . s w in g . JC onoponent 1 . 2

void revalidate()

void setFont(Font f)

j a v a . a w t . C o m p o n en t 1 . 0

void validate()

.
,
.

Font getFont()


, .
(, ). ,
.
. , ,
, . ,
, .
1. JLabel, .
2. ,
, .
JLabel ,
, . ,
SwingConstants.
, LEFT, RIGHT, CENTER, NORTH, EAST ..
JLabel Swing,

379

. ,
, , .
JLabel label = new JLabel("User name:

", SwingConstants.RIGHT);

JLabel label = new JLabel("User name:

", JLabel.RJGHT);

.1: () se tlc o n ()
.
. ,
, , HTML.
HTML ,
. ,
.
<html>. . .</html> :
label = new JLabel ("<htmlxb>Required</b> entry :</html>");

, , , ,
HTML, ,
, HTML.


. ,
, .
j a v a x . s w in g . J L a b e l 1 .2

JLabel(String t e x t )

JLabel(Icon ico n )

JLabel(String t e x t , int a lig n )

JLabel(String t e x t ,

Icon ic o n ,

int a lig n )

. .
:

te x t

ic o n

a lig n

, sWingConstants: LEFT
( ), CENTER

String getTextO

void setText(String t e x t)

r i g h t

Icon getlconO

void setlcon(Icon ico n )

380

9 Swing


.
,
. -,
(*). Swing JPasswordField,
.
,
"--".
,
, ,
-.
j a v a x . s w in g . J P a s s w o r d F ie ld 1 .2
<

JPasswordField(String text,

int colum ns)

void setEchoChar(char ech o )

-, .
, - .

char[]

getPassword()

, .
.
, String.
, ,
" ".


. ,
JTextArea.
,
, <Enter>.
1\', Java.
. 9.13.
JTextArea
, :
textArea = new JTextArea(8, 40); // 8 40

columns, ( , )
, , ;
.
. ,
.
setColumns , setRows ().
,
.

xt t 11 > 11 e n tT e
U ser troosevelt

381

Password:

----- '.
----- J
User name: troosevelt Password: jabberw ock

. 9 .1 3 .

, ,
. ,
:
textArea.setLineWrap(true); //

. ,
, 1\ 1.


Swing .
, ,
.
textArea = new JTextArea(8, 40);
JScrollPane scrollPane = new JScrollPane(textArea);

.
,
, , .
,
, .
, ,
. ,
.
9.2 .
,
.
. , Insert
().

9 Swing
! JTextArea
.
(, HTML-) JEditorPane,
.

9.2. text/TextComponentFrame, java 1


1
2
3
4
5

package text;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

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

46

47
48
49

/**
*
.*/
public class TextComponentFrame extends JFrame

{
public static final int TEXTAREA_ROWS = 8;
public static final int TEXTAREA_COLUMNS = 20;
public TextComponentFrame()
{
final JTextField textField = new JTextField{);
final JPasswordField passwordField = new JPasswordField();
JPanel northPanel = new JPanelO;
northPanel.setLayout(new GridLayout(2, 2));
northPanel.add(new JLabel("User name: ", SwingConstants.RIGHT));
northPanel.add(textField);
northPanel.add(new JLabel("Password: ", SwingConstants.RIGHT));
northPanel.add(passwordField);
add(northPanel, BorderLayout.NORTH);
final JTextArea textArea =
new JTextArea(TEXTAREA_ROWS, TEXTAREA_COLUMNS);
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane, BorderLayout.CENTER);
//
JPanel southPanel = new JPanelO;
JButton insertButton = new JButton("Insert");
southPanel.add(insertButton);
insertButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
textArea.append ("User name: " + textField.getText() +
" Password: " + new String(passwordField.getPassword()) + "\n");
}
});

____________________________

383

50
add(southPanel, BorderLayout.SOUTH);
51
pack () ;
52
}
53 }

ja v a x . s w in g . J T e x tA r e a 1 .2

JTextArea()

JTextArea(int row s,

JTextArea(String t e x t ,

int c o l s )
int row s,

int c o ls )

void setColumns(int c o ls )

, .

void setRows(int rows)

void append(String newText)

void setLineWrap(boolean wrap)

void setWrapStyleWord(boolean word)

word true,
, .

void setTabSize(int )

. ,

.

j a v a x . s w in g . J S c r o llP a n e

1 .2

JScrollPane(Component c)

, .
, .


, , .

.
. ( ,
.)
, ,
-, .

384

a Swing


, ,
. ,
, .
,
, .
. 9.14 ,
,
. , .
. ,
,
.

The quick brown ftmjwms & dog

. 9 . .

, .
:
bold = new JCheckBox("Bold") ;

setSelected (),
.
bold.setSelected(true);

is Selected () .
false, , ,
true .
, . ,
.

:
ActionListener listener = . . .
bold.addActionListener(listener);
italic.addActionListener(listener);

actionPerformedO
bold italic,

385

, : ,
.
public void actionPerformed(ActionEvent event)

{
int mode = 0;
if (bold.isSelectedO) mode += Font.BOLD;
if (italic.isSelectedO) mode += Font.ITALIC;
label.setFont(new Font("Serif, mode, FONTSIZE));

}
9.3 ,
.
9.3. checkBox/CheckBoxTest.ja v a *1
package checkBox;
2
3 import java.awt.*;
4 import javax.swing.*;
5 /**
6
* version 1.33 2007-06-12
7
* author Cay Horstmann

8 */
9

public class CheckBoxTest

10 {
11

public static void main(String[] args)

12

13
14
15
16
17
18
19
20
21

EventQueue.invokeLater(new Runnable()
{
public
voidrun()
{
JFrame frame = new CheckBoxFrame();
frame.setTitle("CheckBoxTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

22

}) ;

23
}
24 }

j a v a x . s w in g . J C h e c k B o x 1 . 2

JCheckBox(String l a b e l )

JCheckBox(String l a b e l ,

icon ic o n )

, .

JCheckBox(String l a b e l ,

boolean s t a t e )

boolean isSelected

void setSelected(boolean s t a t e )

386

9 Swing

-
,
.
. ,
. -,


. . 9.15
-.
Small (), Medium (), Large () Extra large ( ).
, .
R R.:-HlioBuUonT^st

Small Mttfittm liret ffijlxtraFargtj


, 9 .1 5 . -

Swing -
. ButtonGroup
. -
JRadioButton. ButtonGroup ,
-, .
, .
ButtonGroup group = new ButtonGroup();
JRadioButton smallButton = new JRadioButton("Small", false);
group.add(smallButton);
JRadioButton mediumButton = new JRadioButton("Medium", true);
group.add(mediumButton);

true,
- ,
false, . ,
ButtonGroup -.
-,
, JPanel.
. 9.14 9.15, , -
.
, ,

387

- : ,
.
-
, .
-, .
,
, .
ActionListener listener = new
ActionListener()

{
public void actionPerformed(ActionEvent event)

{
//
// addRadioButton()
label.setFont(new Font("Serif, Font.PLAIN, size));

}
};
.
- .
,
. .
.
, .
-?
,
, .
,
-.
if (smallButton.isSelected()) size = 8;
else if (mediumButton.isSelected()) size = 12;

! -.
, , - .
ButtonGroup -, ,
-. ,
ButtonGroup getSelection (),
-. ButtonModel ,
-. , ButtonModel
.
ButtonModel ItemSelectable getSelected
Objects , null.
getActionCommandO ,
, , -.
-
null. , -
setActionCommandO , ,
.
- , buttonGroup. getSelection () .
getActionCommand().

388

a Swing

9.4 ,
-.

9. r a d i o B u t t o n / R a d i o B u t t o n F r a m e .java

package radioButton;

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* -
*
V
public class RadioButtonFrame extends JFrame

{
private
private
private
private

JPanel buttonPanel;
ButtonGroup group;
JLabel label;
static final int DEFAULT_SIZE = 36;

public RadioButtonFrame()
{
//
label = new JLabel("The quick brown fox jumps over the lazy dog.");
label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
add(label, BorderLayout.CENTER);
// -
buttonPanel = new JPanel();
group = new ButtonGroup();
addRadioButton("Small", 8);
addRadioButton("Medium", 12);
addRadioButton("Large", 18);
addRadioButton("Extra large", 36);
add(buttonPanel, BorderLayout.SOUTH);
pack();
}
/**
* -,
*
* name
* size ,
*/
public void addRadioButton(String name, final int size)
{
boolean selected = size == DEFAULT_SIZE;
JRadioButton button = new JRadioButton(name, selected);
group.add(button);
buttonPanel.add(button);
//
ActionListener listener = new ActionListener()
{


53.
54
55
56
57
58
59
58

389

public void actionPerformed(ActionEvent event)


{
//
// addRadioButton ()
label.setFont(new Font("Serif, Font.PLAIN, size));
}
};

59
button.addActionListener(listener);
60
}
61 }

j a v a x . s w in g . J R a d io B u tto n 1 . 2

JRadioButton(String l a b e l ,

Icon ico n )

-, .

JRadioButton(String l a b e l ,

boolean s t a t e )

- .

j a v a x . s w in g . B u tto n G ro u p 1 .2

void add(AbstractButton b)

- .

ButtonModel getSelection()

j a v a x . s w in g . B u tto n M o d e l 1 .2

String getActionCommand()

j a v a x . s w in g .A b s t r a c t B u t t o n

1 .2

void setActionCommand(String s)

-,
- . Swing
. ,
JComponent. ,

390

9 Swing

, , -.
, , .
1. BorderFactory,
(. 9.16):
f* lei Test
^Border types----------- - ------------

--------------- ----- :------------------------------------------------- --

Lowered bevel R aised bevel Etched Q lin e jManel Empty

. 9 .1 6 .

Lowered bevel ( )

Raised bevel ( )

Etched ()

Line ()

Matte ()

Empty ( , )

2. , BorderFactory.
createTitledBorder().

3. , ,
BorderFactory.createCompoundBorder().

4. setBorder ()
JComponent.


.
Border etched = BorderFactory.createEtchedBorder();
Border titled = BorderFactory.createTitledBorder(etched,
p anel.setBorder(titled);

"A Title");

,
9.5, , , .
.
API.

, SoftBevelBorder LineBorder.

BorderFactory.

9.5. b o r d e r /B o r d e r F r a m e . j a v a
1
2
3,
4
5
6
7

package border;
import
import
import
import

java.awt.*;
java.awt.event.*;
javax.swing.*;
javax.swing.border.*;

8 /**
9

* -

10 * /
11 public class BorderFrame extends JFrame
12 {
13
private JPanel demoPanel;
14
private JPanel buttonPanel;
15
private ButtonGroup group;
16
17
public BorderFrame()
18
{
19
demoPanel = new JPanel ();
20
buttonPanel = new JPanel();
21
group = new ButtonGroup ();
22
23
addRadioButton("Lowered bevel",
24
B o rd erF acto ry.createLoweredBevelBorder( ) ) ;
25
addRadioButton("Raised bevel",
26
BorderFactory.createRaisedBevelBorder());
27
addRadioButton("Etched", BorderFactory.createEtchedBorder());
28
add R ad ioB u tton ("Lin e", B o rd erF acto ry .cre ate Lin e B ord e r(C olor.B LU E ) );
29
addRadioButton("M atte", B o rd erF acto ry .createM atteBorder (
30
10, 10, 10, 10, Color.BLUE));
31
addRadioButton("Empty", BorderFactory.createEmptyBorder ());
32
33
Border etched = B o rd erF acto ry .createEtchedBorder ();
34
Border titled =
35
BorderFactory.createTitledBorder(etched, "Border types");
36
buttonPanel.setBorder(titled);
37
38
setLayout(new GridLayout(2, 1));
39
add(buttonPanel);
40
add(demoPanel);
41
pack () ;
42
}
43
44
p u b lic v o id add R ad io B u tto n (Strin g buttonName, f i n a l Border b)
45
{
46
JRadioButton button = new JRadioButton(buttonName) ;
47
button.addActionListener(new ActionListener ()
48
{
49

50
51
52
53
54
55
56

p u b lic v o id actionPerform ed(ActionEvent event)

{
demoPanel.setBorder(b);
}
});
grou p . add (b u tto n ) ;

buttonPanel.add(button);

39

> Swing

j a v a x . s w in g . B o r d a r F a c t o r y 1 . 2

static Border createLineBorder(Color c o l o r )

static Border createLineBorder(Color c o l o r ,

int t h i c k n e s s )

.
I

static MatteBorder createMatteBorder(int t o p ,


r ig h t,

int b o t t o m ,

int

int l e f t ,

int b o t t o m ,

int

Color c o l o r )

static MatteBorder createMatteBorder(int t o p ,


r ig h t,

int l e f t ,

Icon t i l e l c o n )

, .

static Border createEmptyBorder()

static Border createEmptyBorder(int t o p ,

int l e f t ,

int b o t t o m ,

int r i g h t )

static Border createEtchedBorder()

static Border createEtchedBorder(Color h i g h l i g h t ,

static Border createEtchedBorder(int t y p e )

static Border createEtchedBorder(int t y p e ,

Color s h a d o w )

Color h i g h l i g h t ,

Color s h a d o w )

.
:

h ig h lig h t, shadow

type

,
EtchedBorder.RAISED,
EtchedBorder.LOWERED

static Border createBevelBorder(int type)

static Border createBevelBorder(int type,

static Border createLoweredBevelBorder()

static Border createRaisedBevelBorder()

Color highlight,

Color shadow)

highlight, s h a d o w

type

,
EtchedBorder.RAISED,
EtchedBorder.LOWERED

static TitledBorder createTitledBorder(String title)

static TitledBorder createTitledBorder(Border border)

static TitledBorder createTitledBorder(Border border,

static TitledBorder createTitledBorder(Border border,


justi f i c a t i o n ,

String

title,

int

String

title,

int

int position)

static TitledBorder createTitledBorder(Border border,


j u s t i fication,

String title)

int po s i t i o n ,

Font font)

*
s ta tic

T itle d B o r d e r

justi f i c a t i o n ,

in t

c r e a te T itle d B o r d e r (B o r d e r

p o s ition,

Font

font,

C o lo r

S tr in g

border,

393

title,

in t

color)

.
:

title

border

justification

,
:
L E F T , C E N T E R , R I G H T , L E A D IN G ,
T R A IL IN G

D E F A U L T _ J U S T IF IC A T IO N

( )

s ta tic

font

color

C o m p o u n d B o rd e r

c re a te C o m p o u n d B o rd e r(B o rd e r

T itle d B o r d e r

outsideBorder,

B o rd e r

insideBorder)

javax.swing.border.SoftBevelBorder 1.2

S o ftB e v e lB o r d e r (in t

ty p e )

S o ftB e v e lB o r d e r (in t

type,

C o lo r

highlight,

C o lo r

shadow)

.
:

highlight, s h a d o w

type

E t c h e d B o r d e r . R A IS E D ,

E t c h e d B o r d e r . LO W ERED

javax.swing.border.LineBorder 1.2

p u b lic

L in e B o r d e r (C o lo r

color,

in t

thickness,

b o o le a n

roundedCorners)

tru e ,

javax.swing.JConponent 1.2

v o id

s e tB o rd e r(B o rd e r

border)

roundedCorners

394

D m a 9 Swing


, -
, .
.
, , (. 9.17).
< <>11|| > 1*.|

_ X

quick brown fox jumps over the lazy dog.


yri:

M onospaced

. 9 .1 7 .

,
, . ,

,
.
JComboBox. Java SE 7, JComboBox
. , JComboBox<String>
String,
JComboBox<Integer> .
, ..
, setEditable (). , , ,
.
.

g e t S e l e c t e d l t e m O .
,
. (
6 .)
,
:
combo.getltemAt(combo.getSelectedlndex())

395

, S u n s S e r i f , M o n o s p a c e d
..). , ,
addltem ().
addltem () , ,
.
(Serif

J C o m b o B o x < S tr in g >

fa c e C o m b o

new

JC om boB oxo();

faceCombo.addltem("Serif");
fa c e C o m b o . a d d lt e m ( " S a n s S e r if " ) ;

.
,
insertItemAdd () :
fa c e C o m b o . in s e r t l t e m A t ( " M o n o s p a c e d " ,

0 );

/ /

,
t o S t r i n g O . *
, remove Item () remove ItemAt (),
, :
, .
removeAl I I terns ( ) .
fa c e C o m b o . r e m o v e lte m ( " M o n o s p a c e d " ) ;
fa c e C o m b o . r e m o v e Ite m A t( 0 ) ;

/ /

. ,
a d d l t e m ( ) ,
. D e f a u l t C o m b o B o x M o d e l ,
, a d d E l e m e n t ( ) ,
s e t M o d e l ( ) J C o m b o B o x .

,
.
, getSource ()
. , .
g e t S e l e c t e d l t e m O ,
. , ,
( , String).
get ItemAt , ,
.
p u b lic

v o id

a c tio n P e r fo r m e d (A c tio n E v e n t

e v e n t)

{
l a b e l . s e tF o n t(n e w

F o n t(

fmceCoobo.gm tltm akt (fadeCombo.getSelectedlndex ()),


F o n t.P L A IN ,
D E F A U L T _ S IZ E ) ) ;

}
,
, 9.6.

396

9 Swing

! , ..
, J l i s t ,
.

9.6. comboBox/ComboBoxFrame .java1


1
2
3
4
5
6
7
8
9

package comboBox;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
*

10 * /
11 public class ComboBoxFrame extends JFrame
12 {
13
private JComboBox<String> faceCombo;
14
private JLabel label;
15
private static final int DEFAULT_SIZE = 24;
16
17
public ComboBoxFrame()
18
{
19
//
20
label = new JLabel("The quick brown fox jumps over the lazy dog.");
21
label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
22
add(label, BorderLayout.CENTER);
23
24
//
25
/ /
26
faceCombo = new JComboBoxo ();
27
faceCombo.addltem("Serif");
28
faceCombo.addItem("SansSerif");
29
faceCombo.addltem("Monospaced");
30
faceCombo.addltem("Dialog");
31
faceCombo.addltem("Dialoglnput");
32
33
//
34
// ,
35
faceCombo.addActionListener (new ActionListener()
36
{
37
public void actionPerformed(ActionEvent event)
38
{
39
label.setFont(new Font(
40
faceCombo.getItemAt(faceCombo.getSelectedlndex()),
41
Font.PLAIN, DEFAULT_SIZE));
42.
}
43
});
44
45
//
46
JPanel comboPanel = new JPanelO;
47
comboPanel.add(faceCombo);
48
add(comboPanel, BorderLayout.SOUTH);
49
pack();
50
}
51 }

397

jvax.owing.JConboBox 1.2
V

------------------------------------------------------------------------------------------------------------------------------------------------------------------ -------------------------

boolean isEditableO

void setEditable(boolean b)

editable .

void addltem(Object i t e m )

void insertltemAt(Object i t e m ,

int i n d e x )

void remove Item (Object i t e m )

void removeItemAt(int i n d e x )

void removeAlIIterns ()

Object getSelectedltemO



.
, , 1 100.
1 :
JSlider slider = new JSlider(min, max,

initialValue);

, ,
0, 100 50 . 1

,

JSlider slider = new JSlider(SwingConstants.VERTICAL, min, max,


initialValue);

.
, . 9.18.
1 .
,
.
1 ChangeEvent.

, ,
ChangeListener, addChangeListener ().
stateChanged ().
, , .

398

Swing

public void stateChanged(ChangeEvent event)

{
JSlider slider = (JSlider) event.getSource();
int value = slider.getValue();

_ nx

Sli< le iT e st

EE
I

>i

1i

S552Z
*

> i

? t

<

<

to ticks

i > i i <{ <i j t i i j < t j


{ l

) i i

J i l J

i > >i i i i i i i i > i i i ' i i


0
20 40
0 80

in verted

> ( i Labels
100

4< ? 4 ** j *> * i * *i *iCustom ||||


A
8
C D

E
1
*

sgr

i ,, _L

::.tf

f^

icon lab els

-V-'

.--.

i i*

50
. 9.18.

, . ,
, ,
:
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5) ;

,
20 , ,
5 .
, ,
.
. ,
:
slider.setPaintTicks(true);

399

!
. ,
, , . ,
,
.

,
:
slider.setPaintLabels(true);

, 0 100 ,
20 ,
0, 20, 40, 60, 80 100.
, , ,
(. . 9.18), - .
- Integer Component,
setLabelTable ().
.
JLabel. , 1
, , , D, F.
Hashtable<Integer, Component> labelTable =
new Hashtablecinteger, Component>();
labelTable.put(0, new JLabel("A"));
labelTable.put(20, new JLabel("B"));

labelTable.put(100, new JLabel("F"));


slider.setLabelTable(labelTable);

- 13. 9.7
,
, .
. , ,
setPaintTicks(true) setpaintLabels(true).

. 9.18
. , , ,
:
slider.setPaintTrack(false);


.
slider.setlnverted(true);

,
, .
, ,
, ,
.

400

Swing

9.7. slider/SliderFrame.java
1

package slider;

3
4
5
6
7

import
import
import
import

/**

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

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

*
* ,
*/

public class SliderFrame extends JFrame


{
private JPanel sliderPanel;
private JTextField textField;
private ChangeListener listener;
public SliderFrame()
{
sliderPanel = new JPanel ();
sliderPanel.setLayout(new GridBagLayout());

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

//
listener = new ChangeListener ()
public void stateChanged(ChangeEvent event)
// ,
//
JSlider source = (JSlider) event.getSource ();
textField.setText("" + source.getValue());

};
//
JSlider slider = new JSliderO;
addSlider(slid6r, "Plain");
//
slider = new JSliderO;
slider.setPaintTicks(true);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
addSlider(slider, "Ticks");
// ,
slider = new JSliderO;
slider.setPaintTicks(true);
slider.setSnapToTicks(true);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
addSlider(slider, "Snap to ticks");
//
slider = new JSliderO;
slider.setPaintTicks(true);
slider.setMajorTickSpacing(20);


57
58
59
60
61
62
63
64
65
66

67

slider.setMinorTickSpacing(5);
slider.setPaintTrack(false);
addSlider(slider, "No track");
//
slider = new JSliderO;
slider.setPaintTicks(true);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
slider.setlnverted(true);
addSlider(slider, "Inverted");

68

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

86
86

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113

//
slider = new JSliderO;
slider.setPaintTicks(true);
slider.setPaintLabels (true);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
addSlider(slider, "Labels");
//
slider = new JSliderO;
slider.setPaintLabels (true);
slider.setPaintTicks(true);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
Dictionary<Integer, Component> labelTable = new Hashtableo ();
labelTable.put (0, new JLabel("A"));
labelTable.put(20, new JLabel("B"));
labelTable.put (40, new JLabel("C"));
labelTable.put (60, new JLabel("D"));
labelTable.put (80, new JLabel("E"));
labelTable.put (100, new JLabel("F"));
slider.setLabelTable(labelTable);
addSlider(slider, "Custom labels");
//
slider = new JSliderO;
slider.setPaintTicks(true);
slider.setPaintLabels (true);
slider.setSnapToTicks(true);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(20);
labelTable = new Hashtable<Integer, Component> ();
//
labelTable.put(0, new JLabel(new Imagelcon("nine.gif")));
labelTable.put (20, new JLabel(new Imagelcon("ten.gif")));
labelTable.put (40, new JLabel(new Imagelcon("jack.gif")));
labelTable.put (60, new JLabel(new ImageIcon(queen.gif")));
labelTable.put (80, new JLabel(new Imagelcon("king.gif")));
labelTable.put (100, new JLabel(new Imagelcon("ace.gif")));
slider.setLabelTable(labelTable);
addSlider(slider, "Icon labels");

401

402
114
115
116
117
118
119
120
121

9 Swing

// ,
//
textField = new JTextField();
add(sliderPanel, BorderLayout.CENTER);
add(textField, BorderLayout.SOUTH);
pack () ;
}

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140 }

/**
*
* s
* description
*/
public void addSlider(JSlider s, String description)
{
s .addChangeListener(listener);
JPanel panel = new JPanelO;
panel.add(s);
panel.add(new JLabel(description));
panel.setAlignmentX(Component.LEFT_ALIGNMENf);
GridBagConstraints gbc = new GridBagConstraints ();
gbc.gridy = sliderPanel.getComponentCount ();
gbc.anchor = GridBagConstraints.WEST;
sliderPanel.add(panel, gbc);
}

j a v a x . s w in g . J S l i d e r 1 .2

JSlider ()

JSlider(int d ir e c t io n )

JSlider (int m in , int max)

JSlider(int m in , int max , int i n i t i a l V a l u e )

JSlider(int d i r e c t i o n , int min,

int max,

int i n i t i a l V a l u e )

,
.
:

d ir e c tio n

SwingConstant.HORIZONTAL
swingConstants.VERTICAL.

SwingConstantc.HORIZONTAL,

min, max


. 0
100

in itia lV a lu e

.
50.

403

void setPaintTicks(boolean b)

b true, ,
.

void setMajorTickSpacing(int u n it s )

void setMinorTickSpacing(int u n it s )

void setPaintLabels(boolean b)

b true, .

void setLabelTable(Dictionary t a b le )

. -"
:

new In t ( ) /.

void setSnapToTicks(boolean b)

b true,
.

void setPaintTrack(boolean b)

b true, ,
.


, ,
, . Swing
, , -
.
.
, ,
. ,
. . 9.19
, .
II *

c m .
'

H B H H I
Ovenypc

. 9 .1 9 . ,

404

9 Swing


.
:
JMenuBar menuBar = new JMenuBar();

,
. ,
set JMenuBar (), .
frame.setJMenuBar(menuBar);

:
menuBar.add(editMenu);

, .
menuBar.add(editMenu);

, :
JMenuItem pasteltem = new JMenuItem("Paste);
editMenu.add(pasteltem);
editMenu.addSeparator() ;
JMenu optionsMenu = . . .; //
editMenu.add(optionsMenu);

. 9.19. Paste
() Read-only ( ). ,
. ,
, .
ActionListener listener = . . .;
pasteltem.addActionListener(listener);

JMenu. add (String s),


, , , .
editMenu.add("Paste") ;

,
:
JMenuItem pasteltem = editMenu.add("Paste");
pasteltem.addActionListener(listener);

,
, .
8, Action.
, Action.
AbstractAction. AbstractAction
actionPerformedO,
, ,
.
Action exitAction = new AbstractAction("Exit") //

{
public void actionPerformed(ActionEvent event)

405

System.exit (0);

};

A ction :
JMenuItem exitltem = fileMenu.add(exitAction);

.
. :
JMenuItem exitltem = new JMenuItem(exitAction);
fileMenu.add(exitltem);

j a v a x . s w in g . JM enu 1 . 2

JMenu(String l a b e l )
.

JMenuItem add (JMenuItem item )


( ).

JMenuItem add(String l a b e l )
.

JMenuItem add(Action )
.

void addSeparator()
.

JMenuItem insert (JMenuItem menu,

int in d ex )

( ) .

JMenuItem insert(Action a ,

int in d ex)

Action .

void insertSeparator(int in d ex)


.
:

in d e x

void remove(int in d ex)

void remove (JMenuItem item )


.

ja v a x . s w in g . J M e n u Ite m 1 .2

JMenuItem(String l a b e l )

JMenuItem (Action ) 1 . 3

406

9 Swing

j a v a x . s w in g .A b s t r a c t B u t t o n

1 .2

void setAction(Action a) 1.3

ja v a x . s w in g . J F ra m e 1 .2

void setJMenuBar(JMenuBar m enubar)


. JMenuItem
AbstractButton. , ,
. , ,
JMenuItem (String, Icon) Jmenultem(lcon), ,
set Icon (), JMenuItem
AbstractButton. .
JMenuItem cutltem * new JMenuItem("Cut", new Imagelcon("cut.gif"));

. 9.19 .
. ,
,
setHorizontalTextPosition (), JMenuItem
AbstractButton. ,
.
cutltem.setHorizontalTextPosition(SwingConstants.LEFT);

Action :
cutAction.putValue(Action.SMALL_ICON,

new Imagelcon("Cut.gif"));

,
Action, Act ion. NAME ,
Action.SMALL_IC0N . ,
AbstractAction, .
cutAction = new
AbstractAction("Cut", new Imagelcon("cut.gif"))

public void actionPerformed(ActionEvent event)

};

j a v a x . s w in g . J M tn u Ito m

407

1 .2

JMenuItem(String l a b e l ,

Icon ico n )

j a v a x . a w in g . A b e t r a c t B u t t o n

1 .2

void setHorizontalTextPosition(int p o s)

.
:

pos

SwingConstants .RIGHT ( )
SwingConstants.LEFT ( )

j a v a x . s w in g . A b a t r a c t A c t io n

AbstractAction(String name,

1 .2
Icon s m a lllc o n )

AbstractAction .

-
-
(. . 9.19). ,
, -
.
-,
. ,
.
JCheckBoxMenuItem readonlyltem - new JCheckBoxMenuItem("Read-only");
optionsMenu.add(readonlyltem);

- ,
-. -
. ,
. -
.
ButtonGroup group = new ButtonGroup();
JRadioButtonMenuItem insertltem = new JRadioButtonMenuItem("Insert");
insertltem.setSelected(true);
JRadioButtonMenuItem overtypeltem - new JRadioButtonMenuItem("Overtype");
group.add(insertltem);
group.add(overtypeltem);
optionsMenu.add(insertltem) ;
optionsMenu.add(overtypeltem);

,
.

408

9 Swing

is S e le c t e d (). (, , -
.) ,
s e t S e le c t e d ().
j a v a x . s w in g . J C h e c k B o x M e n u Ite m 1 .2

JCheckBoxMenuItem(String l a b e l )

JCheckBoxMenuItem(String l a b e l ,

boolean s t a t e )

( s t a t e
true, ).

j a v a x . s w in g . J R a d io B u tto n M e n u I te m 1 .2

JRadioButtonMenuItem(String l a b e l )

- .

JRadioButtonMenuItem(String l a b e l ,

boolean s t a t e )

- (
s t a t e true, ).

j a v a x . s w in g . A b s t r a c tB u t t o n

1 .2

boolean isSelected()

void setSelected(boolean s t a t e )

( s t a t e
true, ).


, , ,
(. 9.20).
, , ,
.
.
JPopupMenu popup = new JPopupMenu();

:
JMenuItem item = new JMenuItem("Cut");
item.addActionListener(listener);
p opup.add(item);

, ,

409

show ().
:
popup.show(panel,

, ) ;

. 9 .2 0 .

,

. Windows Linux .
:
component.setComponentPopupMenu(popup);

,
.
, :
child.setlnheritsPopupMenu(true);

j a v a x . s w in g . JP op upM enu 1 .2

void show (Component c, int x ,

in t

y)

.
:

( )

boolean isPopupTrigger(MouseEvent e v e n t )

1 .3

true,
( , ).

j a v a . a w t . e v e n t . M o u s e E v e n t 1 .1

boolean isPopupTrigger()

true,
( , ).

410

9 Swing

ja v a x . s w in g . J C o n p o n e n t 1 . 2

JPopupMenu getComponentPopupMenu() 5 .0

void setComponentPopupMenu (JPopupMenu popup)

5 .0

boolean getInheritsPopupMenu() 5 .0

void setlnheritsPopupMenu (boolean jb) 5 .0

inheritsPopupMenu.
, null,
.



. ,
:
JMenuItem aboutltem = new JMenuItem("About", 'A');

, ,
(. 9.21). , ^
, About,
.. .
<>. ( ,
, , ,
. , "
" .)

. 9 .21 . ,

,
. ,
Save As () <>,
As (Save As). ,
setDisplayedMnemonicIndex ().

411

Action, ,
Action .MNEMONIC KEY :
cutAction.putValue(Action.MNEMONIC_KEY,

new Integer('A'));

, ,
( ).
- , setMnemonic ():
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic(H ');

, , <Alt>
. , Help (
), <Alt+H>.
.
, ,
. ,
<Ctrl+0> <Ctrl+S> Open () Save ()
File ().
setAccelerator (). Iteystroke.
, <Ctrl+0>
open Item.
openltem.setAccelerator(Keystroke.getKeyStroke("Ctrl 0"));


,
.
, . ,
, .

, Swing. ( ,
, . 8.) ,
(. 9.22).
_ X

1 <*I I

* ,

. 9 .2 2 .
! <Alt+F4> Windows .
Java.
Windowclosing ,
, Close.

412

9 Swing

ja v a x . s w in g . J M e n u Ite m 1 .2

JMenuItem(String l a b e l ,

.
:

int m n e m o n ic )

la b e l

m n e m o n ic

,
.

void setAccelerator(Keystroke )

.
.

j a v a x . s w in g . A b s t r a c t B u t t o n

1 .2

void setMnemonic(int m n e m o n ic )

, .
.

void setDisplayedMnemonicIndex(int index)

1.4

. ,
, , .

..................

--------- -- -----------------------------------------------------------------------------------------------------------



. , , Save
. , JMenu. remove (),
.
,
. . 9.23
- .

. 9 .2 3 . ,

413

,
setEnabled ():
saveltem.setEnabled(false);
%

.
setEnabled ()
. , ,
Save Save As. ,
.
, .
javax.swing.event MenuListener,
:
void menuSelected(MenuEvent e v e n t)
void menuDeselected(MenuEvent ev en t)
void menuCanceled(MenuEvent ev en t)

menuSelected () .
, .
, Save Save As
Read Only ( ).
public void menuSelected(MenuEvent event)

{
saveAction.setEnabled(!readonlyltem.isSelected());
saveAsAction.setEnabled(!readonlyltem.isSelected());

}
!
, ,
. ,
, ,
.

j a v a x . s w in g . J M e n u Ite m 1 . 2

void setEnabled {b o o le a n b)

j a v a x . s w in g , e v e n t . M e n u L is te n e r 1 . 2

void menuSelected(MenuEvent e)

, , .

void menuDeselected(MenuEvent )

, .

void menuCanceled(MenuEvent )

, ; , ,
.

414

9 Swing

9.8 , .
,
: , , -
,
.
9.8. menu/MenuFrame.java1
1
2
3
4
5

package menu;

/**

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

*/

public class MenuFrame extends JFrame

10

11
12
13
14
15
16
17
18
19

private static final int DEFAULT_WIDTH = 300;


private static final int DEFAULT_HEIGHT = 200;
private Action saveAction;
private Action saveAsAction;
private JCheckBoxMenuItem readonlyltem;
private JPopupMenu popup;

20

*/

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

class TestAction extends AbstractAction


{
public TestAction(String name)
{
super(name);
}

41

42
43
44
45
46
47
48
49
50

/**
* , System.out

public void actionPerformed(ActionEvent event)


{
System.out.println(getValue(Action.NAME) + " selected.");
}
}
public MenuFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
JMenu fileMenu = new JMenu("File");
fileMenu.add(new TestAction("New"));
//
JMenuItem openltem = fileMenu.add(new TestAction("Open"));
openltem.setAccelerator(Keystroke.getKeyStroke("Ctrl 0"));
fileMenu.addSeparator ();
saveAction = new TestAction("Save");
JMenuItem saveltem = fileMenu.add(saveAction);
saveltem.setAccelerator(Keystroke.getKeyStroke("ctrl S"));
saveAsAction * new TestAction("Save As");


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

fileMenu.add(saveAsAction);
fileMenu.addSeparator();

'

fileMenu.add(new AbstractAction("Exit")
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
});
// -
readonlyltem = new JCheckBoxMenuItem("Read-only");
readonlyltem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
boolean saveOk = !readonlyltem.isSelected();
save^ction.setEnabled(saveOk);
saveAsAction.setEnabled(saveOk);
}
});
ButtonGroup group = new ButtonGroup ();
JRadioButtonMenuItem insertltem =
new JRadioButtonMenuItem("Insert");
insertltem.setSelected(true);
JRadioButtonMenuItem overtypeltem =
new JRadioButtonMenuItem("Overtype");
group.add(insertltem);
group.add(overtypeltem);
//
Action cutAction = new TestAction ("Cut");
cutAction.putValue(Action.SMALL_ICON, new Imagelcon("cut.gif"));
Action copyAction = new TestAction("Copy");
copyAction.putValue(Action.SMALL_ICON, new Imagelcon("copy.gif"));
Action pasteAction = new TestAction("Paste");
pasteAction.putValue(Action.SMALL_ICON, new Imagelcon("paste.gif"));
JMenu editMenu = new JMenu("Edit");
editMenu.add(cutActioa);
editMenu.add(copyAction);
editMenu.add(pasteAction);
//
JMenu optionMenu = new JMenu("Options");
optionMenu.add(readonlyltem);
optionMenu.addSeparator();
optionMenu.add(insertltem);
optionMenu.add(overtypeltem);
editMenu.addSeparator();
editMenu.add(optionMenu);
//

415

416

9 Swing

110
JMenu helpMenu = new JMenu("Help");
111
helpMenu.setMnemonic('H');
112
113
JMenuItem indexltem = new JMenu Itern ("Index") ;
114
indexltem.setMnemonic('I ');
115
helpMenu.add(indexltem);
116
117
// ,
118
Action abputAction = newTestAction("About);
119
aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A'));
120
helpMenu.add(aboutAction);
121
122
//
123
JMenuBar menuBar = new JMenuBarO;
124
setJMenuBar(menuBar);
125
126
menuBar.add(fileMenu);
127
menuBar.add(editMenu);
128
menuBar.add(helpMenu);
129
130
- I I
131
popup = new JPopupMenu ();
132
popup.add(cutAction);
/
133
popup.add(copyAction);
134
popup.add(pasteAction) ;
135
136
JPanel panel = new JPanelO;
137
panel.setComponentPopupMenu(popup);
138
add(panel);
139
140
// ,
141
// 4966109
143
panel.addMouseListener(new MouseAdapter() {});
144
}
145 }


,
(. 9.24).

. 9 .2 4 .

417


,
(. 9.25).
(. 9.26).
T o o lB a i T e st

Color

1
k

. 9 .2 5 .
f t 16 I T est

Color

____

. 9 .26 .

! ,
,
, ,
.

.
(. 9.27).
, ,
.

418

9 Swing

. 9 .2 7 .

.
.
JToolBar bar = new JToolBarO;
b a r .add(blueButton);

JToolBar ,
Action.
Action, . , ,
.
b a r .add(blueAction);


:
b a r .addSeparator();

, , . 9.24,
.
, .
add(bar, BorderLayout.NORTH);

, ,
. ,
.
bar = new JToolBar(titlestring);

.
,
:
bar = new JToolBar(SwingConstants.VERTICAL)

bar = new JToolBar(titlestring,

SwingConstants.VERTICAL)

.
, ,
. ,
.

419


:
.
,
, .
(. 9.28).
, .
f* I <>|.I *'. I

_ I |

Color

. 9 .2 8 .

Swing
JComponent, setToolTipText ():
exitButon.SetToolTipText("Exit");

, Action,
SHORT_DESCRIPTION :
exitAction.putValue(Action.SHORT_DESCRIPTION,

"Exit");

9.9 , ,
Action
. ,
,
.
9.9. toolBar/ToolBarTest. java 1
1
2
3
4
5

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

6 /**
7
* (Aversion 1.13 2007-06-12
8
* author Cay Horstmann
9 */
10 public class ToolBarTest
11 {
12
public static void main(String[] args)
13
{
14
EventQueue.invokeLater(new Runnable ()
15
{

420

9 Swing

16
11
18
19
20
21
22
23
24
}
25 }

public void run()

{
ToolBarFrame frame = new ToolBarFrame ();
frame.setTitle("ToolBarTest);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});

ja v a x . s w in g . J T o o lB a r 1 .2

JToolBar()

JToolBar(String t i t l e s t r i n g )

JToolBar(int o r ie n t a t io n )

JToolBar(String t i t l e s t r i n g , int o r ie n t a t io n )

.
o r i e n t a t i o n SwingConstants.HORIZONTAL (
) SwingConstants.VERTICAL.

JButton add(Action a)

, ,
. .

void addSeparator()

j a v a x . s w in g . JC o m p o n e n t 1 .2

void setToolTipText(String t e x t )

,
.



, .
.

.
Windows
: Java ?

, .
, ,

.

421

:
,
. ?
. -,
.
Windows, ,
. ,
"" .
. ,
"Cancel" "Abbrechen".
, "Cancel",
.
, Windows, ,
? ,
, ,
.
,
. ,
, ,
, .
Java
. , ,
.
AWT,
.
,
,
.
Swing.
Metal,
.
,
.
Java 1.0, AWT -
.
,
. ,
, , "
- "
Java.
,
- ,
Swing .
JDK, BoxLayout "
,
, GridLayout
, , ".
,
, .

422

9 Swing

Java SE 1.4
- .

.
, 1
.
,
.
2005 NetBeans Matisse,
( Swing GUI
Builder). Swing
GUI Builder, ,
.
. ,
.
Java SE. NetBeans ,

. NetBeans,
.
-
,

Java. ,

.
Swing GUI Builder
.
, ,
, .
, ,
, .

-
-
.
, .. -
.
, ,
. ( HTML-
: ,
.)
,
.
,
. 9.29. .

423

. 9 .2 9 .


. 9.30. ( .)
, , .
, -
, .
1. GridBagLayout. ,
.
, .

..

..1*^

(The quick brown fox jum j


jps

ele?--------j

?
\

. 9 .3 0 . ,

2. GridLayout
.
3. GridBagConstraints.
,
.
4. , :
add(Component, constraints);.

424

9 Swing

, .
( ,
.)
GridBagLayout layout = new GridBagLayout();
panel.setLayout(layout);
GridBagConstraints constraints = new GridBagConstraints();
constraints.weightx = 100;
constraints.weighty = 100;
constraints.gridx = 0;
constraints.gridy = 2 ;
constraints.gridwidth = 2;
constraints.gridheight = 1 ;
panel.add(component, constraints);

G r i d B a g
Constrains. ,
.

g r id x , g r id y , g r id w id th g r id h e ig h t
. ,
gridx gridy
. gridwidth gridheight
, .
. , gridx=0
gridy=0 . ,
gridx=2 gridy=0,
2 (.. ).
, gridwidth=l, a gridheight=4.


-
, weightx weighty. ,
. ,
. 9.29, weightx.
.
, ,
, .
, ,
, , .
, -
.
. ,
,
.

. "" ,
, .
,
.
. 100,

425

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

f i l l an c h o r
,
, fill.
: G r i d B a g C o n s t r a i n t s .
NONE, G r i d B a g C o n s t r a i n t s .HORIZONTAL, G r i d B a g C o n s t r a i n t s .V E R T I C A L
GridBagConstraints.BOTH.

, ,
, anchor.
: GridBagConstraints .CENTER ( ),
GridBagConstraints.NORTH, GridBagConstraints.NORTHEAST, GridBagConstraints.
EAST ..


insets G r i d B a g
Constraints,
.
, left, top, right
bottom Insets. .
, ipadx ipady,
. ,
, .


g r id x , g r id y , g r id w id th g r id h e ig h t
AWT
gridx gridy,
GridBagConstraints .RELATIVE. ,
- : .
, , ,
gridheight gridwidht. ,
. ,
GridBagConstraints .REMAINDER.
, .
.

, ,
. ,
- . ,
,
.

426

9 Swing

1. .
2. ,
, .
3. 0, 1, 2, 3... .
gridx, gridy, gridwidth gridheight.
4. ,
? , ?
fill anchor.
5. 100. ,
,
weightx weighty ,
.
6. . ,
GridBagConstraints.
.
7. ,
.

. . 9.31
NetBeans.
>1i<IH, )l <tyout * ir.t 11iiz <m

Grid X
Grid Y
Grid Width
Grid Height

Internal Padding X
Internal Padding Y
Anchor

' ''

.t

'

'

0
3
2
1
Horizontal
0
0
Center

[ita b S li j]ComboBo,j i
e

(5SSSJ jjComboBo. J

jScrottPanel

jCbecMoxl

f~

]ChecfcBox2

jCheckBox2 iJCheckBox]

Insets

pArtchor

1
i

!!
i
1
1

'-ji

is*

4,

- L+

i
E2
rFffl

AI
r

Si

t!

IS

+,

I__ _

Grid Size-

1-Padding

i--

. 9 .3 1 . N etB eans

.
-

427


-
-
, .
.
,
. ,
.

GridBagConstraints, ,
, G B C .EAST.

GBC

GBC

add(component,

new GBC(1,

2));

new GBC(1,

2, 1, 4));

new GBC(1,

2).setWeight(100, 100));


this, :
add(component,


, .
add(component,

GridBagConstraints).


gridx gridy, gridx gridy, gridwidth gridheight, , :
add(component,

new GBC(1,

2).setAnchor(GBC.EAST).setWeight(100, 100));

setlnsets() Insets.
, ,
.
add(component,

new GBC(1,

2).setAnchor(GBC.EAST).setlnsets(1));
4

9.10
, 9.11
GBC.
.
add(faceLabel, new G B C (0,0).setAnchor(GBC.EAST));
add(face, new GBC(1,0).setFill(GBC.HORIZONTAL).setWeight(100,0).setlnsets(1));
add(sizeLabel, new GBC(0, 1).setAnchor(GBC.EAST));
add(size, new G B C (1,1).setFill(GBC.HORIZONTAL).setWeight(100,0).setlnsets(1));
add(bold, new GBC(0, 2, 2, 1).setAnchor(GBC.CENTER).setWeight(100, 100));
add(italic, new GBC(0, 3, 2, 1).setAnchor(GBC.CENTER).setWeight(100, 100));
add(sample, new G B C (2, 0, 1, 4).setFill(GBC.BOTH).setWeight(100, 100));

- ,
.
! , http://docs.oracle.com/javase/
tutorial/uiswing/layout/gridbag.html,
GridBagConstraints . ,
, .

428

9 Swing
http://docs.oracle./
javase/tutorial/uiswing/events/containerlistener .html.
, BOTH,
fill?

9.10. gridbag/Font Frame, java


1
2
3
4
5
6

package gridbag;
import
import
import
import

7
8 /**
9
10

java.awt.*;
java.awt.event.*;
java.beans.*;
javax.swing.*;

* , -
* ,

11 */

12 public class FontFrame extends JFrame


13 {
14
public static final int TEXT_ROWS = 10;
15
public static final int TEXT_COLUMNS = 20;
16
17
private JComboBox<String> face;
18
private JComboBox<Integer> size;
19
private JCheckBox bold;
20
private JCheckBox italic;
21
private JTextArea sample;
22
23
public FontFrame()
24
{
25
GridBagLayout layout = new GridBagLayout ();
2 6
setLayout(layout);'
27
28
ActionListener listener =
29
EventHandler.create(ActionListener.class, this, "updateSample");
30
31
//
32
33
JLabel faceLabel = new JLabel("Face: ");
34
face = new JC o m b o B o x o (new String[] { "Serif", "SansSerif",
35
"Monospaced", "Dialog", "Dialoglnput" });
36
37
face.addActionListener(listener);
38
39
JLabel sizeLabel = new JLabel("Size: ");
40
41
size =
42
new JC o m b o B o x o (new Integer [] { 8, 10, 12, 15, 18, 24, 36, 48 });
43
44
size.addActionListener(listener);
45
46
bold = new JCheckBox ("Bold");
47
bold.addActionListener(listener);
48
49
italic = new JCheckBox("Italic");
50
italic.addActionListener(listener);
51
52
sample = new JTextArea(TEXT_ROWS, TEXT_COLUMNS);


53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

sample.setText("The quick brown fox jumps over the lazy dog);


sample.setEditable(false);
sample.setLineWrap(true);
sample.setBorder(BorderFactory.createEtchedBorder());
// , GBC
add(faceLabel, newGBC(0, 0).setAnchor(GBC.EAST));
add(face, newGBC(l, 0).setFill(GBC.HORIZONTAL).
setWeight(100, 0).setlnsets (1));
add(sizeLabel, new GBC(0, 1).setAnchor(GBC.EAST));
add(size, new GBC(1, 1) .setFill(GBC.HORIZONTAL).
setWeight(100, 0).setlnsets (1));
add(bold, new GBC(0, 2, 2, 1).setAnchor(GBC.CENTER).
setWeight(100, 100));
add(italic, newGBC(0, 3, 2, 1) .setAnchor(GBC.CENTER).
setWeight(100, 100));
add(sample, newGBC(2, 0, 1, 4) .setFill(GBC.BOTH).
setWeight (100, 100));
pack();
updateSample();
}
public void updateSample()
{
String fontFace = (String) face.getSelectedltem();
int fontStyle = (bold.isSelected() ? Font.BOLD : 0)
+ (italic.isSelected() ? Font.ITALIC : 0);
int fontSize = size.getltemAt(size.getSelectedlndex ());
Font font = new Font(fontFace, fontStyle, fontSize);
sample.setFont(font);
sample.repaint();
}

9.11. gridbag/GBC. java 1


1 package gridbag;
2
3
import java.awt.*;
4
5
/**
6
* GridBagConstraints
7
* (Aversion 1.01 2004-05-06
8
* Oauthor Cay Horstmann
9
*/
10 public class GBC extends GridBagConstraints
11 {

12

/**

13
14
15
16
17
18
19
20
21
22
23
24

* GBC,
* gridx gridy,
* -
* @param gridx
* @param gridy
*/
public GBC(int gridx, int gridy)

{
this.gridx = gridx;
this.gridy = gridy;

429

430
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

9 Swing
/**
* GBC,
* gridx, gridy, gridwidth, gridheight,
* -
* @param gridx
* gridy
* gridwidth
* gridheight
*/
public GBC(int gridx, int gridy, int gridwidth, int gridheight)
{
this.gridx = gridx;
this.gridy = gridy;
this.gridwidth = gridwidth;
this.gridheight = gridheight;
}
/**
*
* 0paramanchor
* 0return this
*/
public GBC setAnchor (int anchor)
{
this.anchor = anchor;
return this;
}
/**
*
* fill
* 0return this
*/
public GBC setFill(int fill)
{
this.fill = fill;
return this;
}
/**
*
* weightx
* weighty
* 0return this
*/
public GBC setWeight(double weightx, double weighty)
{
this.weightx = weightx;
this.weighty = weighty;
return this;
}
/**
*

* distance
* return this
*/
public GBC setlnsets(int distance)
{
this.insets = new Insets(distance, distance, distance, distance)
return this;

431

87

88

/**

89
90
91
92
93
94
95
96
97
98
99

*
* @param top
* @param left
* Qparambottom
* Qparam right
* @return this
*/
public GBC setlnsets(int top, int left, int bottom, int right)
{
this.insets = new Insets(top, left, bottom, right);
return this;

100

101
102
103
104
105
106
107
108
109
110
111
112
111

/**
*
* Qparam ipadx
* Qparam ipady
* Qreturn this
*/
public GBC setlpad(int ipadx, int ipady)
{
this.ipadx = ipadx;
this.ipady = ipady;
return this;

}
)

j a v a . a w t . G r id B a g C o n a t r a in t s

int gridx,

1 .0

gridy

.
.

int gridwidth,

gridheight

, . 1.

double weightx,

weighty

.
.

int anchor

. ,
.
NORTHWEST

NORTH

NORTHEAST

WEST

CENTER

EAST

SOUTHWEST

SOUTH

SOUTHEAST

, :
FIRS T_LINE_START

LINE_START

FIRST_LINE_END

PAGE_START

CENTER

PAGE_END

LAS T_LINE_START

LINE_END

LAST_LINE_END

,
, .
________________

432

9 Swing

j a v a . a w t . G r id B a g C o n s t r a in t s

1 .0

int fill

.
v e r r t i c a l . n o n e .

int ipadx,

n o n e ,b o t h ,h o r i z o n t a l

ipady

. .

Insets insets

. .

GridBagConstraints(int g r id x ,
double w eigh tx ,

ip a d x ,

int g r id y ,

int g r id w id th ,

int g r id h e ig h t ,

double w eig h ty , int a n ch o r , int f i l l , Insets i n s e t s , int

int ip ad y )

1.2

GridBagConstraints, .
,
.


API
GroupLayout ,
Swing GUI Builder ( Matisse),
NetBeans.
https://netbeans.org/features/java/swing.html.
,
, . 9.13, .
JFrame. ,
, , .

:
jL ab ell

feiSeI2f

433

,
, .
.

JU *tt2

, ,
.

Swing GUI Builder


Java:
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldl))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPasswordFieldl)))
.addContainerGap(222, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(j Labe11)
.addComponent(jTextFieldl))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(j Label2)
.addComponent(jPasswordFieldl))
.addContainerGap (244, Short-.MAX_VALUE) ) ) ;

. , .
,

434

Swing

. .
API
, .
GroupLayout.
SequentialGroup GroupLayout.ParallelGroup.
GroupLayout.Group. ,
. add ()
,
:
group.addComponent (...). addPreferredGap (...). addComponent (...);

,
.
, ,
, .
/
/

jL a b e l1

jT e x t F ie ld l

OK

:-| :

jP a ssw o rd F ie ljil

j jL ab e l2
9 i

//

. . . / . ........

/
i

....... ...-j...-... ....-.

[i

J.
,
( ) : ,
.addContainerGap()
.addGroup(layout.createParallelGroup()
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap (Layou.tStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldl) )
.addGroup(layout.createSequentialGroup()
.addComponent(j Label2)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPasswordFieldl)))

? ,
. - Swing GUI Builder,
. ,
Aligns Left to Column (1^
) . ,
AlignRight to Column (1^ ),
. 9.32.

lO JEM cLl

/
1

Anchor
Auto Resizing

I
I,

Right to Column
T o p to Row
Bottom to Row

Same Size

//'.

Set Default Size

Left

Space Around Component...

Right

Move Up
Move Down

Top
Bottom

C trl-X
C trl-C

o py
gelete

''';.;

.'.--7-:'.- "'''V:"/ " g j ^ ' / ;' ' ; -

':./:/. ./^ h i'ij:!::':: -: i.,,n .)

_ Deitte

'^ ' / V / . / > V/.V/'-V----' /'/^///V.'. *.7^ J/ ./^-

///^v v/vy;A ///^/V;:V/ v' '\vV;:''. ./'/?'.v/.; i:!;;ri:i:!:::!il:;i\:ni?r!;:;:.!/:'!

^/'

.? tt
v t!;ji.

ij:
jjij

ile x iH e id l.

I
I

7/;

Edit T e x t

Change Variable Mam*


Events

7/ /

>:

Left to Column
Anchor

Auto Resizing

T o p to Row

iSame Size

Bottom to Row

Set Default Size


"Space AfOund .Cpmpuntrrt -.

Move Up

Top

Move Down

Bottom
Ctrt-X

opy

C trl-C

V ///

I
.7/7-

Left
Right

Cut

f
It

7//

7/V.

I
I
I

. 9 .3 2 . Swing GUI Builder

435

436

9 Swing

:
.addGroup(layout.createSequentialGroup()
.addContainerGap ()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2, GroupLayout.Alignment.TRAILING))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldl)
.addComponent(jPasswordFieldl))

.
TRAILING (..
), .

Swing GUI Builder


, , -

. , .
, , ,
, .

437

:
layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextFieldl) )
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(j Label2)
.addComponent(jPasswordFieldl))

, .
( , .)
. ,
, ,
Swing GUI Builder, Same
Size^Sam e Width ( ^ ) ,
. 9.33.

Anchor
AutoResizing
Same Width
Set Default S ilt

Space Around Component,


Move Up
Move Down
Cu
Copy

Ctfi-X
Ctri-C

. 9.33.

Swing GUI Builder :


layout.linkSize(SwingConstants.HORIZONTAL,
{jPasswordFieldl, jTextFieldl});

new Component[]

9.12

GroupLayout GridBagLayout.
, 9.10, .
Swing GUI Builder,
.

438

Swing

9.12.
1
2
3
4
5
6
7

package groupLayout;

/**

import
import
import
import

g r o u p L a y o u t/F o n tF r a m e . j a v a

java.awt.*;
java.awt.event.*;
java.beans.*;
javax.swing.*;

9
* ,
10
* ,
11 */
12 public class FontFrame extends JFrame
13 {
14
public static final int TEXT_ROWS = 10;
15
public static final int TEXT_COLUMNS = 20;
16
17
private JComboBox<String> face;
18
private JComboBox<Integer> size;
19
private JCheckBox bold;
20
private JCheckBox italic;
21
private JScrollPane pane;
22
private JTextArea sample;
23
24
public FontFrame()
25
{
26
ActionListener listener =
27
EventHandler.create(ActionListener.class, this, "updateSample");
28
//
29
30
JLabel faceLabel = new JLabel("Face: ");
31
32
face = new JComboBoxO(new String[]{ "Serif", "SansSerif",
33
"Monospaced", "Dialog", 32 "Dialoglnput" });
34
35
face.addActionListener(listener);
36
37
JLabel sizeLabel = new JLabel("Size: ");
38
39
size = new JComboBoxO (new Integer []
40
{ 8, 10, 12, 15, 18, 24, 36, 48 });
41
42
size.addActionListener (listener) ;
43
44
bold = new JCheckBox("Bold");
45
bold.addActionListener(listener);
46
47
italic = new JCheckBox("Italic");
48
italic.addActionListener(listener);
49
50
sample = new JTextArea(TEXT_ROWS, TEXT_COLUMNS);
51
sample.setText("The quick brown fox jumps over the lazy dog");
52
sample.setEditable (false);
53
sample.setLineWrap(true);
54
sample.setBorder(BorderFactory.createEtchedBorder());
55


56
57
58
59
60
61
62
63
64
65
66
67

pane = new JScrollPane(sample);


GroupLayout layout = new GroupLayout(getContentPane ());
setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(
layout.createSequentialGroup().addContainerGap()
.addGroup(
layout.createParallelGroup (GroupLayout7.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addGroup(
layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addComponent(faceLabel).addComponent(sizeLabel))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
layout.createParallelGroup(
GroupLayout.Alignment.LEADING, false)
.addComponent(size).addComponent(face)))
.addComponent(italic).addComponent(bold)).addPreferredGap(
LayoutStyle.ComponentPlacement.RELATED).addComponent(pane)
.addContainerGap ()));

68

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

layout.linkSize(SwingConstants.HORIZONTAL,
new java.awt.Component[] { face, size });
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(
layout.createSequentialGroup ().addContainerGap () .addGroup (
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(
pane, GroupLayout.Alignment.TRAILING).addGroup(
layout.createSequentialGroup().addGroup(
layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(face).addComponent(faceLabel))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
layout.createParallelGroup(
GroupLayout.Alignment.BASELINE).addComponent(size)
.addComponent(sizeLabel)).addPreferredGap(
LayoutStyle.ComponentPlacement.RELATED).addComponent(
italic, GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bold, GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap()));
pack ();

86

87
88

89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109

public void updateSample()

110

111
112

String fontFace = (String) face.getSelectedltemO ;


int fontStyle = (bold.isSelected() ? Font.BOLD : 0)

439

440

9 Swing

113
114
115
116
118
119
}
120 }

+ (italic.isSelected() ? Font.ITALIC : 0);


int fontSize = size.getltemAt(size.getSelectedlndex ());
Font font = new Font(fontFace, fontStyle, fontSize);
sample.setFont(font);
sample.repaint();

j a v a x . s w in g . G ro u p L a y o u t 6 *

GroupLayout(Container h o st)

GroupLayout h o s t .
(, , , host
setLayout ().)

void setHorizontalGroup(GroupLayout.Group g)

void setVerticalGroup(GroupLayout.Group g)

, .

void linkSize(Component.. . com ponents)

void linkSize(int axis,

Component...

component)


(SwingConstants.HORIZONTAL SwingConstants.
VERTICAL ).

GroupLayout.SequentialGroup createSequentialGroup()

, .

GroupLayout.ParallelGroup createParallelGroup()

GroupLayout.ParallelGroup createParallelGroup(GroupLayout.Alignment a li g n )

GroupLayout.ParallelGroup createParallelGroup(GroupLayout.Alignment a l i g n ,
boolean r e s i z a b l e )

, .
:

a lig n

: BASELINE,

l e a d i n g (

), TRAILING CENTER
r e s iz a b le

true ( ),
;
false,

boolean getHonorsVisibility()

void setHonorsVisibility(boolean b)

honorsVisibility.
true ( ), .
false,
. , ,
.

boolean getAutoCreateGaps()

void setAutoCreateGaps(boolean b)

boolean getAutoCreateContainerGaps()

void setAutoCreateContainerGaps(boolean b)

441

autoCreateGaps autoCreateContainerGaps.
true,
. false.
true , GroupLayout
.

j a v a x . s w in g . G ro u p L a y o u t. G ro u p

GroupLayout.Group addComponent(Component c)

GroupLayout.Group

p r e fe r r e d S iz e ,

c,

addComponent(Component

m in im u m S ize,

int

int

int maximumSize)

. , ,
() GroupLayout.DEFAULT_
SIZE GroupLayout.PREFERRED_SIZE. DEFAULT_SIZE,

getMinimumSize (), getPreferredSize ()


getMaximumSize ( ) . PREFERRED_SIZE,
getPreferredSize ().

GroupLayout.Group addGap(int s i z e )

GroupLayout.Group

addGap(int

m in im u m S ize,

int

p r e fe r r e d S iz e ,

int

maximumSize)

GroupLayout.Group addGroup(GroupLayout.Group' g)

j a v a x . s w in g . G ro u p L a y o u t. P a r a lle lG r o u p

GroupLayout.ParallelGroup addComponent(Component c ,

GroupLayout.Alignment

a lig n )

GroupLayout.ParallelGroup addComponent(Component c ,

a lig n ,

int m inim um Size,

int p r e f e r r e d S i z e ,

GroupLayout.ParallelGroup

GroupLayout.Alignment

int maximumSize)

addGroup(GroupLayout.Group

g,

GroupLayout.

Alignment a lig n )

, (

b a s e l i n e ,l e a d i n g ,t r a i l i n g c e n t e r ).

442

9 Swing

j a v a x . s w in g . G ro u p L a y o u t. S e q u e n tia lG r o u p

GroupLayout.SequentialGroup addContainerGap()

GroupLayout.SequentialGroup

addContainerGap(int

p r e fe r r e d S iz e ,

int

maximumSize)

, .

GroupLayout.SequentialGroup addPreferredGap(LayoutStyle.ComponentPlacement

type)

. ty p e
LayoutStyle. ComponentPlacement .RELATED

LayoutStyle.

ComponentPlacement.UNRELATED.


- ,
.
. -,
. ,
.
,
.
1. null .
2. .
3.
:
frame.setLayout (null);
JButton ok = new JButton("OK");
frame.add(ok);
ok.setBounds(10, 10, 30, 15);

j a v a . a w t . C o m p o n en t 1 . 0

void setBounds (int x, int y, int w id th , int h e ig h t)

.
:

width, h e ig h t


LayoutManager,
.
, (. 9.34).

443

. 9 .3 4 .


LayoutManager. :
void addLayoutComponent(String s, Component c);
void removeLayoutComponent(Component c);
Dimension preferredLayoutSize(Container parent);
Dimension minimumLayoutSize(Container parent);
void layoutContainer(Container parent);

.
,
. ,
.
. setBounds ()
.
! AWT LayoutManager2.
, . ,
add() . ,
BorderLayout GridBagLayout LayoutManager2.
9.13 ,

CircleLayout,
. ,
. 9.14 ,
.
9.13. c i r c l e L a y o u t / C i r c l e L a y o u t .j ava 1
1

package circleLayout;

3
4
5
6

import java.awt.*;
/**
* ,

7 V
8 public class CircleLayout implements LayoutManager
9
{
10
private int minWidth = 0;
11
private int minHeight = 0;

444

66
67
68

private
private
private
private
private

int preferredWidth = 0;
int preferredHeight = 0;
boolean sizesSet = false;
int maxComponentWidth = 0;
int maxComponentHeight = 0 ;

public void addLayoutComponent(String name, Component comp)


{

}
public void removeLayoutComponent(Component comp)

{
}
public void setSizes(Container parent)
{
if (sizesSet) return;
int n = parent.getComponentCount ();
preferredWidth = 0 ;
preferredHeight = 0;
minWidth = 0 ;
minHeight = 0;
maxComponentWidth = 0;
maxComponentHeight = 0;
//
//
for (int i = 0; i < n; i++)
{
Component c = parent.getComponent (i);
if (c.isVisible())
{
Dimension d = c.getPreferredSize();
maxComponentWidth = Math.max(maxComponentWidth, d .w id th ) ;
maxComponentHeight = Math.max(maxComponentHeight, d.height)
preferredWidth += d.width;
preferredHeight += d.height;
}
}
minWidth = preferredWidth / 2;
minHeight = preferredHeight / 2;
sizesSet = true;
}
public Dimension preferredLayoutSize(Container parent)
{
setSizeS(parent) ;
Insets insets = parent.getlnsets() ;
in t width = preferredW idth + i n s e t s . l e f t + i n s e t s .r ig h t ;
int height = preferredHeight + insets.top + insets.bottom;
return new Dimension(width,

h e ig h t);

}
p u b lic

Dimension minimumLayoutSize(Container parent)

{
s e t S iz e s ( p a r e n t ) ;

Insets insets = parent.getlnsets ();

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

9 Swing


69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

int width = minWidth + insets.left + insets.right;


int height = minHeight + insets.top + insets.bottom;
return new Dimension(width, height);
}
public void layoutContainer(Container parent)
{
setSizes(parent);
//
Insets insets = parent.getlnsets();
int containerWidth =
parent.getSize().width - insets.left - insets.right;
int containerHeight =
parent.getSize().height - insets.top - insets.bottom;
int xcenter = insets.left + containerWidth / 2;
int ycenter = insets.top + containerHeight /2;

88

89
//
90
91
int xradius = (containerWidth - maxComponentWidth) / 2;
92
int yradius = (containerHeight - maxComponentHeight) / 2;
93
int radius = Math.min(xradius, yradius);
94
95
//
96
97
int n = parent.getComponentCount ();
98
for (int i = 0; i < n; i++)
99
{
100
Component c = parent.getComponent(i);
101
if (c.isVisible ())
102
{
103
double angle = 2 * Math.PI * i / n;
104
105
//
106
int x = xcenter + (int) (Math.cos(angbfe) * radius);
107
int = ycenter + (int) (Math.sin(angle) * radius);
108
109
// ,
110
/ / (, )
111
Dimension d = c.getPreferredSize();
112
.setBqunds ( - d.width / 2, - d.height / 2, d.width, d.height);
113
}
112
}
113
}
114 }

9.14. circleLayout/CircleLayoutFrame. java 1


1
2
3
4
5

package circleLayout;
import javax.swing.*;
/**

445

446

6
7
8

10

9 Sw ing________

* ,
*/
public class CircleLayoutFrame extends JFrame
{
public CircleLayoutFrame()

11
12
13
14
15
16
17
18
19
20
21
22

setLayout(new CircleLayout());
add(new JButton("Yellow"));
add(new JButton("Blue"));
add(new JButton("Red"));
add(new JButton("Green"));
add(new JButton("Orange"));
add(new JButton("Fuchsia"));
add(new JButton("Indigo"));
pack();

ja v a .a w t .L a y o u t M a n a g e r 1 . 0

void addLayoutComponent(String name,

Component comp)

.
:

void emoveLayoutComponent(Component comp)

Dimension preferredLayoutSize(Container cont)

, .

void layoutContainer(Container con t)


, .
, ,
. ,
<>, .
(, , ,
. , , , ,
.) ,
, .
"" , ,
, .
, Swing
.

447

: ,
. ,
(. 9.35).

. 9 .3 5 .

.
. ( ,
<Ctrl+Tab> ,
.)
.
.
.
, .
,
, .
, .
,
, , .
! component. setFocusable (false);,
. ,
, .


,
, ,
, .
,
.

448

9 Swing

, AWT ()
() .

. , ,
. ,
. ,
,
.

, .
. ,
,
.

, . Swing
JOptionPane, ,
. ,
. ,
.

.
.
JFileChooser Swing.
,
JColorChooser.


Swing ,
.
JOptionPane .
S h o w M e s s a g e D i a l o g ()

S h o w C o n f i r m D i a l o g ()


( C ancel)

S h o w O p t i o n D i a l o g ()

s h o w I n p u t D i a l o g ()

. 9.36 .
, :
;
;
.

449

. 9 .3 6 .

.
,
, ,
.
.

. :
ERROR_ME SSAGE
INFORMATION_MES SAGE
WARNING_MESSAGE
QUE STION_MES SAGE
PLAIN_MESSAGE

PLAIN_MESSAGE .
,
.
,
, ,
. ,
.
S tr in g

C om ponent

Ob j e c t [ ]

t o S t r i n g ()


9.15. , .
C o m p o n e n t
, , p a in t C o m p o n e n t (),
, .
, ,
, . s h o w M e s s a g e D i a l o g ()
s h o w I n p u t D i a l o g O , (
C an cel). s h o w C o n f i r m D i a l o g (),
:
DEFAULT_OPTION
YES NO OPTION

450

9 Swing

YES_NO_CANCEL_OPTION
OK_CANCEL_OPTION

showOptionDialogO
, , .
.
St r i n g

Icon

Component

t o S t r i n g ( ) ,

, ,
.
S h o w M e s s a g e D i a l o g ()

s h o w C o n f i r m D i a l o g ()

s h o w O p t i o n D i a l o g ()

s h o w I n p u t D i a l o g ()

showConf irmDialog () showOptionDialogO


, , .
.
,
CLOSED_OPTION. ,
.
0K_0PTI0N
CANCEL_OPTION
YES_0PTI0N
N0_0PTI0N
CL0SED_0PTI0N


, .
.
V

1. ( ,
, ).
2. ( , , ,
, ) .
3. ( , ,
).
4. ,
( Yes/No, No/Cancel OK/Cancel).
5. ,
( ,
), , .

451

6. ,
.
7.

JOptionPane.

, ,
. 9.36. ,
. ,
. , , ,
.
0K_CANCEL_0PTI0N.
:
int selection = JOptionPane.showConfirmDialog(parent,
"Message", "Title",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (selection == JOptionPane.OK OPTION) . . .

. ( 11\ 1).
.

,
9.15, (. 9.37).
9.16 .
Show (), .
9.15. optionDialog/OptionDialogFrame. java
1
2
3
4
5
6
7

package optionDialog;
import
import
import
import
import

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

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

/**
*
*/

public class OptionDialogFrame extends JFrame


{
private ButtonPanel typePanel;
private ButtonPanel messagePanel;,
private ButtonPanel messageTypePanel;
private ButtonPanel optionTypePanel;
private ButtonPanel optionsPanel;
private ButtonPanel inputPanel;
private String messagestring = "Message";
p r iv a te Icon messagelcon = new Im agelcon (" b l u e - b a l l .g i f ");
p r iv a te Object messageObject = new Dat e( ) ;
private Component messageComponent = new SampleComponent ();
p u b lic O ptionDialogFram e ()

452

9 Swing

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
4 8
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

/**
*
* @return , ,
*

66

*/

67

public Object getMessage()

68

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

JPanel gridPanel = new JPanelO;


gridPanel.setLayout(new GridLayout(2/3));
typePanel =
new ButtonPanel("Type", "Message", "Confirm", "Option", "Input");
messageTypePanel = new ButtonPanel("Message Type", "ERROR_MESSAGE",
"INFORMATI ON_ME SSAGE ", "WARN ING_ME SSAGE ", "QUEST ION__MES SAGE",
"PLAIN_MES SAGE");
^
messagePanel = new ButtonPanel("Message", "String", "Icon",
"Component", "Other", "Object[]");
optionTypePanel = new ButtonPanel("Confirm", "DEFAULT_OPTION",
"YES_NO_OPTION", 35 "YES_NO_CANCEL_OPTION", "OK_CANCEL_OPTION")
optionsPanel = new ButtonPanel("Option", "String[]",
"Icon[]", "Object[]");
inputPanel = new ButtonPanel("Input", "Text field", "Combo box");
gridPanel.add(typePanel);
gridPanel.add(messageTypePanel);
gridPanel.add(messagePanel);
gridPanel.add(optionTypePanel);
gridPanel.add(optionsPanel);
gridPanel.add(inputPanel);
// Show
JPanel showPanel = new JPanelO;
JButton showButton = new JButton("Show");
showButton/addActionListener(new ShowAction());
showPanel.add(showButton);
add(gridPanel, BorderLayout.CENTER);
add(showPanel, BorderLayout.SOUTH);
pack () ;
}

String s = messagePanel.getSelection ();


if (s.equals("String")) return messagestring;
else if (s.equals("Icon")) return messagelcon;
else if (s.equals("Component")) return messageComponent;
else if (s.equals("Object[]")). return new Object []
{ messagestring, messagelcon, 69 messageComponent, messageObject };
else if (s.equals("Other")) return messageObject;
else return null;
}
/**
*
* @return , ,
*

*/
public Object [] getOptionsO


85
86

String s = optionsPanel.getSelection();
if (s.equals("String[])) return new String[]
{ "Yellow", "Blue", "Red" };
else if (s.equals("Icon[]")) return new Icon[]
{ new Imagelcon("yellow-ball.gif"),
new Imagelcon("blue-ball.gif"), new Imagelcon("red-ball.gif") }
else if (s.equals("Object[]")) return new Object[]
{ messagestring, messagelcon, messageComponent, messageObject }
else return null;

87
88

89
90
91
92
93
94
95
96
97
98
99
100
101

102
103
104
105
106
107
108
109

}
j
*
* @param panel Message ( )
*
Confirm ()
* 0return XXX_MESSAGE XXXjDPTION,
*
JOptionPane
*/
public int getType(ButtonPanel panel)

{
String s = panel.getSelection();
try
{
return JOptionPane.class.getField(s).getlnt(null);

110

catch (Exception e)

111
112
113
114
115
116
117
118
119
120
121
121
122
123
124
125
126
127
128
129
130
131
132
132
133
134
135
136
137
138
139
140

{
return -1;

j
* Show.
* (Confirm), (Input), (Message)
* (Option) ,
*
*/
private class ShowAction implements ActionListener

{
public void actionPerformed(ActionEvent event)

{
if (typePanel.getSelection().equals("Confirm"))
JOptionPane.showConfirmDialog(OptionDialogFrame.this,
getMessage(), "Title", getType(optionTypePanel),
getType(messageTypePanel));
else if (typePanel.getSelection().equals("Input"))

{
if (inputPanel.getSelection().equals("Text field"))
JOptionPane.showInputDialog(
OptionDialogFrame.this, getMessage(), "Title",
getType(messageTypePanel));
else JOptionPane.showInputDialog(OptionDialogFrame.this,
getMessage(), "Title", getType(messageTypePanel), null,
new String[] { "Yellow", "Blue", "Red" }, "Blue");

}
else if (typePanel.getSelection().equals("Message"))
JOptionPane.showMessageDialog(OptionDialogFrame.this,
getMessage(), "Title", getType(messageTypePanel));

453

454
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
162
163
164
165
166
167
168
169

9 Swing
else if (typePanel.getSelection().equals("Option"))
JOptionPane.showOptionDialog(OptionDialogFrame.this,
getMessage(), "Title", getType(optionTypePanel),
getType(messageTypePanel), null, getOptions (), getOptions()[0]);
}

}
/**
*
*/
class SampleComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle2D rect =
new Rectangle2D. Double (0, 0, getWidth() - 1, getHeightO - 1) ;
g 2 .setPaint(Color.YELLOW);
g 2 .fill(rect);
g 2 .setPaint(Color.BLUE);
g 2 .draw(rect);
}
public Dimension getPreferredSize()
{
return new Dimension (10, 10);
}
}

9.16. optionDialog/ButtonPanel. java 1


1
2
3
4
5
6
7
8
9
10
11

package optionDialog;
import javax.swing.*;
/**
* -,
*/
public class ButtonPanel extends JPanel
{
private ButtonGroup group;

12

/**

13
14
15
16
17
18
19
20
21
22
23
24
25
26

*
* @param title ,
* @param options -
*/
public ButtonPanel(String title, String... options)
{
setBorder(BorderFactory.createTitledBorder(BorderFactory.
createEtchedBorder(), title));
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
group = new ButtonGroup ();
// -
for (String option : options)
{
JRadioButton b = new JR ad io B u tto n (o p tio n ) ;


27

b . setActionCommand(option);

28

a d d (b );

29

grou p .a d d (b );

30

b . se tS e le c te d (o p tio n == o p t io n s [0 ]);

31

455

32

33
34

/**

35

36

* @return -

37

*/

38

p u b lic

39

40

S t r in g

g e tS e le c tio n ()

return grou p.g e t S e le c t io n ( ) . getActionCommand();

41

42 }

. 9 .3 7 . OptionDialogTest
j a v a x . s w in g . J O p tio n P a n e 1 .2

s t a t ic

v o id

title ,

in t

s t a t ic

v o id

title ,

in t

s t a t ic

v o id

s t a t ic

v o id

S t r in g

title ,

s t a t ic

v o id

S t r in g

title ,

showMessageDialog(Component

m essageT yp e,

Icon

p a re n t,

O bject

m e ssa g e ,

S t r in g

p a re n t,

Object

m e ssa g e ,

S t r in g

ico n )

showMessageDialog(Component

m essageType)
showMessageDialog(Component

p a re n t,

show InternalM essageDialog(Com ponent


in t

m essageT yp e,

Icon

m essageT ype)

m essage)

p a re n t,

Object

m e ssa g e ,

p a re n t,

Object

m e ssa g e ,

ico n )

show InternalM essageDialog(Com ponent


in t

Object

456

9 Swing
static void showInternalMessageDialog(Component p a r e n t ,

Object m essage)

.
( .)
:

p aren t

(null)
m e ssag e

,
( , ,
)

title

m essageT ype

:
ERROR_MESSAGE, INFORMATION_MESSAGE,

WARNING_MESSAGE, QUESTION_MESSAGE
PLAIN MESSAGE

ic o n

static

title ,

static

title ,

static

title ,

int showConfirmDialog(Component
int o p tio n T y p e,

int m essageT y p e,

int showConfirmDialog(Component
int o p tio n T y p e,

p a re n t,

Object m e ssa g e ,

String

p a re n t,

Object m e ssa g e ,

String

p a re n t,

Object m e ss a g e ,

String

Icon ico n )

int m essageT ype)

int showConfirmDialog(Component
int option T ype)

static int showConfirmDialog(Component p a r e n t ,

static

static

static

int m essageT y p e,

Icon ico n )

int o p tio n T y p e,

p a r e n t , Object m e ssa g e ,

int m essageT ype)

int showInternalConfirmDialog(Component

String t i t l e ,

int o p tio n T y p e,

int showInternalConfirmDialog(Component

String t i t l e ,

p a r e n t , Object m e ssa g e ,

int showInternalConfirmDialog(Component

String t i t l e ,

Object m essage)

p a r e n t , Object m e ssa g e ,

int' option T ype)

static int showInternalConfirmDialog(Component p a r e n t ,

Object m essage)

. (
.) ,
( : ok _ o p t io n , y e s _ o p t io n no _ o p t io n ),

:

c l o s e d o p t io n ,

p aren t

.
(
(null)

m e ssa g e

,
( , ,
)

title

m essageT ype

457

:
ERROR_MESSAGE, INFORMAT ION_MESSAGE,
WARNING_MESSAGE, QUEST ION_MES SAGE
PLAIN_MESSAGE

o p tio n T y p e

:
DEFAULT_OPTION, YES_NO_OPTION,
YE S_NO_CANCE L_OPT ION OK_CANCEL OPTION

ic o n

static int

showOptionDialog(Component

title ,

o p tio n T y p e ,

int

int

p a re n t,

m e ssa g e T y p e ,

Object m e ss a g e ,

Icon ic o n ,

String

Object[]

o p t io n s ,

Object d e f a u l t )

static int

showInternalOptionDialog(Component

String t i t l e ,

o p t io n s ,

int

o p tio n T y p e ,

int

p a re n t,

m e ssa g e T y p e ,

Object m e ssa g e ,

ic o n , Object[]

Icon

Object d e f a u l t )

.
( .)
, ,
.
:

p aren t

c l o s e d _ o p t io n ,

(
(null)

m e ssa g e

,
( , ,
)

title

m essageT ype

:
ERROR MESSAGE, INFORMAT ION_MESSAGE,
WARNING_MESSAGE,QUESTION_MESSAGE
PLAIN_MESSAGE

o p tio n T y p e

:
DEFAULT_OPTION, YES_NO_OPTION,
YES NO CANCEL OPTION OK_CANCEL_OPTION

ic o n

d e fa u lt

static Object

showInputDialog(Component p a r e n t ,

title ,

int m essageT yp e,

static

String

title ,

int m essageT ype)

Icon ic o n ,

Object

Object[] v a lu e s ,

showInputDialog(Component p a r e n t ,

m e ssa g e ,

String

Object d e f a u lt )

Object m e ssa g e ,

String

458

9 Swing

static String showInputDialog(Component p a r e n t ,

static String showInputDialog(Object m essage)

static

String

d e fa u lt)

showInputDialog(Component p a r e n t ,

static String showInputDialog(Object m e ssa g e ,

static Object
String t i t l e ,
static

Object d e f a u l t )

showInternallnputDialog(Component p a r e n t ,

Object

int m essageT ype,

Icon ic o n ,

1.4

Object m e ssa g e ,

Object[] v a lu e s ,

String showInternallnputDialog(Component p a r e n t ,

String t i t l e ,

m e ssa g e ,

Object

1.4

Object m essage)

Object d e f a u lt )
Object m e ssa g e ,

int m essageT ype)

static String showInternallnputDialog(Component p a r e n t ,

Object m essage)

. (
.) ,
, null, .
:

p aren t

(
(null)

m e ssa g e

,
( , ,
)

title

m essageT ype

:
ERROR_MESSAGE, INFORMATION_MESSAGE,
WARNING_MESSAGE, QUESTION_MESSAGE
PLAIN_MESSAGE

ic o n

v a lu e s

d e fa u lt


,
JOptionPane. ,
. . 9.38 ,
. ,
About ( ).
, ,
JDialog. ,
JFrame. ,
.


A b o u t D io lo q T o st

459

Core Java
By Cay Horstmann anil Gaiy Cornell

. 9 .3 8 . About

1. JD ia lo g
.
2. .
3. , .
4. .
-,
. -
. n u ll,
.
,
, . (..
) . (.. )
(
). ,
, .
, ,
,
.
! Java SE 6 .
- , "',
, ,
. .
Java ,
. -
Java,
.
w w w . o r a c l e . c o m / t e c h n e t w o r k / a r t i c l e s / j a v a s e / m o d a l i t y - 1 3 7 6 0 4 . h t m l .

, .
public AboutDialog extends JDialog
{
public AboutDialog(JFrame owner)

super(owner, "About DialogTest", true);


add(new JLabel(
"<html><hlxi>Core Java</ix/hlxhr>

9 Swing

460

By Cay Horstmann and Gary Cornell</html>"),


BorderLayout.CENTER);
JPanel panel = new JPan e l O ;
JButton ok = new JButton("OK");
o k .addActionListener(new
ActionListener()

{
public void actionPerformed(ActionEvent event)

{
setVisible(false);

}
}) ;
p a n e l .add(ok);
add(panel, BorderLayout.SOUTH);
setSize(250, 150);

,
, . ,
.
, JDialog setVisible ()
:
JDialog dialog = new AboutDialog(this);
dialog.setVisible(true);

, ,
, ,
About, .
if (dialog == null) //
dialog = new AboutDialog(this);
dialog.setVisible(true);

0,
.
0 , .
ok.addActionListener(new
ActionListener()

{
public void actionPerformed(ActionEvent event)

{
setVisible(false);

}
}) ;
, Close,
. JFrame,
setDefaultCloseOperation ().
9.17 ,
,
. 9.18
.

9.17. dialog/DialogFrame. java


1
2
3
4
5

package dialog;
import java.awt.event.*;
import javax.swing.*;

6 /**
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
53
54

* ,
* About
*/
public class DialogFrame extends JFrame

File^About

{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
private AboutDialog dialog;
public DialogFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
//

File

JMenuBar menuBar = new JMenuBarO;


setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
//

About Exit

// About
//
JMenuItem aboutltem = new JMenuItem("About");
aboutltem.addActionListener(newActionListener()
{
public void actionPerformed(ActionEvent event)
{
if (dialog == null) //
dialog = new AboutDialog(DialogFrame.this);
dialog.setvisible(true); //
}
});
fileMenu.add(aboutItern);
//

Exit

JMenuItem exitltem = new JMenuItem("Exit");


exitltem.addActionListenfer(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.exit (0);
}
});
fileMenu.add(exitltem);
}
}

461

462

9 Swing

9.18. dialog/AboutDialog. java


1
2
3
4
5

package dialog;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

7
8
9

/**
* ,
* , Ok

10 */
11 public class AboutDialog extends JDialog
12 {
13
public AboutDialog(JFrame owner)
14
{
15
super(owner, "About DialogTest", true);
16
17
// HTML-
18
19
add(
20
new JLabel(
21
"<html><hlxi>Core Java</ix/hlxhr>
22
By Cay Horstmann and Gary Cornell</html>"),
23
BorderLayout.CENTER);
24
25
// Ok
26
27
JButton ok newJButton("Ok");
28
ok.addActionListener (new ActionListener ()
29
{
30
public void actionPerformed(ActionEvent event)
31
{
32
setVisible(false);
33
}
34
});
35
// Ok
36
JPanel panel = new JPanelO;
37
panel.add(ok);
38
add(panel, BorderLayout.SOUTH);
39
40
pack();
41
}
42 }

ja v a x . s w in g . J D ia lo g

1 .2

public JDialog(Frame p a r e n t , String t i t l e , boolean m o d a l)

, ,
.
:
parent
-
t i tie

m odal
true,
(.. )

463


,
. ,
JDialog: setv i s i b l e (true),
. ,
. , . 9.39.

.

>

youmame

nvor*

. 9.39.


, . , PasswordChooser
setUser () ,
:
public void setUser(User u)

{
username.setText(u.getName());

}
, ,
. s e t visible (true) .
Cancel.
s e t v i s i b l e (false) .
, ,
setvisible (true) . , npocfb
. ,
.
, setvisible (true) .
, setvisible (true)
,
, .
.
,
. ,
, .
ok f a l s e .

464

9 Swing

true
.
.
! () -
. setvisible (true)
.
,
.


. JDialog -
.
. , - ,
, PasswordChooser.
, PasswordChooser
JPanel, JDialog. JDialog
showDialog () :
public boolean showDialog(Frame owner,

String title)

{
ok = false;
if (dialog == null

|| dialog.getOwner() != owner)

{
dialog = new JDialog(owner,
dialog.add(this);
dialog.pack();

true);

}
dialog.setTitle (title);
dialog.setvisible(true);
return ok;

}
,
null.
.
parent

owner
. -

:

Frame owner;
if (parent ins^anceof Frame)
owner = (Frame) parent;
else
owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);

.
JOptionPane.
,
, (
<Enter>).
, .
:
dialog.getRootPane().setDefaultButton(okButton);

465

,
:
. .
9.19 ,
. 9.20
.
9.19. dataExchange/DataExchangeFrame .java1
1
2
3
4
5
6
7
8
9

package dataExchange;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* , File^Connect
*

10 * /
11 public class DataExchangeFrame extends JFrame
12 {
13
public static final int TEXT_ROWS = 20;
14
public static final int TEXT_COLUMNS = 40;
15
private PasswordChooser dialog = null;
16
private JTextArea textArea;

17

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

36
37
38
39
40
41
42
43
44
45
46
47

public DataExchangeFrame()
{
// File
JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar);
JMenu fileMenu = new JMenu("File);
mbar.add(fileMenu);

// Connect Exit
JMenuItem connectltem = new JMenuItern("Connect");
connectltem.addActionListener(new ConnectAction());
fileMenu.add(connectltem);
// Exit
JMenuItem exitltem = new JMenuItem("Exit");
exitltem.addActionListener (new ActionListener ()
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
});
fileMenu.add(exitltem);
textArea = new JTextArea(TEXT_ROWS, TEXT_COLUMNS);
add(new JScrollPane(textArea), BorderLayout.CENTER);
pack () ;
}
/**
* Connect

466

9 Swing

48
*
49
*/
50
51
private class ConnectAction implements ActionListener
52
{
53
public void actionPerformed(ActionEvent event)
54
{
55
//
56
if (dialog ~ null) dialog new PasswordChooser();
57
58
//
59
dialog.setUser(new User("yourname", null));
60
61
//

62
if (dialog.showDialog(DataExchangeFrame.this, "Connect"))
63
{
64
// ,
65
//
66
User u = dialog.getUser ();
67
textArea.append ("user name - " + u.getNameO + ", password 68
+ (new String(u.getPassword())) + "\n");
69
}
' 70
}
71 }
72 }

9.20. dataExchange/P assw ordC hooser. ja v a 1


1

package dataExchange;

3
4
5

import
import
import

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

7
8

/**
* ,

9
10

*/
public class PasswordChooser extends JPanel

11

12
13
14
15
16
17
18
19

private JTextField username;


private JPasswordField password;
private JButton okButton;
private boolean ok;
private JDialog dialog;
public PasswordChooser()
{
setLayout(new BorderLayout());

20
21
22

//
//

23
24
25
26
27
28
29

JPanel panel - new JPanel ;


panel.setLayout(new GridLayout (2, 2));
panel.add(new JLabel("User name:"));
panel.add(username - new JTextField(""));
panel.add(new JLabel("Password:"));
panel.add(password - new JPasswordField(""));
add(panel, BorderLayout.CENTER);


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

/**
*
* @param
*/
public void setUser(User u)
{
username.setText(u.getName());
}

66

/**

67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

* ,

* 0return User,
*

*/
public User getUserO
{
return new User(username.getText (), password.getPasswordO);
}

// Ok Cancel
okButton = new JButton("Ok");
okButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
ok = true;
dialog.setVisible(false);
}
});
JButton cancelButton * new JButton("Cancel");
cancelButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
dialog.setVisible(false);
}
});
//
JPanel buttonPanel new JPanelO;
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
add(buttonPanel, BorderLayout.SOUTH);
}

/**
*
* 0param parent -
*
null
" * param title
*/
public boolean showDialog(Component parent, String title)
{
ok - false;
// -
Frame owner - null;

467

468
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

9 Swing
if (parent instanceof Frame) owner = (Frame) parent;
else owner =
(Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);
//
// -
if (dialog == null || dialog.getOwner () != owner)

{
dialog = new JDialog(owner, true);
dialog.add(this);
dialog.getRootPane().setDefaultButton(okButton);
dialog.pack();

}
//
dialog.setTitle(title) ;
dialog.setVisible(true);
return ok;

j a v a x . s w in g . S w i n g U t i l i t i e s

1 .2

Container getAncestorOfClass(Class c, Component comp)

,
.

j a v a x . s w in g . J C c m p o n e n t 1 .2

JRootPane getRootPane()

, .
, null.

j a v a x . s w in g . J R o o tP a n e 1 .2

void setDefaultButton(JButton b u tto n )

.
, null b u tto n .

ja v a x . s w in g . J B u tto n 1 .2

______________________^

boolean isDefaultButton()

true,
.

469


.
,
, - . , ,
! Swing JFileChooser,
,
. .
, , , JFileChooser JDialog.
setvisible (true)
showOpenDialog (),
showSaveDialog (). , ,
Open Save. showDialog ()
. . 9.40 .

. 9 .4 0 .


, , .
1. JFileChooser, .
JDialog,
.
.
JFileChooser chooser = new JFileChooser();

. ,
JFileChooser .
Windows, .

470

9 Swing

2. , setCurrentDirectory (). ,
, :
chooser.setCurrentDirectory(new File

File. File
1 ,
, File (String file n a m e ),
filen am e
File.
3. ,
, setSelectedFile () :
chooser.setSelectedFile(new File(filename));
%

4. setMultiSelectionEnabled (), ,
.
, ,
.
5. ,
(, .gif).
.
6.
.
, setFileSelectionMode ()
: JFileChooser .FILES_ONLY ( ), JFileChooser.
DIRECTORIES_ONLY JFileChooser.FILES_AND_DIRECTORIES.
7. showOpenDialog ()
showSaveDialog ().
, .
int result = chooser.showOpenDialog(parent);

:
int result = chooser.showSaveDialog(parent)


, .. ,
, . showDialog ()
:
int result = chooser.showDialog(parent,

"Select");

,
,
.
: JFileChooser.APPR0VE_0PTI0N, JFileChooser. CANCEL_0PTI0N
JFileChooser.ERR0R_0PTI0N.

8. get
SelectedFile () getSelectedFiles ().
File .
, get Path (), .
String filename = chooser.getSelectedFile().getPath();

471

.
,
. ,
GIF. ,
, .gif. ,
, . ,
JPEG, .jpg
.jpeg.
: ,
, j a v a x .
swing, filechooser.FileFilter.
.
:
, , ,
.
. ,
FileFilter :
public boolean accept(File f );
public String getDescription();

,
. ,
.
! java.io FileFilter (
).
boolean accept (File f ) . listFiles ()
File , . ,
Swing . ,
Java ,
!
java.io j avax. swing,
filterchooser, - .
javax. swing, filechooser . * javax. swing, filechooser.
FileFilter.

,
setFileFilter () JFileChooser,
:
chooser.setFileFilter(new FileNameExtensionFilter("Image files", "gif", "jpg");


:
chooser.addChoosableFileFilter(filterl);
chooser.addChoosableFileFilter(filter2) ;


.
All files ( ). , ,

472

9 Swing

.
All files, :
chooser.setAcceptAUFileFilterUsed (false)

!
, chooser.resetChoosableFilters (),
.

, ,
.
, FileView j a v a x . swing,
filechooser. .
,
.
,
.
FileView ,
set FileView (),
.
Icon getIcon(File f);
String getName(File f ) ;
String getDescription(File f );
String getTypeDescription(File f ) ;
Boolean isTraversable(File f );


. null
, ,
, . ,
.
, , ,
isTraversable (). ,
, , Boolean,
boolean! , . ,
,
null.
, . ,
Boolean, :
(Boolean.TRUE), (Boolean.FALSE) (null).
, ,
.
, .
, .
class FilelconView extends FileView

{
public FilelconView(FileFilter aFilter,

{
filter = aFilter;
icon = anlcon;

Icon anlcon)

473

public Icon getIcon(File f)

{
if (!f .isDirectory() && filter.accept(f))
return icon;
else return null;

}
private FileFilter filter;
private Icon icon;

}
,
setFileView ():
chooser.setFileView(new FilelconView(filter,
new Imagelcon("palette.gif") ) ) ;


,
, . ,
,
.
. demo/jfc/FileChooserDemo JDK
ExampleFileView.
.

,
. . 9.41 ,

, .

Look 1
%

( Im ageView er

Cay.gif
Tower.gif

File Nam e:

Tower.gif

F lie s of Type:

Im age fifes

. 9.1.

474

9 Swing


Swing. JLabel,
, ,
.
class ImagePreviewer extends JLabel

{
public ImagePreviewer(JFileChooser chooser)

{
setPreferredSize(new Dimension(100, 100));
setBorder(BorderFactory.createEtchedBorder());

}
public void loadlmage(File f)

{
Imagelcon icon = new Imagelcon(f.getPath());
if (icon.getlconWidth () > getWidthO)
icon = new Imagelcon(icon.getlmage().getScaledlnstance(
g e t W i d t h O , -1, Image.SCALE_DEFAULT));
setlcon(icon);
repaint();

}
}
.
,
.
JavaBeans,
. ,
PropertyChangeListener.
8 .
,
, .
chooser.addPropertyChangeListener(new
PropertyChangeListener()

{
public void propertyChange(PropertyChangeEvent event)

{
if

(event.getPropertyName() ==
JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)

{
File newFile = (File) event.getNewValue();
//

}
}) ;

ImagePreviewer.
9.21-9.23.
ImageViewer 2,

.

9.21. file C h o o s e r /Im a g e V ie w e r F r a m e . ja v a


1
2
3
4
5
6
7

package fileChooser;
import
import
import
import

java.awt.event.*;
java.io.*;
javax.swing.*;
javax.swing.filechooser.*;

8 /**
9

* .

10 * /
11 public class ImageViewerFrame extends JFrame
12 {
13
private static final int DEFAULT_WIDTH= 300;
14
private static final intDEFAULT_HEIGHT = 400;
15
private JLabel label;
16
private JFileChooser chooser;
17
p u b lic ImageViewerFrame()
18
19
setSize(DEFAULT WIDTH, DEFAULT HEIGHT);
20
21
22

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

/ /
JMenuBar menuBar = new JMenuBarO;
setJMenuBar(menuBar) ;
JMenu menu = new JM e n u ("F ile ") ;
menuBar. add(menu);
JMenuItem openltem = new JMenuItem("Open");
menu.add(openItern);
openltem.addActionListener(new ActionListener()

p u b lic void actionPerform ed(A ctionEvent event)


c h o o se r. setC urrentD irectory(new F i l e ( " . " ) ) ;
/ /
in t r e s u lt = c h o o se r. showOpenDialog(Im ageView erFram e.this);
/ / ,
/ /
i f ( r e s u lt == JF ile C h o o se r. APPROVE_OPTION)
S tr in g name = c h o o se r. g e t S e le c t e d F il e ( ) .g e tP a th ( ) ;
l a b e l . setlcon(new Im agelcon(nam e)) ;
pack ();

}) ;
JMenuItem e x itlte m = new JMenuItem(" E x i t " ) ;
m en u .ad d (ex itltem );
ex itltem .ad d A ctio n L isten er(n ew A c tio n L iste n e r ()
p u b lic void actionPerform ed(A ctionEvent event)

475

476

9 Swing
*

56
57
58
59
60
61
62
63
64
65

System.exit(0);
}
});
//
label = new JLabelO;
add(label);
//
chooser = new JFileChooser ();

66
67

// .jpg/ .jpeg/ .gif

68

/*

69
70
71
72
73
74
75
76
77
78
79
81
82
81
82
}
83 }

final ExtensionFileFilter filter = new ExtensionFileFilter();


filter.addExtension("jpg);
filter.addExtension("jpeg");
filter.addExtension("gif") ;
filter.setDescription("Image files");
*/
FileNameExtensionFilter filter =
new FileNameExtensionFilter("Image files", "jpg", "jpeg", "gif");
chooser.setFileFilter(filter);
chooser.setAccessory(new ImagePreviewer(chooser));
chooser.setFileView(new FilelconView(filter,
new Imagelcon("palette.gif")));

9.22. fileChooser/ImagePreviewer.java 1
1
2
3
4
5
6
7

package fileChooser;
import
import
import
import

java.awt.*;
java.beans.*;
java.io.*;
javax.swing.*;

8 /**
9
*
10 *
U */
12 public class ImagePreviewer extends JLabel
13 {
14
/**
15
* ImagePreviewer
16
* @param chooser ,
17
*
18
*
19
*/
20
public ImagePreviewer(JFileChooser chooser)
21
{
22
setPreferredSize(new Dimension(100, 100));
23
setBorder(BorderFactory.createEtchedBorder());
24


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

chooser.addPropertyChangeListener(new PropertyChangeListener()

{
public void propertyChange(PropertyChangeEvent event)

{
if (event.getPropertyName() ==
JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)

{
//
File f = (File) event.getNewValue();
if (f == null)

{
setlcon(null);
return;

}
//
Imagelcon icon = new ImageIcon(f.getPath ());
// ,,
if (icon.getlconWidth () > getWidthO) icon =
new Imagelcon(icon.getImage()
.getScaledlnstance(getWidth(), -1, Image.SCALE_DEFAULT));
setlcon(icon);

}
}
});

9.23. fileChooser/FilelconView. java1


1
2
3
4
5
6
7

package fileChooser;
import
import
import
import

java.io.*;
javax.swing.*;
javax.swing.filechooser.*;
javax.swing.filechooser.FileFilter;

8 /**'
9
*
10 *
11 */
12 public class FilelconView extends FileView
13 {
14
private FileFilter filter;
15
private Icon icon;
16
17
/**
18
* FilelconView
19
* @param aFilter .
20
*

21
* @param anlcon ,
22
*

23
*/
24
public FilelconView(FileFilter aFilter, Icon anlcon)
25
{

477

478

9 Swing

26
filter = aFilter;
27
icon = anlcon;
28
}
29
30
public Icon getIcon(File f)
31
{
32
if (!f .isDirectory() && filter.accept (f)) return icon;
33
else return null;
34
}
35 }

ja v a x .s w in g .J F ile C h o o s e r 1 . 2 *

JFileChooser()

, .

void setCurrentDirectory(File dir)

,
.

void setSelectedFile(File f i l e )

void setSelectedFiles(File[] f i l e )

, .

void setMultiSelectionEnabled(boolean b)

void setFileSelectionMode(int mode)

( ),
. mode : JFileChooser.FILES_ONLY,
JFileChooser.DIRECTORIES_ONJjY

JFileChooser.FILES_AND_DIRECTORIES.

int showOpenDialog(Component p a r e n t)

int showSaveDialog(Component p a r e n t)

int showDialog(Component p a r e n t ,

String ap p ro v eB u tto n T ex t)

, Open,
Save , a p p r o v e B u t t o n T e x t .
: a p p r o v e _ o p t i o n , c a n c e l _ o p t i o n (
C ancel )
).

File getSelectedFile()

File[]

e r r o r _o p t i o n

getSelectedFiles()

, ,
, null.

void setFileFilter(FileFilter f i l t e r )

.
, filter.accept () true.
, .

479

void addChoosableFileFilter(FileFilter f i l t e r )

void setAcceptAUFileFilterUsed (boolean b)


.
*

void resetChoosableFileFilters()

, ,
.

void setFileView(FileView view)

,
.

void setAccessory(JComponent component)

j a v a x . s w in g . f i l e c h o o s e r . F i l e F i l t e r

1 .2

boolean accept(File f)

true,
.

String getDescription()

, "Image
( *.gif * . jpeg).

files

(*
.gif,

*.jpeg)"

j a v a x . s w in g . f i l e c h o o s e r . F ile N a m e E x t e n s io n F ilt e r 6

FileNameExtensionFilter(String description,

String

.. . e x te n s io n s )

, ,

.

j a v a x . s w in g . f i l e c h o o s e r . F ile V ie w

1 .2

String getName(File f)

f null.
f .getName ().

String getDescription(File f)

f null. , f
HTML-, .

480

9 Swing

String getTypeDescription(File f )

null. ,

HTML-,

"Hypertext document".
Icon getIcon(File f )

f,

null. ,

f JPEG,

Boolean isTraversable(File f )

, Boolean.
TRUE. ,
Boolean.FALSE. FileView,

null, ,
, .


,
,
.

, , , .. :
,
.
Swing, ,
, .
JColorChooser.
. 9.42-9.44. JFileChooser,
JColorChooser , .
,
.
:
Color selectedColor = JColorChooser.showDialog(parent,title,

initialColor);

.
.

.
,
.

.
0 Cancel ( null,
).

Set bat : k t | i

ouik

\ rgb

_ 1_ 11 ^ .. 1 .1 .1. . . . .].:1 i i 1 i i i i

jj

R
e
c
e
n
t:

i m m

11 1 I I 1 1 1 1 1 11
ii i
i !
^ . -1 U M i l l 1 1 B fljjj
iiiiM M iiia j j j j j
BflflBBBBBflflBBBBBBBBflflflflflflflflflflflflfl j j j j j

J a m m iim m iia

a _U
_U
_J

a _ I_ U _ U

Preview

OK

Cancel
^ |||^^>;

. 9.42. Swatches ( )

Set

backg ro u n d

(Swatches

jf HS8 'RGB 1 ......,.................., ....................... ..., J

<T\

19 9

10 0

A.

*
*
*

Preview

OK

Cancel

VBfiiSii*

lesei

. 9.43. HSB (- -)

481

482

9 Swing
>< < k 1 )i < I

Sw atcties

#SB

Reg

Green

,<

1
A

> |

0 5

'

'

<

lin e

i i

102

i
z j

2 5 5

<

l l

< j

>

1 7 0

204

A
it.

:
.

2 5 5

J /,

255
---------- T *

. A -'.

Preview

Sample xi Sample

Samote Text Sample Text

. 9 M . RGB ( - - )

,
.
.
chooser = new JColorChooser ();
dialog = JColorChooser.createDialog(
parent,
"Background Color",
false /* */,
chooser,
new ActionListener() // OK

{
public void actionPerformed(ActionEvent event)

{
},

setBackground(chooser.getColor());

null /* Cancel */) ;


.
, .
chooser.getSelectionModei().addChangeListener(new
ChangeListener()

public void stateChanged(ChangeEvent event)

{
}

chooser .getColor () ;

483

Cancel .

:
dialog = new JDialog(parent,
dialog.add(chooser);
dialog.pack();

false /* */);

, 9.24,
. Modal,
, ,
- . Modeless,
,
.
Immediate, .
, .
9.24. colorChooser/ColorChooserPanel. java *
1

1
2
3
4
5
6
7

package colorChooser;

/**

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

import
import
import
import

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

*
*
*/

public class ColorChooserPanel extends JPanel


{
public ColorChooserPanel ()
{
JButton modalButton = new JButton("Modal");
modalButton.addActionListener(new ModalListener ());
add(modalButton);
JButton modelessButton = new JButton("Modeless");
modelessButton.addActionListener(new ModelessListener());
add(modelessButton);
JButton immediateButton = new JButton("Immediate");
immediateButton.addActionListener(new ImmediateListener());
add(immediateButton);
}
/**
*
*
*/
private class ModalListener implements ActionListener
{
public void actionPerformed(ActionEventevent)
{
Color defaultColor = getBackground();

9 Swing
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
56
57
58
59
60
61
62
63
64
65

Color selected = JColorChooser.showDialog(


ColorChooserPanel.this, "Set background, defaultColor);
if (selected != null) setBackground(selected);

}
}
j
*
* . ,
*

*/
private class ModelessListener implements ActionListener

{
private JDialog dialog;
private JColorChooser chooser;
public ModelessListener()

{
chooser = new JColorChooser();
dialog = JColorChooser.createDialog(
ColorChooserPanel.this, "Background Color",
false /* */, chooser,
new ActionListener() // OK
{
public void actionPerformed(ActionEvent event)

{
setBackground(chooser.getColor());

}
}, null /* Cancel */);

66
67

68

public void actionPerformed(ActionEvent event)

69
70
71
72
73
74
75
76

{
chooser.setColor(getBackground());
dialog.setVisible(true);

}
}
j
*
* . ,
* ,

V
78
79
80
81
82
83
84

*/
private class ImmediateListener implements ActionListener

{
private JDialog dialog;
private JColorChooser chooser;
public ImmediateListener()

{
chooser = new JColorChooser ();
chooser.getSelectionModel().addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent event)

{
setBackground(chooser.getColor());


94
95
96
97
98
99
100
101
102
103
104
105
102

485

}) ;
dialog = new JDialog((Frame) null, false /* */);
dialog.add(chooser);
dialog.pack();
}
public void actionPerformed(ActionEvent event)
{

chooser.setColor(getBackground());
dialog.setVisible(true);
}
}

j a v a x . s w in g . J C o lo r C h o o s e r 1 . 2

JColorChooser()

, .

Color getColor()

void setColor(Color c)

static Color showDialog(Component p a r e n t , String t i t l e ,

Color i n i t i a l C o l o r )

, .
:

p aren t

title

in itia lC o lo r

static

m odal,

JDialog

createDialog(Component

JColorChooser

c h o o se r ,

p a re n t,

ActionListener

String

o k L is t e n e r ,

title ,

boolean

ActionListener

c a n c e lL is t e n e r )

, .
V

p aren t

title

modal

true,

,

c h o o se r
o k L is t e n e r

c a n c e l L is t e n e r Cancel

486

9 Swing

. 7-9
Swing.
Swing
.

...



AWT

.
,
Java. ,
Java AWT. ,
.
, ,
.


, ,
, ,
, ,
. , Visual Basic,
: ,
, .
, HelpButton Visual Basic
HelpButton Click.
Visual Basic ,
.

488

, , , ,
, ,
, . (

switch.) , ,
.
: , Visual Basic,
.
, Java,
, Visual Basic . . ,
AWT,
(, )
. .
,
.
Visual Basic, .
,
. ,
. -
, Java,
. Java , java.
util.EventObject. , ,
ActionEvent WindowEvent.
. ,
ActionEvent, WindowEvent.
AWT
.

,
, () .

,
.


.
, ,
, .

. 8.1
. ,
.
ActionListener listener = . . ./
JButton button = new JButton("Ok");
button.addActionListener(listener);

489

. 8.1.

listener " " .


, ,
. ActionListener,
actionPerformed,
ActionEvent, .
class MyListener implements ActionListener

public void actionPerformed (ActionEvent event)

{
// ,

, JButton
ActionEvent listener .actionPerformed (event),
. .
JButton actionPerformed ()
. . 8.2
, .



, ,
. , ,
,
.
, -
, ,
ActionEvent, .
, ,
.

490

. 8.2.

,
, ,
. ( 9.)
,
, .
.
JButton yellowButton = new JButton("Yellow");
JButton blueButton = new JButton(new Imagelcon("blue-ball.gif"));

add (), :
JButton yellowButton = new JButton("Yellow");
JButton blueButton new JButton ("Blue");
JButton redButton = new JButton("Red");
buttonPanel.add(yellowButton);
buttonPanel.add(blueButton);
buttonPanel.add(redButton);

. 8.3.


But tonlest

491

_ X

. 8 .3 . ,

, .
, A c t i o n L i s t e n e r , , ,
a c t i o n P e r f o r m e d ().
:
public void actionPerformed(ActionEvent even t)

! ActionListener, ,
. ,
.

<Enter>, .

, Timer.

.
ActionListener :
actionPerformed () ActionListener
ActionEvent.
.

, .
:
class ColorAction implements ActionListener
{
private Color backgroundColor;
public ColorAction(Color c)

{
backgroundColor = c;

}
public void actionPerformed(ActionEvent event)

{
//

492

.
:
ColorAction yellowAction = new ColorAction(Color.YELLOW);
ColorAction blueAction = new ColorAction(Color.BLUE);
ColorAction redAction = new ColorAction(Color.RED) ;
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);

, Y e l l o w ,
a c t i o n P e r f o r m e d () y e l l o w A c t i o n . b a c k g r o u n d C o l o r
C o l o r .YELLOW,
( ) .
. C o l o r A c t i o n
b u t t o n P a n e l .
. , b u t t o n P a n e l
C o l o r A c t i o n . C o l o r A c t i o n
B u t t o n F r a m e .
. ( . 6.)
. , C o l o r A c t i o n
B u t t o n F r a m e .
class ButtonFrame extends JFrame

{
private JPane.l buttonPanel;

private class ColorAction implements ActionListener


{
private Color backgroundColor;

public void actionPerformed(ActionEvent event)

{
buttonPanel.setBackground(backgroundColor);

}
}
}
a c t i o n P e r f o r m e d () .
, b u t t o n P a n e l C o l o r A c t i o n ,
B u t t o n F r a m e . .
,
.
,
.
8.1 ,
. - ,
.
8.1. b u t t o n / B u t t o n F r a m e . j a v a
1
2
3

package button;
import java.awt.*;


4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

import j ava.awt.event.*;
import ja v a x .s w i n g . *;
/**
*
*/
public class ButtonFrame extends JFrame

private JPanel buttonPanel;


private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public ButtonFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
//
JButton yellowButton = new JButton("Yellow);
JButton blueButton = new JButton("Blue");
JButton redButton = new JButton("Red");
buttonPanel = new JPanel ();
//
buttonPanel.add(yellowButton);
b utto n P an el .add (blu eB u tton ) ;
buttonPanel.add(redButton);
//
add(buttonPanel);
//
ColorAction yellowAction = new ColorAction(Color.YELLOW);
ColorAction blueAction = new ColorAction(Color.BLUE);
ColorAction redAction = new ColorAction(Color.RED);
//
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);
}
/**
* , .
*/

p r i v a t e c l a s s ColorAction implements A c tio n L isten e r


{

p r i v a t e Color backgroundColor;
p u b lic ColorAction(Color c)
{

backgroundColor = c;
}
public voidactionPerformed(ActionEvent event)
{

493

494
60
61
62

8
buttonPanel.setBackground(backgroundColor);
}

63 }

ja v a x .s w in g .J B u tto n

1 .2

JButton(String label)

JButton(Icon icon)

JButton(String label,

Icon icon)

. , , ,
Java SE 1.3 - HTML-, <h t m l x b >o k </b

/h t m l >.

ja v a .a w t.C o n ta in e r 1 .0

Component add(Component c)


, ,
.
.
.
. ,
. .
.
i f / e l s e ,
, , .
,
. 8.1.
, ?
.
1. .
2. .
3. , .
4. .
,
:
public void makeButton(String name, Color backgroundColor)

JButton button = new JButton(name);

495

buttonPanel.add(button);
ColorAction action = new ColorAction(backgroundColor);
button.addActionListener(action);

}
:
makeButton("yellow", Color.YELLOW);
makeButton("blue", Color.BLUE);
makeButton("red", Color.RED);

.
, C o l o rAction : m a k e B u t t o n ().
, , .
public void makeButton(String name,

final Color backgroundColor)

{
JButton button * new JButton(name);
buttonPanel.add(button);
button.addActionListener(new ActionListener()

{
public void actionPerformed(ActionEvent event)

{
buttonPanel.setBackground(backgroundColor);

}
});

. actionPerformed ()
backgroundColor. ( ,
, .)
. 6,
,
, .
. , .
, ,
, ,
button. addActionListener (new ActionListener ()

{
public void actionPerformed(ActionEvent event)

{
buttonPanel.aatBackground (backgroundColor);

}
});
, .
, ,
, .

! ,
ActionListener, .
,
. ,
, ,
ActionListener.
:

496


yellowButton.addActionListener(this);
blueButton.addActionListener(this);
redButton.addActionListener(this);

.
. , actionPerformedO
, :
class ButtonFrame extends JFrame implements ActionListener
{
public void actionPerfozmed (ActionEvent event)

{
Object source = event.getSource();
if (source == yellowButton) . . .
else if (source == blueButton) . . .
else if (source == redButton ) . . .
else . . .

}
}
, , .

j a v a . u t i l . E v e n t O b je c t 1 . 1

Object getSource()

, .

ja v a .a w t . e v e n t. A c tio n E v e n t 1 .1

String getActionCommand()

, .
, , ,
setActionCommand ().



. , Load (),
:
frame.loadData();

,
:
loadButton.addActionListener(new ActionListener()

{
public void actionPerformed(ActionEvent event)

{
frame.loadData();

})

497

EventHandler
:
EventHandler.create(ActionListener.class,

frame,

"loadData")

, , .
loadButton.addActionListener(
EventHandler.create(ActionListener.class,

frame,

"loadData"));

,
, create ()
. , :
EventHandler.create(ActionListener.class,

frame,

"loadData",

"source.text")

:
new ActionListener()

{
public void actionPerformed(ActionEvent event)

{
frame.loadData (((JTextField) event.getSource ()) .getText ());

}
}
source text getSource ()
getText().

! EventHandler.create ()
.
.

j a v a , b e a n s . E v e n t H a n d le r 1 . 4
static

Object

create (Class

liste n e r In te r fa c e ,

Object

ta rg e t,

String

Object

create(Class

liste n e r In te r fa c e ,

Object

ta rg e t,

String

liste n e r In te r fa c e ,

Object

ta rg e t,

String

a c t io n )
static

a c t i o n , String e v e n t P ro p e rty )
create (Class

static

Object

a c t io n ,

String e v e n t P ro p e rty ,

String liste n e rM e th o d )

-, .
.
. ,
. , action text,
setText ( ) .
, .
,
.. , source.text
getSource () getText ().

498


Swing- Metal.
. j r e / l i b
sw in g .p ro p e r tie s s w in g .d e fa u lt la f
, :
wing.defaultlaf=com.sun.java.swing.plaf.motif.MotifLookAndFeel

, Metal ja v a x . swing,
com.sun. jav a .
Java. ,
,
Windows Mac OS ,
.
. , #, , ,
. s w in g .p r o p e r tie s
, # :
#swing.defaultlafjavax.swing.plaf.metal.MetalLookAndFeel
swing.defaultlafcom.sun.java.swing.plaf.motif.MotifLookAndFeel
#swing.defaultlaf-com.sun.java.swing.plaf.windows.WindowsLookAndFeel

Swing-,
. s w in g .p r o p e r tie s
.

.
UIManager.setLookAndFeel (),
. S w i n g U t i l i t i e s .
updateComponentTreeUI (),
. ,
.
, UIManager.setLookAndFeel ()
.
, .
, Motif
.
String plaf * "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
try

{
UIManager.setLookAndFeel(plaf);
SwingUtilities.updateComponentTreeUI(panel);

}
catch(Exception e) { e.printStackTrace(); }

,
:
UIManager.LookAndFeellnfo[] infos UIManager.getlnstalledLookAndFeels();

,
.

499

String name = infos[i].getName();


String className = infos[i].getClassName();

8.2 ,
(. 8.4).
8.1.
makeButton () ,
, .
! I ,111 \

_ X

. 8 .4 .

8.2. p l a f / P l a f F r a m e . j a v a 1
1
2
3
4
5

package plaf;
import java.awt.event.*;
import javax.swing.*;

6 /**
8

*
V

public class PlafFrame extends JFrame

10 {
11
12
13
14
15
16
17
18
19
20

private JPanel buttonPanel;


public PlafFrame()
{
buttonPanel * new JPanel ();

UIManager .LookAndFeellnfo [] in fo s - U IM anager.getlnstalledLookA ndFeels ();


fo r (UIManager.LookAndFeellnfo in fo : in fo s)
makeButton(info.getName(), info.getClassName());
add(buttonPanel);

21 * p a c k ();
22

500

23
I --
24
25
*
26
* @param name
27
* @param plafName
28
*/
29
void makeButton(String name, final String plafName)
30
{
31
//.
32
33
JButton button = new JButton(name);
34
buttonPanel.add(button);
35
36
//
37
38
button.addActionListener(new ActionListener()
39
{
40
public void actionPerformed(ActionEvent event)
41
{
42
// :
43
try
44
{
45
UIManager.setLookAndFeel(plafName);
46
SwingUtilities.updateComponentTreeUI(PlafFrame.this);
47
pack();
48
}
49
catch (Exception e)
50
{
51
e .printStackTrace ();
52
}
53
}
54
}) ;
55
}
56 }

.
actionPerformed ()
updateComponentTreeUI () this Plaf Panel.
6, this
:
SwingUtilities.updateComponentTreeUI(PlafPanel.this);

j a v a x . s w in g . U IM a n a g e r 1 . 2

static UIManager.LookAndFeelInfo[] getlnstalledLookAndFeels()

, .

static setLookAndFeel(String classN am e)

, (, "javax.swing,
plaf .metal .MetalLookAndFeel").

501

j a v a x . s w in g . U IM a n a g e r . L o o k A n d F e e lln f 1 . 2

String getName()

String getClassName()

, .


, .
,
, ,
. ,
,

.
, J F r a m e
W in d o w E v e n t. ,
,
:
WindowListener listener = . . .;
frame.addWindowListener(listener);

,
W in d o w L is t e n e r . W i n d o w L i s t e n e r .
, .
. i c o n i f i e d ,
Windows "" . ,
W in d o w L is t e n e r .
public interface WindowListener

{
void
void
void
void
void
void
void

windowOpened(WindowEvent e ) ;
windowclosing(WindowEvent e ) ;
windowClosed(WindowEvent e ) ;
windowlconified(WindowEvent e ) ;
windowDeiconified(WindowEvent e) ;
windowActivated(WindowEvent e ) ;
windowDeactivated(WindowEvent e ) ;

}
! , ,
WindowStateListener.
API.

, , - ,
. .
w i n d o w c l o s i n g (). ,
, W in d o w L is t e n e r ,

502

windowclosing () System.exit (0),


, .
class Terminator implements WindowListener
{
public void windowclosing(WindowEvent e)

{
if ( )
System.exit(0);

}
public
public
public
public
public
public

void
void
void
void
void
void

windowOpened(WindowEvent e) {}
windowClosed(WindowEvent e) {}
windowlconified(WindowEvent e) {}
windowDeiconified(WindowEvent e) {}
windowActivated(WindowEvent e) {}
windowDeactivated(WindowEvent e) {}

}
, ,
. ,
AWT, , ,
, . , WindowAdapter
, . ,
,
.
, . (
, ActionListener ,
.)
. WindowAdapter
,
windowclosing () :
class Terminator extends WindowAdapter

{
public void windowclosing(WindowEvent^e)

{
i f ( )
System.exit (0);

}
Terminator
, .
WindowListener listener = new Terminator();
frame.addWindowListener(listener);

,
( listener) (. 8.5).
, windowclosing ()
System.exit (0), .

503

dWindowUstener

windowClosing

windowdosed

. 8.5.
! , , ,
. , windowisClosingO ,
WindowAdapter, , ,
windowclosing .

, WindowAdapter,
, .
, :
frame.addWindowListener(new Terminator());

!
:
frame.addWindowListener(new
WindowAdapter()

{
public void windowclosing(WindowEvent e)

504

{
if ( )
System.exit(0);

}
});
.

,
WindowAdapter.

windowclosing () .
, .

WindowAdapter ,
.

. .

addWindowListener () .

,
.
.
j a v a . a w t . e v e n t . W in d o w L is t e n e r 1 . 1
............................................................-

............... - ........................... ... -

...............

................................

.........................

void windowOpened(WindowEvent e)

void windowclosing(WindowEvent e)

, .
, , hide ()
dispose ().

void windowClosed(WindowEvent )

void windowlconified(WindowEvent )

void windowDeiconified(WindowEvent e)

void windowActivated(WindowEvent e)

.
. , ,
.

void windowDeactivated (WindowEvent )

, .

505

j a v a . a w t . e v e n t . W in d o w s t a t e L i s t e n e r 1 . 4

void windowStateChanged(WindowEvent ev en t)

, ,
.

j a v a .a w t .e v e n t .W in d o w E v e n t 1 . 1

int getNewState() 1.4

int getOldState() 1.4

,
. :
Frame.NORMAL
Frame.ICONIFIED
Frame.MAXIMIZED_HORIZ
Frame.MAXIMIZED_VERT
Frame .MAXIMIZED_B0TH

. ,
,
.
AWT:
. , blueAction
, actionPerf ormed ()
. ,
.

Blue () .

Blue.

<Ctrl+B>.

, , , ,
,
. Swing
,
. Action.
, .

( ).

, (
).

506

A c tio n

void actionPerformed(ActionEvent event)


void setEnabled(boolean b)
boolean isEnabledO
void putValue(String key, Object value)
Object getValue(String key)
void addPropertyChangeListener(PropertyChangeListener listener)
void removePropertyChangeListener(PropertyChangeListener listener)

A c t i o n L i s t e n e r .
A c t i o n A c t i o n L i s t e n e r .
, , A c t i o n L i s t e n e r ,
, A c t i o n .
,
, .
,
- .
p u t V a l u e () g e t V a l u e ()
"-" ,
A c t i o n . , A c tio n .N A M E A c t i o n . SMALL_
ICON
:
action.putValue(Action.NAME, "Blue");
action.putValue(Action.SMALL_ICON, new Imagelcon("blue-ball.gif"));

. 8.1 .
8.1.

NAME

S M A L L _ IC O N

, ,

S H O R T _ D E S C R IP T IO N

L O N G _ D E S C R IP T IO N

.
.
Swing

M N E M O N IC _K E Y

. (. 9)

A C C E L E R A T O R _K E Y

.
Swing

A C T I0 N _ C 0 M M A N D _ K E Y


r e g i s t e r e d K e y B o a r d A c t i o n ()

DEFAULT

.
Swing

- ,

. SHORT DESCRIPTION .

507

A c t i o n
, , ,
. ,
,
-
. ,
JavaBeans. JavaBeans
.
, , , A c t i o n , .
, ,
. , , ,
, A b s t r a c t A c t i o n ,
"-",
.
a c t i o n P e r f o r m e d ( ) .
, .
,
. , "-
", A b s t r a c t A c t i o n .
C o l o r A c t i o n , .
"-", A c t i o n P e r f o rm ed () .
public class ColorAction extends AbstractAction

{
public ColorAction(String name,

Icon icon, Color c)

{
putValue(Action.NAME, name);
putValue(Action.SMALL_IC0N, icon);
putValue("color", c ) ;
putValue(Action.SH0RT_DESCRIPTI0N, "Set panel color to " +
n a m e .toLowerCase()) ;

}
public void actionPerformed(ActionEvent event)

{
Color c = (Color) getValue("color");
buttonPanel.setBackground(c);

}
, ,
:
Action blueAction = new ColorAction("Blue", new Imagelcon("blue-ball.gif"), Color.BLUE);

.
J B u t t o n ,
C o l o r A c t i o n , .
JButton blueButton = new JButton(blueAction);

,
C o l o r A c t i o n
.
. 8.6. ,
.

508

. 8 .6 .

, , ,
, .
, Keystroke.
, :
Keystroke ctrlBKey = Keystroke.getKeyStroke("Ctrl ");

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

<>. , ,
, . ;
, .
,
.
, , <Ctrl+Y>,
<Ctrl+B> <Ctrl+R>.
, Swing
. JComponent
, Keystroke .
, . 8.2.
8.2.

WHEN_FOCUSED

WHEN_ANCE ST0R_0F_F0CU SE D_COMPNENT

HEN IN FOCUSED WINDOW

,
,

. ..

509

*.

.
1. WHEN FOCUSED ,
. ,
. ,
.
2. , ,
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
. ,
. ,
.
3. , ,

WHEN_IN_FOCUSED_WINDOW. (
)
. ,
.
WHEN IN FOCUSED WINDOW,
.
getlnputMap ()
:
InputMap imap = panel.getlnputMap(JComponent.WHEN_FOCUSED);

WHEN FOCUSED , ,
. ,
, .

.
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT.
InputMap Keystroke
ColorAction, Action.
, ,
ActionMap, .
,
.
,
. ,
. ,
.
imap.put(Keystroke.getKeyStroke("Ctrl Y"), "panel.yellow");
ActionMap amap = p anel.getActionMap();
amap.put("panel.yellow", yellowAction);

,
"" ().
, .
imap.put(Keystroke.getKeyStroke ("Ctrl C") , "none");

510

! JDK ,
. .
, . ,
,
. ,
.

, ,
, .
1. , A b s t r a c t A c t i o n .
.
2. .
3. .
.
4. , ,
.

, ,
, .


COMPONENT .

, , ,
, .

( , ) .

, ,
( , )
.

K e y str o k e

W HEN_ANCESTOR_OF_FOCUSED_

8.3 ,
, .
<Ctrl+Y>, <Ctrl+B> <Ctrl+R>.
8.3. action/ActionFrame. java 1
1

package a ctio n ;

3
4
5
6
7
8
9

import ja v a .a w t.*;
import j a v a .awt.e ve n t.*;
import ja v a x .sw in g .*;

/**'
*
*/

10 p u b lic

11

c la s s ActionFrame extends JFrame

12

p r iv a te

JPanel buttonPanel;

13

p r iv a t e

s t a t ic

fin a l

in t

DEFAULT_WIDTH = 300;

14

p r iv a t e

s t a t ic

fin a l

in t

DEFAULT_HEIGHT = 200;

15


16
17
18
19
20

511

public ActionFrame()

{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
buttonPanel = new JPanelO;

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

//
Action yellowAction = new ColorAction("Yellow",
new Imagelcon("yellow-ball.gif"), Color.YELLOW);
Action blueAction = new ColorAction("Blue",
new Imagelcon("blue-ball.gif"), Color.BLUE);
Action redAction = new ColorAction("Red",
new Imagelcon("red-ball.gif"), Color.RED);
//
buttonPanel.add(new JButton(yellowAction));
buttonPanel.add(new JButton(blueAction));
buttonPanel.add(new JButton(redAction));
//
add(buttonPanel);

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

// <Y>, <>, <R>


InputMap imap =
buttonPanel.getlnputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
imap.put(Keystroke.getKeyStroke ("Ctrl Y"), "panel.yellow");
imap.put(Keystroke.getKeyStroke("Ctrl B"), "panel.blue");
imap.put(Keystroke.getKeyStroke ("Ctrl R"), "panel.red");
//
ActionMap amap = buttonPanel.getActionMap ();
amap.put("panel.yellow", yellowAction);
amap.put("panel.blue", blueAction);
amap.put("panel.red", redAction);

}
public class ColorAction extends AbstractAction

/**
*
* Qparam name
* param icon
* @param
*/
public ColorAction(String name, Icon icon, Color fc)

{
putValue(Action.NAME, name);
putValue(Action.SMALL_ICON, icon);
putValue(Action.SHORT_DESCRIPTION, "Set panel color to " +
name.toLowerCase());
putValue("color", c);

66

67

68

69
70
71
72
73
74

public void actionPerformed(ActionEvent event)

{
Color c = (Color) getValue("color");
buttonPanel.setBackground(c);

512

j a v a x . s w in g . A c t i o n

1 .2

boolean isEnabledO

void setEnabled(boolean b)

enabled .

void putValue(String k ey , Object v a lu e )

-" .
:

k ey

, .
,
(. . 8.1)

v a lu e

Object getValue(String key)

-.

j a v a x . s w in g . K e y s t r o k e

1 .2

static Keystroke getKeyStroke(String d e s c r ip t io n )

Keystroke (
, ).
shift control Ctrl meta alt altGraf
typed (, "typed ")
( pressed released) .
, VK_, KeyEvent; ,
<INSERT> KeyEvent.VK_INSERT.

j a v a x . s w in g . J C o m p o n e n t 1 . 2

ActionMap getActionMap () 1.3

, ,
, , Action.

InputMap getlnputMap(int f l a g )

1.3

, .
:

fla g

,
(. . 8.2)

513



,
.
.
, , ,
.
,
, (. 8.7).

. 8 .7 . ,

,
: m o u s e P r e s s e d (), ;
mouseReleasedO, ; mouseClickedO,
. ,
. getx () getY () MouseEvent,
,
.
(!), getClickCount ( ) .

,
, <Control+Shift+n^40K> .
, ,
,
.
. API
, ,
:
BUTT0N2_MASK == ALT_MASK
BUTTON3_MASK == META_MASK

,
,
. Java SE 1.4 ,
:

514

BUTTONl_DOWN_MASK
BUTTON2_DOWN_MASK
BUTTON3_DOWN_MASK
SHIFT_DOWN_MASK
CTRL_DOWN_MASK
ALT_DOWN_MASK
ALT_GRAPH_DOWN_MASK
META_DOWN_MASK

getModifiersEx () ,
.
, BUTTON3__D0WN_MASK
Windows. , ,
, :
if ((event.getModifiersEx() & InputEvent.BUTT0N3_D0WN_MASK) != 0)
. . . // ,

, ,
mousePressed () m o u s e C l i c k e d (). ,
,
. mousePressed (),
,
. - .
m o u s e C l i c k e d (),
. .
public void mousePressed(MouseEvent event)

{
current = find(event.getPoint());
if (current == null) //
add(event.getPoint());

}
public void mouseClicked(MouseEvent event)

{
current = find(event.getPoint());
if (current != null && event.getClickCount() >= 2)
remove(current);

}

, .
MouseListener MouseMotionListener.
,
, .
,
( ),
. getPredefinedCursor ()
Cursor. . 8.3 , ,
Windows.

515

8.3.

DEFAULT_CURSOR

NE_RESIZE_CURSOR

CROSSHAIR_CURSOR

4*

E_RESIZE_CURSOR

SE_RESIZE_CURSOR

HAND_CURSOR

4+*

MOVE_CURSOR

S_RESIZE_CURSOR

1 1

TEXT_CURSOR

I
I

WAIT_CURSOR

<-

W_RESIZE_CURSOR

N_RESIZE_CURSOR

NW_RESIZE_CURSOR

SW_RESIZE_CURSOR

mouseMoved (),
MouseMotionListener
.
public void mouseMoved(MouseEvent event)

{
if (find(event.getPoint()) == null)
setCursor(Cursor.getDefaultCursor());
else
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));

}
! createCustomCursor () Toolkit,
:
Toolkit tk = Toolkit.getDefaultToolkit() ;
Image img = tk.getImage("dynamite.gif");
Cursor dynamiteCursor =
tk.createCustomCursor(img, new Point(10,

10),

"dynamite stick");

createCustomCursor () ,
,
, . ,
, , ,
.

,
mouseClicked () mouseDragged ().
. ,
, .
, .
mouseClicked().
public void mouseDragged(MouseEvent event)

{
if (current != null)

516

8
int = event.g e t X ();
int = event.getY();
current.setFrame(x - SIDELENGTH J 2,
- SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
repaint();

}
! mouseMoved () ,
. mouseDragged () ,
.

, : mouseEntered ()
mouseExited (). ,
.
, ,
. mousedicked(),
MouseListener.
, ,
, ,
MouseMotionListener.

.
: MouseHandler MouseMotionHandler. MouseHandler
MouseAdapter,
MouseListener. MouseMotionHandler
MouseMotionListener .
8.4 ( ) 8.5 ( ,
).
8.4. mouse/MouseFrame.java
1
2
3
4
5
6
7
8

package mouse;

10
11

import javax.swing.*;
/**
* , ,
*/
public class MouseFrame extends JFrame
public J^ouseFrame ()

12
add(new MouseComponent());
13
pack();
14
}
15 }

8.5. mouse/MouseComponent .java


1
2
3

package mouse;
import java.awt.*;


4
5
6
7
8

10
11
12
13
14
15
16
17
18
19

import
import
import
import

j *
*
*/
public class MouseComponent* extends JComponent

{
private static final int SIDELENGTH = 10;
private ArrayList<Rectangle2D> squares;
private Rectangle2D current;
public MouseComponent()

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

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

squares = new ArrayListo () ;


current = null;
addMouseListener(new MouseHandler());
addMouseMotionListener(new MouseMotionHandler());

}
public void paintComponent(Graphics g)

{
Graphics2D g2 = (Graphics2D) g;
//
for (Rectangle2D r : squares)
g 2 .draw(r);

}
j -k

* ,
* Oparam
* 0return ,

*/
public Rectangle2D find(Point2D )

{
for (Rectangle2D : squares)

{
if (r.contains(p)) return r;

}
return null;

}
j
*
* 0param

*/
public void add(Point2D )

{
double = p.getXO;
double = p.getYO;
current = new Rectangle2D.Double(x - SIDELENGTH / 2,
- SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
squares.add(current); '
repaint ();

517

518
62
63
64
65
66
67
68
69
70
71

12

8
}
/**
*
* s
*/
public void remove(Rectangle2D s)
{
if (s == null) return;
if (s == current) current = null;
squares.remove(s);
repaint();
}
// ,
private class MouseHandler extends MouseAdapter
{
public void mousePressed(MouseEvent event)
{
// ,
current = find(event.getPoint ());
if (current == null) add(event.getPoint ());
}
public void mouseClicked(MouseEvent event)
{
// ,
current = find(event.getPoint ());
if (current != null && event.getClickCount () >= 2) remove(current);
}
}

73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
private class MouseMotionHandler implements MouseMotionListener
93
{
94
public void mouseMoved(MouseEvent event)
95
{
96
// ,
97
//
98
if (find(event.getPoint ()) == null)
99
setCursor(Cursor.getDefaultCursor ());
100
else setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
100
}
101
102
public void mouseDragged(MouseEvent event)
103
{
104
if (current != null)
105
{
106
int x = event.getX () ;
107
int - event.getY();
108
109
// ,
110
/ / (, )
111
current.setFrame( - SIDELENGTH / 2,
112
- SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
113
repaint ;
114
}
113
}
114 }
115 }

519

ja v a .a w t . e v e n t. M o u s e E v e n t 1 .1

int getX()

int getY()

Point getPoint()
() ,
. ,
.

int getClickCount()
,
. ( , ,
.)

j a v a . a w t . e v e n t . In p u t E v e n t 1 . 1

int getModifiersEx()

1.4

.
.
BUTTONl_DOWN_MASK
BUTTON2_DOWN_MASK
BUTTON3_DOWN_MASK
SHIFT_DOWN_MASK
CTRL_DOWN_MASK
ALT_DOWN_MASK
ALT_GRAPH_DOWN_MASK
META_DOWN_MASK

static String getModifiersExText(int m o d ifie r s )

1.4

,
, "Shift+Buttonl".

ja v a .a w t .T o o lk it 1 .0

public Cursor createCustomCursor (Image im age, Point h o tS p o t, String name)

.
:

im age

h o tS p o t

(,
)

name

1.2

520

j a v a . a w t. C o m p o n en t 1 . 0

p u b lic

v o id

se tC u rso r(C u rso r

cursor)

1.1

AWT

AWT.
, Java -
. EventObject java,
util. ( Event,
.
, Java.)
EventObject AWTEvent,
AWV. . 8.8
AWT.
Swing
EventObject.
,
. ,
, getSource ()
getActionCommand().

AWT
Java. , PaintEvent
AWT ,
. paintComponent (),
. AWT ,
.
,
.
.


AWT .
, ,
ActionEvent .
.
, , , ,
(
).
, ,
<>.
,
.

AWT

521

. 8 .8 .
AWT

, j a v a . a w t. e v e n t
, .

A c tio n E v e n t ( , ,
, <Enter> ).

A d ju stm e n tE v e n t ( ).

Ite m E v e n t ( -,
).

522

KeyEvent ( ).

MouseEvent ( ,
, , ..
).

MouseWheelEvent ( ).

FocusEvent ( ).

WindowEvent ( ).

:
A c tio n L iste n e r
Adj us tmentLis tener
FocusListener
ItemListener
KeyListener

M ouseM otionListener
MouseW heelListener
WindowListener
W indowFocusListener
W indow StateListener

I^useListener

AWT, ,
, ,
. (
, .)
.
FocusAdapter

MouseMotionAdapter
WindowAdapter

KeyAdapter
MouseAdapter

. 8.4
AWT, . j a v a . sw in g . even t
, Swing.
.
8.4. AWT

A c tio n L iste n e r

actionP erform ed

ActionEvent
getActionCommand

A b stractB u tto n
JComboBox

g e tM o d itie rs

JT e x tF ie ld
Timer

A d ju stm en tL isten er

ad j ustmentValueChanged Adj ustmentEvent


g e tA d ju sta b le

J S c r o llb a r

getAdjustm entType

getV alue
Item L isten er

item StateChanged

ItemEvent
g e tlte m
g e tlte m S e le c ta b le
getStateC h an ge

A b stractB u tto n
JComboBox

AWT
.

523

. 8.4

FocusListener

focusGained
focusLost

FocusEvent
isTemporary

Component

KeyListener

keyPressed
keyReleased

KeyEvent
getKeyChar

Component

keyTyped

getKeyCode
getKeyModifiersText
getKeyText
isActionKey

MouseListener

mousePressed
mouseReleased

MouseEvent
getClickCount

mouseEntered

getX

mouseExited

getY

mouseClicked

getPoint

Component

translatePoint
MouseMotionListener

mouseDragged
mouseMoved

MouseEvent

Component

MouseWheelListener

mouseWheelMoved

MouseWheelEvent
getWheelRotation

Component

getScrollAmount
WindowListener

windowclosing
windowOpened

WindowEvent
getWindow

Window

windowlconified
windowDeiconi fied
windowClosed
windowActivated
windowDeactivated
WindowFocusListener

windowGainedFocus
windowLos tFocus

WindowEvent
getOppositeWindow

Window

WindowStateListener

windowStateChanged

WindowEvent
getOldState

Window

getNewState

AWT .

Swing,
.


...
JAR
Java Web Start

/ ,
Java.

Java. ,
, ,
. ,
Java,
. Java,
, Java, .
,
,
Java
.

. ,
Java Web Start,
- ,

526

10

. , -

.

JAR
,
, ,
.
Java Archive (JAR). JAR ( JAR-)
, , ,
. , JAR-
ZIP.
. ZIP 200
. Oracle
90%.
h t t p ://docs.oracle./javase/1.5./docs/guide/deployment/deploymentguide/pack200.html.

JAR- ja r . ( JDK
j a r jd k /b in .) JAR-
:
jar cvf

- _1 _2 ...

:
jar cvf CalculatorClasses.jar *.java icon.gif

ja r .
jar

_1 __2 ...

. 10.1 ja r .
ta r , Unix.
JAR- ,
( beans,
JavaBeans, 8 ),
. , JDK
r t . j ar.
10.1. j a r

______________________________________________________________________ __

.
, jar

. ,
classes:
jar cvf JARFileName.jar -C classes *.class

e _________ (. " JAR- )

JAR

527

_ _ _________________________________________________________ . 10.1

JAR- .
, jar (
JAR-) (
JAR-)

( )

JAR- ,
. ,
JAR-

JAR-

. , .

_________ , ZIP_____________________________


, , JAR-
,
. MANIFEST.MF
-INF. ,
.
Manifest-Version: 1.0

,
. .
JAR-. ,
URL. Name.
, .
Manifest-Version: 1.0

Name: Woozle.class


Name: com/mycompany/mypkg/

,
, ,
:
jar cfm - &

, JAR- ,
j :
jar cfm MyArchive, jar manifest.mf ccm/company/mypkg/*.class

528

10

JAR- ,
, :
jar ufm MyArchive.jar manfest-additions.mf
! JAR-,
http://docs.oracle.eom/javase/7/docs/technotes/guides/jar.

JAR-
j a r
, .. ,
j ava, .
jar cvfe Program.jar com...MainAppClass

,
, :
Main-Class: com...MainAppClass

. c l a s s .

, :
java -jar MyProgram. jar
! .
.
Main-Class, .*


JAR-.
JAR- .

Windows Java
. j a r ja v a w
- j a r . ( ja v a , javaw
.)

Solaris " " (..


) JAR- ja v a - j a r .

Mac OS . j
Java JAR-.

Java, JAR-, ,
. Windows
- , JAR-
Windows. Windows
. , Java (JVM)
, , .
JAR-

JAR

529

Jsmooth (http: //jsmooth, sourceforge.


net) Launch4J (http: //launch4j .sourceforge.net).
IzPack (http://izpack.org)
Java. http://www.
javalobby.org/articles/j ava2exe.

Mac OS . Jar Bundler,


XCode, JAR-
Mac OS.

, ,
. . Java
.

, .

, , , .
! Windows .
, ..,
,
. Java, , ,
,
.

About Panel,
, . 10.1.

Re s o u n eT est

Core Java: Fundamentals


8th Edition
CayHorstmann and Gary Cornell
Copyright (C) 2007
Sun Microsystems Press

. 10.1. JAR-

530

10

, , ,
. ,
,
. a b o u t. t x t ?
,
, JAR-.
, ,
, CLASSPATH, -
.
, .
.
1. Class, , AboutPanel.class.
2. ,
getResource (_) ,
URL. get Image ()
getAudioClip().
3. ,
getResourceAsStream(), .
, , ,
. , ,
about.gif, .
, , : " about.gif ,
AboutPanel.class".
URL url = ResourceTest.class.getResource("about.gif");
Image img = new Imagelcon(url).getlmage();

a b o u t .txt,
:
InputStream stream = ResourceTest.class.getResourceAsStream("about.txt");
Scanner in = new Scanner(stream);

.
.
:
data/text/about.txt

, ,
, . ,
/,
, . ,
Windows / \.
, /, .
, . ,
core java.
, CLASSPATH, JAR-
-, .
/corejava/title.txt

JAR

531

,
.
- ,
.
, .
, , .
. API,
5 ,

.
10.1 ,
. , JAR-
, :
javac ResourceTest.java
jar cvfm ResourceTest.jar ResourceTest.m *.class *.gif *.txt
java -jar ResourceTest.jar

JAR- , ,
, , JAR-, .
10.1. resource/ResourceTest.java1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

package resource;
import
import
import
import
import

/**
* (Aversion 1.4 2007-04-30
* author Cay Horstmann
*/

public class ResourceTest


{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()

20

21
22
23
24
25
26
27
28
29
30
31
32
33

java.awt.*;
java.io.*;
java.net.*;
java.util.*;
javax.swing.*;

JFrame frame = new ResourceTestFrame();


frame.setTitle("ResourceTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
/**
* ,
*/
class ResourceTestFrame extends JFrame

532

10

34 {
35
private static final int DEFAULT_WIDTH = 300;
36
private static final int DEFAULT_HEIGHT = 300;
37
38
public ResourceTestFrame()
39
{
40
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
41
URL aboutURL = getClass().getResource("about.gif");
42
Image img = new Imagelcon (aboutURL) .getlmage ()
43
setlconlmage(img);
44
45
JTextArea text Area = new JTextAreaO;
46
InputStream stream = getClass().getResourceAsStream("about.txt");
47
Scanner in = new Scanner(stream);
48
while (in.hasNext())
49
textArea.append(in.nextLine () + "\n");
50
add(textArea);
51

52 }

j a v a . l a n g . C la s s

1 .0
1 .1

URL getResource(String name)

InputStream getResourceAsStream(String name)

1 .1

, , URL ,
. ,
null, -.


4, , Java, ,
.
, , ,
, .
, com.mycompany.util, ,
,
:
package com.mycompany.util;

JAR-.
JAR- .
, :
Sealed: true

, efo ,
, . /
Name: com/mycompany/util/
Sealed: true
Name: com/mycompany/misc/
Sealed: false

Java Web Start

533

,
, .
jar cvfm MyArchive. jar manifest.mf

Java Web Start


Java Web Start ,
. Java Web Start .

. Java Web
Start , .

.
.

Java.
.
,
Adobe Acrobat RealAudio.

, ,
. ,
, (
""), .

Java
Web Start, JAR-.
JNLP (Java Network Launch Protocol
Java). -.
, - a p p l i c a t i o n / x - ja v a jn i p f i l e MIME . jn lp . ( MIME
,
.)
, -.
. Java Web Start, Tomcat.
http://tomcat.apache.org/. Tomcat
JSP-, -.
MIME JNLP-.*1

Java Web Start


, 9.
, .
1. , :
javac -classpath .:/path/to/javaws.jar webstart/*.java

2. JAR-, :
jar cvfe Calculator.jar webstart.Calculator webstart/*.class

534

10

3. Calculator, jnip,
.
<?xml version=Ml .0 encoding="utf-8"?>
<jnlp spec="l.0+" codebase=
"h t t p ://localhost:8080/calculator/" href="Calculator.jnlp">
<information>
<title>Calculator Demo Application</title>
<vendor>Cay S. Horstmann</vendor>
<description>A Calculator</description>
<offline-allowed/>
</i n f o r m a t i o n
<resources>
<java version="l.6.0+"/>
<jar href="Calculator.jar"/>
</resources>
<application-desc/>
</jnlp>

4. ( , 1.6.0, 6.0.)
.
h t t p : / / d o c s . o r a c l e . c o m / j a v a s e / t u t o r i a l /
deployment/deploymentlnDepth/jnlpFileSyntax.html.

5. Tomcat, to m cat/ webapps/


calculator, tomcat , Tomcat.
tomcat/webapps/calculator/WEB-INF
web.xml :
<?xml version="l." encoding="utf-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
x s i :schemaLocation="h t t p ://java.s u n .com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_5,xsd">
</web-app>

6. JAR- JNLP- - , URL


, codebase JNLP-.
Tomcat, tomcat/webapps/calculator.
7. , Java Web Start, ,
application/x-java-jnip-file MIME
javaws. JDK,
.
8. Tomcat.
9. - JN LP-. ,
Tomcat, http://localhost:8080/
calculator/Calculator.jnlp.
f

10. Java Web Start,


. 10.2.
. ,
, Java Web Start (. 10.3).

Java Web Start

535

f * l-iv.i w<'l> S t . l i t

(^^

Downloading application.

N am e:

Calculator Demo Application

Publisher: Cay S* Horstmann


From :

httpr/ylocalhost :8080
:; ; ............. . . '.""<

Cancel
........ - f

......................................................................................................................................... ............................................................. ........... ........

... .............................................................

..................

.....................................- ................

. 10.2. Java Web S tart

. 10.3. Calculator,
Java Web S tart

12. JNLP-, .
Java
Plug-in (. 10.4). Windows, Java Plug-in
. Linux
jdfc/jre/bin/ControlPanel.
.

- , JNLP,
URL codebase ,
:
javaws -codebase file : / / _

JNLP-

, UNIX , JNL
-:
javaws -codebase file://'pwd4 WebStartCalculator.jnlp

536

10

. 10..

,
, .
, JNLP :
<shortcut>
<desktop/>
<menu submenu=MAccessoriesn/>
</shortcut>

, "
" (. 10.5).
S*m: ity

W a r n in g

T h e a p p lic a tio n h a s r e q u e s t e d r e a d a c c e s s
to a file o n th e m ach in e . D o y o u w a n t to
a llo w th is a c tio n ?

Name:

Calculator Dem o Application

Publisher Cay S. Horstm ann


From;

http ://loc alhost :8Q8Q

Q {Always allow this action.


* 1111............... '

OK

Cancel
.. . . - r . n j - r r f . - - r .-1

. 10.5.


. Oracle 32*32

Java Web Start

537

64*64. - JNLP JAR-, in f o r m a t io n


JNLP-:
<icon href="calc_icon32.png" width="32" height="32" />
<icon href="calc_icon64.png" width=M64" height="64" />

,
. ,
, JAR-
setlcon lm age () ( . 10.1).


, ,
, . Java Web Start
. -
-.
-,
,
,

( ).
Java,
, .
.
.
, ,
.
?
, ,
,
( ),
.
, .
"". ,
"",
.
, , "",
.


.
,
Java ,
. , ""
, ..


, , .

538

10

.
: " ".
, .
*

.
, ,
. ,
-,
,
,
-. JDK
: "Untrusted Java Applet Window" ( Java,
).
: "Unauthenticated Java Applet Window" ( Java), "Warning: Java Applet Window" (
: Java).
.


, "",
. , Java Web Start
,
. ,
, 9
. ,
, Java Web Start .
JNLP-:
<security>
<all-permissions/>
</security>

"", JAR- Java Web Start


. JAR-
, , .
,
.
, ,
yWorks GmbH, ,
Thawte (. 10.6). ,
.
1. , ,
.
2. yWorks GmbH.
3. Thawte ( Java Web Start
Thawte,
).

539

Java Web Start

Moi e Infoimat ioi i


^ yWorks GmbH (Thawte Code fpjnl/4
|r?W O
b Thawte Code Signing CA ( Version
This application will be run without the security
Serial Nui
restrictions normally provided by java.
Signature
Issuer
Caution: yWorks GmbH" asserts that this
Validity
application is safe. You should only run this
i Subject
application if you trust "yWorks GmbHuto make
that assertion.
Signature
MD5 Fing
The digital signature was generated with a trusted
&6:18:5E
certificate.
___________

50

W. | - S44 in it

Certificate Details..,

The application's digital signature has been


verified. Do you w ant to run the
application?

Name:

Close

yEd Graph Editor

Publisher; yWorks GmbH


From:

Close

http ://www,yworks.com

IAlways trust content from this publisher.!


Run

T h e d ig ita l s ig n a tu re h a s b e e n v a lid a te d b y a
tru s te d so u rce.

Cancel

M o re in fo rm a tio n .

. 10.6.

, , . :
. , More Information
( ), ,
, Java.
?
yWorks GmbH.

.
. , Java Web Start
. ,
, .
1. , , .
2. - , Java Web Start , .
.
, , . , Java Web Start
(. 10.7).
,
, .

540

10

Dr. Guido Roesslina (Dr. Guir


1
1iVersion
11
1 Serial Numb
!1 Signature Al
1 issuer
I Validity
(
Subject
Signature

________________ L
"* V V a m iiH j - s e c u r i t y

M o i <.' Infoi i i i a t i o n

This application wit! fee run without the security


restrictions normally provided feyjava.
A

The digital signature was generated with an


untrusted certificate.
The digital signature has expired.

The application's digital signature cannot be


verified. Do you w ant to run the
application?

Name:

Certificate Details...

CloseI

Animal Algorithm Animation, version 2.0.1a

Publisher: Dr. Guido Roessling


From:

http ://www.animal .ahrgr.de

N w ays trust content from this publisher.)


i
Run 1 Cancel
T h e d ig ita l s ig n a tu re ca n n o t b e v e rifie d b y a
tru s te d so u rc e. O n ly ru n if y o u tru s t d ie o rig in o f
th e ap p licatio n .

In fo rm a tio n .

. 10.7.

,
. ,
-, ,
. ( h ttp : / /
d o c s . o r a c l e . / j a v a s e / 6/ d o c s / t e c h n o t e s / g u id e s / ja v a w s /d e v e lo p e r s g u id e /
developm ent.htm l.).
, "".
JNLP API ( ),

.

JNLP API
JNLP API
""
. ,
.
. ,
.

(. 10.8). ,

F ile . , .

Java Web Start

541


,
.
I

| I Intecji dti on W h i n i n g

T h e a p p lica tio n w o u ld like to c re a te


sh o rtc u ts. D o y o u w a n t to co n tin u e ?

Name:

Calculator Dem o Application

Publisher Cay S. Horstmann


From:

http ://locafhost :8080


vrWiW ViV'V

1 1

'

Skip

The application will add shortcuts to the desktop and the applications menu.

. 10.8.
Java Web S tart
*

JNLP API
.

, ,
.

,
ServiceManager, .
FileSaveService service =
(FileSaveService) ServiceManager.lookup("javax.jnip.FileSaveService");

,
UnavailableServiceException.
! , JNLP
API, javaw ^. j a r .
j r e / l i b JDK.


JNLP API. ,

542

10

,
. :
service.saveFileDialog(".", new String[] { "txt" }, data,

"calc.txt"};

InputStream.
. ,
10.2, .
/

1. ByteArrayOutputStream,
, .
2. PrintStream,
ByteArrayOutputStream.

3. PrintStream.

4. ByteArraylnputStream,

.
5. saveFileDialog ( ) .
- 1
.
.
FileOpenService.
openFileDialog () ,
FileContents. getlnputStreamO
. , openFileDialog ()
null. ,
.
FileOpenService service = (FileOpenService) ServiceManager.lookup("javax.
jnlp.FileOpenService");
FileContents contents = s e r v i c e . o p e n F i l e D i a l o g n e w String[] { "txt" });
if (contents != null)

{
InputStream in = contents.getlnputStream ();

}
,
. ,
ExtendedService:
ExtendedService service = (ExtendedService) ServiceManager.lookup("javax.
jnlp.ExtendedService");
FileContents contents = service.openFile(new File("c:Wautoexec.bat"));
if (contents != null)

{
OutputStream out = contents.getOutputStream();

}
,
. 10.9.

Java Web Start

543

. 10.9.

,
BasicService, . ,
.
BasicService service =
(BasicService) ServiceManager.lookup("javax.jnlp.BasicService");
if (service.isWebBrowserSupported())
service.showDocument(url);
else . . .

PersistentService,
,
. cookie-,
HTTP.
URL. URL
.
. URL-
. (
.)
,
, - (URL),
codebase JNLP-. , -
http://myserver.com/apps,
h t t p ://myserver . com/apps/subkeyl/subkey2/ ----
.
- (URL)
getCodebase () BasicService.
create () PersistenceService :
URL url = new URL(CodeBase, "mykey");
service.create(url, maxSize);

, , get ().
FileContents,
,
.

544

10

FileContents contents = service.get(url);


InputStream in = contents.getlnputStreamO;
OutputStream out = contents.getOutputStream(true); // true = overwrite

, ,
, . get (),
, - .
FileNotFoundException, .
! Java Web Start, ,
API.
, .
API 7
.

, 10.2,
, .
,
.
.
. ,
(. 10.10).
t . i v it * t i t l e

_
........
^
-1|''

__

Fite
9*
9 +
1000 =
1 7 2 9 .0
12 *
12 *
12 +
1 =
1 7 2 9 .0

;
::=H

Wi
V

~ " 1

JL
i

4,
*
0

.i
*

...

3
"P

'

'
,+ . ,

. 10.10. W e b S t a r t C a l c u l a t o r
10.2. w e b s t a r t / C a l c u l a t o r F r a m e .j ava 1
1

package webstart;

3
4
5

import java.awt.event.*;
import java.beans.*;
import java.io.*;

Java Web Start


6
7

import ja v a .n e t .* ;

import ja v a x .s w in g .*;

import j a v a x . j n lp . *;

10
11
12
13
14
15
16
17
18
19

*
*
*/
p u b lic

c la s s

CalculatorFram e extends JFrame

{
p r iv a t e
p u b lic

C a lc u la to rP a n e l panel;
C alcu la to rF ra m e ()

{
s e t T i t l e ();

20

panel = new C a lc u la t o r P a n e l();

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

a d d (p a n e l);

JMenu fileM enu = new J M e n u ("F ile ");

JMenuBar menuBar = new JMenuBar();


menuBar.add(fileMenu);
setJMenuBar(menuBar);
JMenuItem openltem = fileM enu.add("O pen) ;
o p e nltem .add A ctio n Listen e r(E ven tH an d le r.create (
A c t io n L is t e n e r .c la s s ,

th is ,

"o p e n "));

JMenuItem saveltem = file M e n u .a d d ("S a v e ) ;


sa v e lte m .a d d A ctio n L iste n e r(E v e n tH an d le r.cre a te (
A c t io n L is t e n e r .c la s s ,

th is ,

"sa v e "));

pack () ;

}
j
*
* ,

*/
p u b lic v o id s e t T it le ()

{
try

{
S t r in g

t it le

= n u ll;

B a sic S e r v ic e b a s ic
(B a sic S e rv ic e )

ServiceM anager. lo o k u p ( " j a v a x . j n lp . B a s ic S e r v ic e " ) ;

URL CodeBase = b a sic .g e tC o d e B a se ();


P e rsiste n c e S e rv ic e

se rv ic e =

(P e rsiste n c e S e rv ic e )

ServiceManager

.lo o k u p ( " j a v a x . j n lp . P e r s is t e n c e S e r v ic e " ) ;


URL key = new URL(CodeBase,

"t it le ");

try

{
F ile C o n te n ts

contents = s e r v ic e . g e t ( k e y ) ;

InputStream in = co n te n ts.getln pu tStream O ;


BufferedReader reader =
new BufferedReader(new In pu tStream R ead er(in ));
t it le

= re a d e r.re a d L in e ();

}
catch

(FileNotFoundException e)

545

546

10

65

66

title =
JOptionPane.showInputDialog("Please supply a frame title:)
if (title == null) return;

67

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

service.create(key, 100);
FileContents contents = service.get(key);
OutputStream out = contents.getOutputStream(true);
PrintStream printout = new PrintStream(out);
printout.print (title);

}
setTitle(title);

}
catch (UnavailableServiceException e)

{
JOptionPane.showMessageDialog(this, e);

}
catch (MalformedURLException e)

{
JOptionPane.showMessageDialog(this, e);

}
catch (IOException e)

{
JOptionPane.showMessageDialog(this, e);

88

89
90
91
92
92
93
94
95
96
97
98
99

*
*/
public void open ()

{
try

{
FileOpenService service - (FileOpenService) ServiceManager
.lookup("javax.jnip.FileOpenService);
FileContents contents service.openFileDialog(.", new String[] { "txt });

100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

JOptionPane.showMessageDialog(this, contents.getName());
if (contents !- null)

{
InputStream in = contents.getlnputStreamO;
BufferedReader reader *
new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null)

{
panel.append(line);
panel.append("\n");

}
V }

catch (UnavailableServiceException e)

JOptionPane.showMessageDialog(this, e);

}
catch (IOException e)

Jovo Web Start


122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
143
144
145
146
147
148
149 }

547

{
JOptionPane.showMessageDialog(this, e);
}
}
/**
*
*/
public void save()
{
try
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream printout = new PrintStream(out);
printout.print (panel.getText ());
InputStream data = new ByteArraylnputStream(out.toByteArray());
FileSaveService service = (FileSaveService) ServiceManager
.lookup("javax.jnip.FileSaveService");
service.saveFileDialog(".", new String[]
{ "txt" }, data, "calc.txt");
}
catch (UnavailableServiceException e)
{
JOptionPane.showMessageDialog(this, e);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(this, e) ;
}
}

j a v a x . j n l p . S e r v ic e M a n a g e r

static String[] getServiceNames()


.

static Object lookup(String name)


.

j a v a x . j n l p . B a s ic S e r v ic e

URL getCodeBase()
- , .

boolean isWebBrowserSupportedO
true, Java Web Start -.

boolean showDocument(URL u r l)
URL . ,
true.

548

10

j a v a x . j n l p . F ile C o n t e n t s

InputStream getlnputStreamO
.

OutputStream getOutputStream(boolean o v e r w r ite )


. overwrite
true, .

String getName()
( ).

boolean canRead()

boolean canWriteO
true, .

j a v a x . j n l p . F ile O p e n S e r v ic e

FileContents openFileDialog(String p a th H in t,

String[] e x t e n s io n s )

FileContents[] openMultiFileDialog(String p a th H in t,

String[] e x t e n s io n s )

.
, , null,
.

j a v a x . j n l p . F ile S a v e S e r v ic e

FileContents

saveFileDialog(String

InputStream d a t a ,

FileContents

p a t h H in t ,

S t r i n g []

e x te n sio n s,

String nameHint)

saveAsFileDialog(String

p a t h H in t ,

String[]

e x te n sio n s,

FileContents d a ta )
.
, ,
null, .

j a v a x . j n l p . P e r s is t e n c e S e r v ic e

long create(URL key,

long m ax size )

.
, .

void delete (URL key)


.

549

String[] getNames(URL u r l)
, URL.

FileContents get(URL key)


, ,
. ,
FileNotFoundException.

Java, HTML-
. HTML- ,
. ,
, ,

- (, ..).
( )
.
, -
Hotjava, Sun Microsystems
. ,
Netscape Java .
Internet Explorer. ,
. Netscape Java,
Microsoft Java.

Java Plug-In.
,
,
Java.
! , ,
Java Plug-In
, . Java Plug-In
http://java.com.


,
N o t H e l lo W o r d .
Swing.
J A p p l e t , ,
Swing. . 10.11, J A p p l e t
A p p l e t .

550

10

. 10.1 1.
! Swing,
JApplet. Swing ,
Applet.

551

10.3 , ,
NotHelloWord.
7. -,
.
10.3. applet/NotHelloWorld. java
1

package applet;

2
3
4
5

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

6 /**
7
* (Aversion 1.23 2012-05-14
8
* @author Cay Horstmann
9 */
10 public class NotHelloWorld extends JApplet
11 {
12
public void init()
13
{
14
EventQueue.invokeLater(new Runnable()
15
{
16
public void run()
17
{
18
JLabel label = new JLabel("Not a Hello, World applet",
19
SwingConstants.CENTER);
20
add(label);
21
}

22

});

23
}
24 }2
1
*

,
.
i

1. Java .
2. HTML-, ,
.
HTML-.
<applet code="applet/NotHelloWorld.class" width="300" height="300">
</applet>

,
appletviewer,
. JDK.
appletviewer, :
appletviewer NotHelloWorldApplet.html

HTML-, .
. 10.12 appletviewer,
NotHelloWorldApplet.

552

10

A p p le t V ie w e r: N o tH ello W o i Id __ X
J\- $"4
... ...... ..

Not a Hollo World appdt

Applet started.

. 10.1 2. NotHelloWorldApplet

. ,
. , Emacs JD E ^ R u n A p p let
^ ), Eclipse R u n ^ R u n a s ^ J a v a A p p let (
1^ ^ Java).

appletviewer
, ,
, . ,
appletviewer .
HTML- <applet>, appletviewer
.
, HTML-
(. 10.13). , , ,
Java. ,
Java Plug-In
.
M o z i l k i F i r e fox

file fdit Mtew History fipefetprite loots fcjelp


0

file:///h om e/cay/b ook s/cj

Not a Hello, World applet

~.7/77;.1~->. I

Applet NotHelloWorldApplet started

. 10.13.

553

. ,
, . HTML-
.
, Java ,
. HTML-,
. Windows, Java Plug-In,
, Linux jcontrol
Java. .


-.
,
. ,
.
1. HTML-
.
2. , JApplet.
(public), .
3. main ().
, .
4.
init ().
init ( ) .
5. s e t S i z e O .
HTML- width height.

6. s e t D e f a u l t C l o s e O p e r a t i o n ().
; .
7. s e t T i t l e O ,
, . (,
-, HTML- < t it le > .)
8. setVisible (true) .
.
ja v a , a p p le t . A p p le t 1 .0

void init ()
.
, .

void start()
, ,
, -, .
.

554

10

void stop()
, ,
, -, .
.

void destroy()
, ,
, .

void resize(int w i d t h , int height)


.
, . ,
, -.

HTML- < a p p l e t >


<a p p le t>
:
<applet code=applet/NotHelloWorld.class" width="300" height=,,100">

, code .
, , .c l a s s .
width h e ig h t ,
. .
< / ap p let> . ,
< ap p le t> < / ap p let> , ,
. code, width h e ig h t .
, .
HTML-
, .
<html>
<head>
< t it le > N o t H e llo W o r ld A p p le t < / t it le > l

</head>
<body>
<>

Java:</>
<applet code="applet/NotHelloWorld.class width="100" height="100">
Java,
</applet>
</body>
</html>

< ap p let> .

w idtht, h eigh t
.
. a p p le tv ie w e r
. , a p p le tv ie w e r,
. . ,

555

HTML-, ,
.

align

.
, align <img>.

vspace, hspace


(vspace), (hspace).

code

, .
, codebase,
, codebase . ,
com.mycompany, code=,,com/mycompany/MyApplet.
class code=com.mycompany.MyApplet.class.
. -
, codebase.
code , . ,
. ,
, , ,
. HTML-
code object.

codebase

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

aDirectory/
|__MyPage.html
|__myApplets/
|__CalculatorApplet.class

MyPage.html
:
<applet code="MyApplet.class codebase*"myApplets" width="100" height="150">

archive

Java ,
.
.
, JAR-,
, HTTP-. JAR-
, .
<applet code="MyApplet.class"
archive*"MyClasses.jar,corejava/CoreJavaClasses.jar"
width*"100" height="150">

556

10
object

,
. ( ,
.
1 .)
. , in it ()
, start ().
s t o p ().
,
,
, .
, -
. <applet>
code object, .
<applet object="MyApplet.ser" width="100n height="150">

name

name ,
. Netscape Internet Explorer
, -, JavaScript.
JavaScript
:
<applet code="MyApplet.class" width=M100" height="150" name="mine">
</applet>

document .applets.
_, .
var myApplet = document.applets .mine;

Java JavaScript,
Netscape Internet Explorer,
:
myApplet.init() ;

name ,
-.
,
getApplet () AppletComplex.
.
! , http://www.javaworld.com/javatips/
jw-javatip80.html, , JavaScript
Java :
, width height. Java
JavaScript.

alt

Java
, .

557


alt :
<applet code="MyApplet.class" width=,,100M height="150"
alt="EcnH Java,
">

,
<applet> <>. ,
<applet> </applet>,
. , Java, ,
<applet> </applet>.
,
, .
<applet code="MyApplet.class" width="100" height=,,150>
Java,
.
</applet>

< 6 b je c t>
<object> HTML 4.0.
W3C <applet>. ,
, align height,
<applet>. Java
<object> class id.
. , <object>
, , ActiveX
Java Plug-in. code type.
Java application/java.
<object> :
cobject
codetype="application/java"
classid="java:MyApplet.class"
width="100" height="150">

, class id
codebase, , <applet>.


, ,
, , HTML-.
HTML- <param>. , -
, .
HTML-:
<applet code="FontParamApplet.class" width="200" height="200">
<param name="font" value="Helvetica"/>
</applet>


get Parameter (), Applet:
public class FontParamApplet extends JApplet
{

558I

10

public void init()

{
String fontName = getParameter("font");

}
}
! getParameter () init () ,
. , .
,
.
init ().

.
,
. , ,
, parselnt () Integer. ,
, HTML-:
<applet code="FontParamApplet.class" width=n200M height="200">
<param name"font" value="Helvetica/>
<param name="size" value="24,,/>
</applet>

,
.
public class FontParamApplet extends JApplet
{
public void init()

{
String fontName = getParameter("font);
int fontSize = Integer.parselnt(getParameter("size"));

}
}
! name <param>
getParameter () .

, ,
size.
null, .
int fontsize;
String sizeString = getParameter("size");
if (sizeString == null) fontsize = 12;
else fontsize = Integer.parselnt(sizeString);

, .
, . 10.14.
.

559

. 10.1 4. ,

HTML- <param>.
, HTML- ,
. 10.14.
<applet code=" C hart.class" width="400" height="300n>
<param name= "title" value="Diameters of the Planets"/>
<param name= "values" value="9"/>
<param name= "name.1" value="Mercury"/>
<param name= "name.2" value="Venus"/>
<param name=" n a m e .3" value="Earth"/>
_ ii
n a m e .4" value="Mars"/>
<param name=
_

<param name= n a m e .5" value="Jupiter"/>


_ n a m e .6" value="Saturn"/>
<param name=
_ ii
n a m e .7" value="Uranus"/>
<param name=
_n a m e .8" value="Neptune"/>
<param name=
_n
n a m e .9" value="Plut 9 "/>
<param name=
<param name= "value.1" value="3100"/>
<param name= "value.2" value="7500"/>
<param name= "value.3" value="8000"/>
<param name= "value.4" value="4200"/>
<param name= "value.5" value="88000"/>
<param name= "value.6" value="71000"/>
<param name= "value.7" value="32000"/>
<param name= "value.8" value="30600"/>
<param name= "value.9" value="1430"/>
</applet>

560

10


, <param> . -,
-,
.
< ap p le t> . -,
.
, . ,
- ,
. - ,
. Java
.
, JavaBeans,
, .
, - ,
, .
10.4 ,
. , i n i t (),
paintComponent ().
10.. chart/Chart .java1

package chart;

2
3

import ja v a .a w t.*;

import j a v a .a w t .fo n t .*;

import java.awt.geom .*;

import ja v a x .s w in g .*;

/**

* (Aversion 1.33 2007-06-12

10

* @author Cay Horstmann

11

*/

12

p u b lic

13

c la s s

Chart extends JApplet

14

p u b lic v o id i n i t ( )

15

16

17
18
19

EventQueue . invokeLater(new Runnable ()


p u b lic v o id run()

20

S t r in g v = g e tP a r a m e te r ("v a lu e s");

21

if

22

in t

23
24
25
26
27
28
29
30
31
32
33

doublet]

valu e s = new double[n];

S t r i n g []

names = new S t r i n g [ n ] ;

fo r

(v == n u ll)

return;

n = In t e g e r . p a r s e ln t ( v ) ;

(in t

= 0;

< n;

i++)

valu e s [i] =
Double.parseDouble(getParameter ( " v a lu e . " +
names[i]

= getParameter("name."

add(new ChartComponent(values,

(i

names,

(i

+ 1) ) ) ;

+ 1) ) ;

g e t P a r a m e t e r ( " t it le " ) ) ) ;


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

89
90

>>;

}
}
I

* ,
*/
class ChartComponent extends JComponent

{
private doublet] values;
private String[] names;
private String title;

j
* ChartCoaapoiwnt
* @param v ,
*
* 0 t
*/
public ChartComponent(double[] v, String[] n, String t)

{
values = v;
names = n;
title = t;

}
public void paintComponent(Graphics g)

{
Graphics2D g2 = (Graphics2D) g;
//
if (values == null) return;
double minValue = 0 ;
double maxValue = 0 ;
for (double v : values)

{
if (minValue > v) minValue = v;
if (maxValue < v) maxValue = v;

}
if (maxValue == minValue) return;
int panelWidth = getWidth();
int panelHeight = getHeightO;
Font titleFont = new Font ("SansSerif", Font.BOLD, 20);
Font labelFont = new Font("SansSerif", Font.PLAIN, 10);
//
FontRenderContext context = g2.getFontRenderContext();
Rectangle2D titleBounds = titleFont.getStringBounds(title, context);
double titleWidth = titleBounds.getWidth();
double top = titleBounds.getHeight ();
//
double = -titleBounds.getY (); // ascent
double x = (panelWidth - titleWidth) / 2 ;
g 2 .setFont(titleFont);
g 2 .drawstring(title, (float) x, (float) y);

561

562

10

91
92
93
94
95
96
97
98

//
LineMetrics labelMetrics = labelFont.getLineMetrics("", context);
double bottom - labelMetrics.getHeight ();
= panelHeight - labelMetrics.getDescent ();
g 2 .setFont(labelFont);

99
100
101

//
double scale = (panelHeight - top - bottom) / (maxValue - minValue);
int barWidth = panelWidth / values.length;

102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
12,1
128
129
130
131
132
}
133 }

//
for (int i = 0; i < values.length; i++)
{
//
double xl i * barWidth + 1;
double yl = top;
double height = values[i] * scale;
if (values[i] >= 0) yl += (maxValue - values[i]) * scale;
else

{
yl += maxValue * scale;
height = -height;
}
//
Rectangle2D rect =
new Rectangle2D.Double (xl, yl, barWidth - 2, height);
g 2 .setPaint(Color.RED);
g 2 .fill (rect);
g 2 .setPaint(Color.BLACK);
g 2 .draw(rect);
//
Rectangle2D labelBounds =
labelFont.getStringBounds(names[i], context);
double labelWidth = labelBounds.getWidth();
x = xl + (barWidth - labelWidth) / 2;
g2.drawstring(names[i], (float) x, (float) y);
}

ja v a , a p p le t . A p p le t 1 .0

public String getParameter(String name)


, <param> -,
. .

public String getAppletlnfo()


, ,
. .

563

public String[][] getParameterlnfo()


,
<>, .
: , .
, .
"fps", "1-10", "frames per second"
"repeat", "boolean", "repeat image loop?"
"images", "url", "directory containing images"


, . ,
GIF, PNG JPEG,
AU, AIFF, WAV MIDI.
GIF
.

URL. URL
getDocumentBase () getCodeBase (). URL HTML-
, , URL ,
codebase .
! Java SE
( #4456393; http://bugs.sun.com/bugdatabase/
index, jsp). Java SE 5.0.


get Image () getAudioClip (), URL ,
.
Image cat = getlmage(getCodeBase(), "images/cat.gif");
AudioClip meow = getAudioClip(getCodeBase(), "audio/meow.au");

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

ja v a , a p p le t . A p p le t 1 .0

URL getDocumentBase()
URL -, .

URL getCodeBase()
URL , . URL,
, c o d e b a s e , ,
, HTML-.

564

10

void play (URL u r l)

void play (URL u r l ,

String name)

, URL,
, URL,
. , .

AudioClip getAudioClip(URL u r l)

AudioClip getAudioClip(URL u r l ,

String name)

, URL,
, URL, .
, null.

Image getImage(URL u r l)

Image getImage(URL u r l ,

String name)

Image, ,
URL. ,
null.
.


appletviewer.
, ,
,
-. , ,
. ,
appletviewer, - .
getAppletContext ().
, AppletContext.
AppletContext
. getAudioClip ()
getlmage () AppletContext ,
.


- .
codebase ,
. , ,
.
HTML- name ,
get Applet (String), AppletContext,
. , HTML-
:
<applet code="Chart.class" width="100 height="100" name=HChartr'>

565

Applet chartl = getAppletContext().getApplet("Chart1");

? Chart
, ,
:
((Chart) chartl).setData(3,

"Earth",

9000);

, , -,
name. getApplets ()
( 13).
, , .
, ,
-. -
, -.
Enumeration<Applet> = getAppletContext().getApplets();
while (.hasMoreElements())

{
Applet a = e .nextElement();
System.out.printIn(a.getClass().getName());


,
: -.
AppletContext. ,
showStatus ()
:
showStatus("Loading data . . . please wait");

! , showStatus ()
. , ,
"Applet running" ( ).
,
.

showDocument () -.
showDocument () ,
URL , .
URL u = new URL("http://horstmann.com/index.html");
getAppletContext().showDocument(u);

, - ,
, .
,
Back (), .
showDocument () , ,
.
. 10.2. .
" b l a n k , , .
:

566

10

, ,
. ,
.
10.2. s h o *D o c u m ftn t()

"_self"
" parent"

"_top"

"_blank"


.
, ,

! appletviewer -,
showDocument ().

ja v a , a p p le t . A p p le t 1 .2

public AppletContext getAppletContext()


.
,
.

void showStatus(String m s g )
.

j a v a , a p p l e t . A p p le t C o n t e x t 1 . 0

Enumeration<Applet> getAppletsO
1. 13) , ..
-.

Applet getApplet(String n a m e )
. ,
null. -.

void showDocument (URL url)

void showDocument(URL u r l ,

String t a r g e t )

- .
.
t a r g e t (. . 10.2).

567


,
,
.
,
Java, API
, .


,
"-".
.

,
.

Properties.
,
.
Properties settings = new Properties();
settings.put("width", "200");
settings.put("title", "Hello, World!");

s t o r e ().
p ro g ram .p ro p e rtie s.
, .
FileOutputStream out = new FileOutputStream("program.properties");
settings.store(out, "Program Properties");


:
#Program Properties
#Mon Apr 30 07:22:52 2007
width=200
title=Hello, World!

.
FilelnputStream in = new FilelnputStream("program.properties");
settings.load(in) ;


. UNIX
, .
,
.
, System.
getProperties (), , , Properties

568

10

. "user,
home. :
String userDir = System.getProperty("user.home");


,
. Properties
.
,
:

String title = settings.getProperty("title", "Default title");

"title", title
.
title "Default title".

getProperty () , ,
,
, .
Properties defaultSettings = new Properties ();
defaultSettings.put("width", "300");
defaultSettings.put("height", "200");
defaultSettings.put("title", "Default title");

Properties settings = new Properties(defaultSettings);


,
defaultSettings, .
10.5 ,
.
, .
. corejava/program. properties
, .
! , .
, window.main.color, window,
main.title .. Properties

. ,
Preferences,
.

10.5. properties/PropertiesTest.java 1
1
2
3
4
5
6
7
8

package properties;
import
import
import
import

java.awt.EventQueue;
java.awt.event.*;
java.io.*;
java.util.Properties;

import javax.swing.*;

10 **
11
12
13
14
15
16
17
18
19

*
*
*
*

.
,
(Aversion 1.00 2007-04-29
@author Cay Horstmann

V
public class PropertiesTest

{
public static void main(String[] args)

20

EventQueue.invokeLater(new Runnable()

21
22

public void run()

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

66
67
68
69

PropertiesFrame frame = new PropertiesFrame ();


frame.setVisible(true);

}
>);

}
j

* ,
*
*/
class PropertiesFrame extends JFrame

{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
private File propertiesFile;
private Properties settings;
public PropertiesFrame()

{
// ,
String userDir = System.getProperty("user.home);
File propertiesDir = new File(userDir, " .corejava");
if (
.propertiesDir .exists ()) propertiesDir .mkdir () ;
propertiesFile = new File(propertiesDir, "program.properties")
Properties defaultSettings = new Properties ();
defaultSettings.put("left", "0");
defaultSettings.put("top", "0") ;
defaultSettings.put("width", "" + DEFAULT_WJDTH);
defaultSettings.put("height", "" + DEFAULT_HEIGHT);
defaultSettings.put("title", "");
settings = new Properties(defaultSettings);
if (propertiesFile.exists()) try

FilelnputStream in = new FilelnputStream(propertiesFile);


settings.load(in);

}
catch (IOException ex)

{
ex.printStackTrace();

569

570

IB

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

addWindowListener(new WindowAdapter()

85

int left = Integer.parselnt(settings.getProperty("left"));


int top = Integer.parselnt(settings.getProperty("top"));
int width = Integer.parselnt(settings.getProperty("width"));
int height = Integer.parselnt(settings.getProperty("height"));
setBounds(left, top, width, height);
// ,
String title = settings.getProperty("title");
if (title.equals ("")) title =
JOptionPane.showInputDialog("Please supply a frame title:");
if (title == null) title = "";
setTitle(title);

86
87

public void windowclosing(WindowEvent event)

88

89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
102
103
104 }

settings .put ("left", "" + getXO);


settings .put ("top", "" + getYO);
settings .put ("width", "" + getWidthO);
settings.put("height", "" + getHeight ());
settings.put("title", getTitle ());
try
{
FileOutputStream out = new FileOutputStream(propertiesFile);
settings.store(out, "Program Properties");

}
catch (IOException ex)

{
ex.printStackTrace();

}
System.exit(0);

}
});

ja v a . u t i l . P r o p e r tie s

1 . 0 *

Properties() /
.

Properties(Properties d e f a u l t s )
.
:

d e fa u lts

String getProperty(String key)


, ,
, , ,
. ,
, null.
:

k ey

String getProperty(String k e y ,

571

String d e fa u ltV a lu e )

, .
, , .
:

key
d e fa u lt V a lu e

void load(InputStream in )

,
, ,

throws IOException

.
:

k ey

void store(OutputStream o u t,

String h e a d e r ) 1 . 2

.
:

out
h eader

j a v m . l a n g . S y s te m 1 . 0

Properties getProperties()

. ,
.

String getProperty(String key)

.
, .
:
java.version
java.vendor
java.vendor.url
java.class.version
o s .name
os.version
os.arch
file.separator
path.separator
line.separator
java.specification.version
java.vm.specification.version
java.v m .specification.vendor
java.vm.specification.name
java.vm.version
java.v m .vendor
java.v m .name

572

10

!
security/java.policy, Java.

API
, Properties
.
.


,
.


, ,
.


.
Windows.
Preferences . , Windows
Preferences
, Linux . ,
,
Preferences.

, Preferences, ,
, /com/mycompany/myapp.
,
, .
API
, ,
.
"-",
,
. .
API ,
. ,
,
.
.
. ,
, ,
.
Preferences " ".

:
Preferences root = Preferences.userRoot();

Preferences root = Preferences.systemRoot();

573

:
Preferences node = root.node("/com/mycompany/myapp);


.
. , obj
this:
Preferences node = Preferences.userNodeForPackage(obj.getClass());

Preferences node = Preferences.systemNodeForPackage(obj.getClass());

, "-",
:
String get(String key, String defval)
int getlnt(String key, int defval)
long getLong(String key, long defval)
float getFloat(String key, float defval)
double getDouble(String key, double defval)
boolean getBoolean(String key, boolean defval)
b y t e [] getByteArray(String key, byte[] defval)

,
, .
. -, ,
. -,
- . -,
.
, ,
put(String key, String value)
putlnt(String key, int value)

. ,
, String [] keys ().
, ,
. ,
Windows, .

-, .

-,
,
.

Preferences .
, ,
.
void exportSubtree(OutputStream out)
void exportNode(OutputStream out)

XML. ,
:
void importPreferences(InputStream in)

574

10

,
XML.
<?xml version=l ." encoding="UTF-8"?>
<!DOCTYPE preferences SYSTEM "h t t p ://java.s u n .com/dtd/preferences.dtd">
p r e f e r e n c e s EXTERNAL_XML_VERSION="l.0">
<root type=,,user">
<map/>
<node name="com">
<map/>
<node name=MhorstmannH>
<map/>
<node name="corejava,,>
<map>
<entry key-"left" value="ll"/>
<entry key=Mtop" value=H9"/>
<entry key="widthH value=n453"/>
<entry key="height" value="365"/>
<entry key="title" value="Hello, World!"/>
</map>
</node>
</node>
</node>
</root>
</preferences>

,

,
. ,
10.6.
. ,
.
, .
10.6. p r e fe r e n c e s /P r e fe r e n c e s T e s t. j ava 1
1
2
3
4
5
6
7

package preferences;
import
import
import
import
import

java.awt.EventQueue;
java.awt.event.*;
java.io.*;
java.util.prefs.*;
javax.swing.*;

9
10
11
12
13
14
15
16
17
18
19
20

/**
* .
* ,
* (Aversion 1.02 2007-06-12
* 0author Cay Horstmann
*/
public class PreferencesTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()


21

public void run()

22

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

66

PreferencesFrame frame = new PreferencesFrame ();


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

}
} );

}
I
* ,
*

*/
class PreferencesFrame extends JFrame
{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public PreferencesFrame()

{
// ,
Preferences root - Preferences.userRoot();
final Preferences node = root.node("/com/horstmann/corejava");
int left - node.getlnt("left", 0);
int top * node.getlnt("top", 0);
int width - node.getInt("width", DEFAULT_WIDTH);
int height - node.getlnt("height", DEFAULT_HEIGHT);
setBounds(left, top, width, height);
// ,
String title node.get("title", "");
if (title.equals ("")) title JOptionPane.showInputDialog("Please supply a frame title:");
if (title -- null) title * "";
setTitle(title);
// XML-
final JFileChooser chooser * new JFileChooser ();
chooser.setCurrentDirectory(new File("."));
// .ami
chooser.setFileFilter(new javax.swing.filechooser.FileFilter ()

67

public boolean accept(File f)

68

69
70
71
72
73
74
75
76
77

575

return f .getNameO .toLowerCase () .endsWith (" .xml")

}
public String getDescription ()

(
return "XML files";

}
>);

|| f .isDirectory ()

10
78
79
80
81
82
83
84
85
86

87

//
JMenuBar menuBar = new JMenuBar ();
setJMenuBar(menuBar);
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem exportltem = new JMenuItem("Export preferences");
menu.add(exportltem);
exportltem.addActionListener(new ActionListener ()

88

public void actionPerformed(ActionEvent event)

89
90
91
92
93
94
95
96
97
98
99
100
101

{
if (chooser.showSaveDialog(PreferencesFrame.this) ==
JFileChooser.APPROVE_OPTION)

{
try

{
OutputStream out =
new FileOutputStream(chooser.getSelectedFil^());
node.exportSubtree(out);
out.close();

}
catch (Exception e)

{
e.printStackTrace ();

102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119

}
}
}
}>;
JMenuItem importItern = new JMenuItem("Import preferences");
menu.add(importItem);
importItern.addActionListener(new ActionListener()

{
public void actionPerformed(ActionEvent event)

{
if (chooser.showOpenDialog(PreferencesFrame.this) ==
JFileChooser.APPROVE_OPTION)

{
try

{
InputStream in =
new FilelnputStream(chooser.getSelectedFile());
Preferences.importPreferences(in);
in.close ();

120
121

122
123
124
125
126
127
128
129

}
catch (Exception e)

{
e.printStagkTrace ();

}
}
}
});
JMenuItem exitltem = new JMenuItem("Exit");
menu.add(exitltem);
exitltem.addActionListener(new ActionListener()

577

135
136
public void actionPerformed(ActionEvent event)
137
138
node.putlnt ("left", getXO);
139
node .putInt ("top", getYO);
140
node.putInt("width", getWidth());
141
node.putInt("height", getHeight());
142
node.put("title", getTitle ());
143
System.exit(0) ;
144
145
});
146
}
147 }

ja v a . u t i l .p r e f s . P re fe re n c e s

1 . 4 *

Preferences userRootO

.

Preferences systemRootO
.

Preferences node(String p a th )
, .

p a th , (/),
. ,
.

Preferences userNodeForPackage(Class c l)

Preferences systemNodeForPackage(Class cl)


,
, c l.

String [] keys ()
, .

String get(String key, String d e fv a l) .

int getlnt(String key,

long getLong(String key,

float getFloat(String key,

double getDouble(String k ey,

boolean getBoolean(String key,

byte[]

int d e f v a l)
long d e f v a l)
float d e fv a l)
double d e f v a l)

getByteArray(String key,

boolean d e fv a l)
byte[]

d e fv a l)

, .
, ,
, .
*

void put(String key,

String v alu e )

578

10

void putlnt(String key,

int v alu e )

void putLong(String key,

void putFloat(String key,

void putDouble(String key,

void putBoolean(String k ey,

void putByteArray(String key,

long v alu e )
float v alu e )
double v a lu e )
boolean v a lu e )
byte[]

v a lu e )

- .

void exportSubtree(OutputStream out)

,
.

void exportNode(OutputStream out)


, ,
.

void importPreferences(InputStream in )
.

,
Java .
, .
, ,
.

,
,


...






,
, , ,
.
. ,
,
Java,
.

580

11 , ,

.
-
, .
, , .

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

.
- ,
.
.
.
,
Java
, .


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


.

.

- : ,
( , ),
,

581

, .
,
. ,
.
?

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

. .
, - .

, ,
.

. ,
.

. - .
,
. ,
-,
.

, ,
. , , ,
-1 .
.
n u ll.
, .
. , ,
, -1, ,
.
5, Java
, ,
.
, ,
. , , ,
, . ,
, , .
,
.

. ,

.

582

11 , ,


Java ,
T h r o w a b le . ,
, . . 11.1
Java.

. 1 1 .1 . Java

,
: E r r o r E x c e p t io n ,
T h p o w a b le . E r r o r
,
Java. .

.
,
.
Java
E x c e p t io n . : ,
R u n tim e E x c e p tio n , . R u n t im e E x c e p tio n
.
, ,
-,
, R u n t im e E x c e p tio n ,
.

.
n u l l .

583

C la s s ,
.

R u n t im e E x c e p tio n
. , A r r a y ln d e x O u t B o u n d s E x c e p tio n ,
. N u l l P o i n t e r E x c e p t i o n
, , , ,
n u l l .
, ? ,
? ,
. ,
, .
Java , E r r o r
R u n t im e E r r o r , .
.
.
!

. ,
.
Runtim eException

C++! ( )
C++, , , . C++
, : ru n tim e_ erro r lo g ic _ e r r o r .
lo g ic _ e r r o r RuntimeException Java. runtim e_error
,
. , Java,
RuntimeException.


, ,
. : ,
, , .
, , , ,
. , ,
, ,
IO E x c e p t io n .
, ,
.
F i l e I n p u t S t re a m . (
12.)
p u b lic

F ile ln p u t S t r e a m (S t r in g

name)

throws FileNotFoundException

584

11 , ,

,
F i l e l n p u t S t r e a m , name S t r i n g ,
, - ,
F i l e N o t F o u n d E x c e p t i o n . ,
,
F ile N o t F o u n d E x c e p t io n .

,
, . ,
th r o w s , ,
.

, ,
F i l e l n p u t S t r e a m .

, t h r o w
( t h r o w
).

, ,
[ - 1 ] = 0,
, , A r r a y ln d e x O u tO fB o u n d s E x c e p tio n .

,
, . ? , ,
,
.
, .
, , ,
, .
c la s s

MyAnim ation

{
p u b li c

Image

loadlm age ( S t r i n g

s)

throws IOException

}
,
:
c la s s

MyAnim ation

{
p u b li c

Image

lo a d lm a g e ( S t r in g

s)

throws FileNotFoundException, EOFException

}
, .. , E r r o r ,
. ,
, .

585

,
R u n tim e E x c e p tio n :
c la s s

MyAnim ation

v o id

d ra w lm a g e (in t

i)

throws ArraylndexOutOfBoundsException

//


. ,
,
,
.
, ,
.
( E r r o r )
, ( R u n t im e E x c e p t io n ) .
,
.
, , ,
. ,
th r o w s . , :
- .
! ,
. (
.) , ,
, . , JComponent.
paintComponent (), paintComponent ()
, .

,
, .
, F i l e l n p u t S t r e a m
IO E x c e p t io n , , .
, , IO E x c e p t io n
, F ile N o t F o u n d E x c e p t io n .
C++!

Java throws C++.


. C++ throws
, . , C++
. ,
throws, unexpected ()
. , throws C++ ,
.
throws

586

11 , ,


, . ,
r e a d D a t a (), ,
:
C o n t e n t -le n g t h :

1024

733 .
, .
, .
IO E x c e p t io n .
E O F E x c e p tio n : " ,
EO F". , !
:
throw

new E O F E x c e p tio n ();

, , :
EOFException
throw

= new E O F E x c e p tio n ();

,
.
S t r in g

readData (Scanner

in )

throws EOEException

{
w h ile

(.

.)

{
if

( ! in .h a s N e x t ())

//

EOF)

{
if

(n < le n )

throw new EOFException ();

}
}
r e tu rn

s;

}
E O F E x c e p tio n ,
.
, .
S t r in g
throw

g r ip e

" C o n t e n t - le n g t h :

"

+ le n

+ ",

R ece ive d:

"

+ n;

new E O F E x c e p t io n ( g r ip e ) ;

,
,
. .
1. .
2. .
3. .

587

,
. ,
, , .
C++! C++ Java ,
. Java ,
Throwable, C++ .


,
.
. , ,
E x c e p t io n , , IO E x c e p t io n ,
.
, . ( ,
t o S t r i n g () T h ro w a b le ,
.)
c la s s

F ile F o r m a tE x c e p tio n

extends

IO E x c e p tio n

{
p u b li c

F ile F o r m a t E x c e p t io n ()

{}

p u b lic

F ile F o r m a t E x c e p t io n ( S t r in g

g r ip e )

{
s u p e r (g r ip e );

}

:
S t r in g

re a d D a ta (B u ffe re d R e a d e r

in )

throws

F ile F o r m a tE x c e p tio n

{
w h ile

(.

.)

{
if

(ch

==

-1)

//

{
if

(n < le n )

throw now FiloForma fException () ;

}
}
re tu rn

s;

EOF)

588

11 , ,

ja v a .la n g .T h r o w a b le

1 .0

Throwable()

T h ro w a b le (Strin g

Throwable,

m essage)

T h ro w a b le , .
:
.

S t r in g

getM essageO

Throwable.


, . ,
: , . ,
, .
,
, .
( )
,
. ( ,
, .)
try /c a tc h .
:
try

}
c a tch

}
t r y ,
catch, .
1. try .
2. catch.
t r y ,
catch. - tr y ,
, catch ,
( , ) . (
,
.)

589

, ,
:
p u b lic

v o id

r e a d (S t r in g

file n a m e )

{
try

{
In p u tStre a m
in t

in

= new F ile ln p u t S t r e a m ( f il e n a m e ) ;

b;

w h ile

( (b = i n . r e a d O )

!=

-1)

}
}
catch (IOException exception)

e x c e p t i o n . p r in t S t a c k T r a c e ( ) ;

, t r y
: ,
. API,
, r e a d ( ) IO E x c e p t io n .
w h i le ,
c a t c h .
.
?
,
. r e a d () ,

! , ,
r e a d () IO E x c e p t io n
:
p u b li c

v o id

read ( S t r i n g

file n a m e )

throws IOException

{
In p u tStre a m
in t

in

= new F ile ln p u t S t r e a m ( f ile n a m e ) ;

b;

w h ile

( (b = i n . r e a d O )

!=

-1)

}
}
, th r o w s .
, ,

. ? , ,
, .
, t h r o w s ,
.
API,
, . ,

590

11 , ,

throws. :
,
.
, .
, ,
(, paintComponent () JComponent),

. throws,
.
C++! Java C++ .
Java:
c a tc h

(E x c e p tio n )

//

Java

C++:
c a tc h

(E x c e p tio n s )

//

C++

t r y ,
. catch
:
try

c a tc h

c a tc h

c a tc h

(U n k n o w n H o s tE x c e p tio n )

(F ile N o tF o u n d E x c e p tio n )

(IO E x c e p tio n )

}
.
,
. getMessage (),
, . getClass () . getName ( ) .
Java SE7,
catch. , ,
, . catch
, .
,
.
try

{
}

c a tc h
{

(F ile N o tF o u n d E x c e p tio n

591

| U n k n o w n H o s tE x c e p tio n )

}
c a tc h

(IO E x c e p tio n )

{

-

}
1
(fin a l). , :
c a tc h

(F ile N o tF o u n d E x c e p tio n

| Unknow nHostException )

{ ...

! , .
- catch .


catch,
. , . ,
,
,
, .
ServletException. ,
, , ,
, ,
. ,
.
try

c a tc h

(S Q L E x c e p tio n )

th ro w new S e r v le t E x c e p t io n ( " d a t a b a s e e r r o r :

" + e .g e tM e s s a g e ( ) ) ;

}

ServletException. ,
.. , .
try

{
}

c a tc h

(S Q L E x c e p tio n )

T h ro w a b le se - new S e r v le t E x c e p t io n ( " d a t a b a s e e r r o r " ) ;


s e . in itC a u s e (e );
th ro w s e ;

592

11 , ,


:
Throwabl-e

= s e . getC au se () ;

.
,
.
.
, ,
.
.


:
try

}
c a tch

(E x c e p tio n

{
lo g g e r .lo g (le v e l,
throw

message,

e );

e;

}
Java SE 7 .
, :
p u b li c

v o id

u p d a te R e c o rd ()

throws

SQ LException

t h r o w c a t c h ,
,
E x c e p t i o n , S Q L E x c e p t io n .
Java SE 7. ,
t r y .
S Q L E x c e p t io n
c a t c h ,
: t h r o w s
S Q L E x c e p tio n .

f i n a l l y
,
. - ,
, . , ,
, ,
: .
Java f i n a l l y .
d i s p o s e () G r a p h i c s .
, ,
. 4 ,
,
.

593

finally ,
. , dispose ()
.
In p u tStre a m

in

= new F ile ln p u t S t r e a m ( . . . ) ;

try
{

// 1
,

// 2
}
c a tch

(IO E x c e p tio n

{
// 3

}
fin a lly

{
//

i n . c lo s e ( ) ;

}
//
,
finally.

1. .
try, finally. ,
1, 2, 5 6,
2. , catch (
IOException).
try , ,
try .
catch , , finally.
3. catch ,
, try. ,
1, 3, 4, 5 6.
catch,

1, 3 5.
4. , catch.
try ,
, try .
finally
. ,
1 5.
finally catch.
:
In p u tStre a m
try

in

...;

594

11 , ,

{
,

}
finally

{
in.close ();

}
i n . c lo s e () f i n a l l y ,
try . , ,
catch. , f i n a l l y
,
.
. try/catch try/finally.
. :
In p u tS tre a m in = . . . ;
try

{
try

}
finally

{
in.close();

}
}

c a tc h

(IO E x c e p tio n e)

try , try
. , ,
finally.

! finally return,
. , try
return. ,
finally. return,
. :
public static int f(int n)
{
try

{
int r = n * n;
return r;

}
finally

{
if (n == 2) return 0;
}

595

f ( 2) , t r y = 4
r e tu r n . r e t u r n f i n a l l y .
,
4.

finally Java ,
, , .
, ,
.
In p u tS tre a m i n = . . . ;
try
{
,

fin a lly

i n . c lo s e ( ) ;

}
, try ,
IOException. finally,
close (), IOException!
,
close ().
,
,
. ,
, .
, .
In p u tS tre a m in = . . . ;
E x c e p tio n ex = n u l l ;
try
{
try

c a tc h

(E x c e p tio n e)

ex = e ;
th ro w e ;

}
}

fin a lly

try

i n . c lo s e ();

c a tc h

{
}
}

if

(E x c e p tio n e)
(e x == n u l l )

th ro w e ;

L 596

11 , ,

, Java SE 7 ,
, ^
.

t r y
Java SE 7 ,
, :

try

}
fin a lly

}
, , ,
: ,
A utoC loseable. ,
:
v o id

c lo s e ()

throws

E x c e p tio n

! C l o s e a b l e ,
AutoCloseable. c lo se ().
lOException.

t r y
:
try

(Resource

re s

...)
re s

}
try , r e s . c lo s e () .

.
try

(Scanner

in

= new Scanner(new

F ile ln p u t S t r e a m ( " / u s r / s h a r e / d ic t / w o r d s " ) ))

{
w h ile

( i n . h a s N e x t ())

S y s t e m . o u t . p r in t In ( in . n e x t ( ) ) ;

}
t r y ,
, i n .c l o s e () ,
f i n a l l y . t r y ,
.
try

(Scanner

in

P r in t W r i t e r

= new Scanner(new
out

F ile ln p u t S t r e a m ( " / u s r / s h a r e / d ic t / w o r d s " ) ),

= new P r i n t W r i t e r ( " o u t . t x t " ))

{
w h ile

(in .h a s N e x t ())

o u t . p r i n t I n ( i n . n e x t ( ) . toUpperCase ( ) ) ;

597

, try
.
, try/
finally.

, ,
try, close (). try
.
, ,
close (), "".
addSuppressed ().
- ,
get Suppressed (),
c l o s e ().

, . ,
,
try .
! t r y catch
f i n a l l y . .
t r y
.



. , , .
, Java
.

printStackTrace () Throwable, .
Throwable

t,=

new T h ro w a b le ( ) ;

Byte A rrayO u tp u tStre am

out

= new B y te A rra y O u tp u tS tre a m ( ) ;

t .p r in tS ta c k T r a c e (o u t) ;
S t r in g

d e s c r ip t io n

= o u t . t o S t r i n g ();

getStackTrace (),
StackTraceElement,
, :
Throwable

= new T h ro w a b le ( ) ;

S ta c k T ra c e E le m e n t[]
fo r

frames

(StackT raceE le m en t

= t .g e tS ta c k T r a c e ();

frame

frames)

StackTraceElement , ,
, .
, , t o S t r i n g ().
Thread.getAHStackTraces () .
:
Map<Thread,

StackT raceE le m e n t [] > map = T h r e a d .g e t A H S t a c k T r a c e s () ;

fo r

(Thread

: map. k e y s e t ())

598

11 , ,

{
StackTraceElement[] frames = map.get(t);

}
13
14 . 11.1 /
.
, 3
f a c t o r i a l (3):
factorial (3):
StackTraceTest.factorial(StackTraceTest.java:18)
StackTraceTest.main(StackTraceTest.java:34)
factorial (2):
StackTraceTest.factorial(StackTraceTest.java:18)
StackTraceTest.factorial(StackTraceTest.java:24)
StackTraceTest.main(StackTraceTest.java:34)
factorial (1):
StackTraceTest.factorial(StackTraceTest.java:18)
StackTraceTest.factorial(StackTraceTest.java:24)
StackTraceTest.factorial(StackTraceTest.java:24)
StackTraceTest.main(StackTraceTest.java:34)
return 1
return 2
return 6

11.1.
1

s t a c k T r a c e / S t a c k T r a c e T e s t .java 1

package stackTrace;

2
3

import j a v a . u t i l . * ;

4
5

/**

* (Aversion 1.01 2004-05-10

* author Cay Horstmann

10 */
11 p u b lic

c la s s

StackTraceTest

12 {
13

/**

14

15

* @param

16

* Qreturn n ! = l * 2 * . . . * n

17

*/

18

p u b lic

19

s t a t ic

in t

fa c t o r ia l(in t

n)

20

S y s t e m . o u t . p r in t ln ( " f a c t o r ia l ("

21

Throwable t = new ThrowableO;

22

StackTraceElem ent[]

23

fo r

24
25

frames = t.ge tS ta c k T ra c e ();

(StackTraceElement

S y s t e m . o u t . p r in t ln ( f ) ;
in t

r;

+ n + "):");

: frames)


26
27
28
29
30
31
32
33
34
35
36
37
38 }

if (n <= 1) = 1;
else = n * factorial (n - 1);
System.out.println("return " + r) ;
return r;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out .'print ("Enter n: ");
int n = in.nextlnt ();
factorial(n);
}

j a v a . l a n g . T h r o w a b le 1 . 0

Throwable(Throwable cause) 1.4

Throwable(String message, Throwable c a u s e )

1.4

Throwable cause,
.

Throwable initCause(Throwable c a u s e )

1.4

. ,
. this.

Throwable getCause() 1.4

,
. ,
null.

StackTraceElement[] getStackTrace() 1.4

void addSuppressed(Throwable t) 7

. try
, t , close().

Throwable[] getSuppressed() 7

, . , ,
close try .

ja v a .la n g .E x c e p tio n

1 .0
cause)

Exception(Throwable

E x c e p t io n (S t r in g

m essage,

Exception

1 .4
Throwable

cause)

cause.

11 , ,

ja v a .la n g .R u n tim e E x c e p tio n

RuntimeException(Throwable

R u n tim e E xce p tio n (Strin g

1 .0

c a u se ) 1 .4

m essage ,

RuntimeException

Throwable

cause)

1 .4
cause.

j a v a . l a n g . S t a c k T r a c e E le m e n t 1 . 4

S t r in g

getFileN am e()

, , .
, n u ll.

in t

getLineNumber()

, , .
, -1 .

S t r in g

getClassN am e()

, , .

S t r in g

getMethodName()

, , .
< in it > , < c l i n i t > .
.

boolean

isN a tiv e M e th o d ()

S t r in g

true,

t o S tr in g O

, ,
( ).



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

.
1. .
,
Stack . 10 .
. , :
if

(!s .e m p ty ))

s.p o p O ;

601

, ,
, .
EmptyStackException, , .
try
{
s.p o p O ;

}
c a tc h

(Em p tyStackException

{
}
,


isEmpty (), 646 ,
EmptyStackException 21739 .

, ,
. :
, ,
.
2. .

try. ,
Java.
P r in tS tr e a m
S ta c k
fo r

ou t;

s;

(i

= 0;

<

1 0 0 ; i++)

{
try

{
n = s .p o p ( ) ;

}
c a tc h

(E m p tyStackEx cep tion

e)

{
//

}
try

{
o u t .w r i t e l n t ( n ) ;

}
c a tc h

(IO E x c e p tio n

e)

{
//

}
.
, .
100 . (,
. .)
. ,
.
, . ,
try
, .
, , .

602

11 , ,
try

{
fo r

(i

= 0;

< 100;

i+ + )

{
n = s .pop () ;
o u t .w r i t e l n t ( n ) ;

c a tc h

(IO E x c e p tio n

e)

{
//

}
c a tc h

(E m p tyStackEx cep tion

{
//

}
.

.
i

3. ,
.


R u n t im e E x c e p tio n . .
T h r o w a b le .
.
.
,
. ( ,
, .
,
.)
,
. ,
, ,
N u m b e r F o r m a tE x c e p tio n ,
IO E x c e p t io n M y S u b s y s te m E x c e p tio n ,
.
4. .
Java
. , , ,
.
, th r o w s
.
th r o w s ,
, ,
:
p u b lic

{
try

Image

lo a d lm a g e ( S t r in g

s)

603

}
c a tc h
{}

//

(E x c e p tio n

}
. ,
. , .
- , ,
.
5. ,
.
,
. , ,
. , , ,
S t a c k . p o p O
null , . ,
EmptyStackException ,
, NullPointerException .
6. , .

. , ,
FilelnputStream readLine (),
, .
,
, .
p u b lic

v o id

throw s

r e a d S tu ff(S tr in g
IO E x c e p tio n

//

file n a m e )

{
In p u tStre a m

in

= new F ile ln p u t S t r e a m ( f il e n a m e ) ;

}

.
! .5 6 :
, .



. , , ,
. ,
, :
double

= M a th .sq rt( );

, ,
, ,

604

11 , ,

.
,
. ,
:
if

( < 0)

throw

new Ille g a lA r g u m e n t E x c e p t io n ("

< 0" ) ;

:
, .
,
.
, .
assert. .
a sse rt

asse rt

: ;


AssertionError, .
AssertionError
.
! , a sse rt,
. A s s e r t io n E r r o r
, . JDK
, , "
, ,
".

,
, :
asse rt

>=

0;

,
AssertionError, , .
asse rt

>=

: ;

C++! a s s e r t
, , . , a s s e r t (>=0)
fa ls e , , ,
>= 0 . Java .
,
A s s e r t io n E r r o r : a s s e r t >= 0 : " >= 0".


.
- e n a b le a s s e r t io n s -,
:
java -enableassertions

605

, , ,
, .
, ,
.

:
java -earMyClass -:com.mycompany.mylib ... MyApp

MyClass,
com. mycompany. myl i b . - . . .
, .
, .
- d i a b l e a s s e r t i o n s -da
:
java -:... -da:MyClass MyApp

4 ,
. ,
, - -da .
,
" " .
, ,
- e n a b l e s y s t e m a s s e r t i o n s / - e s a .
.
API.


Java .

?
, .

, .

.
( :
, , .)

,
.
.
,
. , ,
, ? ,

II

606

11 , ,

, .
A r r a y .sort () .
I

tolndex

tolndex,

fromlndex

. .

@param
@param from lndex

@param to ln d e x

()

@throws

Ille g a lA r g u m e n t E x c e p t io n

from index

@throws

A rra yln d e x O u tO fB o u n d sE x ce p tio n

> to ln d e x ,

from lndex
to ln d e x

<

> a . le n g t h

* /
s t a t ic

v o id

so rt[]

a,

in t

from lndex,

in t

to ln d e x

, ,
. ,
. ,
.
.
? ,
.
, null.
,
AssertionError.
, , :
@param .

,
.
:
a s s e r t (

!= n u l l ) ;

.
, ,
.
: null.
,
. , ,
, .
assertionError,
NullPointerexception, .



. ,

607

h t t p :/ / d o c s .o r a c le .e o m /ja v a s e / 6 /d o c s / t e c h n o t e s / g u id e s / la n g u a g e /
assert.html:
if (i % 3 == 0)

else if (i % 3 == 1)

else // (i % 3 == 2)


:
if (i % 3 == 0)

else if (i % 3 == 1)

else

{
assert i % 3 == 2;

}
, . ,
i % 3? i
, 0, 1 2.
, -1 -2.
, , i
. ,
i f :
assert(i >= 0);

, ,
.
,
,
. .
ja v a .la n g .C la e s L o a d e r 1 .0

void setDefaultAssertionStatus(boolean b) 1 . 4

,
, .

void setClassAssertionStatus(String c l a s s N a m e , boolean b) 1 . 4

void setPackageAssertionStatus(String p a c k a g e N a m e ,

boolean b) 1 .4

void clearAssertionStatus() 1 . 4

, ,
, .

11

, ,

Java S y ste m .o u t.
p r in t ln (), . ,

.
API
. .

,
, ..

.
, ,
.

. , ,
XML.

,
, , com.mycompany.myapp.


.
. *


.
:
L o g g e r . g e t G l o b a l ( ) . in f o ( " F il e - > O p e n

menu

item

s e le c t e d ");

:
May

10,

INFO:

2013

10:12:15

F ile -> O p e n

menu

PM Loggin glm age V ie w e r


item

file O p e n

s e le c t e d

, , main (),
, .
L o g g e r . g e t G l o b a l ( ) . s e t L e v e l ( L e v e l .OFF)

! , 7184195,
Logger .g e tG lo b a l () . se tL e v e l ( L e v e l. INFO ),
.


, ,
, .

609

, ,
.
. ,
getLogger (), .
p r iv a te

s t a t ic

fin a l

Lo gge r

myLogger

Lo gge r.ge tL o gge r("co m .m yco m p a n y.m ya p p ");

, .
, .
,
. ,
com.mycompany ,
.
:

SEVERE

WARNING

INFO

CONFIG

FINE

FINER

FINEST

.
, setLevel () :
l o g g e r . s e t L e v e l ( L e v e l . F IN E ) ;

, FINE .
,
Level.ALL, Level.OFF
. ,
.
lo g g e r . w a r n in g ( m e s s a g e ) ;
l o g g e r . fin e (m e ssa g e ) ;

, lo g (),
:
l o g g e r . l o g ( L e v e l . FINE,

m e ssa g e );

. , i n f o .
, , ,
, CONFIG, f i n e , f i n e r f i n e s t .

! INFO,
. ,
INFO.

610

11 , ,

, ,
, .
,
.
logp () :
v o id

lo g p ( L e v e l

1,

S t r in g

classNam e,

S t r in g

methodName,

S t r in g

message)


:
v o id

e n t e r in g (S t r in g

classNam e,

S t r in g

methodName)

v o id

e n t e r in g (S t r in g

classNam e,

S t r in g

methodName,

O b je ct

v o id

e n t e r in g (S t r in g

classNam e,

S t r in g

methodName,

O b j e c t []

v o id

e x it in g (S t r in g

classNam e,

S t r in g

methodName)

v o id

e x it in g (S t r in g

classNam e,

S t r in g

methodName,

O bje ct

param)
params)

r e s u lt )

.
, FINER
ENTRY RETURN.
in t

r e a d (S t r in g

file ,

S t r in g

p atte rn )

{
logger.entering("com.mycompany.mylib.Reader", "read",
new Object[] { file, pattern });

lo g g e r .e x itin g ("c o m .m y c o m p a n y .m y lib .R e a d e r ",


r e tu r n

"re a d ",

c o u n t);

count;

}
!
. :
entering("com.mycompany.mylib.Reader",

"re a d ",

file ,

lo g g e r ,

p attern ).

.
,
:
v o id

t h r o w in g ( S t r i n g

v o id

lo g (L e v e l

1,

classNam e,

S t r in g

S t r in g

message,

methodName,

Throwable

Throwable

t)

t)

.
throwing () , FINER,
, THROW.
if

(.

{
IO E x c e p tio n

e x c e p tio n

= new IO E x c e p t io n ( " .

l o g g e r . th ro w in g("co m .m yco m p an y.m ylib .R e ad er",


throw

e x c e p tio n ;

try

catch

{
}

(IOException

e)

Logger.getLogger("com.mycompany.myapp").
log(Level.WARNING, "Reading image", e ) ;

.");
"re a d ",

e x c e p t io n ) ;

611


,
. : jre/lib/
logging.properties

,
j a v a .u t i l .logging.config.file :
j&va -Djava.util.logging.config.1=^_

!
m a in (). System .
s e t P r o p e r t y ("ja v a .u t il.lo g g in g . c o n f ig . f ile " ,
f i l e ) m a in ( ) ,

LogManager.r e a d C o n fig u r a t io n ().

, ,
, :
. le v e l= IN F O


. ,
. le v e l.
com.mycompany.myapp . le v e l= F IN E

,
, .
. ,
FINE, :
j a v a . u t i l . l o g g i n g .C o n s o le H a n d le r . le v e l= F IN E

!
. -Dcam.mycompany.myapp.level=FINE
.

! Java SE 7' API


LogManager j a v a . u t i l . l o g g i n g . c o n f i g . c l a s s ja v a ,
u t i l . l o g g i n g . c o n f i g . f i l e API
. .
4 6 9 1 5 8 7 h ttp ://b u gs.su n .co m /b u gd a ta ba se .

! , ,
ja v a .u t il.lo g g in g .L o g M a n a g e r .
j a v a . u t i l . lo ggin g.m a n age r, .
, ,
. LogManager
API.

612

11 , ,

,
jconsole. www.oracle.com/
technetwork/articles/java/jconsole-1564139.html#LoggingControl.


, .
5 .
,
.
, ,
.
(, ). ,
"readingFile"
"Reading file" Achtung! Datei
wird eingelesen .
,
, , .
(, "com.mycompany. logmessages").
,
.
com/mycompany/logmessages_
en.properties, /
mycompany/logmessages_de.properties. ( de
.)
. , ResourceBundle
. ,
.
r e a d in g F ile = A c h t u n g !
r e n a m in g F ile = D a te i

D a te i

w ird

w ird

e in g e le s e n

umbenannt

:
Logger

lo g g e r

= L o g g e r.g e tL o g g e r(lo g g e rN a m e ,

"com.mycompany. lo g m e s s a g e s " ) ;


, , .
lo g g e r . i n f o (" r e a d i n g F i le " ) ;

-
.
{0}, {1} .. , .
:
R ead in g
Achtung!

file

{0}.

D a te i

{0}

w ird

e in g e le s e n .


:
l o g g e r . l o g ( L e v e l . INFO,

"r e a d in g F ile ",

lo g g e r . l o g ( L e v e l. IN F O ,

" r e n a m in g F i le " ,

file N a m e );
new0bject[]

{ oldName,

newName

});

613



ConsoleHandler, System.err.
,
, ( "")
ConsoleHandler.
, .
,
.
, ,
.
j a v a . u t i l . l o g g i n g . C o n s o le H a n d le r . le v e l= IN F O

, FINE, 1
,
. ,
:
Lo gge r

lo g g e r

= Logger.getLogger("com .m ycom pany.m yapp);

l o g g e r . s e t L e v e l ( L e v e l . F IN E ) ;
l o g g e r . s e t U s e P a r e n t H a n d le r s ( f a ls e ) ;
H an d ler

h a n d le r

= new C o n s o le H a n d le r ( ) ;

h a n d le r . s e t L e v e l ( L e v e l . F IN E ) ;
l o g g e r . a d d H a n d le r (h a n d le r );

,
.
( ""),
INFO . ,
, useParentHandlers
false.
-,
. API
: FileHandler SocketHandler.
SocketHandler
. FileHandler,
.
FileHandler, :
F ile H a n d le r

h a n d le r

= new F i l e H a n d l e r ();

l o g g e r . a d d H a n d le r (h a n d le r );

javan.log,
, ,
.
(, Windows 95/98/), ,
, : \Windows.
XML. :
<record>
<date>2002-02-04T07: 4 5 : 15</date>
< m illis > 1 0 1 2 8 3 7 5 1 5 7 1 0 < / m illis >
<sequence>l</sequence>
< lo gge r> c o m .mycompany.m yapp</logger>

614

11 , ,

<level>INFO</level>
<class>com.mycompany.mylib.Reader</class>
<method>read</method>
<thread>10</thread>
<message>Reading file corejava.gif</message>
</record>

F ile H a n d le r
, (. 11.1)
(.
API ). ,
, , . ,
, %h/myapp.log (
. 11.2).
(
) ,
append, . ,
% ,
.
.
: m y a p p .l o g .,
app.log , . 2 . .
, , ,
0.
11.1. FileHandler

java.util.logging.
FileHandler.level
java.util.logging.
FileHandler.append

Level.ALL

false

java.util.logging.
FileHandler.limit


.

(0 )

0 (.. )
FileHandler; 50000

java.util.logging.
FileHandler.pattern

(.
. 11.3)

%h/java%u.log

java.util.logging.
FileHandler.count

1 ( )

java.util.logging.
FileHandler.filter
java.util.logging.
FileHandler.encoding

java.util.logging.
FileHandler.formatter

java.util.logging.
XMLFormatter

615

11.2.

%h

user.home

%t

%u

%g


. ( , %,
. %.|

.
. -
, .
, append,
.


, Handler StreamHandler.
, .
(. 11.2).

'

May 14, 2 0 0 7 9:15:47 PM ImageViewerFrame <init>

FINER: ENTRY
4
May 14, 2007 9:15:47 PM ImageViewerFrame <init>
1
FINER: RETURN
May 14, 200 7 9:15:47 PM LoggingfmageViewer main
FINE: Showing frame
May 14, 2007 9:16:17 PM ImageViewerFrame.FileOpenListene
FINER: ENTRY java. awt. event. Act ionEvent[ACTIGN_PERFORM ED, :
May 14, 200 7 9:17:32 PM ImageViewerFrameSFiteOpenListem *r-|

\
'
!

.._____ jL>

. 11.2. ,

StreanHandler
write () ,
, .
class WindowHandler extends StreamHandler
{
public WindowHandler()
{
final JTextArea output = new JTextAreaO;
setOutputStream(new
OutputStream()
{
public void write(int b) {} // !
public void write(byte[] b, int off, int len)
{

616

11 , ,
output.append(new String(b, off, len));
}
}) ;
}

:
,
. , p u b lish (),
.
:
class WindowHandler extends StreamHandler
{
public void publish(LogRecord record)
{
super.publish(record);
flush();
}
}


. Handler
p u b lis h (), f l u s h () c l o s e ().


. ,
.
Filter :
boolean isLoggable(LogRecord record)

,
true ,
. ,
, .
record.getMessage () ,
ENTRY RETURN.
,
set Filter (). , , ,
.


ConsoleHandler FileHandler
XML.
. Formatter
:
String format(LogRecord record)


. format ()

617

. ,
,
.
String formatMessage(LogRecord record)

(, XML)
,
. :
String getHead(Handler h)
String getTail(Handler h)

, s e t F o m a t t e r (),
.
, .
.

""
"" ,
.
1. . ,
,
c o m .m y c o m p a n y .m y p r o g . ,
:
Logger logger = Logger.getLogger("com.mycompany.myprog");

, ,
:
private static final Logger logger = Logger.getLogger("com.mycompany.myprog");

2. , INFO ,
. ,
, , , .
,
. ,
, .
m a in () .
if (System.getProperty("java.util.logging.config.class") == null
&& System.getProperty("java.util.logging.config.file") == null)
{
try
{
Logger.getLogger("").setLevel(Level.ALL);
final int LOG_ROTATION_COUNT = 10;
Handler handler =
new FileHandler(%h/myapp.log", 0, LOG_ROTATION_COUNT);
Logger.getLogger("").addHandler(handler);
}
catch (IOException e)
{
logger.log(Level.SEVERE,
}
}

"Cant create log file handler",

e);

618

11 , ,

3. . , ,
INFO, WARNING SEVERE, . ,
,
. FINE
, . ,
System, out .printIn (),
:
logger.f i n e ("File open dialog canceled");

, ,
, .
try
{

}
catch (SomeException )
{
logger.log(Level.FINE,
}

"explanation",

e);

11.2 ,
"" , :
, .
11.2. logging/LogginglmageViewer.java 1
1
2

package lo g g in g ;

import j a v a .awt.*;

import ja v a .a w t.e v e n t.*;

import j a v a . i o . * ;

import j a v a . u t i l . l o g g i n g . *;

import j a v a x .s w in g .*;

/**

* ,

10

11

* Aversion 1.02 2007-05-31

12

* @author Cay Horstmann

13

*/

14

p u b lic

15

c la ss

16

p u b lic

17

18

if

19

20
21
22

LogginglmageViewer

s ta tic

v o id m a i n ( S t r i n g []

args)

(S y ste m .g e tP ro p e rty ("ja v a .u til.lo g g in g .c o n fig .c la ss")


&&

System.getProperty("java.util.logging.config.file")

== n u l l
==

null)

{
try

23

L o g g e r .getL ogger("com .h orstm ann.corejava"). s e t L e v e l(L e v e l.A L L );

24

fin a l

25

Handler handler = new F ile H a n d le r (

26

30

LOG_ROTATION_COUNT = 10;

"%h/LoggingImageViewer. l o g " ,

27
28

in t

0,

LOG_ROTATION_COUNT);

L o g g e r .getL ogger("com .h orstm ann.corejava").addHandler(handler);


}
catch

(IOException e)


31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

66
67

{
Logger.getLogger("com.horstmann.corej ava").log(Level.SEVERE,
"Can't create log file handler, e) ;
}
}
EventQueue.invokeLater(new Runnable()
{
public void run()
{
Handler windowHandler = new WindowHandler();
windowHandler1.setLevel (Level .ALL) ;
Logger.getLogger("com.horstmann.corejava) .
addHandler(windowHandler);
JFrame frame = new ImageViewerFrame();
frame.setTitle("LogginglmageViewer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Logger.getLogger("com.horstmann.corejava").
fine("Showing frame");
frame.setVisible(true);
}
>);
}
}

I
* ,
V
class ImageViewerFrame extends JFrame
{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 400;
private JLabel label;
private static Logger logger =
Logger.getLogger("com.horstmann.corejava");

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

87

public ImageViewerFrame()
{
logger.entering("ImageViewerFrame", "<init>");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
//
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem openltem = new JMenuItern("Open");
menu.add(openltem);
openltem.addActionListener(new FileOpenListener());
JMenuItem exitltem = new JMenuItem("Exit");
menu.add(exitltem);
exitltem.addActionListener(new ActionListener()
{

619

620

11 , ,

88

89
90
91
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145

public void actionPerformed(ActionEvent event)


{
logger.fine("Exiting.");
System.exit(0);
}
});
//
label = new JLabelO;
add(label);
logger.exiting("ImageViewerFrame", "<init>");

private class FileOpenListener implements ActionListener


{
public void actionPerformed(ActionEvent event)
{
logger.entering("ImageViewerFrame.FileOpenListener",
"actionPerformed", event);
//
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
// .gif
chooser.setFileFilter(new javax.swing.filechooser.FileFilter ()
{
public boolean accept(File f)
{
return f.getName().toLowerCase().endsWith(".gif") II
f .isDirectory();
}
public String getDescription()
{
return "GIF Images;
}
});
//
int = chooser.showOpenDialog(ImageViewerFrame.this);
// ,
//
if ( == JFileChooser.APPROVE_OPTION)
{
String name = chooser.getSelectedFile().getPath ();
logger.log(Level.FINE, "Reading file {0}", name);
label.setlcon(new Imagelcon(name));
}
else logger.fine("File open dialog canceled.");
logger.exiting("ImageViewerFrame.FileOpenListener",
"actionPerformed");
}
}
}


146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
175
176
177
178
179
180
181
182

621

/**
*
*/
class WindowHandler extends StreamHandler
{
private JFrame frame;
1
public WindowHandler()
{
frame = new JFrame ();
final JTextArea output = new JTextAreaO;
output.setEditable(false);
frame.setSize(200, 200);
frame.add(new JScrollPane(output));
frame.setFocusableWindowState(false);
frame.setVisible(true);
setOutputStream(new OutputStream()
{
public void write(int b)
{
} // !
public void write(byte[] b, int off, int len)
{
output.append(new String(b, off, len));
}
});
}
public void publish(LogRecord record)
{
if (!frame.isVisible()) return;
super.publish(record);
flush();
}
}

ja v a . u t i l , lo g g in g . L o g g e r 1 .4

Logger getLogger(String loggerNam e)

Logger getLogger(String loggerN am e , String bundleName)

. ,
.
:

loggerN am e

,
I

...
bundleName

void severe(String m essage)

void warning(String m essage)

622

11 , ,

void info(String m essage)

void config(String m essage)

void fine(String m essage)

void finer(String m essage)

void finest(String m essage)

, ,
.

void entering(String classN am e,

String methodName)

void entering(String classN am e,

String methodName,

Object param)

void entering(String classN am e,

String methodName,

Object[] param )

void exiting(String classN am e,

String methodName)

void exiting(String classN am e,

String methodName,

Object r e s u l t )

,
.

void throwing(String classN am e,

String methodName,

, .

void log(Level

l e v e l , String m essage)

void log(Level

l e v e l , String m e ssa g e ,

Object o b j)

void log(Level

l e v e l , String m e ssa g e ,

Object[] o b js )

void log(Level

l e v e l , String m e ssa g e ,

Throwable t)

Throwable t)

.
.
{0}, {1} ..

void

logp(Level

le v e l,

String

c la ssN a m e ,

String

methodName,

String

le v e l,

String

c la ssN a m e ,

String

methodName,

String

String

c la ssN a m e ,

String

methodName,

String

String

c la ssN a m e ,

String

methodName,

String

m essage)

void

logp(Level

m e ssa g e ,

void

logp(Level

m e ssa g e ,

void

Object o b j)

Obj e c t [] o b js )

logp(Level

m e ssa g e ,

le v e l,

le v e l,

Throwable t)

.
.

void logrb(Level

bundleName,

String

c la ssN a m e ,

String

methodName,

String

c la ssN a m e ,

String

methodName,

String

String m essage)

void logrb(Level

bundleName,

le v e l,

le v e l,

String

String m e ssa g e ,

Object o b j)

void logrb(Level
bundleName,

String

c la ssN a m e ,

String methodName,

String

String methodName,

String

String m e ssa g e , Object[] o b js )

void logrb(Level
bundleName,

le v e l,

623

le v e l,

String

String m e ssa g e ,

c la ssN a m e ,

Throwable t)

,
. .

Level getLevel()

void setLevel(Level 1)

Logger getParent()

void setParent(Logger 1)

Handler[] getHandlers()

void addHandler(Handler h)

void removeHandler(Handler h)

boolean getUseParentHandlers()

void setUseParentHandlers(boolean b)

,
. true,
.

Filter getFilterO

void setFilter(Filter f)

j a v a . u t i l . l o g g i n g . H a n d l e r 1 . 4 *

a b s tr a c t v o id p u b lis h (L o g R e c o rd r e c o r d )
.

a b s tr a c t v o id f l u s h ()
.

a b s t r a c t v o id c lo s e ()
.

F i lt e r g e tF ilte r O

v o id s e t F i l t e r ( F i l t e r f )
.

F o rm a tte r g e tF o r m a tte r ()

624

11 , ,

void setFomatter (Formatter f)

Level getLevel()

void setLevel(Level 1)

j a v a . u t i l . l o g g i n g . C o n s o le H a n d le r 1 . 4

ConsoleHandler()

j a v a . u t i l . lo g g in g . F ile H a n d le r 1 .4

FileHandler(String p a t t e r n )
FileHandler(String p a t t e r n ,

boolean append)

FileHandler(String p a t t e r n ,

int l i m i t ,

int count)

FileHandler(String p a t t e r n ,

int l i m i t ,

int co u n t,

boolean append)

.
:

p a tte rn

(. . 11.2)

lim it

cou n t

append

true,

j a v a . u t i l . l o g g i n g . L o g R e c o rd 1 . 4

Level getLevel()

String getLoggerName()

, .

ResourceBundle getResourceBundle()

String getResourceBundleName()

, ,
. , null.

625

String getMessageO

, .

Object[] getParameters ()

null, .

Throwable getThrown()

null,
.

String getSourceClassName()

String getSourceMethodName()

, .
,
.
, ,
.

long getMillisO

, 1
1970 .

long getSequenceNumber()

int getThreadID()

,
. LogRecord
.

ja v a . u t i l . lo g g in g . F i l t e r

1 .4

boolean isLoggable(LogRecord re c o rd )

true, .

j a v a . u t i l . lo g g in g . F o rm a tte r 1 .4

abstract String format(LogRecord re c o rd )

,
.

String getHead(Handler h)

String getTail(Handler h)

, ,
. Formatter
.
.

626

11 , ,

String formatMessage(LogRecord re c o rd )

,
.


,
. ,
. ? (
, .)
,
. , Eclipse
NetBeans. ,
, ,
.
1.
System.out.println("=" + ) ;

Logger.getGlobal().i n f o ("=" + ) ;

,
. ,
toString (). ,
, :
Logger.getGlobal () .info (,,this=n + this);

Java toString ()
,
. .
.
2. , ,
main () ,
, .
public class MyClass
{



public static void main(String[] args)
{


)
}

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

627

3. ,
JUnit, http://junit.org.JUnit
,

. .

.
4. - ,
,
. , nextDouble ()
Random, -
:
Random generator = new
R a n d o m ()
{
public double nextDouble()
{
double result = super.nextDouble();
Logger.getGlobal().info("nextDouble:
return result;
}
};

" + result);

nextDouble ()
. , ,
, .
5. printStackTrace () Throwable,
.
,
, ,
.
try
{

}
catch (Throwable t)
{
t .printStackTrace() ;
throw t;
}

.
:
Thread.dumpStack() ;

6. ,
System.err.
, ,
.
ByteArrayOutputStream out = new ByteArrayOutputStreamO;
new Throwable().printStackTrace(out);
String description = o u t .toString();

628

11 , ,

7. , ,
.
System.err, System.out.
:
java Program > errors.txt

:
java MyProgram 2> errors.txt

,
,

Stream, err

Stream, out,

java MyProgram >4 errors.txt

bash

Windows.

8.
, System.err . ,
, ,
. ,
.
Thread.setDefaultUncaughtExceptionHandl
er () :
Thread.setDefaultUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler()
{
public void uncaughtException(Thread t, Throwable e)
{


};
});

9. , Java
- v e r b o s e . , :
[Opened
[Opened
[Opened
[Opened
[Loaded
[Loaded
[Loaded
[Loaded
[Loaded
[Loaded
[Loaded
[Loaded
[Loaded
[Loaded

/usr/local/jdk5.0/jre/lib/rt.jar]
/usr/local/jdk5.0/j/lib/jsse.jar]
/usr/local/jdk5.0/j re/lib/j ce.jar]
/usr/local/jdk5.0/jre/lib/charsets.jar]
java.lang.Object from shared objects file]
java.i o .Serializable from shared objects file]
java.lang.Comparable from shared objects file]
java.lang.CharSequence from shared objects file]
java.lang.String from shared objects file]
java.lang.reflect.GenericDeclaration from shared objects file]
java.lang.reflect.Type from shared objects file]
java.lang.reflect.AnnotatedElement from shared objects file]
java.lang.Class from shared objects file]
java.lang.Cloneable from shared objects file]

,
.
10. -Xlint
. , , ,
, break switch.
javac -Xlint:fallthrough

629

lint ,
, .
, ,
.
-X lin t.
-Xlint

-Xlint:all

-Xlint:deprecation

-deprecation,

..

-Xlint:fallthrough


break

switch

-Xlint:none

-Xlint:path

, ,

-Xlint:serial



serialVersionUID

(. 1

)
-Xlint:unchecked



(
12)

11. Java
, Java. ,
, ,
..
, ,
, .
JDK j console,

(. 11.3).
Java,
, . Unix/Linux
ps, Windows .
jconsole :
j console ^

. w w w . o r a c l e ,
/technetwork/articles/java/jconsole-1564139.html.

630

11 , ,

rC la s s e s -

20,000

15,000

Ledtd

1 10,SJ

10,000-*21:22
Loaded: 1 0 ,6 6 3

U nloaded: 20

Total: 1 0 ,683

. 1 1 .3 . j c o n s o l e

12. , "" (
), jmap.
:
jmap -dum p: fo rm a t= b , = ^
jh a t _ _

_ _ _

l o c a l h o s t : 7 0 0 0 .
-,
"" .
13. Java - X p r o f , ,
, ,
.
System.out. ,
.
! , -X,
JDK .
ja v a - X



. , AWT
.
1. , Swing, ,
, , ,
, .
<Ctrl+Shift+Fl>, ,
.
FontDialog[frameO,0,0,300x200,layout=java.awt.BorderLayout,...
javax.swing.JRootPane[, 4,23,292x173,layout=javax.swing.JRootPane$RootLayout,...
javax.swing. JPanel[null.glassPane,0,0,292x173,hidden,layout=java.awt.FlowLayout,...
javax.swing.JLayeredPane[null.layeredPane,0,0,292x173,...
javax.swing.JPanel[null.contentPane,0,0,292x173,layout=java.awt.GridBagLayout, ...
javax.swing.JList[,0,0,73x152,alignmentX=null,alignmentY=null,...
javax.swing.CellRendererPane[,0,0,0x0,hidden]
javax.swing.DefaultListCellRenderer$UIResource[,-73,-19,0x0,...
javax.swing.JCheckBox[,157,13,50x25,layout=javax.swing.OverlayLayout,...
javax.swing.JCheckBox[,156,65,52x25,layout=javax.swing.OverlayLayout,...
javax.swing.JLabel[,114,119,30x17,alignmentX=0.0,alignmentY=null,...
javax.swing.JTextField[,186,117,105x21,alignmentX=null,alignmentY=null,...
javax.swing.JTextField[,0,152,291x21,alignmentX=null,alignmentY=nul

2.
Swing ,
Swing.
, ,
.
Swing, setDebugGraphicsOptions ()
JComponent. .
DebugGraphics.FLASHjOPTION

DebugGraphics.LOG OPTION

DebugGraphics.BUFFERED_OPTION

ebugGraphics.NONE_OPTION

,
,



,

,
,
.
.
RepaintManager.currentManager (getRootPane() )
.setDoubleBufferingEnabled(false);
((JComponent) getContentPane()).setDebugGraphicsOptions(
DebugGraphics.FLASH_OPTION);

632

11 , ,

.
,
.
setDebugGraphicsOptions (). ,
(
DebiigGraphics ).
3. AWT,
,
.
. 11.3
EventTracer, .

EventTracer :
EventTracer tracer = new EventTracer();
tracer.add(frame);


, . 11.4.
tid

......

iiSSSifegja'fe
BWL
pmhC

t.MouseEvent ):java.awt .event.MouseEvent[HOUSE_HOVED,(305,28),absolute(380,232),b


utton=G,clickCount=G] on null.contentPane
public abstract void java.awt.vent.NouseNotionListener.niouseHoved(java.awt.even
t.HouseEvent):java.awt.vent.MouseEvent[MOUSE_MOVED,(341,46),absolute(416,250),b
utton=G,clickCount=] on null,contentPane
public abstract void java.awt.event.HouseHotionListener.mouseMoved(java.awt.even
t.MouseEvent):java.awt.event.HouseEvent[M0USEJ40VED,(389,68).absolute(464,272),b
utton=0,clickCount0] on null.contentPane
public abstract void java.awt.event.HouseListener.mouseExited(java.awt.event.Hou
seEvent):java.awt.event.HouseEvent[H0USE_EXITED,(441,90).absolute(516,294).butto
n=G,clickCount=G] on null.contentPane
public abstract void java.awt.event.FocusListener.focusLost(java.awt.event.Focus
Event):java.awt.FocusEvent(F0CUS_L0ST,temporary,opposite=null,causeACTIVATIONl
on javax.swing.JSlider[,0,0,398x16,alignmentXaO.0,alignmentY*0.0,borders,flags*2
96,maximumSizes,nininuR6izes,preferredSize,islnvertedsfelse,majrTickSpacing*0,
minorTickSpacing=,orientation=H0RIZ0NTAL,paintLabels=false,paintTicksxfalse,pai
ntTracketrue,snapToTicks*false,snapToValue=true]
public abstract void java.awt.event.WindowFocusListener.windowLostFocus(java.awt
.event.WindowEvent):java.awt.event.WindowEvent[WINDOW_LOST_FOCUS,opposite*null,
ldState=G,newState=G] on frameO
public abstract void java.awt.event.WindowListener.windowDeactivated(java.awt.ev
ent.WindowEvent):java.awt.event.WindowEvent[WINOOW_DEACTIVATED,opposite^xill,oldI:
State=Q,newState^O] on frameO
I

1
. 11.4. EventTracer

11.3.
1
2
3
4
5

package eventTracer;
import java.awt.*;
import java.beans.
import java.lang.reflect.*;

eventTracer/EventTracer.java1

/**


8
9

* (Aversion 1.31 2004-05-10


* Qauthor Cay Horstmann

10 */
11 public class EventTracer

12 {
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
43
44
45
46
47
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

private InvocationHandler handler;


public EventTracer()
{
// -
handler = new InvocationHandler ()
{
public Object invoke(Object proxy, Method method, Object[] args)
{
System.out.println(method + IfttIt + args[0]);
return null;
};
}
j itit

* ,
*
*
*/
public void add(Component )
{
try
{
// ,
Beanlnfo info = Introspector.getBeanlnfo(c.getClass ());
EventSetDescriptor[] eventSets = info.getEventSetDescriptors();
for (EventSetDescriptor eventSet : eventSets)
addListener(c, eventSet);
}
catch (IntrospectionException e)
{
// ,
if ( instanceof Container)
{
//
// add()
for (Component comp : ((Container) c).getComponents ())
add(comp);
}
}

I
*
*
* eventSet
*/
public void addListener(Component c, EventSetDescriptor eventSet)
{
// -
//

633

634
66
67

11 , ,
Object proxy = Proxy.newProxylnstance(null, new Class[]
{ eventSet.getListenerType() }, handler);

68

69
70
71
72
73
74
75
76
77
78
79
}
80 }

// -
Method addListenerMethod = eventSet.getAddListenerMethodO;
try
{
addListenerMethod.invoke(c, proxy);
}
catch(ReflectiveOperationException
e)
{
}
// ,

AWT
Robot
AWT-.
. Robot,
GraphicsDevice.
:
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice screen = environment.getDefaultScreenDevice();

Robot:

Robot robot = new Robot(screen);

, Robot
. ,
.
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);

,
.
:
robot.mouseMove(, ); //
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTT0N1_MASK);

, ,
, ,
. ,
createScreenCapture (), . ,
Rectangle,
.
Rectangle rect = new Rectangle(, , width, height);
Bufferedlmage image = robot.createScreenCapture(rect);

635

, ,
Robot,
. delay (),
:
robot.d e l a y (1000); // 1000

, 11.4,
Robot. ,
8.
. Robot
,
. Robot
<> .
. (
, .) ,
(. 11.5).

apt

_ :

Yellow

Igginglmag
km rtm iim iim fw m tm m iim fw w

mport jc
mport j<
mport jc
mport j c
"
7 vlch09-G roupLayoutT est
7 vlch 0 9 -M e n u T e st

mm

pr

W
m

ers:

vlch0 9 -O ptionD ialogT e st


I

I*

Hr
,

*/

public cl

. 11.5. AWT
! AWT ,
11.4. 14.

, Robot
. ,
.
,

636

11 , ,

,
,
.
11.4. r o b o t / R o b o t T e s t . ja v a
1
2
3
4
5
6
7
8
9

package robot;

10

*/

11
12
13
14
15
16
17
18
19

public class RobotTest

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
/**
* (Aversion 1.04 2012-05-17
* Qauthor Cay Horstmann

{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
//

20
21
22

ButtonFrame frame = new ButtonFrame();


frame.setTitle("ButtonTest");

23

fram e. setDefaultCloseOperation(JFram e.EXIT_ON_CLOSE);

24
25
26
27
28
29
30
31
32

frame.setVisible(true);

GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice screen = environment.getDefaultScreenDevice ();

33
34
35
36
37
38

try
{
final Robot robot = new Rpbot(screen);
robot.waitForldle ();
new Thread()

}
});
//

39

40
41
42
43
44
45
46
47
48
49

public
voidrun()
{
runTest(robot);
};
}.start();
}
catch (AWTException e)
{
e.printStackTrace();


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

*
* 0param robot ,
*/
public static void runTest(Robot robot)
{
//
robot.keyPress(* ');
robot.keyRelease(' ');
//
robot.delay(2000);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK TAB);
robot.keyPress(* ');
robot.keyRelease(' ') ;
//
robot.delay(2000);
robot.mouseMove(220, 40);
robot.mousePress(InputEvent.BUTT0N1_MASK);
robot.mouseRelease(InputEvent.BUTT0N1_MASK);
//
robot.delay(2000);
Bufferedlmage image =
robot.createScreenCapture(new Rectangle(0, 0, 400, 300));
ImageFrame frame = new ImageFrame(image);
frame.setVisible(true);
}
}

*
*/
class ImageFrame extends JFrame
{
private static final int DEFAULT_WIDTH = 450;
private static final int DEFAULT_HEIGHT = 350;
/*
* @param image
V
public ImageFrame(Image image)
{
setTitle("Capture");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
JLabel label = new JLabel(new Imagelcon(image));
add(label);
}
}

637

638

11 , ,

j a v a . a w t . G r a p h ic s E n v ir o n m a n t 1 . 2

static GraphicsEnvironment getLocalGraphicsEnvironment()

GraphicsDevice getDefaultScreenDevice()

, .
,
, ,
getScreenDevices ().

ja v a .a w t.R o b o t 1 .3

Robot(GraphicsDevice d e v ic e )

Robot, .

void keyPress(int key)

void keyRelease(int key)

.
:

k ey

.
Keystroke

void mouseMove (int x ,

int y)

.
:

void mousePress(int eventM ask)

void mouseRelease(int eventM ask)

.
:

eventM ask

, .

. inputEvent

void delay(int m illis e c o n d s )

Robot .

Bufferedlmage createScreenCapture(Rectangle r e c t )

.
:

rect

639



.
,
. ,
. ,
, ,
.
11.7 ButtonTest 8,
. ,
. , ,
.

. ,
.
, Eclipse
.
! , , , JSwat
(h t t p : / /c o d e .g o o g le . e o m / p / js w a t ) jd b ,
-,
:

javac -g BuggyButtonTest.java
.

11.5. debugger/BuggyButtonTest .java1


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

package debugger;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* (Aversion 1.22 2007-05-14
* @author Cay Horstmann
*/
public class BuggyButtonTest

{
public static void main(String[] args)
{
EventQueue.invokeLater (new Runnable()
{
public void run()
{
JFrame frame = new BuggyButtonFrame ();
frame.setTitle("BuggyButtonTest");
frame.setDefaultCloseOperation(JFrame.EXIT_0N_CL0SE);
frame.setVisible(true);

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

11 , ,
}) ;
)

)
class BuggyButtonFrame extends JFrame
{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public BuggyButtonFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
//
BuggyButtonPanel panel = new BuggyButtonPanel();
add(panel);
}
}
class BuggyButtonPanel extends JPanel
{
public BuggyButtonPanel()
{
ActionListener listener = new ButtonListener ();
JButton yellowButton = new JButton("Yellow");
add(yellowButton);
yellowButton.addActionListener(listener);
JButton blueButton = new JButton("Blue");
add(blueButton);
blueButton.addActionListener(listener);
JButton redButton = new JButton("Red");
add(redButton);
redButton.addActionListener(listener);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String arg = event.getActionCommandO;
if (arg.equals("yellow")) setBackground(Color.yellow);
else if (arg.equals("blue")) setBackground(Color.blue);
else if (arg.equals("red")) setBackground(Color.red);
}
}
}

Eclipse Rurv=>Debug As=>Java


Application (^ 1^ Java).
.
actionPerformed (),

641

Toggle Breakpoint (/
) .
, Java
a c t i o n P e r f o r m e d O .
Yellow ().
actionPerformedO, . 11.6.
r

fbrfa&or fcjayigate Search roject San

'(&*
I^ D e b u g
^

I 1

S e rv e rs ! *|g

CC Exceptlfest [Java A p plicatio n ]

V/blue

I /h o m e /a p p s /jd k l.6 .0 _ 0 1 /b in /ja v a (M a y 14. 2 0 0 7 6 :1 0 :3 3 PM )

B u ggyB uttonP anj


.i

0 0 ExceptTest [Java A p plication]

A ction E vent (id=;l

| | /h o m e /a p p s /jd k 1 .6 .0_0 1/bin /java (M a y 14. 2 0 0 7 6 :1 0 :4 8 PM )

! v J31 B uggyB uttonTest [Java A p plication]


j

B uggyB uttonTest a t lo ca lh o s t:4 7 0 6 1

*( T h re ad [AWT-XAWT] (Running)

t
|

T h read [A A T -S h u td o w n ] (Running)

# T h re ad [A W T -E ventQ ueue-0] (S u s p e n d e d (b rea k p o in t a t line 5 9 in E


............. .. . .

0i

-X

.............

re d B u tto n .a d d A c tio n L iste n e r(liste n e r);

}
p riv a te c la s s B u tto n Liste n e r ia p le a e n ts A c tio n L iste n e r

{
p u b lic vo id actionPerform ed(ActionEvent event)

i f (a r g . e q u a ls ( "y e llo w " ) )


setBackground (C olor. yellow) ;
e ls e i f ( a r g . e q u a ls ( "b lu e ") )
setBackg round{C o l r .b i u e );
e ls e i f (a r g .e q u a ls ( " r e d " ) )
se tB ack gro u n d (C o lo r. red) ;

}
~: ~
"

i s Console

3 x

-,~
.I
4)

'-rb
f$
i
]!

I
ii

if
i
aaisittsabS'I f e .t. A a ara a * ^

C*'

WhtaWe

) Sm art lnsert

: 59 l

. 11.6.

.
Step Into , Step
Over , .
Eclipse Run^Step Into
Run=>Step Over <F5> <F6> . ,
Step Over , .
, , .

642

11 , ,

BuggyButtonTest .java S3

'- .

' //;'
imJmHfdjJdJ i i J ti,Jt,

re d B u tto n .a d d A c tio n L is te n e ( l i s t e n e r ) ;
}

p r iv a t e c la s s B u tto n L is te n e r in p le a e n ts A c tio n L is te n e r
{

p u b lic v o id a c tio n P e rfo rm e d lA c tio n E v e n t e v e n t)


'{
S tr in g arg = even t.g etA ctio n C o m m an d O ;
i f (a r g .e q u a ls (" y e llo w " ))
s e tkground( C o lo r .y e llo w ) ;
s e tkg round( Col o r .b lue);
e ls e i f ( a r g .e q u a lS { " r e d " ))
s e tfla c k g ro u n d (C o lo r. red) ;
>
}
}

i
...% :

, setColor (Color.
yellow),
. ,
arg, .

643

, . arg
"Yellow", Y,
"yellow", , .
if (arg.equals("yellow"))

, Run^Terminate (1^
). Eclipse
, , ,
, .
, , , NetBeans, .
,
.

: Java.

...









Java 1.0.
Java 5.0 SE
Java (Java Specification Requests JSR 14),
1999 .
.
,
, , , Object
.
ArrayList.
, , , C++. C++,
Java,

646

12

. .
, , , ,
.


,
. ,
String
File, ,
ArrayList.
.
Java SE 5.0 Java
. , ArrayList
Object :
/

public class ArrayList //


{
private Object[] elementData;

public Object get(int i) { . . . }


public void add(Object o) { . . . }
}

. ,
, , .
ArrayList files = new ArrayList()/

String filename = (String) files.g e t (0);

, .
:
files.add(new File(". .

.
get () String .
: . ArrayList
, ,
. .
, String.
ArrayList<String> files = new ArrayList<String>();

! , Java SE 7,
, .
ArrayList<String> files = new ArrayListo ;

..

. ,
get () .
, String, Object.
String filename = files.get (0);

647

, add() ArrayList<String>
String. ,
Object. ,
. , :
files .add (new File(" . . .")); // ArrayList<String>
//

String

,
.
,
.


, ArrayList,
. Java
ArrayList<String>,
Java, String [ ]. (,
, .)
- . ,
,
. ,
.

.
? ,
.
ArrayList addAll (),
. ,
ArrayList<Manager>
ArrayList<Employee>. , , .
? Java
, .
,
.
.
(
, ArrayList, , ).

, .
, ,
.
Java,
, " ". , ,
.
, ,
. JDK
.
:

| |

12

,
, , , Object Comparable.
,
. ,
,

.


.
Pair.
,
, .
Pair.
public class Pair<T>

{
private T first;
private T second;
public Pair() { first = null; second = null; }
public Pair(T first, T second)
{ this.first = first; this.second = second; }
public T getFirstO { return first; }
public T getSecondO { return second; }
public void setFirst(T newValue) { first = newValue; }
public void setSecond(T newValue) { second = newValue; }

}
Pair , ( )
.
. , Pair
:
public class Pair<T, U> { . . . }


, , .
.
private first;

//

!
. , Java ,
V , ( S
) , .


:
Pair<String>

649


:
Pair<String>()
Pair<String>(String,

String)

:
String getFirst()
String getSecond()
void setFirst(String)
void setSecond(String)

, .
12.1 Pair.
minmax()
.
; Pair. , compareTo ()
, ,

,
.
C++! Java
C++. , Java
template. , ,
.

12.1. pairl/PairTestl.java1
1
2
3
4
5

package pairl;
/**
* (Aversion 1.01 2012-01-26
* @author Cay Horstmann

6 */
7

public class PairTestl

8 {
9

10

public static void main(String [] args)

11
String[] words = { "Mary", "had", "a", "little", "lamb" };
12
Pair<String> mm = ArrayAlg.minmax(words);
13
System.out.println("min = " + mm.getFirst());
14
System.out.println("max = " + mm.getSecond());
15
}
16 }
17
18 class ArrayAlg
19 {

20

/**

21
22
23
24
25
26

*
*
*
*
*
*/



@param
@return
,

650

1 12

27
public static Pair<String> minmax(String[] a)
28
{
29
if (a == null || a.length == 0) return null;
30
String min = a[0];
31
String max = a[0];
32
for (int i = 1; i < a.length; i++)
33
{
34
if (min.compareTo (a [i]) > 0) min = a[i];
35
if (max.compareTo (a [i]) < 0) max = a[i];
36
}
37
return new Pair<>(min, max);
38
}
39 }


, .
(
) :
class ArrayAlg

<
public static <T> T getMiddle(... )

{
return a[a.length / 2];

, .
, .
, (
public static) .
,
. ,
, , .
String middle = ArrayAlg.<String>getMiddle("John",

"Q.",

"Public");

( )
String. ,
, .
(.. String [] []) ,
String,
:
String middle = ArrayAlg.getMiddle("John",

"Q.",

"Public");


. ,
, . :
double middle = ArrayAlg.getMiddle(3.14,

1729,

0);


, ,
. ,

651

Double Integer,
. :
Number Comparable, .

double.

. Axe (Peter von der Ahe) ,


, :
.
: ArrayAlg.getMiddle ("Hello", 0, null).
JButton, ,
:
found:
java.lang.Object&java.io.Serializable&j ava.lang.Comparable<? extends
java.lang.Obj ect&j ava.io.Serializable&j ava.lang.Comparable<?>>

,
Object, Serializable Comparable.

C++! C++ .
. ,
g(f<a,b>()) : " ()
f<a, b> () " g () f<a > () .



. ,
:
class ArrayAlg

{
public static <T> T min(T[] ) //
{
if ( == null || a.length == 0) return null;
smallest = [0];
for (int i = 1; i < a.length; i++)
if (smallest.compareTo(a[i]) > 0) smallest = a [i ];
return smallest;

}
. min ().
smallest , ,
. ,
compareTo()?

,
,
Comparable compareTo ().
:
public static < extends > min(T[]

. . .

652

12

Comparable .

. " "
,
Comparable.

min () ,
Comparable, String, Date .. min ()
Rectangle ,
Rectangle Comparable.
C++! C++ .
, ( )
.

, extends
implements, Comparable ? ,
< extends _>

, ,
, .
extends ,
, Java
.
,
. &,
.
extends Comparable & Serializable

Java,
, .
,
.
12.2 minmax ()
.
Pair<T>.

12.2. pair2/PairTest2.java1
1

package pair2;

3
4

import java.util.*;

/**

6
7

* (Aversion 1.01 2012-01-26


* Oauthor Cay Horstmann

8 */
9

public class PairTest2

10 {
11

12

13
14

public static void main(String[] args)

GregorianCalendar[] birthdays =
{


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

653

new GregorianCalendar(1906, Calendar.DECEMBER, 9), // G. Hopper


new GregorianCalendar(1815, Calendar.DECEMBER, 10), //A. Lovelace
new GregorianCalendar(1903, Calendar.DECEMBER, 3), // J. von Neumann
new GregorianCalendar(1910, Calendar.JUNE, 22),
// K. Zuse
};
Pair<GregorianCalendar> mm = ArrayAlg.minmax(birthdays);
System.out.println("min = " + mm.getFirst().getTime());
System.out.println("max = " + mm.getSecond().getTime());
}
}
class ArrayAlg
{
/**
*
*
* Oparam
* @return
* ,
*/
public static < extends Comparable> Pair<T> minmax(T[] a)
{
if (a == null || a.length == 0) return null;
T min = a [0];
T max = a [0];
for (int i = 1; i <a.length; i++)
{
if (min.compareTo (a [i]) > 0) min = a[i];
if (max.compareTo (a [i]) < 0) max = a[i];
}
returnnew Pair<>(min,
max);
}
}



.

, 1.0!
Java
.
, ,
( "") .
.
( Object,
). ,
Pair<T> :
public class Pair

{
private Object first;
private Object second;
public P a i r (Object first, Object second)

654

12

th is.first = first;
t h i s . s e c o n d = second;

}
public
public
public
public

Object g e t F i r s t O { r e t u r n f i r s t ; }
Object g e t S e c o n d ( ) { r e t u r n se con d; }
v o i d s e t F i r s t (Object newValue) { f i r s t = newValue; }
v o i d s e t S e c o n d (Object newValue) { second = newValue; }

,
O b j e c t . ,
Java.
P a i r , P a i r < S t r i n g > P a i r < G r e g o r i a n C a l e n d a r > ,
P a i r .
T

C++! Java C++.


C++ .
. A Java .


O b j e c t , .
, P air<T >
, O b j e c t . ,
, , .
p u b l i c c l a s s I n t e r v a K T e x t e n d s Comparable &
S e r i a l i z a b l e > implements S e r i a l i z a b l e

p r i v a t e T lower;
p r i v a t e T upper;

public Interval(T f i r s t ,

T second)

i f ( f i r s t . c o m p a r e T o ( s e c o n d ) - <= 0) { lower = f i r s t ;
e l s e { lower = second; upper = f i r s t ; }

upper = second;

}
}
:
p u b l i c c l a s s I n t e r v a l implements S e r i a l i z a b l e
{
p r i v a t e Comparable lower;
p r i v a t e Comparable upper;

p u b l i c I n t e r v a l (Comparable f i r s t , Comparable second)

{ . . . }

}
! , : c l a s s I n t e r v a K S e r i a l i z a b l e &
Comparable>? S e r i a l i z a b l e ,
, , Comparable.
(..
).

655


,
.
:
Pair<Employee> buddies = . . .;
Employee buddy = buddies.getFirst();

getFirst () Object.
Employee. ,

:

Pair.getFirst ();

Object Employee.


. , first second , .. public. (,
, Java.)
-
.
Employee buddy = buddies.first;


.
:
public static < extends Comparable> min(T[] )

.
, ,
Comparable.
public static Comparable min(Comparable[] a)

.
:
class Datelnterval extends Pair<Date>

{
public void setSecond(Date second)

if (second.compareTo(getFirst()) >= 0)
super.setSecond(second);

}
Date,
,
.
:
class Datelnterval extends Pair //

{
}

public void setSecond(Date second)

{ . . . }

656

12

, setSecond (),
Pair,
public void setSecond(Object second)

, :
Object Date. .
:
Datelnterval interval = new Datelnterval(. . .);
Pair<Date> pair = interval; //
p a i r .setSecond(aDate) ;

, setSecond () ,
. pair
Datelnterval, Datelnterval.setSecond ().
, .

Datelnterval:
public void setSecond(Object second)

{ setSecond((Date) second);

,
.
p a i r .setSecond(aDate)

pair Pair<Date>,
setSecond, setSecond (Object).
,
pair. Datelnterval,
Datelnterval . setSecond (Object).
. , , Datelnterval.
setSecond (Date), , , .
. ,
Datelnterval getSecondO, .
class Datelnterval extends Pair<Date>

{
public Date getSecondO
#

{ return

(Date)

super.getSecond().c l o n e (); }

}
Datelnterval getSecond:
Date getSecondO
Object getSecondO

// Datelnterval
// Pair
//

Java .
.
.
- , ,
.

! .
5,
, . ,

Object, clone () Employee.clone ()

657

public class Employee implements Cloneable


{
public Employee clone() throws CloneNotSupportedException { ...

}
Object :
Employee c l o n e () //
Object c lone() // ,
// Object.clone()

, Java .

,
.


Java :
. .
JSlider :
void setLabelTable(Dictionary table)

Dictionary , JSlider
Java.
, .
DictionaryCInteger, Component> labelTable = new H a s h t a b l e o ();
labelTable.put(0, new JLabel(new Imagelcon("nine.gif")));
labelTable.put(20, new JLabel(new Imagelcon("ten.gif")));

D i c t i o n a r y < I n t e g e r ,
Component> setLabelTable () ,
.
slider.setLabelTable(labelTable); // !

, setLabelTable ()
Dictionary. ,
, ,
Integer.
.
- ,
, JSlider

658

12

Dictionary ,
JSlider ,
.
,
.
, ,
.
Dictionarycinteger, Components> labelTable
= slider.getLabelTable(); // !

,
Integer Component,
, . ,
Dictionary JSlider.
, .
.
, ,
, .
:
QSuppressWarnings("unchecked")
Dictionarycinteger, Components> labelTable
= slider.getLabelTable(); //


,
, Java.
.


. ,
Pair<double>, Pair<Double>. ,
, . Pair
Object,
double.
,
Java. .
,
, -.


.
.
, ,
Pair :
if (a instanceof Pair<String>)

// !

659

:
if (a instanceof Pair<T>)

// !

:
Pair<String> = (Pair<String>) ; // !
// Pair

, (
instanceof) ( ) ,
, .
getClass () ,
. true,
getClass () Pair .class.
Pair<String> stringPair = . . .;
Pair<Employee> employeePair = . . .;
if (stringPair.getClass() == employeePair.getClass()) // !


:
Pair<String>[] table = new Pair<String>[10]; // !

? Pair [].
Obj ect [ ] :
O b ject[] objarray = table;


ArrayStoreException, ,
.
objarray[0] = "Hello; // ! Pair

.
,
.
.
objarray[0] = new Pair<Employee>();

, , ,
. , , Pair<String>[],
Pair<String> [10].
! ,
:
Pair<String>[] table =

(Pair<String>[]) new Pair<?>[10];

. ,
Pair<Employee> table [0],
table[0] .getFirstO String,
ClassCastException.

660

12

. ,
ArrayList, ArrayList<Pair<String.
.


, Java
.
:
.

:
public static <> void addAll(Collection<T> coll, T... ts)

{
for (t : ts) coll.add(t);

}
, ts ,
.
.
Collection<Pair<String>> table = ...;
Pair<String> pairl = ...;
Pair<String> pair2 = ...;
addAll(table, pairl, pair2);

Java
Pair<String>, .
, .
. -,
@SuppressWarnings ("unchecked ) ,
addAll (). , -, Java SE 7,
@SafeVarargs addAll (), .
@SafeVarargs
public static <> void addAll(Collection<T> coll, T... ts)

.
,

.
! @SafeVarargs
. :
0SafeVarargs static <> [] array(... array)

{ return array;

:
Pair<String>[]

table = array(pairl,

pair2);

, :
Object[] objarray = table;
objarray[0] = new Pair<Employe>();

661

ArrayStoreException,
.
table [0] , .


new ( . . . ) ,
new [ . . . ] . class. , Pair<T> :
public P a i r () { first = new (); second = new T();

} // !

Object,
new Object (), , .
, Class,
newlnstance (). , . ,
, .class .
first = .class.newlnstance(); // !

API,
Class, .
public static <> Pair<T> makePair(Class<T> cl)

{
try { return new P a i r o ( c l .newlnstance(), c l .newlnstance())
catch (Exception ex) { return null; }

}
:
Pair<String> = Pair.makePair(String.class);

, , , Class .
, Str i n g . c l a s s ( )
Class<String>. makePair () .
, .
Comparable [2].
public static < extends Comparable> T[] minmax(T[]
new T [2]; . . . } // !

a)

{ T[] mm =

,
Obj ect [ ]
. , ArrayList :
public class ArrayList<E>

{
private Object[] elements;

@SuppressWarnings("unchecked") public E get(int n)


{ return (E) elements[n]; }
public void set(int n, E e) { elements[n] = e; } //
//

}
, .
[] ,
.

662

12

public class ArrayList<E>

{
private E[] elements;

public ArrayListO

{ elements = (E[]) new Object[10];

}
minmax (),
[ ]. ,
. , minmax ()
:
public static < extends Comparable> [] m i n m a x (... )

{
Object[] mm = new Object[2];

return

(T[3) mm; //

}

.
String[] ss = minmax("Tom",

"Dick",

"Harry");

ClassCastException ,
Obj ect [] String [].
Array.newlnstance () :
public static < extends Comparable> [] m i n m a x (... )

{
[] mm = ([]) A r r a y .newlnstance(.getClass().getComponentType(), 2);

}
toA#rray () ArrayList .
[ ], .
:
Object[] toArrayO
[] toArray(T[] result)

.
, .
result.


.
, :
public class Singleton<T>

{
private static T singlelnstance;

// !

public static T getSinglelnstance() // !

{
if (singlelnstance == null)
return singlelnstance;

663

, '
Singleton<Random>
Singleton < JFileChooser>
. .
Singleton singlelnstance.
.




.
Throwable. ,
.
public class Problem<T> extends Throwable
{ /* . . . * / } / / ! Throwable

, catch. ,
:
public static < extends Throwable> void doWork(Class<T> t)

{
try

}
catch

(T e) // !

{
Logger.global.info (...)

}
}

. , .
public static < extends Throwable> void doWork(T t) throws T //
!

{
try

}
catch

(Throwable realCause)

{
t .initCause(realCause);
throw t;

}
}


Java,
.
, .
:

664

12

@SuppressWarnings("unchecked")
public static <T extends Throwable> void throwAs(Throwable e) throws T
{
throw (T) e;

}
, Block.
, t .
Block.<RuntimeException>throwAs(t);


:
try

}
catch

(Throwable t)

{
Block.<RuntimeException>throwAs(t);

}
.
,
. toThread ()
Thread, run () ,
.
public abstract class Block
{
public abstract void body()
public Thread toThread()

throws Exception;

{
return new T h r e a d ()

{
public void run()

{
try

{
b o d y ();

}
catch

(Throwable t)

{
Block.<RuntimeException>throwAs(t);

}
};

}
@SuppressWarnings("unchecked")
public static <T extends Throwable> void throwAs(Throwable e) throws T
{
throw

(T) e;

}
}
, ,
.
public class Test
{

665

public static void main(String[] args)

{
new Block ()

{
public void body() throws Exception
{
V
Scanner in = new Scanner(new File("ququx"));
while (i n .hasNext())
System.o u t .p r i n t l n (i n .n e x t ());

}
}
.toThread().s t a r t ();

}
}

FileNotFoundException, , ,
ququx. ? ,
, run () ,
. run ()
.
.
,
. ,
@SuppressWarnings
, Java.


,
. , Pair equals ()
:
public class Pair<T>

{
public boolean equals(T value)
{ return first.equals(value)

&& second.equals(value); }

}
Pair<String>. ,
equals ():
boolean equals(String)
boolean equals(Object)

// Pair<T>
// Object

.
boolean equals () boolean equals (Object),
Object .equals (). ,
, - .
:
,
,
.
, :

666

12

class Calendar implements Comparable<Calendar> { . . . }


class GregorianCalendar extends Calendar implements
Comparable<GregorianCalendar> { . . . } / / !

GregorianCalendar
, Comparable <Calendar> Comparable<GregorianCalendar>,
. ,
.
Comparable:
class Calendar implements Comparable { . . . }
class GregorianCalendar extends Calendar implements Comparable { . . . }

\ ,
. ,
Comparable<X>, .
, X
.
public int compareTo(Object other)

{ return compareTo((X) other);



, . ,
.
Employee Manager. Pair<Manager>
, Pair<Employee>? ,
. , :
Manager[] topHonchos = . . .;
Pair<Employee> result = ArrayAlg.minmax(topHonchos); // !

m i n m a x O P a i r < M a n a g e r > ,
Pair<Employee>, .
Pair<S> Pair<T> ,
(. 12.1).

/
./

. 12.1. Pair

667

,
. , Pair<Manager>
- Pair<Employee>,
.
Pair<Manager> managerBuddies = new Pair<>(ceo, cfo);
Pair<Employee> employeeBuddies =
managerBuddies; // , ,
employeeBuddies.setFirst(lowlyEmployee);

, employeeBuddies
managerBuddies . ,
,
Pair<Manager> .
!
Java. , Manager [] Employee []
:
Manager [] managerBuddies = { ceo, cfo };
Employee[] employeeBuddies = managerBuddies;

// !

.
employeeBuddies [0],
ArrayStoreException.

. ,
Pair<Employee> Pair.
.
? , .
:
Pair<Manager> managerBuddies = new Pair<>(ceo, cfo);
Pair rawBuddies = managerBuddies; // !
rawBuddies.setFirst(new File(". . .")); // ,
//

, , .
, Java.
. getFirst ()
Manager, ClassCastException,
.
, .
, ,
.
. , ArrayList<T>
List<T>. , ArrayList<Manager>
List<Manager>. ,
ArrayList<Manager> ArrayList<Employee>
List<Employee>. . 12.2
.

668

12

. 1 2 .2 .


,
. Java
( ) : .
, Pair,
, Employee,
, Pair<Manager>, Pair<String>.
Pair<? extends Employee>

, ,
:
public static void printBuddies(Pair<Employee> p)

{
Employee first = p.getFirst();
Employee second = p.getSecond();

669

System.out.println(first.getName() + " and " +


second.getName() + " are buddies.";

}
, Pair<Manager>
, .
:
public static void printBuddies (Pair<?

extends Enployee> p)

Pair<Manager> Pair<? extends Employee> (. 12.3).

. 12.3.

Pair<Manager> Pair<? extends


Employee>? , .
Pair<Manager> managerBuddies = new Pair<>(ceo, cfo);
Pair<? extends Employee> wildcardBuddies = managerBuddies; // !
wildcardBuddies.setFirst(lowlyEmployee); //

setFirst () .
,
Pair<? extends Employees :
? extends Employee getFirstO
void setFirst(? extends Employee)

setFirst ().
- Employee, , .
, ?
. getFirst () .
, getFirst ,
Employee. , ,
.
.

670

12


.

:
? super Manager

Manager. (
, Java super
.) ?
, ,
. , ,
. , Pair<?
super Manage > :
void setFirst(? super Manager)
? super Manager getFirstO

setFirst (),
Manager, Employee Object,
, Executive. , getFirst ,
.
Object.
. ,

Pair.
Pair? , Pair<Employee>
Pair<Object> (. 12.4).
Pair :
public static void minmaxBonus(Manager[] a, Pair<? super Manager> result)

{
if (a == null I I a.length == 0) return;
Manager min = a[0];
Manager max = a[0];
for (int i = 1; i < a.length; i++)

{
if (min.getBonus() > a[i].getBonus()) min = a [i ];
if (max.getBonus() < a[i].getBonus()) max = a[i];

}
result.setFirst(min);
result.setSecond(max);

}
,
,
.
. Comparable .
:
public interface Comparable<T>

{
public int compareTo(T other);

671

. 12.4.

other. , String
Comparable<String>, compareTo ()
:
public int compareTo(String other)

. .
other Object,
. Comparable
,
min () ArrayList:
public static < extends Comparable<T>> T min(T[]

a)

,
extends Comparable,
. , String,
String, Comparable<String>.
GregorianCalendar
. , GregorianCalendar ,
Calendar, Comparable<Calendar>.
GregorianCalendar Comparable<Calendar>,
Comparable<GregorianCalendar>.
, .
public static <

extends Cooparable<? super min(T[] ) . . .

672

12

() :
int (? super )

,
, , ,
GregorianCalendar. , ()
.
< e x t e n d s C o m p a r a b le < ? s u p e r
. ,
,
. , ,
, ,
, . ,
, ,

, .


, Pair<?>.
, Pair.
. Pair<?> , .
? getFirstO
void setFirst(?)

, g e t F i r s t O ,
Object. setFirst ()
Object. Pair<?>
Pair , setObject () Pair
Ob ject.
! setFirst (null).

? ,
. ,
, .
.
public static boolean hasNulls(Pair<?> p)

{
return p.getFirstO

== null

|| p .getSecond() == null;

}
,
contains () , .
.
public static <> boolean hasNulls(Pair<T> p)

673


, :
public static void swap(Pair<?> p)

, ?
. ,
:
? t = p.getFirst(); // !
.setFirst(.getSecond()) ;
.setSecond(t);

,
. ,
,
swapHelper () , .
public static <> void swapHelper(Pair<T> p)

{
T t = p.getFirst();
p.setFirst(p.getSecond() ) ;
p. setSecond(t) ;

}
, , , swapHelper () ,
swap () .
Pair<?>. swapHelper () swap ()
:
public static void swap(Pair<?> p)

{ swapHelper(p); }


swapHelper (). ,
, .
<T>swapHelper () , .
, .
<> void swap (Pair<T> )
. ,
:
public static void maxminBonus(Manager[] a, Pair<? super Manager> result)

{
minmaxBonus(a, result);
PairAlg.swap(result); // , swapHelper()
//

}
.
.
, , .
, ArrayList<Pair<T>>
ArrayList<Pair<?>>.
Pair<?>, ?
.

674

12

12.3
, ,
.
12.3. pair3/PairTest3 .java
1
2
3
4
5

package pair3;

/**
* (Aversion 1.01 2012-01-26
* Oauthor Cay Horstmann

6 */
7

public class PairTest3

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

public static void main(String[] args)

{
Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
Manager cfo = new Manager ("Sid Sneaky", 600000, 2003, 12, 15);
Pair<Manager> buddies = new Pair<>(ceo, cfo);
printBuddies(buddies);
ceo.setBonus(1000000);
cfo.setBonus (500000);
Manager[] managers = { ceo, cfo };
Pair<Employee> result = new Pair<>();
minmaxBonus(managers, result);
System.out.println ("first: " + result.getFirst().getName()
+ ", second: " + result .getSecondO .getName ()) ;
maxminBonus(managers, result);
System.out.println("first: " + result.getFirst().getName()
+ ", second: " + result. getSecondO .getName ()) ;
}
public static void printBuddies(Pair<? extends Employee> p)
{
Employee first = p.getFirst ();
Employee second = p.getSecondO ;
System.out.println(first.getName() + " and " + second.getName() +
" are buddies.");
}
public static void minmaxBonus(Manager[] a, Pair<? super Manager> result)

38
39
40
41
42
43
44
45
46
47
48
49
50

}
public static void maxminBonus(Manager[] a, Pair<? super Manager> result)

51

if (a == null |I a.length == 0) return;


Manager min = a[0];
Manager max = a[0];
for (int i = 1; i < a.length; i++)
{
if (min.getBonus () > a[i].getBonus ()) min = a[i];
if (max.getBonus () < a[i].getBonus ()) max * a[i];
}
result.setFirst(min);
result.setSecond(max);

675

52
minmaxBonus(a, result);
53
PairAlg.swapHelper (result); // swapHelper()
54
//
55
}
56 }
57
58 class PairAlg
59 {
60
public static boolean hasNulls(Pair<?> p)
61
{
62
return p.getFirstO == null || p.getSecond() == null;
63
}
64
65
public static void swap(Pair<?> p) { swapHelper (p); }
66

67

public static <T> void swapHelper(Pair<T> p)

68

69
T t = p.getFirstO;
70
p.setFirst(p.getSecond());
71
p .setSecond(t);
72
}
73 }


Class . , String.class
( , ) Class<String>.
, Class<T>
. Class<T>
:
newlnstance()
cast(Object obj)
T[] getEnumConstants()
Class<? super T> getSuperclass()
Constructor<T> getConstructor(Class... parameterTypes)
Constructor<T> getDeclaredConstructor(Class... parameterTypes)

newlnstance () ,
. , ..
, , Class<T>.
.
cast () ,
, .
BadCastException.
getEnumConstants () null,
(enum) ,
, .
, , getConstructor () getDeclaredConstructor ()
Constructor<T>. Constructor
, newlnstance ()
.

676

12

ja v a .la n g .C la s s < T >

1 .0

newlnstance() 5.0

, .

cast(Object obj)

5.0

obj, (null)
, BadCastException.

[] getEnumConstants() 5.0

, ,
null.

Class<? super > getSuperclass() 5.0

null,
Object.

Constructor<T> getConstructor(Class... parameterTypes)

Constructor<T> getDeclaredConstructor(Class... parameterTypes)

5.0
5.0

j a v a . la n g . r e f l e c t . C o n s tru e to r< T > 1 ,1

T newlnstance(Object... parameters)

5.0

, .

C la s s < T >
Class<T>
. .
public static <> Pair<T> makePair(Class<T> )
throws InstantiationException, IllegalAccessException

{
return new P a i r o ( c .newlnstance (), c .newlnstance());

}
, E m p l o y e e .class
Class<Employee>.
makePair () Employee,
, Pair<Employee>.
makePair(Employee.class)


Java
. , ,
,

677

. , Pair ,
Pair<T>, , Pair
, Pair<String>
Pair<Employee>.


public static Comparable min(Comparable[] a)

.
public static < extends Comparable<? super

T min(T[]

API ,
.

,
.

, ,
. ,

.
! ,
, .*

,
. .

Class, .

TypeVariable, (, ,
extends Comparable<? super >).

WildcardType, (, , ?
super ).

ParameterizedType,
(, , Comparable<? super >).

GenericArrayType, (,
, []).

. 12.5 .
, .
,
.

678

12

12.4
API .
Pair,
:
class Pair<T> extends java.lang.Object
public T getFirstO
public T getSecondO
public void setFirst(T)
public void setSecond(T)

ArrayAlg PairTest2,
:
public static < extends java.lang.Comparable> Pair<T> minmax(T[])

API
,
12.4.
12.4. genericRef lection/GenericRef lectionTest . j a v a 1
1
2
3
4
5
6
7

package genericReflection;

*/

public class GenericReflectionTest

import java.lang.r e f l e c t ;
import java.util.*;
/**
* version 1.10 2007-05-15
* author Cay Horstmann

10 {
11
12
13
14
15
16

public static void main(String[] args)

{
//
//
String name;
if (args.length > 0) name = args[0];


17
18
19

else

{
Scanner in = new Scanner(System.in);
System.out.println(
"Enter class name (e.g. java.util.Collections): ");
name = in.nextO;

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

}
try

{
//
Class<?> cl = Class.forName(name);
printClass (cl);
for (Method m : cl.getDeclaredMethods ())
printMethod(m);

}
catch (ClassNotFoundException e)

{
e.printStackTrace ();

}
}
public static void printClass(Class<?> cl)

{
System.out.print(cl);
printTypes(cl.getTypeParameters (),
Type sc = cl.getGenericSuperclass ();
if (sc != null)

", ", ">", true);

{
System.out.print (" extends ");
printType (sc, false);

}
printTypes(cl.getGenericInterfaces (),
" implements ", ", ", "", false);
System.out.println ();

}
public static void printMethod(Method m)

{
String name = m.getNameO;
System.out.print(Modifier.toString(m.getModifiers()));
System.out.print(" ");
printTypes(m.getTypeParameters (), "<", ", ", "> ", true);
printType(m.getGenericReturnType(), false);
System.out.print(" ");
System.out.print(name);
System.out.print("(");
printTypes(m.getGenericParameterTypes(), "", ", ", "", false);
System.out.println(")");

67
68

69
70
71
72

public static void printTypes(Type[] types, String pre,


String sep, String suf, boolean isDefinition)

{
if (pre.equals(" extends ") && Arrays.equals(types, new Type[]
{ Object.class })) return;

679

680

12

101

102
103
104
105
106
107
108
109

else if (type instanceof ParameterizedType)


{
ParameterizedType t = (ParameterizedType) type;
Type owner = t.getOwnerType ();
if (owner != null)
{
printType(owner, false);
System.out.print(".") ;

110

111
112
113
114
115
116
117
118
119
120

printType(t.getRawType(), false);
printTypes(t.getActualTypeArguments(), "<", , ", ">", false)

121
}
122 }

}
else if (type instanceof GenericArrayType)
{
GenericArrayType t = (GenericArrayType) type;
System.out.print("");
printType(t.getGenericComponentType(), isDefinition);
System.out.print("[]");

^a

73
if (types.length > 0) System.out.print(pre);
74
for (.int i = 0; i < types.length; i++)
75
{
76
if (i > 0) System.out.print(sep);
77
printType(types[i], isDefinition);
78
}
79
if (types.length > 0) System.out.print(suf);
80
}
81
82
public static void printType(Type type, boolean isDefinition)
83
{
84
if (type instanceof Class)
85
{
86
Class<?> t = (Class<?>) type;
87
System.out.print(t.getName ());
88
}
89
else if (type instanceof TypeVariable)
90
{
91
TypeVariable<?> t = (TypeVariable<?>) type;
92
System.out.print(t.getName ());
93
if (isDefinition)
94
printTypes(t.getBounds(), " extends , " &
", false);
94 ' }
95
else if (type instanceof WildcardType)
96
{
97
WildcardType t = (WildcardType)
type;
98
System.out.print (?);
99
printTypes(t.getUpperBounds(), extends ", " & ", "", false);
100
printTypes(t.getLowerBounds() , " super , " & ", "", false);

ja v a .la n g .C la s s < T >

681

1 .0

TypeVariable[] getTypeParameters,() 5.0

, ,
.

Type getGenericSuperclass() 5.0

, ,
null, Object .

[]

getGenericInterfaces() 5.0

, ,
, , .

j a v a . l a n g . r e f l e c t . M e th o d 1 . 1

TypeVariable[] getTypeParameters() 5.0

, ,
.

Type getGenericReturnType() 5.0

, .

[] getGenericParameterTypes() 5.0

, .
, .

j a v a . la n g . r e f l e c t . T y p e V a r ia b le

5 .0

String getName()

[] getBounds()

,
.

j a v a . l a n g . r e f l e c t . W ild c a r d T y p e 5 . 0

Type[] getUpperBounds()

,
extends, , .

[] getLowerBounds()

,
super, , .

682

12

ja v a . la n g . r e f l e c t . te r iz e d T y p e 5 .0

Type getRawType()

[] getActualTypeArguments()

, .

Type getOwnerType ()

, , null,
.

ja v a .la n g .r e fle c t.G e n e r ic A r r a y T y p e

5 .0

Type getGenericComponentType()

, .

,
,
. , . ,
,
API .
,
Java, (
) http://angelikalanger.com/GenericsFAQ/
JavaGenericsFAQ.html. ,
Java.

...





" ", .
. (
) ?
?
?
, Java
, .
, , ,
,
. . ,
,
,
.


Java
: Vector, Stack, Hashtable, BitSet,
Enumeration,

684

13

, . ,
,
.
Java SE 1.2 ,
.
. ,
.
(STL) C++, "
", STL. ,
.
,
, .
Java, ,
,
.


,
Java . ,

.
, ,
, ,
. ,
" "
(. 13.1).

. 13.1.

,
.
i n t e r f a c e Queue<E> / /
/ /

v o i d add(E e le m e n t ) ;
rem ove( ) ;
in t siz e ();

685

, .

, (. 13.2).

J3I

. 1 3 .2 .

,
Q u e u e , .
class CircularArrayQueue<E> implements Queue<E> //
{
CircularArrayQueue(int capacity) { . . . }
public void add(E element) { . . . }
public
E remove() { . . . }
public
int size() { . . . }
private E[] elements;
private int head;
private int tail;

}
class LinkedListQueue<E> implements Queue<E> //
{
LinkedListQueue() { . . . }
public void add(E element) { . . . }
public
E remove() { . . . }
public int size() ( . . . )
private Link head;
private Link tail;

13

686

! Java CircularArrayQueue
LinkedListQueue. ,

.
, ArrayDeque,
LinkedList, Queue.

, ,
. ,
,
. ,
.
Queue<Customer> expressLane = new CircularArrayQueueo (100) ;
expressLane.add(new Customer("Harry"));

,
.
: . ,
LinkedListQueue,
:
Queue<Cu8tomer> expressLane = new LinkodListQueueO() ;
expressLane.add(new Customer("Harry"));

, ?
.
, ,
. , , .
, .
,
, .
API,
, Abstract, , ,
AbstractQueue. .
, ,
, , AbstractQueue,
Queue.

C o l l e c t i o n I t e r a t o r Java
Java
Collection. :
public interface Collection<E>

{
boolean add(E element);
Iterator<E> iterator ();

}
,
. add () .
tru e , ,

687

false. ,
, ,
add () ,
. iterator () ,
Iterator.
.

Iterator :
public interface Iterator<E>

{
n e x t ();
boolean h asNextO;
void remove ();

}
next (),
. , next ()
NoSuchElementException.
next () hasNext ().
true, ,
. ,
, next () , hasNext ()
true. ,
.
Collection<String> = . . .;
Iterator<String> iter = .iterator();
while (iter.hasNext())

{
String element = iter.next();
-

lament

}
Java SE 5.0 .
, for each
:
for (String element

: )

{
-

lament

}
for each .
for each ,
Iterable :
public interface Iterable<E>

{
Iterator<E> iterator();

}
Collection Iterable.
for each
.

688

13

, , . ,
ArrayList,
,
. HashSet,
.. ,
,
.
, , ,
, .
! Java , next () hasNext ()
Iterator , nextElement () hasMoreElements ()
Enumeration. Java
Enumeration. ,
.


Java . , ,
, Standard Template Library C++,
. , ,
, , [ i ],
i. ,
.
i+ + . Java .
.
next (),
.
, Java ,
. next (),
,
(. 13.3).

! , iterator,
next inputstream.read.
. read()
. next()
.


remove () Iterator ,
next (). ,
, .
, ,
. ,
.

689

Iterator<String> it = c .iterator();
it.next(); //
it.remove(); / /

, next () remove ()
. , remove () ,
next (). ,
IllegalStateException.
, remove ()
, .
i t .remove();
it.remove(); // !

next (),
, , .
i t .remove();
i t .n e x t ();
it.remove(); // !


Collection Iterator , ,
.
, ,
.

690

13

public static <> boolean contains(Collection<E> c, Object obj)

{
for (E element : c)
if (element.equals(obj))
return true;
return false;

}
Java ,
, .
,
. , C o l l e c t i o n
,
. :
int size ()
boolean isEmptyO
boolean contains(Object obj)
boolean containsAll(Collection<?> c)
boolean equals(Object other)
boolean addAll(Collections extends E> from)
boolean remove(Object obj)
boolean removeAll(Collection<?> c)
void c l e a r ()
boolean retainAll(Collection<?> c)
Object [] toArrayO
<T> T [] toArray(T[] arrayToFill)

,
API . ,
, , C o l l e c t i o n ,
.
, Java A b s t r a c t C o l l e c t i o n ,
s i z e () i t e r a t o r () ,
:
public abstract class AbstractCollection<E>
implements Collection<E>

public abstract Iterator<E> iterator();


public boolean contains(Object obj)

{
for (E element : this) // iterator()
if (element.equals(obj))
return = true;
return false;

}
}
A b s t r a c t C o l l e c t i o n .
i t e r a t o r ( ) ,
c o n t a i n s O
A b s t r a c t C o l l e c t i o n .
c o n t a i n s (),
.

691

.

,
.
j a v a . u t i l . C o l l e c t i o n < E > 1 . 2 *

Iterator<E> iterator()

, .

int size ()

, .

boolean isEmptyO

true, .

boolean contains(Object o b j)

true, , o b j.

boolean containsAll(Collection<?> o th e r)

true,
.

boolean add(Object elem ent)

. true,
.

boolean addAll (Collections extends E> o th e r)

. true,
.

boolean remove(Object o b j)

, o b j. true,
.

boolean removeAll(Collection<?> o th e r)

.
true, .

void clear()

boolean retainAll(Collection<?> o th e r)

,
. true,
.

Object[]

toArrayO

<> [] toArray(T[]

a r r a y T o F il l)

. a r r a y T o F i l l
, . ,
n u ll.
, a r r a y T o F ill.

692

13 ai

ja v a .u til.Ite r a to r < E >

1 .2

boolean hasNextO

true, ,
.

next()

. NoSuchElement
Exception, .

void remove()

.
.
, HlegalStateException.


,
,
Java. ,
, , ,
. . 13.1
Java
. ( ,
14.) . 13.1
C o lle c tio n , , ,
, ,
"".
13.1. Java

____________________________________________________________________

ArrayList

LinkedList

ArrayDeque

HashSet

TreeSet

EnumSet

LinkedHashSet

PriorityQueue

HashMap

"-

TreeMap

693

. 1 3 .1

LinkedHashMap

WeakHashMap

, ",

IdentityHashMap , = ,
equals ()


, ,
ArrayList
. .

, , ,
(. 13.4).
.

. 13.4.

.
, .
Java
; .. (. 13.5).

,
, (. 13.6).

694

13

i
----------------------- 1
91

- J f

. 13.5.

. 13.6.

- ,
, , ,
. , ,
Java
LinkedList.
, .

695

List<String> staff = new L i n k e d L i s t o () ; // LinkedList,

//
staff.a d d ("");
staff.add("Bob");
staff.add("Carl");
Iterator iter = staff.iterator();
String first = iter.nextO;
//
String second = iter.nextO; //.
iter.remove(); //

.
,
. LinkedList .add() .
- .
add (), ,
,
.
, . ,
, ,
. Iterator
add ().
Listlterator, add() :
interface ListIterator<E> extends Iterator<E>

{
void add(E element);

}
Collection.addO,
boolean. ,
. , Listlterator
,
:
previous()
boolean hasPrevious()

next (), previous () , .


listlterator () LinkedList ,
Listlterator, .
listIterator<String> iter = staff.listlterator()

add () . ,

"Juliet" (. 13.7).
List<String> staff = new L i n k e d L i s t o ();
staff.a d d ("Amy");
staff.a d d ("Bob");
staff.add("Carl") ;
ListIterator<String> iter = staff.listlterator();
iter.nextO; //
iter.add("Juliet") ;

696

13

. 13.7.

add () ,
, .
.
,
listlterator () ,
.
(.. hasNext () false),
. ,
+ 1 .
+ 1 . ,
, , ,
, | .
|
|
|
|

697

! , | .
, <Backspace>.
remove () next ( ) , ,
, <Backspace>.
previous , ,
. remove () .
add(), ,
remove () .

, , set () ,
next () previous (). ,
:
ListIterator<String> iter = list.listlterator();
String oldValue = iter.next(); //
iter.set(newValue); //

neWValue

, , ,
, .
, ,
. .
.
,
, ConcurrentModif icat
ionException. :
List<String> list = . . .;
ListIterator<String> iterl = list.listlterator();
ListIterator<String> iter2 = list.listlterator();
iterl.next();
iterl.remove();
iter2 .next () ; // ConcurrentModificationException

iter2.next() ConcurrentM
odif icat ionException, iter 2 ,
.
, :
, ,
, ,
, .
.
(,
).
, .

. ,
ConcurrentModificationException.
!
.
. set ()

698

13

. ,
set () .
, Collections,
.

, LinkedList.
Listlterator
, .
, Collection
.
AbstractCollection LinkedList.
, toString ()
[, , ], .
contains ()
. , staff .contains (H a r r y )
true,
"Harry".

,
.
. -
, - 1
, .
,
. LinkedList
get (),
:
LinkedList<String> list = . . .;
String obj = list.get(n);

, . , ,
, .
. ,
.
for

(int i = 0; i < list.size (); i++)

- list.get(i);

,
get (), . LinkedList

.
! get() :
size () /2, .

,
. Java ,
,
. , next Index () ,

n e x t ().
p r e v i o u s I n d e x () ,
p r e v i o u s ( ) . , ,
, n e x t I n d e x . ,
. , , ,
l i s t . l i s t l t e r a t o r ( ) ,
. , n e x t ()
, l i s t . g e t ( n ) . ,
.
,
, s e t () g e t ().
?
.
,
A r r a y L i s t .
,
.
,
A r r a y L i s t , .
13.1
. ,
, ,
r e m o v e A l l ().
,
. , ,
:
| |BDFG
| IBDFG
| |DFG

,
. t o S t r i n g O
A b s tra c tC o lle c tio n .
S y s te m .o u t.p rin tln (a ) ;

13.1. linkedList/LinkedListTest.ja v a 1
1 package linkedList;
2
3 import java.util.*;
4
5 /**
6
*
7
* (Aversion 1.11 2012-01-26
8
* @author Cay Horstmann

9 */
10 public class LinkedListTest

11 {
12
13
14

public static void main(String[] args)


{
List<String> a = new LinkedListo () ;

700

13

15
.add("Amy");
16
a.add("Carl");
17
a.add("Erica");
18
19
List<String> b = new LinkedListO () ;
20
b.add("Bob");
21
b.add("Doug");
22
b .a d d ("Frances");
23
b .add("Gloria");
24
25
// b
26
ListIterator<String>alter = a.listlterator ();
27
Iterator<String> biter =b.iterator();
28
29
while (biter.hasNext())
30
{
31
if (alter.hasNext ()) alter.next();
32
alter.add(biter.next());
33
}
34
35
System.out.println(a);
36
37
// b
38
biter = b.iterator ();
39
while (biter.hasNext ())
40
{
41
biter.next (); //
42
if (biter.hasNext ())
43
{
44
biter.next (); //
45
biter.remove(); //
46
}
47
}
48
49
System.out.println(b);
50
51
//
52
// , b
53
.removeAll(b);
54
55
System.out.println() ;
56
}
57 }

j a v a . u t i l . L i s t < E > 1 . 2 *

ListIterator<E> listlterator()
, .

ListIterator<E> listlterator(int in d e x )
,
next () .

701

void add(int i, E elem ent)

void addAll(int i ,

Collection<? extends E> e lem en ts)

remove (int i)

get(int i)

set (int i ,

elem en t)

int indexOf(Object elem ent)

-1 ,
.

int lastIndexOf(Object elem ent)

-1 ,
.

ja v a .u t i l . L is tIte r a to r < E >

1 .2

void add(E newElement)

void set ( newElement)

,
next() previous ( ) . IllegalStateException,
next()
previous().

boolean hasPrevious()

true,
.

previous()

. NoSuchElementException,
.

int nextlndexO

,
next ().

int previousIndex()

,
previous().

702

13

j a v a . u t i l . L in ] c e d L is t < E > 1 . 2

LinkedListO

LinkedList(CollectiorK? extends E> e le m e n ts)

void addFirst( elem ent)

void addLast(E elem ent)

getFirstO

getLastO

removeFirst()

removeLastO


List
LinkedList. List ,
. :
get () set ().
, get ()
set () .
ArrayList,
List. ArrayList .
! Java , ,
Vector , .
Vector ArrayList?
: Vector . Vector
.
, ,
. , ArrayList .
ArrayList Vector,
.

-
,
. ,
, ,

703

.
, .
,
,
. ,

. ,
.

-. -
, -. -
,
, ,
-. . 13.2 -,
hashCode () String.
13.2. -, h a s h C o d e ()

II I

76268

Lee

"lee"

107020

100300

a it

eel

,
hashCode () ( .
5). e q u als ().
, a .e q u a ls (b) tru e ,
b -. ,
- ,
, -.
Java - .
(. 13.8). ,
- .
, .
, - 76268, 128 ,
108 (
76268 128 108). ,
, . ,
. -.
, ,
.
- ,
.
-,
. ,
-. -
, ,
.

704

13

. 13.8. -

,
-, .
75 150% .
, ,
. .
, ,
2, 16. (
2.)
, ,
-, ,
. - ,
.
, ,
.
. , 0 ,7 5 ( ),
75%,
.
0,75.
-
. .
, . add ()
, , .
Java HashSet,
-.
add(). contains () ,
. ,
.
- .
, ,

705

. HashSet
,
.
13.2
System, in -, . ,
" " (
http://www.gutenberg.net),
:
java SetTest < alice30.txt

-,
-
. (, " " 5909
, .)
- .
! , -. -
,
.

13.2. s e t / S e t T e s t . j a v a 1
1
2
3
4
5
6
7
8
9

package set;
import java.util.*;
/**
* ,
* System, in
* (Aversion 1.11 2012-01-26
* @author Cay Horstmann

10 */
11 public class SetTest
12 {
13
public static void main(String[] args)
14
{
15
Set<String> words = new HashSet<>(); // HashSet,
16
// -
17
long totalTime = 0;
18
19
Scanner in = new Scanner(System.in);
20
while (in.hasNext())
21
{
22
String word = in.nextO;
23
long callTime = System.currentTimeMillis();
24
words.add(word);
25
callTime = System.currentTimeMillis() - callTime;
26
totalTime += callTime;
27
}
28
29
Iterator<String> iter = words.iterator ();
30
for (int i = 1; i <= 20 &&iter.hasNext (); i++)
31
System.out.println(iter.next());

706

13 ai

32
System.out.println(". . .");
33
System.out.println(words.size () + " distinct words. " +
34
totalTime + " milliseconds.");
35
}
36 }

ja v a .u til.H a s h S * t< E >

1 .2

HashSetO

-.

HashSet (Collections extends E> e lem en ts)

- .

HashSet(int i n i t i a l C a p a c i t y )

- ( ).

HashSet(int i n i t i a l C a p a c i t y ,

float lo a d F a c to r )

-
( 0 ,0 1 ,0 ,
-, ).

ja v a . la n g . O b je c t 1 .0

int hashCode()

- . -
( ). equals () hashCode ()
: .equals ()
true, . hashCode ,
.hashCode ().


TreeSet , -,
:
.
. ,
. ,
,
:
SortedSet<String> sorter = new TreeSet<>(); // TraeSet,
//
sorter.a d d ("Bob");
sorter.a d d ("Amy");
sorter.a d d ("Carl");
for (String s : sorter) System.println(s);

707

: Amy, Bob,
Carl. TreeSet,
. (
- .
: . 3- . X. , . , . , , "", 2013 .)

. ,
.
, -
, , .
, log2?i
, . ,
1000 ,
10 .
, TreeSet
, HashSet (. . 13.3),
TreeSet .
13.3. -

H a s b S m t

T z a m S m t

" "

28195

5909

-"

466300

37545

75

98

ja v a . u t i l . T re e S e t< E > 1 .2

TreeSet()

TreeSet(Collection<? extends > e lem en ts)


TreeSet , ?
,
, Comparable.
:
public interface Comparable<T>

{
int compareTo(T other);

}
a.compareTo (b) ,
b ; ,
;

708

13

, . ;
(> 0, 0, < 0). Java
Comparable. String.
() (
).
,
, Comparable. Object
Comparable .
, Item
(part Number):
class Item implements Ccmparable<Item>

{
public int compareTo(Item other)

{
return partNumber - other.partNumber;

}
}
, , ,
,
. ,
; , ; .
! ,
.
, , ,
.

Comparable
.
. ,
? ,
,
Comparable?

, Comparator
TreeSet. Comparator compare ()
, .
public interface Comparator<T>

{
int compare(T a, T b ) ;

}
compareTo (), compare ()
, ;
, .
, ,
Comparator, .
class ItemComparator implements Comparator<Item>

709

public int compare(Item a, Item b)

{
String descrA = a .getDescription();
String descrB = b.getDescription();
return descrA.compareTo(descrB);


:
ItemComparator comp = new ItemComparator();
SortedSet<Item> sortByDescription = new T r e e S e t o (comp) ;

,
, . , , ,
.
. .

,
.
SortedSet<Item> sortByDescription = new T r e e S e t o ( n e w

Canparator<Item> ()

{
public int compare (Item a, Item b)

{
String descrA = a.getDescription();
String descrB = b.getDescription();
return descrA.compareTo(descrB);

}
})
! Comparator<T>
: compare () equals (). , equals (),

. API ,
equals () , - ,
. , addAll () TreeSet
, ,
.

, . 13.3,
:
-?
, .
, .
, .
:
, -. -
,
.
,
. TreeSet,

710

13

Comparator<Rectangle>.
? ? .
, .
.
, ,
.
,
. , - Rectangle.
.
! Java SE 6 TreeSet NavigableSet.

. , API.

13.3
Item. ,
.. , Item .
.
Item 13.4.
13.3. treeSet/TreeSetTest .java1
1
2
3
4
5

package treeSet;
/**
* (Aversion 1.12 2012-01-26
* @author Cay Horstmann

6 */
7
8
9

import java.util.*;

10 / * *
11 *
12 *
13 */
14 public class TreeSetTest
15 {
16
public static void main(String[] args)
17
{
18
SortedSet<Item> parts = new TreeSet<>();
19
parts.add(new Item("Toaster", 1234));
20
parts.add(new Item("Widget, 4562));
21
parts.add(new Item("Modem", 9912));
22
System.out.println(parts);
23
24
SortedSet<Item> sortByDescription = new TreeSeto(new
25
Comparator<Item> ()
26
{
27
public int compare(Item a, Item b)
28
{
i
29
String descrA = a .getDescription();
30
String descrB = b .getDescription();
31
return descrA.compareTo(descrB);


32
33

}
} ) ;

34
35
sortByDescription.addAll(parts);
36
System.out.println(sortByDescription);
37
}
38 }

13.4. treeSet/Item. java1


1 package treeSet;
2

3
4
5
6
7
8
9
10
11

import java.util.*;
/**
*
*/
public class Item implements Comparable<Item>
{
private String description;
private int partNumber;

12

13
14
15
16
17
18
19
20
21
22

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

/**
*
* @param aDescription
* @param aPartNumber
*/
public Item(String aDescription, int aPartNumber)
{
description = aDescription;
partNumber = aPartNumber;
}
/**
*
* @return
*/
public String getDescription ()
{
return description;
}
public String toStringO
{
return " [descripion=" + description + ",
partNumber=" + partNumber + "]";
}
public boolean equals(Object otherObject)
{
if (this == otherObject) return true;
if (otherObject == null) return false;
if (getClass () != otherObject.getClass ()) return false;
Item other = (Item) otherObject;
return Objects.equals(description, other.description) &&
partNumber == other.partNumber;
}
public int hashCodeO

711

712

13

49
{
50
return Objects.hash(description, partNumber);
51
}
52
53
public int compareTo(Item other)
54
{
55
return Integer.compare(partNumber, other.partNumber);
56
}
57 }

java.lang.Caraparable<T> 1.2

int compareTo(T other)

[this] (o th e r)
, ; ,
;
, .

java. util. Conparator<T> 1.2

int compare(T a, T b)

,
; ,
; ,
.

java.util.SortedSet<E> 1.2

Comparators super E> comparator ()

null,
comapreToO Comparable.

first ()

last ()

j a v a .u t i l .N a v i g a b l e S e t < E >

E higher(E value)

E lower(E value)

value,

value,

null.

ceiling( value)

floor( value)

713

, value, ,
value,
null.

pollFirstO

pollLast()


null, .

Iterator<E> descendinglterator()

, .

java.util.TreeSet<E> 1.2

TreeSetO

Comparable.

TreeSet (Comparators super E> c)

TreeSet(SortedSet<? extends > elements)

,
, .


, ()
,
,
. Java SE 6 D e q u e ,
A r r a y D e q u e L i n k e d L i s t ,
, . 14
- .
java.util.Queue<E> 5.0*

boolean add(E element)

boolean offer(E element)

true,
. ,
illegalStateException, false.

714

13

remove()

polio

, .
, NoSuchElementException,
null.

element ()

()

, , .
, NoSuchElementException,
null.

java.util.Deque<E>

void addFirst(E e l e m e n t )

void addLast(E e l e m e n t )

boolean offerFirst(E e l e m e n t )

boolean offerLast(E e l e m e n t )

. ,
IllegalStateException,
false.

removeFirst()

removeLast()

pollFirstO

pollLastO

, . ,
NoSuchElementException,
null.

getFirstO

getLastO

peekFirstO

peekLast()

, , .
, NoSuchElementException,
null.

715

java.util.ArrayDeque<E>
_____

ArrayDeque()

ArrayDeque(int i n i t i a l C a p a c i t y )

16
.



, . ,
r e m o v e () ,
. .
,
.
, "". ""
,
, .
,
, C o m p a r a b l e ,
C o m p a r a t o r , . ,
.
. .
,
. ( 1 ,
.)
13.5
.
,
.
.
13.5. priorityQueue/PriorityQueueTest .java1
1 package priorityQueue;
2

3 import java.util.*;
4
5 /**
6
*
7
* @version 1.01 2012-01-26
8
* Qauthor Cay Horstmann

9 */
10 public class PriorityQueueTest
11 {
12
public static void main(String[] args)
13
{
14
PriorityQueue<GregorianCalendar> pq = new PriorityQueueo();

716

13

15
pq.add(new GregorianCalendar(
16
1906, Calendar.DECEMBER, 9)); // G. Hopper
17
pq.add(
18
new GregorianCalendar(181$, Calendar.DECEMBER, 10));
// A. Lovelace
19
pq.add(
20
new GregorianCalendar(1903, Calendar.DECEMBER, 3));
// J. von Neumann
18
pq.add(new GregorianCalendar(1910, Calendar.JUNE, 22)); // K. Zuse
19
21
System.out.println("Iterating over elements...");
22
for (GregorianCalendar date : pq)
23
System.out.println(date.get(Calendar.YEAR));
24
System.out.println("Removing elements...");
25
while (!pq.isEmpty())
26
System.out.println(pq.remove().get(Calendar.YEAR));
27
}
28 }

java.util.PriorityQueue 5.0

PriorityQueue()

PriorityQueue(int initialCapacity)
Comparable.

PriorityQueue (int i n i t i a l C a p a c i t y , Comparators super E> c)



.

,
. , ,
. , , ,
,
. .
"-". ,
, . ,
,
, Employee.
Java
: HashMap . .
- HashMap ,
.
. ,
, .
-, ?
, , -
,
. ,
- .

717

Map<String, Employee> staff = new HashMap<>(); // HashMap,


// Map
Employee harry = new Employee("Harry Hacker");
staff.put("987-98-9996", harry);

, ,
. ,
Employee. ,
( ) :
^
String s = "987-98-9996";
= staff.get(s); // harry

, get ()
null. .
. put ()
, . , put ()
, , .
remove () .
size () .
. (

, .)
,
Collection .
: , ( )
"-". "-"
,
.
. (
Map.Entry.) , keyset
HashSet TreeSet, , Set,
Collection.
Set<K> keySet()
Collection<K> values()
Set<Map.EntryCK, V entrySetO

, :
Set<String> keys = map.keySet () ;
for (String key : keys)

{
-

}
.

, ,
. :

for

(. E n t r y < S t r i n g , Employee> e n t r y : s t a f f . e n t r y S e t ())

{
String key = entry.getKey();
Employee value = entry.getValue();
-

718

13

remove ,
. .
.
add (), UnsupportedOperationException.
,
"-" .

13.6
. "-".
, , .
, , g e t ()
. , , .
13.6. map/ M a p T e s t .java 1
1 package map;
2

3 import java.util.*;
4
5 /**
6
*
7
* String 1<
8
* version 1.11 2012-01-26
9
* author Cay Horstmann
10 */

11 public class MapTest


12 {
13
public static void main(String[] args)
14
{
15
Map<String, Employee> staff * new HashMap<>();
16
staff.put("144-25-5464", new Employee("Amy Lee"));
17
staff.put("567-24-2546", new Employee("Harry Hacker"));
18
staff.put("157-62-7935", new Employee("Gary Cooper"));
19
staff.put ("456-62-5527", new Employee("Francesca Cruz"));
20

21
//
22
System.out.println(staff);
23
24
//
25
staff.remove("567-24-2546");
26
27
//
28
staff.put ("456-62-5527", new Employee("Francesca Miller"));
29
30
//
31
System.out.println(staff.get("157-62-7935"));
32
33
//
34
for (Map.Entry<String, Employee> entry : staff.entrySet())
35
{
36
String key = entry.getKey();
37
Employee value = entry.getValue();
38
System.out.println("key=" + key + ", value=" + value);
39
}
40
}
41 }

719

java.util.Map<K, V> 1.2

V get (Object key)

, , , ,
n u ll, .
n u ll.

V put ( k e y , V value)

. ,
, .
n u ll, .
n u ll.

void putAll(<? extends , ? extends V> entries)

boolean containsKey(Object key)

true, .

boolean containsValue(Object value)

true, .

Set<Map.Entry<K, V

entrySetO

Map.Entry, .. "-"
. ,
.

Set<K> keySet()

.
,
, .

Collection<V> values()

.
,
, .

java.util.Map.Entry<K, V> 1.2

getKey()

V getValue()

V setValue (V newValue)

720

13

java.util.HashMap<K, V> 1.2

HashMap()

HashMap(int initialCapacity)

HashMap(int i n i t i a l C a p a c i t y , float loadFactor)

-
.( 0 ,0 1 ,0 ,
-, ).
0 ,7 5 .

java.util.TreeMap<K,V> 1.2

TreeMap(Comparator<? super >. )

,
.

TreeMap(<? extends , ? extends V> entries)

TreeMap(SortedMap<? extends , ? extends V> entries)


, ,
.

java.util.SortedMap<K, V> 1.2

Comparator^ super K> comparator ()

, , null,
compareToO Comparable.

firstKeyO

lastKeyO


Java
. .

-
WeakHashMap .
, ?
, . ,

721

-.
, "-
" . " "
? ?
, . " "
. , - ,
.

. ,
WeakHashMap. " "
"-",
-.
. -
W e a k H a s h M a p .
WeakHashMap ( -
). " "
. " "
, , , .
- WeakHashMap, "
" , . ,
- WeakHashMap,
.
, , -
.
- WeakHashMap.

-
Java SE 1.4 LinkedHashSet LinkedHashMap,
. ,
-.
(. 13.9).

, 13.9. -

722

13

,
13.6, LinkedHashMap:
Map staff = new LinkedHashMap();
staff.put("144-25-5464", new Employee("Amy Lee"));
staff.put ("567-24-2546", new Employee("Harry Hacker"));
staff.put("157-62-7935", new Employee("Gary Cooper"));
staff.put("456-62-5527", new Employee("Francesca Cruz"));

s t a f f .k e y se t () . i t e r a t o r ()
:
144-25-5464
567-24-2546
157-62-7935
456-62-5527

staff .values () .iterator ()


:
Amy Lee
Harry Hacker
Gary Cooper
Francesca Cruz

-
. get ( ) put ()

. ( ,
-. , -
.) -,
:
LinkedHashMapCK, V>(initialCapacity, loadFactor, true)


" ". ,

. ,
,
, .
. .
, LinkedHashMap,
:
protected boolean removeEldestEntry(Map.EntryCK, V> eldest)

(e ld e s t)
, tru e .
,
100 :
<, V > cache = new
LinkedHashMapO (128, 0.75F, true)

protected boolean removeEldestEntry(Map.EntryCK, V> eldest)

{
return size() > 100;
.

};

723

, eldest, ,
. , ,
.


EnumSet ,
.
, EnumSet
. 1,
. EnumSet
.
, .
EnumSet Set.
enum Weekday
{ MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };
EnumSet<Weekday> always = EnumSet ..allOf (Weekday.class) ;
EnumSet<Weekday> never = EnumSet.noneOf(Weekday.class);
EnumSet<Weekday> workday =
EnumSet.range(Weekday.MONDAY, Weekday.FRIDAY);
EnumSet<Weekday> mwf =
EnumSet.of(Weekday.MONDAY, Weekday.WEDNESDAY, Weekday.FRIDAY);

EnumMap ,
.
. :
EnumMap<Weekday, Employee> personlnCharge = new EnumMapo(Weekday.class);

! API EnumSet
extends Enum<E>. ,
". Enum.
, Weekday Enum<Weekday>.

-
Java SE 1.4 IdentityHashMap,
- , ,
- hashCode (),
System. identityHashCode (). -,
, Object .hashCode (). ,
IdentityHashMap = ,
equals ().
, - ,
.
(, ),
.

724

13

java.util.WeakHashMap<K, V> 1.2

WeakHashMap()

WeakHashMap(int i n i t i a l C a p a c i t y )

WeakHashMap(int i n i t i a l C a p a c i t y , float lo a d F a c to r )

- .

java.util.LinkedHashSet<E> 1.4

LinkedHashSet()

LinkedHashSet(int i n i t i a l C a p a c i t y )

LinkedHashSet(int i n i t i a l C a p a c i t y , float lo a d F a c to r )

-
.

java.util.LinkedHashMap<K, V> 1.4

LinkedHashMap()

LinkedHashMap(int i n i t i a l C a p a c i t y )

LinkedHashMap(int i n i t i a l C a p a c i t y , float lo a d F a c to r )

LinkedHashMap(int i n i t i a l C a p a c i t y , float lo a d F a c t o r ,

boolean a c c e s s O rd e r)

-
. true a c c e s s O rd e r
, false .

protected boolean removeEldestEntry(Map.Entry<K, V> e ld e s t )

, true,
. e l d e s t ,
. ,
. false,
.. .
true, , ,

.

java.util.EnumSet<E extends 5.0

static < extends Enum<E EnumSet<E> allOf (Class<E> enumType)

, .

725

static < extends Enum<E EnumSet<E> noneOf (Class<E> )

, .

static < extends EnumSet<E> range ( fro m , to )

, fro m to .

static < extends EnumSet<E> of ( v a lu e )

static < extends EnumSet<E> of ( v a lu e , E... v a lu e s )

, .

java.util.EnunMajKK extends >, V> 5.0

EnumMap(Class<K> k e y T y p e )

java. util. IdentityHashMap<K, V> 1.4

IdentityHashMap()

IdentityHashMap(int e x p e c te d M a x S iz e )

- ,
2, 1.5*expectedMaxSize (
expectedMaxSize 21).

java. lang. System 1.0

static int identityHashCode(Object o b j)

1 .1

-, Object.hashCode ( ) ,
, , , o b j ,
hashCode ().


,
.
, ,
. ,
,
. , Swing
.
Java .
,
(. 13.10),

726

13

. ,
.
. ,
, ,
.

. 13.10.


: C o lle c tio n .
:
boolean add(E e le m e n t)

"-",
put (), .
V p u t ( k e y , V v a lu e )

,
. g e t ()
:
V get ( k e y )

.
.

727

:
. List :
void add(int index, element)
get(int index)
void remove(int index)

, List
, .
( )
, Java SE 1.4
RandomAccess. ,
, ,
. RandomAccess ArrayList Vector.
if ( instanceof RandomAccess)

}
else

}
! Array,
List .
Array, , ,
Array,
.
,
.
,
, ,
.

Listlterator
:
void add(E e le m e n t)


next () remove () Iterator. Set
Collection, .
, add () . equals ()
, ,
, .
hashCode () ,
-.
, ?
.
Set , .
SortedSet SortedMap -,
,
. .

728

13

, , Java SE 6 NavigableSet NavigableMap,



. (
SortedSet SortedMap.)
TreeSet .
.
, ,
.
:
AbstractCollection
AbstractList
AbstractSequentialList
AbstractSet
AbstractQueue
AbstractMap

,
,
. Java
:
LinkedList
ArrayList
ArrayDeque
HashSet
TreeSet
PriorityQueue
HashMap
TreeMap

. 13.11 .

. 13.11.

729

, , - ""
, Java,
. .
Vector
Stack
Hashtable
Properties

, . 13.12.
.

. 13.1 2.


. 13.10 13.11, ,

. .
, ,
C o lle c t io n .
k ey set () .
, .
. , k e y set () ,
S e t .

730

13

.
.
.


asList () Arrays List
, Java.
, ,
.
Card[] cardDeck = new Card[52];

List<Card> cardList = Arrays.asList(cardDeck);

ArrayList.
get () set (),
. , (,
add () remove () ),
UnsupportedOperationException.
Java SE 5.0 asList ()

. , ,
, :
List<String> names = Arrays.asList("Amy", "Bob", "Carl");

Collections .nCopies (n, anObject)


, List.
, , ,
anObject. ,
List, 100 "DEFAULT":
List<String> settings = Collections.nCopies (100, "DEFAULT");


.
.
! Collections
. Collection.

Collections.singleton (anObject)
, Set ( nCopies (),
List).
,
. singletonList () singletonMap () .

.
, staff, 10-
19-. subList ,
, .
List group2 = staff.subList(10, 20);

731

, .
substring () String.

, .
, , .
staff,
group2 .
group2.clear(); //
4


, .
SortedSet :
SortedSet<E> subset( from, to)
SortedSet<E> headset( to)
SortedSet<E> tailSet(E from)

,
from to.
,
, .
.
SortedMap<K, V> subMap(K from, to)
SortedMap<K, V> headMap(K to)
SortedMapCK, V> tailMap(K from)

Navigable Set, Java SE 6,



. ,
,
.
NavigableSet<E> subset(
from, boolean fromlnclusive, E to, boolean tolnclusive)
NavigableSet<E> headSet(E to, boolean tolnclusive)
NavigableSet<E> tailSet(E from, boolean fromlnclusive)


Collections ,
.
.
,
.
:
Collections.unmodifiableCollection
Collections.unmodifiableList
Collections.unmodifiableSet
Collections.unmodifiableSortedSet
Collections.unmodifiableMap
Collections.unmodifiableSortedMap

. ,
Collections, unmodif iableList () ArrayList, LinkedList
, List. ,

732

13

,
. ,
.
List<String> staff = new LinkedListo();

lookAt(Collections.unmodifiableList(staff));

Collections .unmodifiableList () ,
List. staff.
, lookAt () List,
. , , add (),
,
UnsupportedOperationException .

. - (
stuff).
.
,
, ,
. , LinkedList addFirst ()
addLast , List.
.
! unmodif iableCollection () (, , synchronized
Collection () checkedCollection (), )
, equals () .
equals () Object,
. ,
.
,
.
hashCode(). , unmodifiableSet ()
unmodif iableList (), equals () hashCode () .


,
- . , ,
, -
, .

,
. , synchronizedMap ()
Collections
:
Map<String, Employee> map =
Collections.synchronizedMap(new HashMap<String, Employee>());

map .
, get () put (), . ,

733

, .
14.


Java SE 5.0 , , ,
. 12,

. ,
add () .
ArrayList<String> strings = new A r r a y L i s t o ();
ArrayList rawList = strings; //
//
// ,
rawList.add(new DateO);
//
// Date!

,
get () String.
.
:
List<String> safeStrings = Collections.checkedList(strings, String.class);

add () ,
, . ,
ClassCastException, .
,
, .
ArrayList rawList = safeStrings;
rawList.add(new DateO); //
// ClassCastException

! ,
. ,
ArrayList<Pair<String>>, Pair<Date>,
Pair.

0
:
,
, ,
.
UnsupportedOperationException,
.
API
" ".
. , ,
?
. ,

734

13

" " , .
, .
""
? . ,
.

. ,
, ,
,
.
. Java
.
, ,
"" .
java.util.Collections 1.2*

static <E> Collection unmodifiableCollection(Collection<E> c)

static <E> List unmodifiableList(List<E> c)

static <E> Set unmodifiableSet (Set<E> c)

static <E> SortedSet unmodifiableSortedSet(SortedSet<E> c)

static <K, V> Map unmodifiableMap (Map<K, V> c)

static <K, V> SortedMap unmodifiableSortedMap (SortedMapcK, V> c)

,
UnsupportedOperationException.

static <> Collection<E> synchronizedCollection(Collection<E> )

static <E> List synchronizedList(List<E> c)

static <E> Set synchronizedSet(Set<E> c)

static <E> SortedSet synchronizedSortedSet(SortedSet<E> c)

static <K, V> Map<K, V> synchronizedMap (Map<K, V> c)

static <K, V> SortedMapcK, V> synchronizedSortedMap(SortedMapcK, V> c)

static

>

Collection

checkedCollection(CollectionCE>

ClassCE>

e l e m e n t Type)

static CE> List checkedList(ListcE> c, ClasscE> elementType)

static CE> Set checkedSet(SetcE> c, ClassCE> elementType)

static CE> SortedSet checkedSortedSet(SortedSetCE> c, ClassCE> elementType)

static CK,
valueType)

V> Map checkedMap(MapcK,

V> c, ClassCK> keyType,

ClassCV>

static

<, V> SortedMap checkedSortedMap(SortedMap<K,


keyType, Class<V> valueType)

V>

c,

735

Class<K>

ClassCastException .

static <> List<E> nCopies(int , value)

static <> Set<E> singleton( value)

java.util.Arrays 1.2

static <E> List<E> asList(E... array)

, ,
.

java.util.List<E> 1.2

List<E> subList(int firstlncluded,

int firstExcluded)

java.util.SortedSet<E> 1.2

SortedSet<E> subset(E f i r s t l n c l u d e d , E firstExcluded)

SortedSet<E> headSet(E firstExcluded)

SortedSet<E> tailSet(E firstlncluded)

java.util.NavigableSet<E> 6

NavigableSet<E>

subset(E

from,

boolean

fromlncluded,

to,

boolean

tolncluded)

NavigableSet<E> headSet(E to, boolean tolncluded)

NavigableSet<E> tailSet (E from, boolean fromlncluded)

.
boolean , .

736

13

java.util.SortedMap<K, V> 1.2

SortedMap<K, V> subMap(K f i r s t l n c l u d e d ,

SortedMapCK, V> headMap(K firstExcluded)

SortedMap<K, V> tailMap(K f i r s t l n c l u d e d )

f ir s t E x c lu d e d )

java.util.NavigableMap<K, V> 6

NavigableMap<K,

V> subMap(K fro m ,

boolean fr o m ln c lu d e d ,

to ,

boolean

t o ln c lu d e d )

NavigableMapCK, V> headMap(K fro m , boolean fr o m ln c lu d e d )

NavigableMapCK, V> tailMap(K t o ,

boolean to ln c lu d e d )

.
boolean , .



.
, . ,
, .. , .
:
Set<String> result = new H a s h S e t o ();

,
, ,
. r e ta in A ll () :
result.retainAll(b);

,
.
.

. , ,
, ,
, , .
Map<String, Employee> staffMap = . . .;
Set<String> terminatedIDs = . . .;


, .
,
.
staffMap.keyset().removeAll(terminatedIDs);

737

/
. , 10
.
10 :
relocated.addAll(staff.subList(0, 10) ) ;

,
:
staff.subList(0, 10).clear();

API Java
,
. ,
, ,
A r r a y s . a s L i s t , .
String[] values = . . .;
HashSet<String> staff = new HashSeto(Arrays.asList(values));

. ,
t o A r r a y () :
Object[] values = staff.toArray();

. ,
, ,
.
String[] values = (String[]) staff.toArray(); // !

, t o A r r a y , O b j e c t [],
.
t o A r r a y (), .
.
String[] values = staff.toArray(new String[0]);

,
:
staff.toArray(new String[staff.size()]);

.
! :
Class (, String.class) toArray ()?
, ( )
.

:
.

738

13

.
. ,
.
if (a.length == 0) throw new NoSuchElementException();
T largest = a [0];
for (int i = 1; i < a.length; i++)
if (largest.compareTo(a[i]) < 0)
largest = a [i];

, ,
:
if (v.sizeO == 0) throw new NoSuchElementException ;
T largest = v.get(O);
for (int i * 1; i < v.sizeO; i++)
if (largest.compareTo(v.get (i)) < 0)
largest v.get(i);

?
, , .
if (1.isEmpty()) throw new NoSuchElementException();
Iterator<T> iter = 1.iterator();
T largest = iter.next();
while (iter.hasNext())

{
T next = iter.nextO;
if (largest.compareTo(next) < 0)
largest ** next;

}
, ,
. :
, ,
?
,
.
static < extends Comparable> max(T[] )
static < extends Comparable> max(ArrayList<T> v)
static <T extends Comparable> T max(LinkedList<T> 1)

.
,
. g e t () s e t () ,
.
,
.
. , max ()
, ,
C o lle c tio n , .
public static < extends Comparable> max(Collection<T> )

{
if (c.isEmpty()) throw new NoSuchElementException();
Iterator<T> iter - c .iterator();
T largest = iter.nextO;
while (iter.hasNext())

739

{
next = iter.next();
if (largest.compareTo(next) < 0)
largest = next;

}
return largest;

}

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


,
.

, Java .
, sort () Collections ,
List, :
List<String> staff = new LinkedListo();

Collections.sort(staff);

,
Comparable. - ,
Comparator
. ( " "
.) , .
Comparator<Item> itemComparator new
Comparator<Item>()

{
public int compare(Item a, Item b)

{
return a.partNumber - b.partNumber;

}
};
Collections.sort(items, itemComparator);

,
Collections.reverseSort ().
, b.compareTo ().
, staff
, compareTo ()
.
Collections.sort(staff, Collections.reverseOrder())


, itemComparator:
Collections.sort(items, Collections.reverseOrder(itemComparator))

740

13

, sort () .
, ,
.
. ,
(., , C++ (. .,
"", 2011, ISBN 978-5-8459-1650-1). Java
. , ,
,
.
, ,
,
. :
, .. .
?
. , ,
..., .
?
... . , ,
, ... .
"" ,
, , ,
. , ,
.
? ,
, . ,
.

, set ( ) .

, add()
remove().

Collections
shuffle (), ,
,
.
ArrayList<Card> cards = . . .;
Collections.shuffle(cards) ;

, RandomAccess,
shuffle () , ,
.
13.7 49
Integer, 1 49.
, 6 . , ,
.

741

13.7. sh u f f le /S h u f f l e T e s t . j ava
1 package shuffle;
2

3
4
5
6
7
8
9
10
11

12
13
14
15
16
17
18
19
20

import java.util.*;
/**
*
*
* (Aversion 1.11 2012-01-26
* @author Cay Horstmann
*/
public class ShuffleTest
{
public static void main(String[] args)
{
List<Integer> numbers = new ArrayListO () ;
for (int i = 1; i <= 49; i++)
numbers.add(i);
Collections.shuffie(numbers);
List<Integer> winningCombination = numbers.subList (0, 6);
Collections.sort(winningCombination);
System.out.println(winningCombination);

21
}
22 }

java.util.Collections 1.2

static <T extends Comparable<? super void sort(List<T> elements)

static <T> void sort(List<T> elements,

Comparators super T> c)

, .
0 ( n lo g ) , .

static void shuffle(List<?> elements)

static void shuffle(List<?> elements,

Random r)

. 0 ( ( ) ),
, ( ) .

static <> Comparator<T> reverseOrder()

, ,
compareToO Comparable.

static <> Comparator<T> reverseOrder(Comparator<T> comp)

, ,


, ,
, .
, ,

742

13

. ,
, .
. . ,
1024 , (
) 10 ,
512 , , 1024 ,
.
binarySearch ()
Collections. , , ,
, .
, , , List,
, .
compareTo () Comparable,
, .
i = Collections.binarySearch(, element);
i = Collections.binarySearch(c, element, comparator);

, binarySearch (),
. , .get (i)
element .
, , .
, element
, .
:
insertionPoint = -i - 1;

-i, .
,
.
if (i < 0)
c.add(-i - 1, element);

,
. ,
, ,
. binarySearch ()
, .
! Java SE 1.3
, binarySearch ()
, list
AbstractSequentialList. Java SE 1.4.
binarySearch () , list
RandomAccess. , ,
.

ja v a .u til.C o lle c tio n s

743

1 .2
int binarySearch(List<T> e le m e n ts,

static <T extends Comparable<? super


T key)

static <T> int binarySearch(List<T> elem en ts, T key, Comparator^ super T> c)

k ey , ,
ele m e n ts AbstractSequentialList,
. 0(a(n) log ),
, () . k ey
i, . k ey
-i-1, .


Collections , .
,
.
, .
?
. ,
. , -
, . ,
, , , Collections .max (),
, .
API Collections.
ja v a .u t i l . C o lle c tio n s

1 .2

static <T extends Comparable<? super

T min(Collection<T> e lem en ts)

static <T extends Comparable<? super

T max(Collection<T> e lem en ts)

static <T> min(Collection<T> e le m e n ts,

Comparator^

static <T> max(Collection<T> e le m e n ts,

Comparator^ super T> c)

super T> c)

(
).

static <> void copy(List<? super > to ,

List<T> from)

.
.

static <> void fill(List<? super > 1,

v alu e )

744

13

static <> boolean addAll(Collection<? super T> , T...

v a lu e s )

5.0

true,
.

static <> boolean replaceAll(List<T> 1,

o ld V a lu e ,

newValue)

1.4

newValue , old V alu e.

static int indexOfSubList(List<?> 1,

static int lastlndexOfSubList(List<?> 1,

List<?> s)

1.4

List<?> s)

1.4

1, s, -1 ,
1 s. , 1 [s, t, , ],
s [t, , ], , 1.

static void swap(List<?> 1,

int i ,

int j )

1.4

static void reverse(List<?> 1)

. , [t, ,
] [, a , t]. 0 ( ) , .

static void rotate (L-ist<?> 1,

int d)

1.4

, i
(i+d) % 1 . size (). , [t, , ] 2
[, , t]. 0 ( ) ,
.

static int frequency(Collection<?> c ,

Object ) 5.0

, .

boolean disjoint(Collection<?> c l ,

Collection<?> c2)

5.0

true, .


( , ,
),
, . ,
JMenu .
:
void fillMenu(JMenu menu, ArrayList<JMenuItem> items)

{
for (JMenuItem item : items)
m e n u .a d d (item);

}
,
,
ArrayList. ,
. .

745

:
, ?
,
Collection. , f i llMenuO,
. ,
ArrayList, LinkedList ,
Arrays.asList.
void fillMenu(JMenu menu, Collection<JMenuItem> items)

{
for (JMenuItem item : items)
menu.add(item);

}
!
, Java ?
, JComboBox :
JComboBox(Object[] items)
JComboBox(Vector<?> items)

: Swing .

, ,

, .
g e t A l I I terns ,
.
List<JMenuItem> g e t A H I t e m s (JMenu menu)

{
List<JMenuItem> items = new A r r a y L i s t O ()
for (int i = 0 ; i < m e n u .getltemCount ( ) ; i++)
items.add(menu.getItem(i));
return items;

}
,
,
, Abstract List, .
List<JMenuItem> getAllItems(final JMenu menu)

{
return new
A b s t r a c t L i s t o ()

{
public JMenuItem get(int i)

{
return m e n u .getltem(i);

}
public int size()

{
return m e n u .getltemCount();

};
}

746

13

, , ,
. ,
"" .
getAllltems (),
.
I


, Java
. Hashtable Properties,
Stack, Vector, BitSet.

H a s h ta b le
Hashtable , HashMap,
. Vector,
Hashtable .
, HashMap.
! Hashtable
t. HashTable, Windows
, Windows
, Java .

Enumeration
. Enumeration :
hasMoreElements () nextElement ().
hasNext () next () Iterator. , elements ()
Hashtable ,
.
Enumeration<Employee> = staff.elements();
while (e.hasMoreElements())

{
Employee e = e .nextElement();

}
,
. Collections .enumeration ()
,
:
List<InputStream> streams = . .
SequencelnputStream in =
new SequencelnputStream(Collections.enumeration(streams));
// SequencelnputStream

747

C++! C++ .
, Java
. , , . ,
, , .
.
,
Java SE 1.2.

j a v a . u t i l . E n u m e r a tio n < E > 1 . 0

boolean hasMoreElements()

true, .

nextElement()

. ,
hasMoreElements () false.

ja v a .u til.H a s h ta b le < K , V > 1 .0

Enumeration<K> keys()

, -.

Enumeration<V> elements ()

, -.

ja v a . u t i l . V e c to r< E > 1 .0

Enumeration<E> elements()

, .


.
.

Java, , Properties.

(. 10).

748

13

ja v a .u til.P r o p e r tie s

1 .0

Properties ()

Properties (Properties d e f a u l t s )

String getProperty(String key)

. , ,
,
.

String getProperty(String k ey , String d e fa u ltV a lu e )

, .
, , ,
.

void load (InputStream in)

InputStream.

void store (OutputStream o u t,

String continentstring)

OutputStream.

1.0 Java S t a c k
p u s h ( ) p o p ( ). S t a c k V e c t o r ,

,
, . , i n s e r t () re m o v e () ,
, .
ja v a .u til.S ta c k < E >

1 .0

push ( item)

item .

pop ()

. , .

()

, , .
, .

749


BitSet Java . (
. , ,
, .)
, (,
). ,
, ArrayList
Boolean.
BitSet ,
. ,
, ,
long.
, bucketOfBits.get (i) bucketOfBits
BitSet true, i- ,
false. bucketOfBits.
set(i) i- . , bucketOfBits.
clear (i) i- .
C++! bitset C++ ,
BitSet Java.

j a v a . u t i l . B i t S e t 1 .0

BitSet(int i n i t i a l C a p a c i t y )

int length()

" : 1 +
.

boolean get(int b i t )

void set(int bit)

void clear(int b i t )

void and(BitSet s e t )

void or(BitSet s e t )

void xor(BitSet s e t )

void andNot(BitSet s e t )

, .

750

13



" ", . (
2, 3 5, 1,
" " ,
.)
,
. (,
, .)
, ,
2 2000000. ( 148 933 ,
.)
, :
2 . . 1.
, .
, , .
13.8 Java, 13.9 C++.
13.8. s i e v e / S i e v e , ja v a 1
1 package s i e v e ;
2

3 import j a v a . u t i l . * ;
4
5 /**
6
* " "
7
* 2000000
8
* (Aversion 1.21 2004-08-03
9
* Gauthor Cay Horstmann
10 */

11 p u b li c c l a s s Sieve
12 {
13
p u b lic s t a t i c void m a i n ( S t r i n g [] s)
14
{
15
i n t n = 2000000;
16
long s t a r t = System.currentTimeMillis ();
17
B i t S e t b = new B i t S e t ( n + 1 ) ;
18
i n t count = 0;
19
int i;
20
f o r (i = 2; i <= n; i++)
21
b .set(i);
22
i = 2;
23
while (i * i <= n)
24
{
25
i f (b.get(i))
26
{
27
count++;
28
i n t k= 2 * i ;
29
while (k <= n)
30
{
31
b.clear(k);
32
k += i ;
33
}


34
35

}
i++;

36

37
38
39
40
41
42
43
44
45
}
46 }

while (i <= n)
{
if (b.get(i)) count++;
i++;
}
long end = System.currentTimeMillis();
System.out.println(count + "primes");
System.out.println ((end - start) + " milliseconds");

13.9. s ie v e / s i e v e . 1
1
2
3
4
5
6
7
8
9

/**
* Qversion 1.21 2004-08-03
* @author Cay Horstmann
'*/
#include < b i t s e t >
#include <iostream>
#include <ctime>
using namespace s t d ;

10

11 i n t main()
12 {
13
const i n t N * 2000000;
14
clo ck _t c s t a r t * c l o c k ( ) ;
15
16
b i t s e t< N + 1> b;
17
i n t count = 0;
18
int i ;
19
f o r (i - 2; i <- N; i++)
20
b .se t(i);
21
i - 2;
22
while (i * i <- N)
23
{
24
if (b.test(i))
25
{
26
count++;
27
int k = 2 * i ;
28
while (k <= N)
29
{
30
b.reset(k);
31
k +- i ;
32
}
33
}
34
i++;
35
}
36
while (i <= N)
37
{
38
if (b.test(i))
39
count++;
40
i++;

751

752
41
42
43
44
45
46
47
48
49 }

13
}
clock t cend = clock();
double millis = 1000.0 * (cend - cstart) / CLOCKS PER SEC;
cout

count

" primes\n"

millis

" milliseconds\n";

return 0;

! " ,

.
ThinkPad 2,4 4 ,
Ubuntu 10.04:

C++ (g++ 4.6.3): 160

Java (Java SE 7): 84

, Java
C++. , ,
C++ Java 20 . Java
,
Hotspot.

Java .
, Java
.

.


...







Callable Future


Swing

, ,
.
,
. ,
,
.
,
.
,
,
. , ..
. , ,
.

754

?
:
, .
, , .

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

. ,
Java.
, , ,
.
, , , .

, , , (Brian
Goetz) Java Concurrency in Practice ( Addison-Wesley Professional, 2006 r.).


,
, , , ,
.
, ,
. ,
,
( ; . 14.1).
X

1 11< II

'

. 14.1.

755

Start (),
. Start
addBall (), 1000 .
move () ,
, ,
.
.
Ball ball = new Ball();
panel.add(ball);
for (int i = 1; i <= STEPS; i++)

{
b a l l .move(panel.getBounds());
panel.paint(panel.getGraphics());
Thread.sleep(DELAY);

}
Thread, sleep () .
sleep () Thread .
sleep () InterruptedException.
.
,
.
, ,
.
, 1000 ,
Close (), .
, .

!
. , comp.paint ( comp.getGraphics ( ) ) addBall ()
BounceFrame. .
repaint , AWT .
comp.repaint () ,
, addBall ()
. , , ,
jpanel, . ,
,
repaint () JComponent.

, .
,
. ,
, . ,
, , ,
. ,
Stop () Back () .
, ,
.
14.1-14.3.

756

14

14.1. bounce/Bounce .ja v a


1 package bounce;
2
3 import java.awt.*;
4
import java.awt.event.*;
5
import javax.swing.*;
6
7
/**
8
*
9
* (Aversion 1.33 2007-05-17
10
* 0author Cay Horstmann
11 */
12 public class Bounce
13 {
14
public static void main(String[] args)
15

16
EventQueue.invokeLater(new Runnable()
17
{
18
public void run()
19
{
20
JFrame frame = new BounceFrame ();
21
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
22
frame.setVisible(true);
23
}
24
});
25
}
26 }
27
28 /**
29
*
30 */
31 class BounceFrame extends JFrame
32 {
33
private BallComponent comp;
34
public static final int STEPS'= 1000;
35
public static final int DELAY = 3;
36
37
/**
38
* ,
39
* , Start Close
40
*/
41
public BounceFrame ()
42
{
43
setTitle("Bounce");
44
45
comp = new BallComponent ();
46
add(comp, BorderLayout.CENTER);
47
JPanel buttonPanel = new JPanelO;
48
addButton(buttonPanel, "Start, new ActionListener()
49
50
51
52
53
54
55

{
public void actionPerformed(ActionEvent event)
{
addBall();

}
}>;


56
57
58
59
60
61
62
63
64
65

addButton(buttonPanel, "Close", new ActionListener()


{
public void actionPerformed(ActionEvent event)
{
System.exit(0);

66

/**

67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

*
* @param
* @param title
* @param listener
*/
public void addButton(Container c, String title, ActionListener listener)
{
JButton button = new JButton(title);
c.add(button);
button.addActionListener(listener);
}

}
});
add(buttonPanel, BordetLayout.SOUTH);
pack();

/**
*
*/
public void addBallO
{
try
{
Ball ball = new Ball();
comp.add(ball);

1000

88

89
for (int i = 1; i <= STEPS; i++)
90
{
91
ball.move(comp.getBounds());
92
comp.paint(comp.getGraphics());
93
Thread.sleep(DELAY);
94
}
95
}
96
catch (InterruptedException e)
97
{
98
}
99
}
100 }

H .2 . b o u n ce /B a ll .ja v a *1
1 package bounce;
2
3 import java.awt.geom.*;
4
5 /**
6
*
1
* (^version 1.33 2007-05-17
8 * Oauthor Cay Horstmann

757

758

14

9 */
10 public class Ball

{
12
private static final int XSIZE = 15;
13
private static final int YSIZE = 15;
14
private double x = 0;
15
private double = 0;
16
private double dx = 1;
17
private double dy = 1;
18
19
/**
20
* ,
21
* ,
22
*/
23
public void move(Rectangle2D bounds)
24
{
25
x += dx;
26
+= dy;
27
if (x <bounds.getMinX())
28
{
29
x = bounds.getMinX ();
30
dx = -dx;
31
}
32
if (x + XSIZE >= bounds.getMaxX () )
33
{
34
x = bounds.getMaxX () - XSIZE;
35
dx = -dx;
36
}
37
if (y <bounds.getMinY ())
38
{
39
= bounds.getMinY();
40
dy = -dy;
41
}
42
if (y + YSIZE >= bounds.getMaxY ())
43
{
44
= bounds.getMaxY() - YSIZE;
45
dy = -dy;
46
}
47
}
48
49
/**
50
*
51
*/
52
public Ellipse2D getShapeO
53
{
54
return new Ellipse2D.Double(, , XSIZE, YSIZE);
55
}
56 }

1 4 .3 . bounce/BallComponent .java1
1 package bounce;
2
3 import java.awt.*;
4 import java.util.*;
5 import javax.swing.*;
6

___ _______________________________________________________________________
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

759

/**
* ,
* (Aversion 1.34 2012-01-26
* @author Cay Horstmann
*/

public class BallComponent extends JPanel


{
private static final int DEFAULT_WIDTH = 450;
private static final int DEFAULT_HEIGHT = 350;
private java.util.List<Ball> balls = new ArrayListo ();
/**
*
* @param b
*/

public void add(Ball b)


{
balls.add(b);
}
public void paintComponent(Graphics g)
{
super.paintComponent (g); //
Graphics2D g2 = (Graphics2D) g;
for (Ballb : balls)
{
g2.fill(b.getShape());
}
}
public Dimension getPreferredSize()
{ returnnew Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
}

ja v a .la n g .T h r e a d

1 .0

static void sleep(long m i l l i s )

.
:

m illis



,
.
. , AWT
, .
,
,
Close .
.

760

,
. ,

.
-. ,
, .
, .
.
1. run () ,
Runnable.
:
public interface Runnable

{
void r u n ();

}
2. :
class MyRunnable implements Runnable

{
public void run()

}
}
3. :
Runnable = new MyRunnable();

4. Thread Runnable,
.
Thread t = new T h read();

5. :
t .s tart();


, BallRunnable
run (), .
class BallRunnable implements Runnable

{
public void run()

{
try

{
for

(int i = 1; i <= STEPS; i++)

{
ball.move(component.getBounds());
component.repaint();
Thread.sleep(DELAY);

catch

(InterruptedException exception)

761

{
}

}
}

InterruptedException,
run ().
. ,
. , , run (). ,
Start, addBall () ,
. . 14.2.

. 14.2.
Ball b = new Ball ;
p a nel.add(b);
Runnable r = new BallRunnable(b, panel);
Thread t = new Thread(r);
t .start ();

, , ! ,
.
. 14.4.
! , ,
Thread, .
class MyThread extends Thread
{
public void run()

762

start ().
. , ,
. ,
. ,
" .

! run() Thread Runnable.


,
. Thread.start (). ,
run ().

14.. bounceThread/BounceThread. java


1
2
3
4
5

package bounceThread;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
11

7
/**
8
*
9
* version 1.33 2007-05-17
10
* author Cay Horstmann
11
*/
12 public class BounceThread
13 {
14
public static void main(String[] args)
15
{
16
EventQueue.invokeLater(new Runnable()
17

<

18
public void run()
19
{
20
JFrame frame = new BounceFrame ();
21
frame.setTitle("BounceThread);
22
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
23
frame.setVisible(true);
24
}
25
});
26
}
27 }
28
29 /**
30
*
31
*/
32 class BallRunnable implements Runnable
33 {
34
private Ball ball;
35
private Component component;
36
public static final int STEPS = 1000;
37
public static final int DELAY = 5;
38
39
/**
*
40


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

67
68

* @param aBall
* @param aComponent ,
*/
public BallRunnable(Ball aBall, Component aComponent)

{
ball = aBall;
component = aComponent;

}
public void run()

{
try

{
for (int i = 1; i <= STEPS; i++)

{
ball.move(component.getBounds());
component.repaint();
Thread.sleep(DELAY);

}
}
catch (InterruptedException e)

{
}
}
}
j
*

69
V
70 class BounceFrame extends JFrame
71 {.
private BallComponent comp;
72
73
j
74
* ,
75
* , Start Close
76
77
*/
public BounceFrame()
78
79
{
comp = new BallComponent ();
80
add(comp, BorderLayout.CENTER);
81
JPanel buttonPanel = new JPanelO;
82
addButton(buttonPanel, "Start", new ActionListener()
83
84
{
public void actionPerformed(ActionEvent event)
85

86

addBall ();

87
88

89
90
91
92
93
94
95
96
97

}
}>;
addButton(buttonPanel, "Close", new ActionListener()

{
public void actionPerformed(ActionEvent event)

{
System.exit(0);

}
});

763

764
98
99
100
101
102
103
104
105
106
107

Diana U

add(buttonPanel, rderLayout.SOUTH);
pack () ;

}
/**

*
*
*
*
*/

0
@param
@param



title
listener

108
public void addButton(Container c, String title, ActionListener listener)
109
{
110
JButton button = new JButton(title);
111
c.add(button);
112
button.addActionListener(listener);
113
}
114
115
/**
116
*
117
*/
118
public void addBallO
119
{
120
Ball b = new Ball();
121
comp.add(b);
122
Runnable r = jiew BallRunnable (b, comp);
123
Thread t = new Thread (r);
124
t.start();
125
}
126 }

ja v a .la n g .T h r e a d

1 .0

Thread(Runnable t a r g e t )

, run()
.

void start()

, run().
. .

void run()

run () Runnable.

j a v a . l a n g . R u n n a b le 1 . 0

void run()

765


, run () ,
return , ,
, .
Java stop (),
, .
, ",
stop () suspend () ".
. interrupt ()
. interrupt ()
, .
boolean, .
, , .
, ,
Thread. currentThread (),
is Interrupted ():
while

(!Thread.currentThread().islnterrupted() && )

}
, .
InterruptedException.
interrupt () , , ,
s l e e p () wait(),
InterruptedException. ( -,
.
. 1 3
.)
Java ,
. .
, .
, .

. run () :
public void r u n ()

{
try

{
while (!Thread.currentThread() .islnterrupted() && )

catch(InterruptedException )

{
//

}
finally

766

{
,

}
// run()

}
islnterrupted()
, sleep () (
) . sleep ()
, ,
. (!)
InterruptedException. , sleep () ,
.
InterruptedException, .
public void r u n ()

{
try

while

( )


Thread.sleep(delay);

c a t c h (InterruptedException e )

{
//

}
finally

}
// run()

}
I interrupted () islnterrupted .
interrupted () , . ,
. ,
islnterrupted () , .
.

,
InterruptedException :
void mySubTaskO
{
try { sleep(delay); }
catch (InterruptedException e)

{} // HE !

}
He ! ,
catch,
.

767

catch Thread.currentThread() .interrupt (),


, .
.
void mySubTaskO
{
try { sleep(delay); }
catch

(InterruptedException e)

Thread.currentThread0 .interrupt(); }

throws InterruptedException ,
, try .
,
run ( ) .
void mySubTaskO

throws InterruptedException

sleep(delay);

}
ja v a .la n g .T h r e a d

1 .0

void interrupt()

.
true.
sleep , InterruptedException.

static boolean interrupted()

, . , .
:
false.

boolean isInterruptedO

, . interrupted (),
.

static Thread currentThread()

Thread, .

768

.
, g e t S t a t e ().


new, new Thread (),
. ,
.
,
.


s t a r t (),
. ,
,
. ( Java, , .
- .)
, .
,
, .
, .

. ,

(. 14.4). ,
, "
".

() .
.
,
y i e l d (), .

, , .
, , ,
. , , ,
.
,
.


,
. .
.
, .

769

(
Lock java.util.concurrent),
, . (
java.util.concurrent "
", "
synchronized".) ,
.


, .
, " ".
Object .wait () Thread, join ()
Lock Condition java.util.concurrent.
.

.
.
,
.
Obj e c t . w a i t (), Thread. j o i n (), Lock. t r y L o c k () C o n d itio n . a w a i t ().
i

. 14.3 , ,
.
(, , ), .
(,
, ),
.
, .


.
*


run ().

,
run ().

, , s t o p ().
ThreadDeath, .
stop () ,
.
j a v a . l a n g . T h r e a d 1 . 0 *

void join ()

void join(long m i l l i s )

770

14

5.0

Thread.State getStateO

.
WAITING, TIMED_WAITING

n e w ,r u n n a b l e ,b l o c k e d ,

TERMINATED.

void stop()

. .

void suspend()

. .

void resume ()

. suspend ().
.

. 16.3.

771


: , ,
.


Java .
, .
, setPriority ().
, MIN PRIORITY (
Thread 1) MAX_PRIORITY ( 10).
N0RM_PRI0RITY, 5.
, ,
.
.
, ,
Java ,
.
, Windows .
Java
. Oracle Linux
. .
.
, .
,
.
! - ,
, . ,
, ,
. , ,
,
.

j a v a . l a n g . T h r e a d 1 .0 *

void setPriority(int n e w P rio rity )

. Thread. m i n _
PRIORITY Thread.MAX_PRI0RITY.
Thread.NORM_PRIORITY.

static int MIN_PRIORITY

, Thread.
1.

772

static int NORM_PRIORITY

Thread .
5.

static int MAX_PRIORITY

, Thread.
10.

static void yield()

.
,
. , .


, :
t .setDaemon(true);

, . ,
, .
, "" ,
, .
, .
, .

, , .
.
, ,
, .
ja v a .la n g .T h r e a d

1 .0

void setDaemon(boolean isDaemon)

.
.


run () ,
.
. catch, ,
. , , ,
.
, Thread.UncaughtExceptionHandler.
:
void uncaughtException(Thread t, Throwable e)

773

setUncaught
ExceptionHandler (). ,
setDefaultUncaughtException
Handler () Thread.
API
.
,
(null). ,
ThreadGroup.
! , .
,
. Java
,
.*1

ThreadGroup Thread.UncaughtExceptionHandler.
uncaughtException () .
1. ,
uncaughtException () .
2. , Thread.getDefaultExceptionHandler ()
(.. null), .

3. , Throwable ThreadDeath,
.
4. Throwable
System.err.
, ,
.
ja v a . la n g . T h re a d 1 .0

static

void

setDefaultUncaughtExceptionHandler(Thread.UncaughtException

Handler h a n d le r)

5 .0

static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() 5 .0

void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h an d ler)

Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() 5.0

5 .0

.
, .

774

j a v a . l a n g . T h r e a d . U n c a u g h t E x c e p t io n H a n d le r 5 . 0

void uncaughtException(Thread t, Throwable e)


.
:

j a v a . l a n g . T h re a d G ro u p 1 . 0

void uncaughtException(Thread t, Throwable e)

, ,
Thread, ,
. (
ThreadDeath, . ThreadDeath
stopO.)


. ,
,
? ,
.
.
.


,
, . ,
, .
, .

. ,
. .
,
, .
, , . Bank
transfer ().
. (
.) transfer ()
Bank.

775

public void transfer(int from, int to, double amount)


// : 1

{
System.out.print(Thread.currentThread());
accounts[from] -= amount;
System.out.printf(" %10.2f from %d to %d", amount, from, to);
accounts[to] += amount;
System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());

}
T r a n s f e r R u n n a b l e . r u n ()
.
r u n () ,
t r a n s f e r () B an k , .
class TransferRunnable implements Runnable

{
public void run()

{
try

{
int toAccount = (int) (bank.size() * Math.random());
double amount = maxAmount * M a t h .random();
bank.transfer(fromAccount, toAccount, amount);
Thread.sleep((int) (DELAY * M a t h .random()));

}
, ,
.
,
, ,
.
t r a n s f e r ()
. .
, <Ctrl+C>.
, .
from
from
from
from

11
12
14
13

to
to
to
to

44
22
22
81

Total
Total
Total
Total

Balance:
Balance:
Balance:
Balance:

100000.00
100000.00
100000.00
100000.00

Thread[Thread-11,5,main]
Thread[Thread-12, 5,main]
Thread[Thread-14,5,main]
Thread[Thread-13, 5,main]

588.48
976.11
521.51
359.89

Thread[Thread-36, 5,main]
Thread[Thread-35, 5,main]
Thread[Thread-37,5,main]
Thread[Thread-34,5,main]
Thread[Thread-36, 5,main]

401.71 from 36 to 73 Total Balance: 99291.06


691.46 from 35 to 77 Total Balance: 99291.06
78.64 from 37 to 3 Total Balance: 99291.06
197.11 from 34 to 69 Total Balance: 99291.06
85.96 from 36 to 4 Total Balance: 99291.06

Thread[Thread-4,5,main]Thread[Thread-33,5,main] 7.31 from 31 to 32


Total Balance: 99979.24
627.50 from 4 to 5 Total Balance: 99979.24

, - .
$100000,
, 100 $1000 .

776

14

.
, ,
. ,
!
14.5-14.7 .
.
.
14.5. u n s y n c h / U n s y n c h B a n k T e s t . j a v a
1 package unsynch;
2
3 /**
4
*
5
*
6
* version 1.30 2004-08-01*
7
* author Cay Horstmann

8 */
9

public c la s s UnsynchBankTest

10 {
11
public static final int NACCOUNTS = 100;
12
public static final double INITIAL_BALANCE = 1000;
13
14
public static void main (String [] argsf
15
{
16
Bank b = new Bank (NACCOUNTS, INITIAL_BALANCE) ;
17
int i;
18
for (i = 0; i < NACCOUNTS; i++)
19
{
20
TransferRunnable r = new TransferRunnable(b, i, INITIAL_BALANCE);
21
Thread t = new Thread(r);
22
t.start ();
23
}
24
}
25 }

14.6.

u n s y n c h / B a n k . j a v a 1

1 package unsynch;
2
3 /**
4
*
5
* (Aversion 1.30 2004-08-01
6
* author Cay Horstmann
7 */
8 public class Bank
9

10

private final doublet] accounts;

11

12

/**

13
14
15
16
17

*
* param n
* param initialBalance
*/
public Bank(int n, double initialBalance)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

52

{
accounts = new double[n];
for (int i = 0; i < accounts.length; i++)
accounts[i] = initialBalance;
}
/**
*
* from ,
* 0param to ,
* 0param amount
*/
public void transfer(int from, int to, double amount)
{
if (accounts[from] < amount) return;
System.out.print(Thread.currentThreadO);
accounts[from] -= amount;
System.out.printf(" %10.2f from %d to%dH, amount, from, to);
accounts[to] += amount;
System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
}
/**
*
* 0return
*/
public double getTotalBalance()
{
double sum = 0;
for (double a : accounts)
sum += a;
return sum;

>

53
54
/**
55
*
56
* 0return
57
*/
58
public int size()
59
{
60
return accounts.length;
61
}
62 }

14.7.

u n s y n c h / T r a n s f e r R u n n a b l e . j a v a

1 package unsynch;
2
3 /**
4
* ,
5
*
6
* 0version 1.30 2004-08-01
7
* author Cay Horstmann

8 */
9 public class TransferRunnable implements Runnable

777

778

{
11
private Bank bank;
12
private int fromAccount;
13
private double maxAmount;
14
private int DELAY = 10;
15
16
/**
17
*
18
* @param b ,
19
* from ,
20
* @param max
21
V
22
public TransferRunnable(Bank b, int from, double max)
23
{
24
bank = b;
25
fromAccount = from;
26
maxAmount = max;
27
}
28
29
public void run()
30
{
31
try
32
{
33
while (true)
34
{
35
int toAccount = (int) (bank.sizeO * Math.random());
36
double amount = maxAmount * Math.random ();
37
bank.transfer(fromAccount, toAccount, amount);
38
Thread.sleep((int) (DELAY * Math.random()));
39
}
40
}
41
catch (InterruptedException e)
42
{
43
}
44
}
45 }

,
,
.
,
. ,
. ,
:
a c c o u n ts[to ]

+= am ou n t;

, .
.
1. accou n ts [to] .
2. amount.
3. accou n ts [ t o ] .

779

, . 1 2,
. ,
accounts.
. 3.
, .
(. 14.4).
. (,
, !)

TransferThread 1

TransferThread 2 J
jl

2j

\7

accountsfto]
{

.........}........................... i..........5000
II
II
?
1)
!I
I

5<

/.

. 14..

-, Bank,
. Bank.class:
javap - -v Bank
, :
accounts[to]

+= amount;

-.
aload_0
getfield #2; // accounts: [D
iload 2

780

14
dup2
daload
dload_3
dadd
dastore
, -. :
, .

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


.
Java synchronized, Java
SE 5.0 ReentrantLock. synchronized
, "",
, .
synchronized ,
. java.util .concurrent
,
" ". ,
, "
synchronized".

ReentrantLock
:
myLock. l o c k () ;

//

ReentrantLock

try
{

}
fin a lly

{
myLock.unlock();

//

//

781

,
.
, lo c k ().
1 (),
, .
! unlock () finally.
, .
.

! try .
close ( ) . ,
try ,
. ,
** , .

tr a n sfe r

()

B ank.

public class Bank

{
private Lock bankLock = new ReentrantLock(); //
// ReentrantLock, Lock

public void transfer(int from, int to, int amount)


t

bankLock.l o c k ();
try
{
System.out.print(Thread.currentThread());
accounts[from] -= amount;
System.out.printf(" %10.2f from %d to %d", amount, from, to);
accounts[to] += amount;
System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());

}
finally

{
bankLock.u n lock();

}
}

}
, t r a n s f e r ()
,
t r a n s f e r ( ) .
l o c k (). ,
, t r a n s f e r ()
. , ,
(. 14.5).
,
t r a n s f e r () .
,
.

782

2
/

...... ,-4/']
;/

. L ,.

J
. 14.5.

, , , B a n k
R e e n t r a n t L o c k .
B an k , .
B an k ,
. ,
,
B an k .
,
, .
, 1 ( ) .
l o c k () u n l o c k (), , ,
. , ,
, .
, t r a n s f e r () g e t T o t a l B a l a n c e (),
b a n k L o c k , 2.
g e t T o t a l B a l a n c e () ,
1. t r a n s f e r () 0,
.

783

,
. , ,
.
! ,
- .
, finally,
.

ja v a .u til.c o n c u r r e n t.lo c k s .L o c k

5 .0

void lock()
. ,
.

void unlock()
.

ja v a .u til.c o n c u r r e n t.lo c k s .R e e n tr a n tL o c k

5 .0

ReentrantLock()
,
.

ReentrantLock(boolean f a i r )
.
, .
.
.

! , , ,
.
, , , .
, ,
.
, ,
.


,
, ,
. ,
, ,
.

784

Java (
).

. , ,
. ,
:
if (bank.getBalance(from) >= amount)
, bank.transfer(from, to, amount)

,
t r a n s f e r ():
if (bank.getBalance(from) >= amount)
//
bank.transfer(from, to, amount);

,
.. . -
,
.
, :
public void transfer(int from, int to, int amount)

{
bankLock.l o c k ();
try

{
while

(accounts[from]

< amount)

{
//

}
//

}
finally

{
bankLock.unlock() ;

}
, ? ,
- .
bankbook,
. .
,
n e w C o n d i t i o n ().
, , .
, , " ",
:
class Bank

{
private Condition sufficientFunds;

public Bank()

785

sufficientFunds = bankbook.newCondition();

t r a n s f e r () , ,
:
sufficientFunds.await ();

.
.
,
, , a w a i t ( ) .
a w a i t (), , .
, .
,
s i g n a l A l l () .
,
:
sufficientFunds.signalAll() ;

, .
, ,
.
.
,
, , a w a i t ( ) .
. ,
. s i g n a l A l l ()
,
.
! , await ()
:
while (! ( * ))
.await();

, s i g n a l l A H O
- . a w a i t () ,
.
.
, .
.
, a w a i t ()
- , .
, ,
, .
s i g n a l A l l ()?
: ,
. , ,

786

14

,
. s i g n a l A l l ()
, .
public void transfer(int from,

int to, int amount)

{
bankbook.lock();
try

<

>

while (accounts[from] < amount)


sufficientFunds.a w a i t ();
//

sufficientFunds.signalAll();

}
finally

{
bankbook.unlo c k ();

, , , s i g n a l A l l ()
.
, ,
.
, s i g n a l (), ,
. ,
, .
, ,
. s ig n a l ,
.
! : await (), signalAll ()
signal (), .

14.8,
, , .
$100000 ,
. ( ,
<Ctrl+C>.) ,
,
, .
- . ,
,
, "".
14.8. s y n c h / B a n k . j a v a
1 package synch;
2
3 import java.util.concurrent.locks.*;
4


6
7
8
9

*
*
*
*

,

(Aversion 1.30 2004-08-01
author Cay Horstmann

10 */
11 public class Bank
12 {
13
private final doublet] accounts;
14
private Lock bankLock;
15
private Condition sufficientFunds;
16
/**
17
*
18
* n
19
* initialBalance
20
*/
21
public Bank(int n, double initialBalance)
22
{
23
accounts = new double[n];
24
for (int i = 0; i < accounts.length; i++)
25
accounts[i] = initialBalance;
26
bankLock = new ReentrantLock();
27
sufficientFunds = bankLock.newCondition();
28
}
29
/**
30
*
31
* from ,
32
* to ,
33
* amount
34
*/
35
public void transfer(int from, int to, double amount)
36
throws InterruptedException
37
{
38
bankLock.lock();
39
try
40
{
41
while (accounts[from] < amount)
42
sufficientFunds.await();
43
System.out.print(Thread.currentThread());
44
accounts[from] -= amount;
45
Systern.out.printf( %10.2f from %d to 4>d", amount, from, to);
46
accounts[to] += amount;
47
System.out.printf( Total Balance: %10.2f%n", getTotalBalance())
48
sufficientFunds.signalAll();
49
}
50
finally
51
{
52
bankLock.unlock();
53
}
54
}
55
56
/**
57
*
58
* return
59
*/
60
public double getTotalBalance()
61
{
62
bankLock.lock() ;
63
try
64
{
double sum = 0;
65

787

788

14

66
67
for (double : accounts)
68
sum += ;
69
70
return sum;
71
}
72
finally
73
{
74
bankbook.unlock();
75
}
76
}
j

77
78
*
79
* @return
80
*/
81
public int size()
82
{
83
return accounts.length;
84
}
85 ]f

ja v a .u t i l . c o n c u rre n t. lo c k s . Lock 5 .0

Condition newCondition()
, .

j a v a . u t i l . c o n c u r r e n t . lo c k s . C o n d itio n

5 .0

void await()
.

void signalAll()
.

void signal()
.

s y n c h r o n iz e d
,
Lock Condition. ,
, , .

,
.
,
.
,
, .

789

L o c k C o n d i t i o n
. ,
, Java. 1.0
Java .
s y n c h r o n i z e d , . ,
, .
, :
public synchronized void m e t h o d ()

}
.
public void m e t h o d ()

{
this.intrinsicLock.l o c k () ;
try

)
finally { t h i s .intrinsicLock.unlock(); }

}
, t r a n s f e r ()
B a n k s y n c h r o n i z e d .
. w a i t ()
, n o t i f y A l l () / n o t i f y .
, w a i t () n o t i f y A l l () :
. await () ;
.signalAll () ;
! wait()p notifyAll () notify () (final)
Object. Condition await,
signalAll signal, .

, B a n k Java
:
class Bank
{
private doublet]

accounts;

public synchronized void transfer (int from,


throws InterruptedException

int to, int amount)

{
while (accounts[from] < amount)
wait(); //
//
accounts[from] -= amount;
accounts[to] += amount;
notifyAll (); // ,

}
public synchronized double getTotalBalance ( { . . . }

790

, s y n c h r o n i z e d
. , , ,
.
, s y n c h r o n i z e d .
, w a i t ( ) .
. .
Java . ,
wait ()/notifyAll (), ,
.

.
,
. , B a n k
, B a n k . c l a s s .

.
,
.

, .

, .

: L o c k C o n d i t i o n
? ,
.

L o c k / C o n d i t i o n ,
s y n c h r o n i z e d .
j a v a . u t i l . c o n c u r r e n t ,
. , " "
,
, .

s y n c h r o n i z e d ,
. ,
, . 14.9
,
.
L o c k / C o n d i t i o n ,
.

.9 . s y n c h 2 / B a n k , j a v a
1 package synch2;
2
3 /**
4
* ,


5
*
6
* (Aversion 1.30 2004-08-01
7
* @author Cay Horstmann
8 */
9 public class Bank
10 {
11
private final doublet] accounts;
12
!
13
14
*
15
* Qparam n
16
* @param initialBalance <-
17
*/
18
public Bank(int n, double initialBalance)
19
{
20
accounts = new double[n];
21
for (int i = 0; i < accounts.length; i++)
22
accounts[i] = initialBalance;
23
}
24
!
25
26
*
27
* @param from ,
* @p^ram to ,
28
* @param amount
29
30
*/
31
public synchronized void transfer(int from, int to, double amount)
throws InterruptedException
32
33
{
while (accounts[from] < amount)
34
wait () ;
35
System.out.print(Thread.currentThread());
36
37
accounts[from] -= amount;
System.out.printf (" %10.2f from %d to %d", amount, from, to);
38
accounts[to] += amount;
39
System.out.printf(" Total Balance: %10.2f%n", getTotalBalance())
40
notifyAll();
41
42
}
43
j
44
*
45
* @return
46
47
*/
public synchronized double getTotalBalance ()
48
49
{
double sum = 0;
50
51
for (double a : accounts)
52
sum += a;
53
54
return sum;
55
56
}
57
58
*
59
* @return
60
61
*/
public int size()
62

791

792

14

63 . {
64
return accounts.length;
65
}
66 }

ja v a . la n g . O b je c t 1 .0

void n o t i f y A H O
, wait() .
.
IllegalMonitorStateException, .

void notify ()
, wait ()
.
. IllegalMonitorStateException,
.

void wait()
.
.
IllegalMonitorStateException, .

void wait(long m i l l i s )

void wait(long m i l l i s ,

int nanos)

.
.
IllegalMonitorStateException, .
:

m illis

n an os

, 1 0 0 0 0 0 0


, Java
. ,
.
. ,
ob j .
synchronized (obj) //

}
:
public class Bank

{
private doublet] accounts;
private Object lock = new O b ject();


public void transfer(int from,

793

int to, int amount)

{
synchronized (lock) / /

{
accounts[from] -= amount;
accounts[to] += amount;

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

}
}
l o c k ,
Java.
.
. V e c t o r ,
.
, V e c t o r < D o u b l e > .
t r a n s f e r ( ) .
public void transfer(
Vector<Double> accounts,

int from,

int to, int amount)

// !

{
accounts.set(from, accounts.get(from) - amount);
accounts.set(to, accounts.get(to) + amount);
System.out.println(. . .);

}
g e t () s e t () V e c t o r ,
. , t r a n s f e r ()
g e t ().
.
:
public void transfer(Vector<Double> accounts,

int from, int to, int amount)

{
synchronized (accounts)

{
accounts.set(from, accounts.get(from) - amount);
accounts.set(to, accounts.get(to) + amount);

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

}
, ,
V e c t o r
. ? V e c t o r
.
,
. ,
, .



, -.

, .

794

,
(Per Brinch Hansen) (
) 1970- . Java
.

, .

. ,
o b j . m e t h o d (), o b j
.
, ,
,
- .


. , a w a i t a c c o u n t s [ f r o m ] >=
b a l a n c e , . ,
.
,
.
Java . Java
.
s y n c h r o n i z e d , .
w a i t () , n o t i f y A l l () , n o t i f y ( ) .
Java
, .

(p r iv a te ).
(s y n c h r o n iz e d ).

,
. ,
Java, : " ,
,
Concurrent Pascal.
". (Java's Insecure Parallelism, ACM SIGPLAN Notices 34:38-45,
April 1999).

v o l a t i l e
,
. ,
? ,
.

795


. ,
,
!


.
, , ,
.
!

,
, .
,
.
Java Memory Model and Thread Specification (
Java), JSR 133 (w w w . j c p . o r g / e n / j s r /
d e t a i l ? i d = l 3 3 ).
, .
, ,
h t t p : / / w w w . i b m . c o m / d e v e l o p e r w o r k s / r u / l i b r a r y / j - j t p 0 2 2 4 4 / .
! " ":
, , ,
, .

v o l a t i l e
. v o l a t i l e ,
,
.
, d o n e b o o l e a n ,
. ,
:
private boolean done;
public synchronized boolean isDoneO { return done; }
public synchronized void setDoneO { done = true; }

, .
i s D o n e () s e t D o n e () ,
. L o c k
. .
v o l a t i l e :
private volatile boolean done;
public boolean isDoneO { return done; }
public void setDoneO { done = true; }
! volatile .
, .
public void flipDone() { done = !done;

} // !

796

1 U

f i n a l
,
,
v o l a t i l e .
, f i n a l .
:
final Map<String,

Double> accounts = new HashMap<>();

a c c o u n t s
. f i n a l , ,
a c c o u n t s .
H ash M ap ,
( n u l l ) . ,
.
, - .


v o l a t i l e , ,
, . j a v a .
u t i l . c o n c u r r e n t . a t o m i c ,
,
. , A t o m i c I n t e g e r
in c r e m e n t A n d G e t () d e c r e m e n t A n d G e t (),
.
.
A t o m i c B o o l e a n , A t o m i c L o n g ,
A t o m i c R e f e r e n c e , ,
. ,
, .


,
. :
1: $200
2: $300
1: $300 1 2
2: $400 2 1

. 14.6, 1 2 .
, 1 2
. , ,
.
.

: $1000.
100 $100000,
$1000.
, , .

797

bank.accounts

bank.transfer(1,2,300)
bank.wiait()

bank.traosfer(2,1,400)
bank,wait()

. 14.6.

r u n (), $1000 ,
. .
NACCOUNTS 10,
R u n n a b l e , 2 *IN IT IA L _B A L A N C E ,
. ,
.
. , <Ctrl+\>.
jio to k o b .
, , .
jconsole, 11, Threads (),
. .7.

i-
i- /- .

798

,
.
. S y n c h B a n k T e s t r u n ()
T r a n s f e r R u n n a b l e , t r a n s f e r ()
f r o m A c c o u n t t o A c c o u n t .
.
l-iv.t

-111m l (' 11 1 ^

- 111. 1( 11 111. 111 ( n i i s o l i '

Time Range: |All

Number ofThread
30-

/i2ta*
Uwthr*d*
as

20-L

Threads
Reference Handler
Finalizer
I Signal Dispatcher

jName: Thread-0
|State: WAITING on Bank@a0e990
{Total blocked: 2 Total waited: 59

r1>

{Stack trace:
jjava Jang.Object .wait(Native Method)
:java Jang .Object .wait(Object .java :485)
Bank.transfeKBank.java:29)
TransferRunnable ,run(TransferRunnable .java :29)
java Jang .Thread.runtThread .java :619)

Thread-1
Thread-2
jThread-3
iThread-4
IThread-5
Thread-6
Thread-7

4.1

^ -.