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

WEB

WEB
PROGRAMMING

MARTY HALL
LARRY BROWN

Prentk Hall PTR, Upper Saddle River, N J 07458


www.phptr.com

Sun Microsystems Press


A Prentice Hall Title

WEB

-
2002

32.973.26-018.2.75
72
681.3.07

""
. ..
..
""
: info@williamspublishing.com, http://www.williamspublishing.com

, , , .
72
Web. .: . .
.: "", 2002. 1264 .: . . . .
ISBN 5-8459-0237-1 (.)
,
Web-, ,
, .
, HTML 4.0,
Java, nJSP,
XML-^ ,
( JavaScript-ceape), .
32.973.26-018.2.75

.

, ,
,
Prentice Hall PTR.
Authoiized ti-anslation fiom the English language edition published by Prentice Hall PTR.
Copyiight Sun Microsystem, Inc., 2001. All rights reseiTed. No pait of this book may be reproduced or
ti^ansmitted in any foiin or by any means, electionic or mechanical, including photocopying, recording or by any
infonnation storage retiieval system, without peiTnission from the Publisher.
Russian language edition published by Williams Publishing House according to the Agieement with
RM Enterprises International, Copyiight 2002

ISBN 5-8459-0237-1 (.)


ISBN 0-13-089793-0 (.)

"", 2001
Sun Microsystem, Inc., 2001

25

I. HTML

33

1. web- HTML 4.0

34

2. HTML 4.0

54

3. HTML 4.0

82

4.

110

5.

136

. JAVA

177

6. Java

178

7. - Java

206

8. Java

252

9.

310

10. Java 2d; Java 2

358

11. ,

394

12.

418

13. awt

454

14. Swing

542

15. Swing

602

16.

664

17.

718

III. ,

18. HTML-

779
780

19. Java :

816

20. JavaServer Pages

900

21.

990

22. JDBC

1016

23. XML-

1050

rv^, J A V A S C R I P T
24. JavaScript: Web-

1099
1100

25. JavaScript

1172

1254

25

1. HTML
1. web- HTML 4.0

33
34

1.1. HyperText Markup Language


1.2. HTML 4.0 HTML
1.3. Web

Web

1.4. HTML-
HTML-
DOCTYPE
1.5. HEAD ..,
HEAD
HEAD
1.6. BODY --

2. HTML 4.0

35
37
38
38
39
41
41
42
43
45
45
46
50

54

2.1.
2.2. ...


2.3. , ...



2.4.




2.5.
2.6.

56
58
58
59
60
61
61
61
64
65
66
66
71
73
75
78
78

3. HTML 4.0
3.1.
3.2.
3.3.
3.4.

82
83
88
90
94


GIF-
IMG
3.5.
3.6.

- ,

ActiveX

3.7.
4.
4.1.
4.2.
4.3.

4.4.

4.5. ...





4.6.
5.
5.1.
5.2.

STYLE JavaScript

5.3.
HTML-
,
,

5.4.
5.5.
5.6.
5.7.
5.8.



5.9.
5.10.

94
94
98
101
101
104
104
106
108
110
112
113
118
120
122
124
125
125
126
126
129
130
130
136
138
140
140
142
142
143
143
144
145
146
146
147
153
156
159
160
160
162
163
163
165

5.11.

5.12.
LAYER ILAYER

5.13.

166
166
167
167
168
172
176

. JAVA

177

6. Java

178

6.1. Java
Web
Java
Java
- Java
Java
6.2. Java:
Java Web
Java
Java
Java - ( ,
)
Java
6.3. Java

Java
6.4.
Java
Java
Java API

( )
Java-
6.5. Java-
Hello, World

Hello, World
,
7. - Java
7.1.
7.2.
7.3. this

7.4.
7.5.
7.6.

180
180
183
186
186
187
188
189
189
190
191
191
192
193
194
194
195
196
196
197
198
198
199
199
200
202
206
207
210
211
214
214
215
218

7.7.Javadoc
javadoc
javadoc
7.8.
7.9.
7.10. , CLASSPATH JAR-
CLASSPATH
7.11.


8. Java
8.1.
8.2.

8.3. ,

8.4. Math


-
Biglnteger BigDecimal
8.5.



8.6. , Java
8.7.

instanceof
8.8.
String

8.9.



8.10.

8.11.
8.12.

catch
finally

223
224
227
230
233
242
245
247
248
249
252
253
255
257
258
258
259
265
268
268
268
270
270
271
272
273
274
274
280
282
283
284
285
290
291
292
292
294
295
295
295
297
302
302
304
305

10

throws


9.
9.1.
9.2.

HTML-
9.3.


,
9.4.
9.5.
9.6. APPLET
9.7.

9.8. HTML- OBJECT
9.9. JaVa Plug-In
9.10.
9.11.




9.12.
,
URL
,
URL

9.13.
9. J4. ...
9.15.

343
345
347
351
357

10. Java 2d: Java 2


10.1. Java 2D
Graphics2D
10.2.
Shape
10.3.


10.4.
10.5.
10.6.

358
360
362
365
366
370
370
373
376
378
381
381

306
307
310
311
312
312
313
314
316
316
317
318
319
325
327
328
330
332
334
335
336
339
339
340
340
341

10.7.

10.8. Java 2D

11

386
389
390

11. ,

394

11.1. ...

11.2. ...
11.3. ...
11.4. ...
11.5.
11.6.
11.7.
11.8. " "
" "
11.9.

396
397
399
400
402
403
409
412
414
416
417

12.
12. 1. FlowLayout
FlowLayout
FlowLayout
12.2. BorderLayout
BorderLayout
BorderLayout
12.3. GridLayout
GridLayout
GridLayout
12.4. CardLayout
CardLayout
CardLayout
12.5. GridBagLayout
GridBagConstraints
GridBagLayout
GridBagLayout
GridBagLayout
12.6. BoxLayout
BoxLayout
BoxLayout
12.7.
12.8.



13. awt
13.1. Canvas
Canvas
, Canvas

418
420
421
421
422
424
424
425
425
427
427
431
431
432
433
434
438
438
439
442
442
443
444
445
448
449
454
456
457
457

12

13.2. C o m p o n e n t
13.3. "" Java 1.1
13.4. Panel
: FlowLayout

Panel
13.5. Container
13.6. Applet
13.7. ScrollPane
ScrollPane
ScrollPane, ,
100
13.8. Frame
: BorderLayout
Frame
Frame
Frame

Frame
13.9.


Frame,
13.10. Dialog
Dialog
:
13.11. FileDialog
1 TextAiea
13.12. Window
: BorderLayout
Window
13.13.


13.14. Button


Button

13.15. Checkbox


Checkbox
Checkbox
13.16.

460
466
469
469
470
470
472
474
474
474
474
475
476
476
477
479
480
481
482
483
483
484
486
487
487
489
489
491
491
491
492
493
495
496
496
497
498
498
501
501
502
503
503
504
504
505

CheckboxGroup Checkbox
CheckboxGroup
13.17. Choice


Choice
, Choice
13.18. List

List
List
List
13.19. TextField


TextField
TextComponent
, TextField
13.20. TextArea


TextAiea
TextArea
13.21. Label

Label
Label
Label
13.22.


Scrollbar
Scrollbar
13.23.


P o p u p M e n u
,
14. Swing
14.1. Swing
Swing AWT
14.2. JApplet
14.3. J F r a m e
14.4. JLabel
: , HTML-
JLabel

13

506
506
507
507
507
508
509
510
511
511
512
514
518
519
519
520
520
523
523
523
524
525
526
526
526
527
527
528
530
530
531
532
534
535
536
536
538
539
542
544
544
552
553
555
555
556

14

JLabel
14.5. JButton
: ,
" "
HTML-
JButton
J B u t t o n AbstractButton
14.6. JPanel
JPanel
:
BorderFactory
14.7. JSlider
:
JSlider
JSlider
14.8. JColorChooser

JColorChooser
14.9.
J I n t e r n a l F r a m e
JInternalFrame
14.10. J O p t i o n P a n e
J O p t i o n P a n e
14.11. JToolBar
JToolBar
JToolBar
14.12. JEditorPane

JEditorPane
J E d i t o r P a n e
Web-
H T M L JavaHelp
14.13. Swing-
JCheckBox
JRadioButton
JTextField
JTextArea
JFileChooser
15. Swing
15.1.

15.2. JList
JList
JList
JList
JList ,

557
559
559
560
561
561
563
564
564
564
567
568
568
569
571
572
572
575
575
575
578
579
583
584
585
589
590
590
591
592
595
595
595
597
598
598
598
602
604
604
605
609
612
617

15.3.JTree
J T r e e
J T r e e
J T r e e
15.4.JTable
JTable
, JTable


15.5. Swing-



JDK 1.3
15.6. Swing
SwingUtilities
16.
16.1.
Thread
, Runnable
16.2. ""
16.3.


,
16.4.
16.5. T h r e a d


16.6.

16.7.
paint

paint
u p d a t e
paint

16.8.
16.9.

Timer
16.10.

15

621
621
625
625
634
634
638
643
645
649
649
651
652
656
658
660
664
666
666
668
671
673
673
674
675
677
681
681
682
683
688
690
690
690
692
693
696
696
699
703
708
712
715
716
717

16

17.
17.1.

17.2. StringTokenizer
StringTokenizer


17.3. , ...
17.4. -...
,
, URL
UrlRetriever
17.5. URL
URL
URL
17.6.WebClient...
17.7.

NetworkClient NetworkSei'ver
17.8. HTTP-
,
17.9. RMI: Remote Method Invocation
RMTpoe
RMI
,
,

RMI



RMI-

718
720
722
725
726
726
726
727
728
731
732
733
734
735
735
736
738
745
747
750
751
754
756
757
758
762
763
768
769
772
774

III. ,

779

18. H T M L -

780

18.1. HTML-
18.2. FORM
18.3.



18.4.
Submit
Reset

781
785
790
790
792
792
794
795
797

JavaScript
18.5.


18.6.
18.7. ...
18.8.
IMAGE
ISMAP
18.9.
18.10.
18.11.
19. Java :
19.1. ...


19.2.
JSP
}^1, JSP




1
19.3.
,
, HTML-
\ HTML-
19.4.
init
service
doGet, doPost doXxx
SingleThreadModel
destroy
19.5.
19.6. :
CGI-


,
19.7. : HTTP-

17

798
799
799
800
802
805
806
807
809
811
812
813
816
818
818
819
819
819
819
820
820
820
822
822
822
823
823
824
824
825
826
828
830
830
831
832
832
833
833
836
836
836
837
839
840
841

18

,
, H T T P 1.1
Web-
19.8. CGI-
19.9. :

H T T P 1.1

19.10. :



Web-
19.11. Cookie
cookie
, cookie
API, cookie
cookie
cookie
cookie
19.12.

URL
API

,
20. JavaServer P a g e s
20.1. oJSP
20.2. JSP
JSP ASP ColdFusion
JSP
JSP
JSP SSI
JSP JavaScript
20.3. JSP


20.4. page
import
ontentType
isThreadSafe
session
buffer
) autoflush

843
845
848
850
853
853
855
860
864
865
866
871
880
880
882
883
886
889
890
890
891
891
892
896
897
900
901
903
903
903
903
904
904
904
905
908
910
912
913
914
916
917
918
918
919

extends
info
errorPage
isErrorPage
language
XML-
20.5. JSP-
include:


, Java Plug-In
jsp:fallback
20.6. JavaBeans JSP
JavaBeans
StringBean
beans
bean
20.7. JSP-
,







20.8. JSP

:
JSP-
21.
21.1. GET
21.2.
21.3. GET...
ASCII-

21.4. ...
21.5. POST...
21.6. , POST
21.7. HTTP-
22. J D B C
22.1. JDBC

URL

Statement

19

919
919
919
920
920
920
920
921
923
925
929
932
933
935
937
942
946
946
949
953
956
961
964
968
970
977
978
981
988
990
992
993
997
997
999
1001
1007
1009
1014
1016
1017
1018
1019
1019
1020

20




22.2. JDBC
22.3. JDBC
22.4. DatabaseUtilities
22.5.
Q u e lyVie we
22.6.
23. XML-
23.1. XML- DOM Level 2

23.2. DOM...
23.3. XML- SAX 2.0

23.4. SAX: ...


23.5. SAX:
23.6. XML XSLT

23.7. XSLT:
23.8. XSLT...

1020
1020
1021
1022
1027
1035
1039
1041
1046
1050
1052
1052
1053
1055
1064
1065
1066
1067
1073
1077
1078
1079
1082
1090

rV^. J A V A S C R I P T

1099

24. JavaScript: Web-

1100

24.1. HTML-

24.2.
24.3. JavaScript


24.4. JavaScript Web-




24.5. JavaScript ...


24.6. JavaScript HTML-


24.8. JavaScript
URL

1103
1107
1108
1109
1110
1110
1111
1116
1117
1117
1120
1122
1122
1128
1131
1133
1135
1144
1144


24.9. Java JavaScript
Java
JavaScript-
JavaScript-
24.10. JavaScript Java
Web-
,
JSObject
25. JavaScript
25.1. Array


25.2. Button


25.3. Checkbox


25.4. Date


25.5. Document


25.6. Element


25.7. FileUpload


25.8. Form


25.9. Function

21

1147
1148
1148
1150
1153
1157
1159
1160
1169
1172
1173
1173
1174
1174
1177
1177
1177
1177
1178
1178
1179
1179
1180
1180
1180
1181
1181
1183
1183
1183
1186
1186
1186
1186
1187
1188
1188
1189
1189
1189
1190
1190
1190
1191
1191
1191

22


25.10. H i d d e n


25.11. History


25.12. Image


25.13. JavaObject
25.14. JavaPackage
25.15. Layer


25.16. Link


25.17. Location


25.18. Math


25.19. MimeType


25.20. Navigator


25.21. N u m b e r

1191
1192
1192
1192
1193
1193
1193
1193
1193
1194
1194
1194
1194
1195
1196
1196
1196
1197
1197
1197
1197
1199
1200
1200
1201
1202
1202
1202
1202
1203
1204
1204
1204
1205
1206
1207
1207
1207
1207
1208
1208
1210
1210
1210
1211
1211
1211


25.22. Object


25.23. Option


25.24. Password


25.25. Plugin


25.26. Radio


25.27. RegExp



25.28. Reset


25.29. Screen


25.30. Select


25.31. String


25.32. Submit

23

1213
1213
1213
1214
1214
1214
1214
1214
1215
1215
1215
1215
1216
1216
1216
1217
1217
1218
1218
1218
1218
1219
1219
1219
1219
1221
1222
1223
1223
1225
1225
1225
1226
1226
1226
1227
1227
1227
1228
1229
1229
1230
1230
1230
1230
1235
1235

24


25.33. Text


25.34. Textarea


25.35. Window

1235
1236
1236
1237
1237
1237
1238
1238
1238
1239
1239
1240
1240
1244
1249
1254

25

1995 . ,
.
, Web, Java-.
, HTML, Java, HTTP, CGI JavaScript
. , .
1996 . Java. .
, , ,
.
, ,
. .
.
1,
, , ,
, , ,
.
.
,
, .
Web.
, ,
. HTML 3.2
HTML 4.0, Java 2, ,
, .
.
JSP 1.0 , JSP,
CGI-, ASP ASP ColdFusion.
XML. Java
.
, ,
, , .
,
Java- Web-.
Java Foundation Classes ,

26

RMI XML .
, , HTML 4, C S S / 1 , H T T P L I
Java, CGI JSP,
, Swing Java 2D. ,
XML- JAXP, DOM Level 2,
SAX 2.0 XSLT. , .
,
.


.
, Web-,
. H T M L
XML, Java- , JavaServer Pages JavaScript,
.
, . ,
, 250 Java-.
,
, , " "
API ( ).
, ,
, . ,
, . 1 ,
.
, ,
, .
, ,
, .
Web-
.
, ,
HTML 4.0.
. Web-
JDBC.
. ,
,
RML ,
, JSP.
H T T P L1 ,
.
, JavaBeans
JSP. JavaScript-
HTML- .
, , .

27


, HTML,
Java, , JavaScript.

L HTML
Web- HTML (HyperText Markup Language).
HTML- , ,
, Web-.
Web-, Netscape Navigator Microsoft Internet Explorer,
Web-. .

HTML 4.01. , HTML. , , , ,


.

Netscape Internet Explorer.


, , -, - ActiveX.

.
HTML-. . .
.

.
, , , ,
.

IL Java
Java ,
, ,
Web-. .

Java. Java ?
Java, .

- Java. ,
, , . .
, CLASS PATH JAR-.

Java. , , , , , Math.

. . . .
. . Java Plug-In.

Java 2D. 2-.


, , ,
.

28

, . .
. .
. .

.
FlowLayout,
BorderLayout,
GridLayout,
C a r d L a y o u t , G r i d B a g L a y o u t B o x L a y o u t ,
. .

AWT. C a n v a s , P a n e l , A p p l e t , S c r o l l P a n e , F r a m e , D i a l o g ,
F i l e D i a l o g Window. . , ,
, , , ,
, .
.

Swing.
Swing. .
. H T M L
. .
. Web- Swing.

Swing. J L i s t , J T r e e J T a b l e .
. Swing
. Swing .

.
. .
.
. . .

. .
URL. . HTTP-.
RMI.

III. ,

, Web-,
, .
Java- CGI-, JSP Active Server
Pages ColdFusion. .

HTML-. , HTML-.
, . .
. . .
.

Java-. .
. .
. ,
H T T P L L cookie .
.

29

JavaServer Pages (JSP). JSP. ,


. JavaBeans JSP.
JSP. JSP.


. GET POST. -.

. HTTP-.

Java Database Connectivity (JDBC).


. , JDBC.
HTML-.
. .

XML- Java. XML-


Document Object Model (DOM) Level 2. ,
XML-, Simple API for XML Parsing (SAX)
2.0. XML XSLT. Java API for XML
Processing (JAXP) .

IV. JavaScript
JavaScript , ,
Web-. .
.

JavaScript. , , , , ,
.

Web-. ,
JavaScript .

Web-. .
. .

HTML-. .
, .

cookie. . C o o k i e .

. .
)'.
. .

Java JavaScript. L i v e C o n n e c t JSOb j e c t .

JavaScript. ,
JavaScript 1.2. , . Document, Window, Form,
E l e m e n t , S t r i n g , Math, RegExp .

30

,
, ,
, ,
. , . A p p l e t ,
.
, , .
( P r o m p t > ) ,
, (Unix>).
,
J a v a S o m e P r o g r a m .
Prompt> Java SomeProgram
Some O u t p u t
,
, .

,
" ".
.
.

Web-
,

Web-

http://www.corewebprogramming.com/
.

, .
.

HTML-, Java- JavaScript.

URL, .

Java.

Ronco.

31

06


Web-.
, JavaSen^er Pages, ,
Web-. Core Servlets and JavaServer Pages, a
Web.
Research and Technology Development Center
TheJohns Hopkins University Applied Physics Laboratory
11100Johns Hopkins Road
Laurel, MD 20723
hall@corewebprogramming. com
-
Web- .
,
, ,
Web- Java.
:
Naval Surface Warfare Center, Carderock Division
9500 MacArthur Boulevard
West Bethesda, MD 20817
brown@corewebprogramming. com

32

.
. , (Don Aldridge),
(Chris B e n n e t t ) , ( Bell), (Pete Clark),
(Maria D i m a l a n t a ) , - ( N g u y e n - K h o a Duy),
(Denise E v a n s ) , (Amy K a r l s o n ) , (Paul M c N a m e e ) ,
(Toddi N o r u m ) , (Walter P a s q u i n n i ) , (Rich
Slywczak), (Bob Tinker) (Kim Topley)
.
. ( Lou Nohr)
. ,
. ( V a n e s s a Moore)
. ,
. ( R a l p h S e m m e l )
( J u l i e Wessel) .
(Greg D o e n c h ) P r e n t i c e Hall
. .
, , B . J . ,
. , , ,
.
.


, , .
, ,
.
, .
.
Web-, ,
, ,
, ,
.
, ,
e-mail.
. :
L-mail:

i n f o @ w i l l i a i n s p u b l i s h i n g . com

WWW:

h t t p : //www. w i l l i a m s p u b l i s h i n g . com

^:jzjs:-r

HTML
1. \/\/' HTML 4.0
2. HTML 4.0
3. HTML 4.0
4.
5.


WEB-

HTML 4.0
...

HyperText Markup Language.

HTML 4.0 HTML.

HTML-.

Web-.

HTML-.

J~1y\ZJSJZJ

, HTML (HyperText Markup Lan


guage ). ,
, Web-.
HTML-,
, Web-.
, ,
. Java-,
(socket), , Java-, JavaSetrver Pages (JSP)
XML-.
Web-.
HyperText Markup Language
, , Web. Web-,
HTML-, ,
, . , ,
, Web- HTML,
, .

1.1. HyperText Markup Language


Web- HyperText Markup Language. ,
HTML, ,
.
(, ,
) (,
).
(, ,
) ,
. L1 HTML- Web-, -

36

1 . Web- HTML 4.0

. 1.1. , ;
HTML .
HTML-. , ,
, ,
. ( )
<> </>.
. 1.1 , Web-
(Internet Explorer 5.0), Windows 2000 Profes
sional. (, )
. , ,
. Web-
, , ,
. 5 ,
Web.
.

Ele
^

..JOJJcj

for lewrencc! . ~9
dft ilew Favorites look jjelp
- *4 - : ^ ^

-^Search JJFuvorte* ^Hetory

-Ji' ^

Home Page for Lawrence M. Brown

CAKOf KOcii^^oiYiSfON

JNSI^f\/C^

Senior Network Engineer


Naval Surface Waifai-e Center
9500 MacArthor Boulevard
West Bethesda. Maryland. MD 20817-5700
email: lan7@corewebpro.eyttrmx^^ com
Phone: (30 \) 277-4648

This IS my personal home page For more specific programmmg-related resoxirces pages, please see

'

. 1.1. , 1.1,
Internet Explorer 5.0,
Windows 2000

1.1. HTML- \/-


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<Title>Home Page for Lawrence M. Brown</Title>
</HEAD>
<BODY BGCOLOR="WHITE">
<H1 ALIGN="CENTER">Home Page for Lawrence M. Brown</Hl>
<HR>
<IMG SRC="images/navsea-nswc.gif" WIDTH=300 HEIGHT=117
HSPACE=10 VSPACE=5 ALIGN="LEFT" ALT="NSWC Logo">
Senior Network Engineer<BR>
<A HREF="http://www.dt.navy.mil/">

1 . 2 . HTML 4 . 0 HTML

37

Naval Surface Warfare Center</A><BR>


9500 MacArthor Boulevard<BR>
West Bethesda, Maryland, MD 20817-5700<BR>
< I > e m a i l : < / I > <A H R E F = " m a i l t o : l a r r y @ c o r e w e b p r o g r a i r a n i n g . " >
larry@corewebprogramming.com</A><BR>
<I>Phone:</I> (301) 277-4648<BR CLEAR="ALL">
<P>
T h i s i s my p e r s o n a l home p a g e . For more s p e c i f i c
programming-related resources pages, please see:
< ! - - Web- >
</BODY>
</HTML>

,
, ,

.
Web- ,
, ,
HTML-. ,
, HTML-
.
WWW-.

1.2. HTML 4.0 HTML


, , Web HTML.
1997 . HTML 2.0, W3C (World Wide
Web Consortium). HTML 2.0 ,
, 1994 . , HTML 2.0,
.
HTML+, HTML 3.0.
Web- .

HTML 3.2 ( "Wilbur").
HTML 3.2 HTML 2.3,
HTML 3.0. , 1997 . HTML 4.0.
, H T M L 4.0
. Netscape 4.0
, Internet Explorer 4.0 ( 3.x
HTML 3.2). HTML 3.2
HTML 4.0 .

38

1 . Web- HTML 4.0

, .

1997 . H T M L 4.0
H T M L 4.01,
. HTML 4.01 W3C
24 1999 . HTML 4.01 ,
X H T M L 1.0, XML Web-.
H T M L 4.01 HTML-. XML
,
. XML 23.
XHTML 1.0 26 2000 .
H T M L :
H T M L 4.01
http://www.w3.org/TR/html401/
H T M L 4.0
h t t p : / / w w w . w 3 . o 3 r g / T R / 1 9 98/REC-html4 0 - 1 9 9 8 0 4 2 4 /
H T M L 3.2

http://www.w3.org/TR/REC-html32.html

1.3. Web
Web, .
1. HTML-.
2. , Web.
3. , HTML-
.


HTML- ASCII-, HTML-
, Notepad,
UltraEdit, emacs BBEdit. HTML, , HomeSite, FrontPage Dreamweaver. ,
HTML- ,
, Microsoft Word WordPerfect. H T M L
, ,
, ,
.

1.3. Web

39

,

Web-. HTML-
"WYSIWYG" (What You See Is What You Get) ; no ,
. ,

. HTML-
Web-;
, .
HTML-, ,
HTML-. , Web ,
, ,
. Web-
, HTML- ,
.

Web
HTML- Internet-,
, Internet, ,
HTTP-. Internet-,
Internet- (),
. Web , .

. Web-
, .
, , , Internet.
.


, Web-,
HTTP-. HTTP (HyperText Transfer Protocol
) 19.
, HTTP , WWW-
() , Web-.
, , HTTP-.
HTTP- URL (Uniform Resource Locator
), "" Web,
. ,
,
p u b l i c h t m l www. URL,
. HTML-
.

40

1 . Web- HTML 4.0

Web-
. HTML-
FTP. ,
, .

Web-. UNIX, ,
Web ( , p u b l i c h t m l www),
Web-.
, j a n e d o e
t e s t . h t m l www. s o m e - i s p . com.
t e s t . h t m l / h o m e / j a n e d o e / p u b l i c _ h t m l . / h o m e / j a n e d o e
, p u b l i c h t m l "" ,
Web-. Web URL
h t t p : / / w w w . s o m e - i s p . c o m / ~ j a n e d o e / t e s t . h t m l .
"--" " ".
ASCII ISO Latin 1,
"~" "%7". ,
h t t p : / / s o m e . h o s t / % 7 E u s e r / p a t h URL.


, HTTP-,
, , HTML- ,
( p u b l i c h t m l ) .
,
FTP-, F e t c h , f t p . e x e Windows
9 5 / 9 8 / 2 0 0 0 / N T / u s r / b i n / f t p UNIX. ,
.
"" HTTP-
. , URL
, . ,
i n d e x . h t m l . Welcome . h t m l d e f a u l t . h t m l . . h t m l . htm.
j a n e d o e / h o m e / j a n e d o e /
p u b l i c _ h t m l / i n d e x . h t m l , , h t t p : / / w w w . s o m e i s p . c o m / - j a n e d o e / . URL, .
: h t t p : //www. s o m e - i s p . c o m / ~ j a n e d o e / i n d e x . h t m l .


Web, ,
, HTTP-. HTTP ,
, .
, UNIX,
,
. , UNIX
umask. UNIX
:

1.4. H T M L -

Unix>
Unix>
Unix>
Unix>
Unix>

41

cd
chmod a+x .
cd public_html
chmod a+x .
chmod a+r file

Web- HTML-
, t e s t . t x t ,
, "Hello!".

, URL h t t p : / / y o u r . i s p . c o m / ' - y o u r a c c o u n t / t e s t . t x t . ,
, .


Web, ,
. Web-)' , .
, , HTML-, "",
.
-1, , Web-,
, -
. HTML SGML (Standard
Generalized Markup Language ),
SGML
HTML. HTML- .
,
. W3C HTML Validator Service.
URL:

http://validator.w3.org/

http://www.htmlhelp.com/tools/validator/

http://jigsaw.w3.org/css-validator/


", ":
', HTML

1-4. HTML-
HTML- ,
. , <TITLE> , ,
TITLE. ,
. HTML-
, -.
, <IMG S R C = ^ ' i m a g e s / s a m p l e . g i f " >

42

1 . Web- HTML 4.0

i m a g e s / s a m p l e . g i f SRC IMG.
, ,
.
, . HTML-
,
. , ,
, ,
. , XHTML L0
, ,
, . XML (. 23).
, .. ,
, (, <BODY>) , , ,
" < / " (, </BODY>).
(, <HR>).
HTML- , .
,
.
" < ! " " - - > " .
, " - - " .

HTML -
HTML- DOCTYPE,
HTML. .
DOCTYPE HTML, HEAD BODY.
HEAD, , TITLE. BODY,
HEAD, (HI),
Web-.
,
DOCTYPE TITLE. HEAD BODY
. HTML-
. HTML- ,
.
. L2 HTML-,
L2. Web-,
HTML 4.0 ( ,
4).
-iq|.xf
file

view

Coiwwjnfctor

^ i' ^ - 1 '> ii^

Main Heading
pocument: Oortc

.,M .:^:..

. 1.2. HTML 4.0,


Netscape 4.7,
Windows 2000 Professional

1.4. -

43

1.2. HTML4 . 0~Template, html


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Title</TITLE>
</HEAD>
<BODY>
<Hl>Main Heading</Hl>
<!-- Web- -->
</BODY>
</HTML>

DOCTYPE
HTML-
DOCTYPE.
H T M L 4.01 D O C T Y P E
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
H T M L 4.01 D O C T Y P E
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0 1

Transitional//EN">

H T M L 4.01 D O C T Y P E
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0 1

Frameset//EN">

HTML 4.01

, HTML.
,
(, ),
HTML.
,
, , ,
. ,
, .
H T M L 4.01
http://www.w3.org/TR/html4/index/elements.html
H T M L 4.01
http://www.w3.org/TR/html4/index/attributes.html
H T M L ,
(frame).

44

1 . Web- HTML 4.0

H T M L .
HTML .
. (...)
,
.
, ,
. ,
. , HTML 4.0,
Netscape Internet Explorer, "".
, HTML-
Netscape 4.08-4.7 Internet Explorer 4.01-5.5.

: <HTML ..> ... </HTML>


: LANG, DIR, VERSION
HTML DOCTYPE
, HEAD BODY. HTML
, ,
HTML- .
HTML ,
, HTML. ,
, HTML .
LANG
LANG ,
. ) LANG
, .
, LANG,
.
RFC 1766. RFC, }^
, h t t p : //www. r f c - e d i t o r . o r g / .
DIR
DIR : LTR (left-to-right
) RTL (right-to-left ). Internet Explorer
)^ DIR, ASCII-
. Netscape ( ,
Netscape 4.7 ),
intranet, Internet Explorer.

!
Netscape DIR HTML,
VERSION
VERSION HTML .
. H T M L -

1.5. HEAD ...

45

DOCTYPE. H T M L 4.0 VERSION


.
HTML LANG DIR
, APPLET, BASE, BASEFONT, BR, FRAME, FRAMESET,
IFRAME, NOFRAMES, PARAM SCRIPT. LANG DIR
HTML.

1.5. HEAD
Web-
: <HEAD>.,. </HEAD>
: PROFILE
HEAD HTML-.
DOCTYPE <HTML>, BODY.
HEAD TITLE,
. PROFILE
, ,
, , ,
. PROFILE URL ,
HEAD
( ). H T M L
HEAD LANG DIR.
.

HEAD
: <TITLE> ... </TITLE>
:
TITLE HTML 4.0
. TITLE )^ HTML-,
, & ""
( . 2.1 2). TITLE
. , Netscape Internet Explorer ,
TITLE, , .
TITLE Web-.
TITLE, ., .
HTML 4.0 TITLE
LANG DIR, Netscape Internet Explorer.
, ASCII, ,
, .

46

1 . Web- HTML 4.0

HEAD
TITLE HEAD
BASE, , BGSOUND LINK. , Web . HTML,
,
.

: <BASE HREF="..." ...> ( )


: HREF (), TARGET
BASE URL.
URL, ,
. ,
. ) ,
, BASE
, URL - .
HREF URL.
, h t t p : / / w w w . m i c r o s o f t . c o m / w i n d o w s 2 0 0 0 . h t m l
www. a p p l e . com www. s u n . com.
BASE. HEAD :
<HEAD>
<TITLE>Why You S h o u l d Buy Windows 2000</TITLE>
<BASE H R E F = " h t t p : / / w w w . m i c r o s o f t . c o m / w i n d o w s 2 0 0 0 / " >
</HEAD>
TARGET
, ,
, . Web <BASE TARGET=" . . . "> (
HREF),
. 4.

: < ...> ( )
: NAME, CONTENT (), HTTP-EQUIV, SCHEME
,
Web-, .

. ,
NAME-CONTENT, NAME , CONTENT .
, a u t h o r ( ), d e
s c r i p t i o n ( ), k e y w o r d s ( , ,
) g e n e r a t o r (
, ). ,
Google, Infoseek Lycos, k e y w o r d s (
, ). d e s c r i p t i o n
, .
1.3 .

1.5. HEAD . . .

47

1.3. HEAD,
<HEAD>
<TITLE>Why You Should Buy Windows 2000</TITLE>
<BASE HREF="http://www.microsoft.com/windows2000/">
<META NAME="author" CONTENT="Bill Gates">
<META NAME="keywords"
CONTENT="Windows,Advocacy,OS,Operating Systems">
<META NAME="description"
CONTENT="A summary of the advantages of Windows 2000.">
</HEAD>
HTTP-EQUIV , R e f r e s h .
, ,
. ?13 ,
30 (1800 ). , Web-
h t t p : / / w w w . m i c r o s o f t . c o m / w i n d o w s 2 0 0 0 / B u y - W i n 2 0 0 0 . h t m l .
1.4 ,
.
EQUIV=" Re f r e s h " , CONTENT (1800
), .
1.4. Web- 3 0
<HEAD>
<TITLE>Why You Should Buy Windows 2000</TITLE>
<META HTTP-EQUIV="Refresh" CONTENT="1800">
</HEAD>

,
URL ( 1.5). ,
URL
URL.
5 . ,
HTTP-EQUIV, R e f r e s h , URL .
,
.
, , .
1.5.
<HEAD>
<TITLE>Why You Should Buy Windows 2000 (New Address)</TITLE>
<META HTTP-EQUIV="Refresh"
C0NTENT="5;
URL=http://www.apple.com/Buy-Win2000.html">
</HEAD>

48

1 . Web- HTML 4.0

URL ,
,
. .
, Internet Explorer BGSOUND ( );
, Netscape, Internet Explorer
EMBED. :
,
.
HTTP-EQUIV CHARSET
. , ,
,
GB2312:
< HTTP-EQUIV="Content-type"
CONTENT="text/html; CHARSET=GB2312">
ISO .
ASCII-, ,
, .
,
16- Unicode.
Unicode UTF-8, 16- Unicode
, ASCII- 8 .
Unicode
h t t p : //wwv/. U n i c o d e . o r g / .
HTTP-EQUIV HTTP-,
CONTENT. HTTP-EQUIV
( Netscape, Internet Explorer),
"" , .
HTTP- 19.
SCHEME ,
NAME-CONTENT . NAME ,
CONTENT . SCHEME ,
-- (SCHEME="Month-Day-Year"),
--.
< SCHEME="Month-Day-Year"
NAME="Date"
VALUE="05-01-2000">
LANG DIR .

: <BGSOUND SRC="..." ...> (


)
: SRC (), LOOP
, Internet Explorer
. BGSOUND
BODY, HEAD.

1.5. HEAD ...

49

SRC
SRC URL ,
. wav, . a u MIDI.
LOOP
LOOP , .
1. , - 1 , INFINITE,
, ,

.

: <SCRIPT TYPE="..." ...> ... </SCRIPT>


: LANGUAGE, SRC, ( ) , CHARSET, DEFER

SCRIPT ,
JavaScript. JavaScript 24.

: <STYLE TYPE="..." ...> ... </STYLE>


: TYPE (), TITLE, MEDIA
STYLE
, , , ,
, .
5.

: <LINK ...> ( )
: HREF, REL, REV, TYPE, CHARSET, HREFLANG, MEDIA, ONCLICK, ONDBLCLICK,
ONMOUSEDOWN, ONMOUSEUP, ONMOUSEOVER, ONMOUSEMOVE, ONMOUSEOUT, ONKEYPRESS,
ONKEYDOWN, ONKEYUP, TARGET. TITLE, I D , CLASS, STYLE

LINK ^ K}TvieHTOB. ,
, . HEAD
LINK.

HREF, REL, REV


HREF URL . REL
, REV
. CONTENTS, INDEX,
GLOSSARY, HELP, NEXT PREVIOUS (
), MADE ( ) STYLESHEET (
).
.
<LINK REL=STYLESHEET
HREF="My-Styles.CSS"
TYPE="text/css">

50

1 . W e b - HTML 4 . 0

TYPE, CHARSET, HREFLANG, MEDIA


TYPE MIME- , .
- TYPE=" t e x t / h t m l " . MIME , RFC 1521 ( ,
RFC, h t t p : / / w w w . r f c - e d i t o r . o r g / ) ,
, t e x t , pdf, g i f . CHARSET
, .
CHARSET="ISO-8859-6". HREFLANG
. , HREFLANG="pt" ,
, , .
MEDIA .
ALL, AURAL, BRAILLE, HANDHELD, PRINT, PROJECTION, SCREEN
(no ), SPEECH, TTY TV.
LINK
.

1.6. BODY
HTML- BODY,
Web-. , .

, .
BODY . TITLE
,
, BODY ,
<1>. ,
, TITLE.
TITLE 1.6.
BODY HTML-:
. , ,

. ,
, , , , ,
. }^
. ,
(, ).
2.
1.6. HTML 4 . 0
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>My First Web Page</TITLE>
</HEAD>
<BODY>

1.6. BODY

51

<1> First Web Page</Hl>


< ! HTML- -->
</BODY>
</HTML>

.
, , ,
, , , ActiveX .
,
,
. 3.

: <BODY ...> ... </BODY>


: BACKGROUND, BGCOLOR, TEXT, LINK, VLINK, ALINK, TITLE, ONCLICK,
ONDBLCLICK, ONMOUSEDOWN, ONMOUSEUP, ONMOUSEMOVE, ONMOUSEOUT, ONKEYPRESS,
ONKEYDOWN, ONLOAD, ONUNLOAD, ONFOCUS (), ONBLUR (),
ONERROR (), ONMOVE (), ONRESIZE (),
ONDRAGDROP (), BGPROPERTIES (), CLASS, ID, STYLE
BODY (..
<BODY>), ,
, , (
, , ,
, , ,
). JavaScript,
, , .

BACKGROUND BGCOLOR
BACKGROUND URL . ,
, Web-.
, .

. , , ,
,
,
. BACKGROUND,
BGCOLOR, .
BGCOLOR "" , -
- .
(WHITE, #FFFFFF)
- (SILVER, #) . BACKGROUND
BGCOLOR ,
.
.

52

1 . Web- HTML 4.0

TEXT, LINK, VLINK ALINK


, ,
(, ,
), , (,
, ),
. , ,
, .
, ALINK.
.
,
.
, "#",
. ,
.
. 1.1. , 256 ,
Color-Safe, 216 ,
. Color-Safe
h t t p : / / w w w . c i o c n p r o f . c o m / s a f e c o l o r A . h t m . Netscape
Internet Explorer ,
X I 1 . X I 1 h t t p : / /www. z d n e t . com/
devhead/resources/tag_library/misc/xllnames.html.

1.1 HTML 4.0



AQUA
BLACK
BLUE
FUCHSIA
GRAY
GREEN
LIME
MAROON

#OOFFFF
#000000
#OOOOFF
#FFOOFF
#808080
#008000
#OOFFOO
#800000


NAVY
OLIVE
PURPLE
RED
SILVER
TEAL
WHITE
YELLOW

#000080
#808000
#800080
#FFOOOO
#COCOCO
#008080
#FFFFFF
#FFFFOO

(BLACK,
# 0 0 0 0 0 0 ) ( TEXT), (BLUE
#0000) ( LINK), -
(#5518) , ,
( VLINK), (RED, #FF0000)
( ALINK).
TITLE
TITLE ,
.
Internet Explorer 4.0 . Netscape (
4.7 ) TITLE.

1.6. BODY

53

ONCLICK, ONDBLCLICK, O N M O U S E D O W N , O N M O U S E U P ,
O N M O U S E M O V E , O N M O U S E O U T , ONKEYPRESS, ONKEY-DOWN,
ONLOAD, ONUNLOAD, ONFOCUS, ONBLUR, ONERROR, ONMOVE,
ONRESIZE, O N D R A G D R O P
JavaScript,
, , .
BGPROPERTIES
Internet Explorer.
BGPROPERTIES = "FIXED", ,
.
" " (watermark).
, HTML-
CLASS, ID STYLE.
BASE, BASEFONT ( ID ), HEAD, HTML, , PARAM (
ID ), SCRIPT, STYLE TITLE. HTML-
, , .
5, .

1.7.
HTML Web. , Web-
,
, , ,
HTML-. HTML-o)^vIea
, Web- Internet.
, :) HTML 4.0,
DOCTYPE, HTML, HEAD BODY.
HEAD TITLE, , HEAD
STYLE, )^ , ,
. ,
, ,
. , <BODY>
, ,
, JavaScript-,
.

Web-. 2 , 3
, )^' . 4
. Web-
"" .
,
, , 5.

HTML 4.0
...

-1\^^^

, ,
BODY HTML-.
Web. ,
. ,
,
,
.
HTML 4.0, ,
JavaScript- (ONCLICK, ONDBLCLICK, ONKEYDOWN, ONKEYPRESS,
ONKEYUP, ONMOUSEDOWN, ONMOUSEMOVE, ONMOUSEOUT, ONMOUSEOVER ONMOUSEUP),
APPLET, BASE, BASEFONT, BDO, BR,
FRAME, FRAMESET, HEAD, HTML, IFRAME, META, PARAM, SCRIPT, STYLE TITLE.

HTML-. JavaScript
24.

HTML- ( )
CLASS, ID STYLE. BASE, BASEFONT
( ID ), HEAD, HTML, , PARAM ( ID
), SCRIPT, STYLE TITLE.
5, HTML-
.
, H T M L 4.0 , APPLET, BASE,
BASEFONT, BR, FRAME, FRAMESET, IFRAME, PARAM SCRIPT, )
LANG DIR. 1
HTML- .
, TITLE, 1,
BASE, BASEFONT, HEAD, HTML, , PARAM, SCRIPT TITLE.
.

56

2 . HTML 4 . 0

2 . 1 .
: <1
<2
<
<4
<5

.. .> . .
.. .> . .
.. .> . .
.. .> . .
. . .> . .
< . . .> . .

</1>
</2>
</>
</4>
</5>
</>

: ALIGN
1-6
. HI , , , 2
, . . , BODY
, , TITLE,
HEAD. (2)
, . .
1 : HI
, .
, ,
,
. , , .
,
, (TABLE)
(FORM). .
, 2.1, ,
.
, .
2 . 1 . ,
<2><1> Italic Heading</I></H2>
<2>< NA]yiE="Section5">Section

Five</A></H2>

, 2.2, ,
.
2 . 2 . ,

<1><2> I t a l i c

Heading</H2></I>

< NAME="Section5"><H2>Section

Five</H2></A>

,
. ( )
, ,
-
Web, HTML 4.0.

2.1.

57

ALIGN
,

. ALIGN,
LEFT, RIGHT, CENTER JUSTIFY.
JUSTIFY, , ,
, .
DIV,
. HTML 4.0
ALIGN .
.
2.3.
1 . . 2.1
Internet Explorer 5.0,
Windows 2000 Professional.

^^llNl^^l-f^'^4l'll^'l^'l^llll1u'^n'^f'l
:^ - -^r Jj}^

'^

-y^-yj

^m\

1 Samples of the six heading types:

Level-l (HI)

'1

Level-2 (H2)

"

Level-3 )
L c v d - 4 (H4)
Level-5(H5)

'

Level-6(H6)

J
^gjDorte

1^

My CoriipUtM

. 2.1. Document-Headings .html


2 . 3 . D o c i o m e n t - H e a d i n g s . h t m l
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
<TITLE>Document H e a d i n g s < / T I T L E >
</HEAD>
<BODY>
Samples of t h e s i x h e a d i n g t y p e s :
< H l > L e v e l - l (H1)</H1>
<H2 ALIGN="CENTER">Level-2 (H2)</H2>
<H3><U>Level-3 (H3)</U></H3>
<H4 ALIGN="RIGHT">Level-4 (H4)</H4>
<H5>Level-5 (H5)</H5>

Transitional//EN">

58

2. HTML 4.0

<H6>Level-6 ()</6>
</BODY>
</HTML>

2.2. ,

, ,
( ), PRE ( ,
), ADDRESS ( )
BLOCKQUOTE ( ,
).


: < . . . > . . . </>(11 )
: ALIGN
,

. ,
. < / > ^,
.
, , .
, ,
. 2.4
. ()
, () .
,
.
<> .
(, 5)
. ,
BR,
3, PRE, .

2.4. () (6)
()
<BODY>
<>
Paragraph
</>
<>
Paragraph
</>

2 . 2 . . . .

59

<>
Paragraph 3
</>
</BODY>
()
<BODY>
Paragraph 1
<>
Paragraph 2
<>
Paragraph 3
</BODY>
!

<> .

ALIGN
ALIGN ,
. ,
, ALIGN
. ALIGN
LEFT, RIGHT, CENTER JUSTIFY. JUSTIFY,
, ,
.
DIV (. 2.6) (. 5).
, ALIGN .
, .

: <PRE>... </PRE>
: WIDTH
( ),
HTML-, . PRE
,
, ,
. PRE
. PRE ,
. "<" "&" ,
PRE, ) HTML- . ,
( < b && < d),
"< " <>.
"<" "&lt;", "&"
"&;".

60

2 . HTML 4.0

ISO 8859-1 (Latin-1)


"&#;:^',
ISO Latin-1. , , &#19,
. ,
, " &;".
Latin-1
h t t p : / / w w w . h t m l h e l p . c o m / r e f e r e n c e / h t m l 4 0 / e n t i t i e s / l a t i n l .html.
. 2.1 ,
H T M L 4.0. TITLE
SUBMIT, .

2 . 1 . HTML

<

&lt;

>
&

&gt;
&amp;

&quot;

Snbsp;

WIDTH
WIDTH .
,
.


: <BLOCKQUOTE> ... </BLOCKQUOTE>
: CITE
BLOCKQUOTE
. ,
. ,
BLOCKQUOTE
intranet, ,
Web-. BLOCKQUOTE
, )^ . CITE,
, URL , .


HTML 4.0
.
BLOCKQUOTE
, .

2.3. , ...

61

: <ADDRESS>... </ADDRESS>
:
ADDRESS .
;
. ( PRE),
.
, BR.

2.3. ,

HTML (0L ordered list),
(UL u n o r d e r e d list) (DL definition list).
MENU DIR,
, .


: <OL ...>... </OL>
: TYPE, START, COMPACT
0L . LI (list item
) ,
(, ),
(HI ) ADDRESS.
2.5. . 2.2 ,
Netscape 4.0, Sun/Solaris.
2 . 5 .

sample l i s t :
<0L>
< L I > L i s t I t e m One
< L I > L i s t I t e m Two
<LI>List Item Three
</0L>

A sample list:
1, List Item One
Z. List i t e m i w o
? Wf Tfpm Three
. i-i^LiLciu 11UCC

p^^^ 2.2.

>

62

2. HTML 4.0

0L
TYPE, START COMPACT.
TYPE
TYPE ( ).
. 2.2. TYPE
,
.

2.2. TYPE

(1, 2, 3 ..);

(, , ..)

(, , ..)

,
(I, II, III, IV ..)
,
(i, ii, iii, iv ..)
START
) START .
, .
. 0L
, .
COMPACT
COMPACT ,
I. Headings
(..
II. Basic Text Sections
). m Lists

A. Ordered
1. The OL tag
.

2.6
. . 2.3 ,
.
,
1,
.

. 2.3.

a TYPE
b, START
COMPACT.
2. The LI tag
B. Unordered
1. The UL tag
2. The LI tag
Definition
1. The DL tag
2. The DT tag
3. The DD tag
IV. Miscellaneous

2.3. , ...

63

2.6.
<0L TYPE="I">
<LI>Headings
<LI>Basic Text Sections
<LI>Lists
<0L TYPE="A">
<LI>Ordered
<0L TYPE="1">
<LI>The OL tag
<0L TYPE="a">
<LI>TYPE
<LI>START
<LI>COMPACT
</0L>
<LI>The LI tag
</0L>
<LI>Unordered
<0L TYPE="1">
<LI>The UL tag
<LI>The LI tag
</0L>
<LI>Definition
<0L TYPE="1">
<LI>The DL tag
<LI>The DT tag
<LI>The DD tag
</0L>
</0L>
<LI>Miscellaneous
</0L>

: <LI ...> ... </LI> (


)
: VALUE, ( 0L)
LI ,
. <>
VALUE . LI ,
.
VALUE
, VALUE
. ,
, , .
TYPE
<LI>
, .
.

64

2. HTML 4.0


: <UL ...>.., < / U L >
: TYPE, COMPACT
UL .
< > .
2.4. . 2.7 ,
Netscape 4.0, Sun/Solaris.

2.7.
sample l i s t :
<UL>
< L I > L i s t I t e m One
< L I > L i s t I t e m Two
<LI>List Item Three
</UL>

A sample list:
List Item One

List I t e m iV/Q
* ^^^^ i t e m i i i r e e

p^^ 2.4. UL
, < >

<UL>
TYPE COMPACT.

TYPE
TYPE . TYPE
. 2.3. ,
.

2.3.

TYPE

DISC

. ,

CIRCLE

SQUARE

. ,

2.3. , ...

65

COMPACT
TYPE, COMPACT .
, ,
.

: < . . .> . . .
)

</>(

: TYPE ( UL)
, LI
.
TYPE. LI ,
.

TYPE
TYPE ( )
. TYPE ,
UL (.. DISC, CIRCLE SQUARE).


: <DL

. . .>

...

</DL>

: COMPACT

: <DT> . . . </DT> (
)
:

: <DD> . . . </DD> (
)
:
DL , , .
, .
(DT definition terms) ,
(DD definition description) .
2.8.
. 2.5. DL
COMPACT,
. DT DD ,
.

66

2. HTML 4.0

2.8.
<DL>
<DT>Term One
<DD>The definition of term number one.
<DT>Term Two
<DD>The definition of term number two.
</DL>

Term One
The definition of term
number one.
Term Two
The aenniuon of term
number two.

p^iQ^ 2.5. DD

DD ,
. DD DL
DT. DD ,
. HTML
DD (
). HTML 4.0
.

2.4.
HTML- (..
),
.
, , , . Web
,
.
)^ , .
Web- HTML-,
.
, HTML-
,
(, BGCOLOR).


HTML- TABLE,
CAPTION ,
TR. (table heading
) TD (table data ).

2.4.

67


. TD
. 2.9. . 2.6
. </TR>,
</></> , .
2 . 9 . HTML-
<TABLE B0RDER=1>
<CAPTION>Table Caption</CAPTION>
<TR><TH>Headingl</TH>
<TH>Heading2</TH></TR>
<TR><TD>Rowl C o l l Data</TD><TD>Rowl Col2 Data</TD></TR>
<TR><TD>Row2 C o l l Data</TD><TD>Row2 Col2 Data</TD></TR>
<TR><TD>Row3 C o l l Data</TD><TD>Row3 Col2 Data</TD></TR>
</TABLE>

||R<>wl Cott Data jRqwl CoE Data


I |[( Coll ^ 1 1 ^ ^

feowi Data [Roi^ ( Bata

. 2.6. ,
2.9

, ,
HTML 4.0 ,
(THEAD, TBODY TFOOT) (COLGROUP COL).
.
.

: <TABLE>... </TABLE>
: BORDER, ALIGN, WIDTH, CELLSPACING, CELLPADDING, FRAME, RULES, SUMMARY,
BGCOLOR, BORDERCOLOR (), BORDERCOLORDARK (),
BORDERCOLORLIGHT (), BACKGROUND ()
<TABLE> ,
, .

.

ALIGN
) ALIGN ( ,
)
. LEFT, RIGHT CENTER,
LEFT . , ,
, ,
. , <BR
CLEAR="ALL">. BR 3.

68

2 . H T M L 4 . 0

BORDER
BORDER ,
.
( ),
. , BORDER,
(
CELLSPACING). <TABLE
BORDER> <TABLE B0RDER=1>.
Web-,
.

BORDER ,
BORDER
CELLSPACING.

CELLSPACING
CELLSPACING
. BORDER ,
,
.
, .

CELLPADDING
CELLSPACING
, .
.

FRAME
FRAME HTML 4.0 ,
. ,
. FRAME
BORDER, BOX ( ), VOID (
), ABOVE ( ) , BELOW (
) , HSIDES ( ,
), VSIDES (
) , LHS ( ) RHS (
). FRAME 2.10.
. 2.7 , .
FRAME Netscape,
Netscape 4.7 .

2 . 4 .

69

2.10. T i c T a c T o e . h t m l
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0 T r a n s i t i o n a l / / E N " >
<HTML>
<HEAD>
<TITLE>2000 World C h a m p i o n s h i p < / T I T L E >
</HEAD>
<BODY>
<H2 ALIGN="CENTER">2000 World C h a m p i o n s h i p < / H 2 >
F i n a l r e s u l t i n t h e 2000 w o r l d t i c - t a c - t o e c h a m p i o n s h i p .
Deep Green i s "X", B a r r y K a s p a r o v i s " 0 " .
<TABLE ALIGN="CENTER" B0RDER=1 FRAME="VOID">
<TR><TH>X<TH>0<TH>X
<TR><TH>X<TH>0<TH>X
<TR><TH>0<TH>X<TH>0
</TABLE>
</BODY>
</HTML>

^*&1
||;1||1|||||
|111111& ^ '^7

2000 World Championship


1 Final result in the 2000 world tic-tac-toe championsh^. Deep Green i5"X".
1 Barry Kasparov is "0".

'

X jO X
X |0 X
OJX(0

^^^-^1
. 2.7.

!
Netscape

FRAME

TABLE.

RULES
H T M L 4.0, Internet Explorer,
Netscape, ,
.
RULES NONE, ROWS, COLS, ALL GROUPS.
!
Netscape

RULES

TABLE.

70

2. HTML 4.0

SUMARY
SUMARY, HTML 4.0,
, HTML-, ,
.
WIDTH
WIDTH (<TABLE WIDTH=250>)
(<TABLE WIDTH="75%">).
,
, .
, .
.
BGCOLOR
( )
Web-.
BGCOLOR <TABLE> (
, 5). ,
Web-,
.

BORDERCOLOR, BORDERCOLORDARK, BORDERCOLORLIGHT


Internet Explorer 4.0
. . BORDERCOLOR
, BORDERCOLORDARK BORDERCOLORLIGHT
.
, BORDER .
BACKGROUND
BACKGROUND , Internet Explorer, ,
, .
,
,
.
. ,
BACKGROUND , Web-
, Internet Explorer.

: <CAPTION>... </CAPTION>
: ALIGN
CAPTION
<TABLE> (ALIGN="TOP")
(ALIGN= "BOTTOM"). .
Web- CAPTION
HTML-,
.

2.4.

71


: <TR ...> ... </TR> (
)
: ALIGN, VALIGN, BGCOLOR, BORDERCOLOR (), BORDERCOLORDARK
(), BORDERCOLORLIGHT (), CHAR, CHAROFF
TR .
TD.

ALIGN
ALIGN ( : LEFT, RIGHT, CENTER, JUSTIFY CHAR)
.
LEFT. JUSTIFY CHAR
Netscape, Internet Explorer.

VALIGN
VALIGN ( : , MIDDLE, BOTTOM BASELINE)
.
BASELINE,
. MIDDLE.

BGCOLOR
BGCOLOR .
, BGCOLOR TABLE.
, , ,
BGCOLOR TD.
. , ,
2.11 ,
,
- . . 2.8.
.
2 . 1 1 . BG-Colors. html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
<TITLE>WWW S t a n d a r d s < / T I T L E >
</HEAD>
<BODY BGCOLOR="WHITE">
<H1 ALIGN="CENTER">WWW S t a n d a r d s < / H l >

Transitional//EN">

<TABLE B0RDER=1 BGCOLOR="#EEEEEE">


<TR BGCOLOR="BLACK">
<TH><FONT COLOR="WHITE">Standard</FONT>
<TH><FONT COLOR="WHITE">Obsolete Version</FONT>
<TH><FONT COLOR="WHITE">Most W i d e l y S u p p o r t e d

72

2. HTML 4.0

Version</FONT>
<TH><FONT COLOR="WHITE">Upcoming Version</FONT>
<TR><TD>HTML
<TD>3.2
<TD>4.0
<TD>XHTML
<TR><TD>HTTP
<TD>1.0
<TD>1.1
<TD>1.2
</TABLE>
</BODY>
</HTML>

11^!!1
WWW Standards
jHIML

3.2

40

"'.'

11 "

XKIML
' 1.2 "

,Oociw*,0w

. 2.8. BGCOLOR

BORDERCOLOR, BORDERCOLORDARK, BORDERCOLORLIGHT


, Internet Explorer,
. BORDERCOLOR , BORDERCOLORDARK
BORDERCOLORLIGHT
. ,
BORDER TABLE .
HTML 4.0 TR, , TD, THEAD, TBODY
TFOOT CHAR CHAROFF. CHAR,
,
(, ) . CHAROFF
. Netscape, Internet Explorer
,
.

2 . 4 .

73


: < . . . > . . . </> (
)
<TD . . . > . . . </TD> (>
)
: COLSPAN, ROWSPAN, ALIGN, VALIGN, WIDTH, HEIGHT, NOWRAP, BGCOLOR,
BACKGROUND (), BORDERCOLOR (), BORDERCOLORDARK
(), BORDERCOLORLIGHT (), ABBR, AXIS, HEADERS, SCOPE
COLSPAN
COLSPAN ,
. 2.12.
. 2.9,.
2.12. ,
<TABLE BORDER-1>
<TR><TH COLSPAN=2>Col 1&2 H e a d i n g
<>13 H e a d i n g
<TR><TD>Coll Data
<TD>Col2 D a t a
<TD>Col3 D a t a
</TABLE>

iteidingi
Co! 1&2 Heading CoB Holding
,
* ,
*>
CoU Data Col2 Data CoB Data
'
(a)

iiiee
^^^^

^
,
,0.0^41.^^^^^^^^
Data for Row 1&2, Coll
.__
|J^ow2 Col2 Data
(6)

. 2.9. (a) (
2.12); () ( 2.13)

ROWSPAN
ROWSPAN ,
. ROWSPAN 2.13,
. 2.9,6.
2.13. ,
<TABLE B0RDER=1>
<TR><TH>Headingl<TH>Heading2
<TR><TD R0WSPAN=2>Data f o r Row 1&2,
<TD>Rowl C0I2 D a t a
<TR><TD>Row2 C0I2 D a t a
</TABLE>

Coll

74

2. HTML 4.0

ALIGNHVALIGN

ALIGN ( : LEFT, RIGHT, CENTER, JUSTIFY CHAR)


.
TD LEFT, CENTER.
VALIGN ( : , MIDDLE, BOTTOM BASELINE)
.
MIDDLE. CHAR BASELINE
TR.
WIDTH HEIGHT
WIDTH HEIGHT ,
, , .
WIDTH HEIGHT .
, .
,
, .
.

.
HTML 4.0 ,
Netscape, Internet Explorer .
,
. WIDTH HEIGHT
.
.
NOWRAP
NOWRAP, ,
. ,
( & n b s p ; ) PRE (

).
NOWRAP, ,
.
BGCOLOR BACKGROUND
BGCOLOR ( HTML 4.0
) . BACKGROUND,
Internet Explorer 3.0 , ,
, .
, .

BORDERCOLOR, BORDERCOLORDARK, BORDERCOLORLIGHT


, Internet Explorer,
. BORDERCOLOR , BORDERCOLORDARK
BORDERCOLORLIGHT

2 . 4 .

75

. ,
BORDER TABLE .
ABBR, HEADERS, SCOPE AXIS
. ABBR, HEADERS SCOPE
. AXIS ( )
.


: <THEAD . . . > . . . </THEAD> (
)
<TBODY . . . > . . . </TBODY> (
)
<TFOOT . . . > . . . </TFOOT> (
)
: ALIGN, VALIGN
THEAD, TBODY TFOOT
. RULES="GROUPS"
TABLE .
(header section), (footer section)
(body section).
,
TR. , , ,
, .
, Internet Explorer.
H T M L 4.0. Netscape 4.x
.
!
Netscape 4.x
TFOOT.

THEAD TBODY

ALIGN VALIGN
ALIGN ( : LEFT, RIGHT, CENTER, JUSTIFY CHAR)
.
THEAD CENTER, TBODY TFOOT
LEFT. CHAR
TR. VALIGN ( : , MIDDLE, BOTTOM BASELINE)
.
MIDDLE.
TR.

76

2. HTML 4.0

2.14 ,
, . . 2.10 ,
Internet Explorer 5.0,
Windows 2000 Professional. GROUPS RULES ,
.
2.14.
<TABLE B0RDER=1 CELLPADDING=4 RULES="GROUPS">
<CAPTION>Table Groups
<THEAD>
<TR><TH>Table Head<TH>Table Head
<TBODy>
<TR><TD>Group l<TD>Group 1
<TR><TD>Group l<TD>Group 1
<TBODy ALIGN="RIGHT">
<TR><TD>Group 2<TD>Group 2
<TR><TD>Group 2<TD>Group 2
<TFOOT ALIGN="CENTER">
<TR><TD C0LSPAN=2>Footer
</TABLE>

Fie

E<k

Vtetv

j >^-Beck - *> " ^

FavorRes

Tools:

J 3 i:2f

Help

1^1

^Search

Table Groups
1

Table Groups

I i Table Head Table Head !


1 Group 1

Group 1

1 j Group 1
i

Group 1

Group 2

Group 2

Group 2

Group 2

Footer
^'Oone

' " ' ''"' |'Intern^'"

. 2.10.
,
2.14

: <COLGROUP . . . > . . . </COLGROUP> (


)
<COL . . . > . . . </COL> (
)
: ALIGN, VALIGN, SPAN, WIDTH

COLGROUP, Internet
Explorer, .

2 . 4 .

77

. COLGROUP

. COLGROUP
.
TABLE RULES="GROUPS",
, COLGROUP,
.
COLGROUP COL. COL
COLGROUP. ,
COLGROUP THEAD TBODY.
ALIGNHVALIGN

ALIGN ( : LEFT, RIGHT, CENTER, JUSTIFY CHAR)


,
COLGROUP COL. LEFT,
, THEAD. ,
, THEAD, .
, , ,
. ,
ALIGN
. VALIGN ( : , MIDDLE,
BOTTOM BASELINE) .
MIDDLE. BASELINE
ALIGN TR. ,
JUSTIFY, CHAR BASELINE .

SPAN WIDTH
SPAN ,
COLGROUP COL. WIDTH
COLGROUP COL .
2.15
. COLGROUP,
THEAD, ,
COLGROUP .
COL. . 2.11 ,
Internet Explorer 5.0, Windows
2000 Professional. TABLE
GROUPS RULES, .
2 . 1 5 .

<TABLE CELLPADDING=3 RULES="GROUPS">
<CAPTION>Stout Medal Award</CAPTION>
<COLGROUP>
<COL ALIGN="CENTER">

78

2. HTML 4.0

<COL ALIGN="LEFT">
<COL ALIGN="CENTER">
<COLGROUP ALIGN="RIGHT">
<THEAD>
<TR><TH>Year<TH>Cultivar<TH>Bloom Season<TH>Cost
<TBODY>
<TR><TD>1965<TD>Luxury Lace <TD>M <TD>11.75
<TR><TD>197 6<TD>Green Flutter<TD>M <TD> 7.50
<TR><TD>1984<TD>My Belle
<TD>E <TD>12.00
<TR><TD>1985<TD>Stella De Oro<TD>E~L<TD> 5.00
<TR><TD>1989<TD>Brocaded Gown<TD>E <TD>14.50
<TFOOT>
<TR><TD C0LSPAN=4>E-early M - m i d s e a s o n L - l a t e
</TABLE>

L^fi^^'^?!'7''^^a;!'7l-li^ft^
' FSe

Edt

! ^^BacK '

View

Favoritej

-lDiiSj|

Took

- - .'^1 J 3 :2}

bsech

^ y Favorites

Table Colgi cups


1

stout Medal Award

1 Year Cultivar

Bloom Season Cost

j 1965 Luxury Lace


I 1976 Green Flutter
1984 MyBeUe
1985 SteUaDeOro
1989 Brocaded Gown

M
M
E
E-L
E

E-early M-midseason L-late


^Oone

1 Interne

11.75
7.50
12.00
5.00
14.50

. 2.11. ,
2.15;
COLGROUP COL

2.5.
FORM .
Web- ,
. , FORM
, , , .
FORM 18.

2.6.
, HR,
, , DIV,
, CENTER,
.

2.6.

79

: <HR ...> ( )
: ALIGN, WIDTH, SIZE, NOSHADE, COLOR ()
, HR,
.
. <HR>.
.
, .

ALIGN
ALIGN .
LEFT, RIGHT CENTER. CENTER.

WIDTH
WIDTH (<HR WI DTH=7 5>)
(<HR WIDTH="50%">).
100%.
SIZE
SIZE .
, , "
". , .
NOSHADE
NOSHADE, ,
"".
COLOR
COLOR , Internet Explorer.
. RGB (. . 1.1).

: <DIV .-> ... </DIV>


: ALIGN
DIV .
ALIGN .
ALIGN LEFT, RIGHT, CENTER JUSTIFY.
HTML 4.0 ALIGN ,
.

: <CENTER>... </CENTER>
:
CENTER HTML 4.0
, <DIV ALIGN= "CENTER">,
.

80

2. HTML 4.0

: <SCRIPT TYPE="..." ...> ... </8>


: TYPE (), LANGUAGE, SRC, DEFER, CHARSET
SCRIPT ,
JavaScript. SCRIPT JavaScript-
24.

: <NOSCRIPT>... </NOSCRIPT>
:
NOSCRIPT ,
JavaScript.
, JavaScript-.
24.

: <MULTICOL CQLS=xx)c...>... </MULTICOL> ()


: COLS (), GUTTER, WIDTH

MULT I COL Netscape-.


Navigator 3.0 ,
. , MULTICOL,
HTML- ,
, , ,
. ,
. Netscape Internet Explorer
.
MULTICOL .

COLS
.
COLS .
GUTTER

. 10.
WIDTH
WIDTH .
, Netscape .

2.7.
Web. , ,
, , .
,
.

2.6.

81

, ,
HTML 3.2, HTML 4.0
. Netscape Internet Explorer,
,
DOCTYPE. .
(, THEAD, COLGROUP MULTICOL)
, , , .

HTML 4.0
...

, -,
- ActiveX-.

J~y\:EJ^zJ

,
, .
,
.
.
,
.
, ,
, (. 5)
JavaScript (. 24). DIR, LANG TITLE,
1.

3 . 1 .


. ,
. TITLE
SUBMIT. , ,
,
.

: <>... </>
:
, ,
, .
, (
5).

84

3. HTML 4.0

: <1> ... </1>


:
I , ,
, .

: <>... </>
:

.

: <U>... </U>
:
U, , HTML 4.0,
, .

: <SUB>... </SUB>
:
SUB , ,
, .

: <SUP> .. </SUP>
:
SUP .

: <BIG>... </BIG>
:
BIG , ,
,
.
, .
.
FONT.

: <SMALL>... </SMALL>
:
SMALL , ,
,
.
, .
.
FONT.

3 . 1 .

85

: < D E L > . . . < / D E L >


: CITE, DATE TIME
DEL ,
. Internet Explorer 5.0 .
Netscape . CITE
URI , , .
DATETIME , ,
. DATETIME YYYY-MMDDThhrmm: ssTZD. DATETIME h t t p : / / w w w .
w3.org/TR/html40/types.html#type-datetime.

: <INS>... </INS>
: CITE, DATETIME
INS , DEL. INS
, . Internet Explorer 5.0
, Netscape
. CITE DATETIME , DEL.

: <Q>... </Q>
: CITE
Q
. CITE URI , .
Netscape, Internet Explorer .

: <BDO DIR="..." ...> ... </BDO>


: DIR, LANG
Unicode ISO (LTR left to
right) (RTL right to left). BDO
, .
01R , LTR, RTL. LANG,
, ,
. . 1.
3.1 ,
. 3.1 , Web- .
3 . 1 .
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
<TITLE>Physical C h a r a c t e r Styles</TITLE>
</HEAD>
<BODY BGCOLOR="WHITE">
<Hl>Physical C h a r a c t e r Styles</Hl>
<B>Bold</B><BR>
<I>Italic</I><BR>
<TT>Teletype (Monospaced)</TT><BR>

Transitional//EN">

3. HTML 4.0

86

<U>Underlined</U><BR>
Subscripts: f<SUB>0</SUB> + f<SUB>l</SUB><BR>
Superscripts: x<SUP>2</SUP> + y<SUP>2</SUP><BR>
<SMALL>Sinaller</SMALL><BR>
<BIG>Bigger</BIG><BR>
<STRIKE>Strike Through</STRIKE><BR>
<B><I>Bold Italic</I></B><BR>
<BIG><TT>Big Monospaced</TT></BIG><BR>
<SMALL><I>Small Italic</I></SiyLALL><BR>
<FONT COLOR="GRAY">Gray</FONT><BR>
<DEL>Delete</DEL><BR>
<INS>Insert</INS><BR>
</BODY>
</HTML>

^ Physicai
Ne

Edit

tbm-m^eitmvkss^^fmm^m
View

4->: ^ ^

Favorites

"'41^]

loots

Hdp

i 2 ' '^Search

^jFavor5

** Links

Physical Character Styles


Bold
Italic
T e l e t y p e (Monospaced)
Underlined
Subscnpts: ^ + fj
Superscripts: x^ + y^
Smaller

Bigger
S t n k e Tlii-ough

Bold

Italic

Big Monospaced
SmaW Italic

Insert

d
jejOone

lyiSi, My Computer

. 3.1. ,
Internet Explorer 5.0
Windows 2000 Professional

: <FONT ...> ... </FONT>


: SIZE, COLOR, FACE ()
FONT . SIZE
, COLOR
,
. ,
. ,
, ,
FONT .
, BODY,
BASE FONT ( ).
H T M L 4.0, FONT .
;
, .
5.

3 . 1 .

87

SIZE
SIZE 1 (
) 7 ( ),
(SIZE=" + 1", S I Z E = " - 1 " , S I Z E = " + 2 " ..),
.
. , .
,
SIZE Web-.


. .

COLOR
BODY,
COLOR (
. 1.1) RGB. ,
, .
FACE
Netscape Internet Explorer FACE,
, .
, ,
. ,
.. , ,
, , .. ,
FACE .

: <BASEFONT SIZE=xxx> ( )
: SIZE ()
BASE FONT ,
, .
1 ( ) 7 (
). 3. FONT, BIG
SMALL,
.
BASE FONT .
BODY FONT.
, . HTML 4,
BASEFONT . ,
,
.

88

3 . HTML 4 . 0

3.2.

,

.
.
,
,
.
. ,
,
.

: <>... </>
:
, ,
, .
, , .

: <STRONG>... </STRONG>
:
STRONG " " .
.

: <CODE>... </CODE>
:
CODE .
, ,
. , , "<"
"&:" , ,
" & l t ; ", "&;" .. . 2.1.
!
CODE, SANP
KBD, "<", "&" ..

: <SAMP>... </SAMP>
:
SAMP
. CODE,
.

3.2.

89

: <KBD> ... </KBD>


:
KBD ,
. CODE, KBD
.

: <DFN>... </DFN>
:
DFN . Internet Explorer
, , . Netscape

.

: <VAR>... </VAR>
:
VAR .
,
<VAR>, .

: <1> ... </1>


:
CITE ,
. , .

: <ACRONYM>... </ACRONYM>
: TITLE
ACRONYM TITLE
. :
<ACRONYM TITLE="Java D e v e l o p m e n t

Kit">JDK</ACRONYM>

, Internet Explorer 5.x


, TITLE. Netscape
TITLE.
3.2 .
. 3.2.

3.2.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
<TITLE>Logical C h a r a c t e r S t y l e s < / T I T L E >
</HEAD>
<BODY BGCOLOR="WHITE">
<Hl>Logical C h a r a c t e r S t y l e s < / H l >

Transitional//EN">

90

3. HTML 4.0

<EM>Emphasized</EM><BR>
<STRONG>Strongly Emphasized</STRONG><BR>
<CODE>Code</CODE><BR>
<SAMP>Sample Output</SAMP><BR>
<KBD>Keyboard Text</KBD><BR>
<DFN>Definition</DFN><BR>
<VAR>Variable</VAR><BR>
<CITE>Citation</CITE><BR>
<EM><CODE>Emphasized Code</CODEX/EM><BR>
<FONT COLOR="GRAY"><CITE>Gray Citation</CITE></FONT><BR>
<ACRONYM TITLE="Java Development Kit">JDK Acronym</ACRONYM>
</BODY>
</HTML>

iMfWTH^ni-i!^.,.!!, I
\ ^-

Hl.l,..i i U L I . l J p^jgfxf

J J ^ a -j J -Ji- ^^3s_ -_'

Logical Character Styles


[|
1
1
:|
1
I
1
1
1

Emphasized
Strongly Emphasized
Code
Semple Output
Keyboard Text
Dejinilion
Variable
Citation
Emphasized Code

1 JDK Acronym
1

^ [Java Developmenl K.it]

.ij^Done

^
: i My CoflfipUer

'

. 3.2.
Internet Explorer 5.0,
Windows 2000
Professional

: <ABBR ...> ... </ABBR>


: TITLE
ABBR, ,
.
<ABBR TITLE="cubic inches">cu. in.</ABBR>
Netscape, Internet Explorer .

: <SPAN ...> ... </SPAN>


: CLASS, ID, STYLE
SPAN ,
. SPAN 5.

3.3.
Web-
.
,

3 . 3 .

91

,
.
,
.
, .

: < ...>... </>


: HREF, NAME, TARGET, REL, REV, TITLE, ONFOCUS, ONBLUR, COORDS,
SHAPE,TYPE, HREFLANG, CHARSET, ACCESSKEY, TABINDEX
A ,
. HREF,
.
, HREF. ,
<>,
, LINK BODY.
.
, ,
, ,
VLINK.
, , ,
.
HREF
HREF ,
, (
). HREF URL, URL,
"#" ( NAME),
URL, "#", .
,
, .
.
19, URL, ,
, HTTP-.
URL,
, URL,
L o c a t i o n HTTP-.
,
.

http://some.host.com/some/directory

h t t p : / / s o m e . h o s t , c o m / s o m e / d i r e c t o r y / .

URL , ,
.

92

3 . HTML 4 . 0

3.3 ,
URL, URL,
, URL. h t t p : ,
m a i l t o : (
), f i l e : (
) f t p : ( FTP-).
3.3.
The official HTML specifications are available from
<A HREF="http://www.w3.org/MarkUp/"> the World Wide Web
Consortium (W3C)</A>, with some examples given in
<A HREF= "HTML-Examples .html">my example page</A>.
The Java programming language is discussed in
<A HREF="#Section-3">Section 3</A>. For a discussion of COBOL, see
<A HREF="johndoe.html#COBOL">my husband's home page</A>.
, ,
, , ,
. ,
,
"click here". .
Recent Dilbert strips are available on-line at
<A HREF="http://www.unitedmedia.com/comics/dilbert/">
The Dilbert Zone</A>.

.
< HREF="http://www.unitedmedia.com/comics/dilbert/">
Click here</A> to see recent Dilbert strips that are
available on-line at The Dilbert Zone.

"click
here". , ,
, .

NAME
NAME .
, HREF "#".
:
< NAME="COBOL">COBOL: Programming Language f o r t h e

Future</A>

, NAME, .

TARGET
TARGET ,
. TARGET 4.

3.3.

93

TITLE
TITLE ,
(, FTP). TITLE
( s u b j e c t : ) . TITLE
.
RELHREV

REL REV , .
(REL)
(REV).
ONFOCUS ONBLUR
, JavaiScript.
JavaScript-, ,
.
.
24.
COORDS SHAPE
, CGI, COORDS (,) .
SHAPE , (,).
3.5.
TYPE, CHARSET H R E F L A N G
TYPE -, ,
, TYPE=" t e x t / h t m l " . CHARSET
, CHARSET="ISO-8859-6". HREFLANG
, , HREFLANG="pt" ,
, , .
ACCESSKEY T A B I N D E X
ACCESSKEY (
), <Alt> ( MSWindows) <Cmd> ( Apple).
. TABINDEX
0-32767, .
, TABINDEX
.
, TABINDEX, 0.
,
. Internet Explorer 5.0 .
Netscape 4.x ACCESSKEY, TABINDEX.

94

3. HTML 4.0

3.4.
IMG .
GIF (Graphic Interchange Format), JPEG (Joint
Photographic Expert Group) PNG (Portable Network Graphic), ,

xbm, x m p bmp. , ,
, GIF-
JPEG. ,
, JPEG-, ,
GIF-.
,
, .

GIF89A,
.
, .
GIF87,
GIF89A. GIF89A
Java, Web- .
GIF89A,
, ,
AVI QuickTime.

IMG
: <IMG SRC="..." ALT="..," ...> (
)
: SRC (), ALT (), ALIGN, WIDTH, HEIGHT, HSPACE,
VSPACE, BORDER, USEMAP, ISMAP, NAME, LONGDESC, ONLOAD (), ONERROR
(), ONABORT ()
IMG . ,
IMG
. IMG ,
.
SRC
SRC . ,
, . SRC
, URL. IMG,
SRC, .
<IMG SRC="http://www.some-isp./~jane/portrait.jpg"
ALT="Jane Doe">
<IMG SRC="images/spot.gif" WIDTH=150 HEIGHT=120
ALT="My dog Spot">

3 . 4 .

95

ALT
ALT , ,
. HTML 4.0
ALT .
WIDTH H E I G H T
,
. . IMG
WIDTH HEIGHT, ,
, .
. ,
Netscape, , , P a g e Info
View, .
Netscape. Internet Explorer 5.0,
, ,
Properties.
WIDTH HEIGHT ,
, ,
IMG. ,
Properties Internet Explorer
, .

ALT, WIDTH HEIGHT.

ALIGN
ALIGN, , HTML 4.0,
,
, <IMG>.
LEFT, RIGHT, TOP, BOTTOM MIDDLE.
BOTTOM. LEFT RIGHT
,
. LEFT RIGHT ,
, <BR
CLEAR="ALL">. BR .
MIDDLE ,
. 3.4
. . 3.3.

96

3. HTML 4.0

^b^3k:i^t^m4A^kMl^tM^^
Image Alignment
I Alignment

LEFT

RIGHT

Result
^ ^ ^ This positions the image at the left side, with text flowing around it
^w\ 5, ^ <5 the nght
.VJIOT^"

r^

^_____

This positions the image at the nght side, with text flowing around ^ ^ ^
it on the left
'^'wi^N^'
,4Jp}^'
^ ^ ^

Here, the image runs into the paragraph and the line containing the

image is aligned with the image top.

Here, the image runs into the paragraph and the line containing the
iimage is aligned with the image bottom.
j9>,*^ Here, the image runs into the paragraph and line containing the

image is aligned with the image center.


^^

' !C^Jatm* DowT'^

"^^^^^!^.

. 3.3.
3.4. Image~Alignment.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Iinage Alignment</TITLE>
</HEAD>
<BODY>
<H1 ALIGN="CENTER">Image Alignment</Hl>
<TABLE B0RDER=1>
<TR><TH>Alignment
<TH>Result
<TR><TH><CODE>LEFT</CODE>
<TD><IMG SRC="rude-pc.gif" ALIGN="LEFT"
ALT="Rude PC" WIDTH=54 HEIGHT=77>
This positions the image at the left side,
with text flowing around it on the right.
<TR><TH><CODE>RIGHT</CODE>
<TD><IMG SRC="rude-pc.gif" ALIGN="RIGHT"
ALT="Rude PC" WIDTH=54 HEIGHT=77>
This positions the image at the right side,
with text flowing around it on the left.
<TR><TH><CODE>TOP</CODE>

3.4.

97

<TD><IMG SRC="rude-pc.gif" ALIGN="TOP"


ALT="Rude PC" WIDTH=54 HEIGHT=77>
Here, the image runs into the paragraph
and the line containing the image is
aligned with the image top.
<TR><TH><CODE>BOTTOM</CODE>
<TD><IMG SRC="rude-pc.gif" ALIGN="BOTTOM"
ALT="Rude PC" WIDTH=54 HEIGHT=77>
Here, the image runs into the paragraph
and the line containing the image is aligned
with the image bottom.
<TR><TH><CODE>MIDDLE</CODE>
<TD><IMG SRC="rude-pc.gif" ALIGN="MIDDLE"
ALT="Rude PC" WIDTH=54 HEIGHT=77>
Here, the image runs into the paragraph
and the line containing the image is aligned
with the image center.
</TABLE>
</BODY>
</HTML>

HSPACE VSPACE
( )
(HSPACE), (VSPACE).
2. HTML 4.0 ,
,
,
. HSPACE, VSPACE ,
.
5.

BORDER
BORDER, ,
, 1,
. , 2.

USEMAP
USEMAP MAP " # n a m e " "URL#name".

.
ISMAP
ISMAP , CGI. ,
.
18.

98

3. HTML 4.0

NAME
NAME .
JavaScript, JavaScript

LONGDESC
LONGDESC URI .
, ,
.

ONLOAD, ONERROR ONABORT


,
JavaScript, , ,
, - .

3.5.
: < NAME='..."> ... </>
: NAME ()
MAP
. URL
. ,
. ,
,
ISMAP INPUT ( 18).
,
ISMAP INPUT, .
NAME USEMAP
IMG. , ,
AREA,
MAP.
3.5 , .
HTML-.
. 3.4 3.5.
Internet Explorer 5.0,
OS 9.

3.5.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Kansas Topography</TITLE>
</HEAD>
<BODY>

3.5.

99

<1 ALIGN="CENTER">Kansas Topography</Hl>


Click on a region of Kansas to get information on
the terrain in that area.
<P>
<IMG SRC="kansas.gif" ALT="Kansas" WIDTH=385 HEIGHT=170
USEMAP="#Kansas" BORDER=0>
<MAP NAME="Kansas">
<AREA HREF="nw.html"
SHAPE="RECT"
COORDS="0,0, 192, 85"
ALT="North West">
<AREA H R E F = " n e . h t m l "
SHAPE="RECT"
COORDS="193, 0 , 3 8 5 , 8 5 "
ALT="North E a s t " >
<AREA H R E F = " s w . h t m l "
SHAPE="RECT"
COORDS="0,86,192,170"
ALT="South West">
<AREA H R E F = " s e . h t m l "
SHAPE="RECT"
COORDS="193,86, 3 8 5 , 1 7 0 "
ALT="South E a s t " >
</MAP>
</BODY>
</HTML>
) Kdnsas Topoerephy i

t^

: Southwest

mm

Kansas Topography
Gick on a region of Kansas to get information on the teiiain
m that area

(j^ link: http://<wvfeprft9r*mm|r>q/Saure/Chai>tr3;/sw.Mml

. 3.4.
Web-

mm

Flat
The southwest legion is flat. Vv'hat did you think this was.
Colorado?

} htffit ?on

. 3.5.
. 3.4

: <AREAALT="..." ...> ( )
: HREF, COORDS, SHAPE, ALT ( ) , NOHREF, TARGET, ONFOCUS,
ONBLUR, ACCESSKEY, TABINDEX
AREA MAP.
, . -

100

3. HTML 4.0

AREA,
, URL ,
,
. , ,
.
HREF
HREF .
, URL, ,
"#".
COORDS
COORDS , .
SHAPE.

.
SHAPE
SHAPE RECT (
), CIRCLE, POLY DEFAULT. DEFAULT,
SHAPE COORDS. RECT
, " , ,
, ". ,
r e g i o n 3 . h t m l 200x200 ,
(20,40):
<AREA H R E F = " r e g i o n 3 . h t m l "
SHAPE="RECT"
COORDS="20,40,220,240">
CIRCLE,
COORDS ",,". POLY "1, 1,2,
y2,...,xN, yN", . DEFAULT
COORDS
. URL, ,
AREA.
, , AREA SHAPE
DEFAULT.
ALT
ALT , .
,
.
NOHREF
NOHREF , URL.
, -

3 . 6 .

101

, AREA.
, , AREA,
NOHREF .

URL ,
AREA,
NOHREF
MAP. ,

URL ,

TARGET
TARGET , .
.
4.
O N F O C U S , O N B L U R , ACCESSKEY T A B I N D E X
, IMG, .

3.6.
Web-, ,
, .
,
Web-. Java-.
-, -, VRML- ActiveX-
, .


: <APPLET CODE="..." W I D T H = x x x H E I G H T = x x x ...> ... < / A P P L E T >
: CODE, WIDTH (), HEIGHT (), CODEBASE, ALT, ALIGN,
HSPACE, VSPACE, NAME, OBJECT, ARCHIVE (), MAYSCRIPT ()
APPLET Web- .
9.
CODE
CODE Java- ,
. ' CODE ,
) OBJECT. CODE URL, 1
. CODEBASE , ,
, Web-.

102

3 . H T M L 4 . 0


CODE

URL.
, CODEBASE.

WIDTH HEIGHT
,
.
. , a p p l e t v i e w e r , Sun
( , HTML-
APPLET), , , ,
, .
WIDTH HEIGHT .
!
appletviewer,
Sun,

WIDTH HEIGHT, .
CODEBASE
CODEBASE URL .
, CODE.
9.
ALT
, Java, ,
<APPLET . . . > </APPLET>, )' ,
, .
ALT , Java,
. ALT
, .
ALIGN
ALIGN ,
. ,
IMG, .
HSPACE
HSPACE
.

VSPACE
VSPACE
.

3 . 6 .

103

NAME
NAME ,
, JavaScript.
OBJECT
OBJECT ,
Java.
ARCHIVE
ARCHIVE ,
. Java Archive (. j a r ) , Netscape
uncompressed Zip (. z i p ) .
MAYSCRIPT
Netscape Internet Explorer ,
JavaScript-.
24.
HTML 4.0 APPLET
.
OBJECT. APPLET
. APPLET OBJECT
9.

: <PARAM NAME="..." VALUE="..."> (


)
: NAME (), VALUE ()
,
g e t ram. PARAM
9. WIDTH HEIGHT WIDTH
HEIGHT, <PARAM NAME= "WIDTH"
. . . > <PARAM NAME="HEIGHT" . . . >. PARAM
OBJECT, .
!
WIDTH HEIGHT
PARAM.

104

3. HTML 4.0

- ,

: <EMBED SRC="..." ...> ... </EMBED>
: SRC, WIDTH, HEIGHT, a ,

EMBED HTML 4.0,
,
.
, . SRC, WIDTH
HEIGHT ,
. Netscape, Internet Explorer
LiveVideo,
AVI. )^ AUTOSTART,
TRUE FALSE. TRUE,
Web-.
FALSE, , ,
.
,
. ,
11 .
<EMBED S R C = " i n a r t i a n - i n v a s i o n . a v i " WIDTH=120 HEIGHT=90>

EMBED :
http://home.netscape.com/plugins/
VRML, QuickTime,
, Adobe Acrobat, PNG .

ActiveX
: <OBJECT ...> ... </OBJECT>
: CLASSID, CODETYPE, CODEBASE, ALIGN, BORDER, WIDTH, HEIGHT, HSPACE,
VSPACE, STANDBY, ARCHIVE, DATA, TYPE, NAME, TABINDEX, DECLARE, USEMAP

Internet Explorer Web-


ActiveX. Java-,
PARAM. ActiveX, Java-,
( ,
..), , Web-
ActiveX. Internet Explorer
, Microsoft ;
.
ActiveX , ActiveX

3.6.

105

Web- Internet Explorer.


intranet,
.
.
CLASSID
URL.
CLASSID c l s i d : _.
CODETYPE
CODETYPE .
C O D E T Y P E = " a p p l i c a t i o n / J a v a " .
9.
CODEBASE
CODEBASE , .
, CODEBASE APPLET.
ALIGN, B O R D E R , W I D T H , H E I G H T , HSPACE VSPACE
,
IMG, .
STANDBY
)^ STANDBY , .
ARCHIVE
ARCHIVE URI ,
. .
URI , CODEBASE.
JAR. JAR-
j a r .
DATA TYPE
DATA URI , .
TYPE - .
NAME
NAME , JavaScript.
, JavaScript-
.
TABINDEX
,
TABINDEX , . -

106

3. HTML 4.0

TAB INDEX 32767.


, TAB INDEX, 0.

, .
Internet Explorer 5.x Netscape 4.x.
HTML 4.0 DECLARE,
Netscape, Internet Explorer.
, OBJECT,
) , ,
, .
HTML USEMAP OBJECT,
1 . USEMAP
Internet Explorer 5.x, Netscape 4.7
, Netscape 6 USEMAP.
ActiveX,
, CNET ActiveX Download Caller)'
h t t p : / / w w w . a c t i v e x . c o m / .


: <MARQUEE ...> ... </MARQUEE>
: WIDTH, HEIGHT, ALIGN, BEHAVIOR, BGCOLOR, DIRECTION, HSPACE, VSPACE,
LOOP, SCROLLAMOUNT, SCROLLDELAY

MARQUEE Internet Explorer. ,


<^4ARQUEE . . . >
</MARQUEE>, . MARQUEE
, MARQUEE
, FONT. , ,
, .
, Internet Explorer, MARQUEE
, , .
MARQUEE
, . ,
, ) Web-,
, MARQUEE, .
WIDTH HEIGHT
.
Internet
Explorer. , ,
.

3.6.

107

ALIGN
ALIGN
. LEFT, RIGHT, CENTER, TOP,
BOTTOM MIDDLE; ,
IMG, .

BEHAVIOR
BEHAVIOR . SCROLL,
, ,
, ,
. SLIDE,
, , .
BOUNCE ,
.

BGCOLOR
BGCOLOR .

DIRECTION
DIRECTION ,
( BEHAVIOR BOUNCE, DIRECTION
, ).
LEFT ( ) RIGHT ( ).
LEFT.

HSPACE VSPACE
HSPACE VSPACE
. .

LOOP
LOOP , .
, -1, INFINITE ( ) ,
, o)^vIe
.

SCROLLAMOUNT
SCROLLAMOUNT
.

SCROLLDELAY
SCROLLDELAY
.

108

3. HTML 4.0

3.7.
,
. 2 PRE,

, . HTML
BR, . ,
,
, NOBR.

: <BR ...> ( )
: CLEAR
BR , .
HTML- (. )
, BR ,
. CLEAR, NONE
( ), LEFT, RIGHT ALL,
. , Netscape
Internet Explorer, <BR>
(
<> ).

: <NOBR>... </NOBR>
:
NOBR HTML 4.0, .
Netscape Internet Explorer. NOBR ,
, , , <WBR>.
, ( & n b s p ; )
, .

: <WBR> ( )
:
WBR NOBR. WBR
, . WBR
HTML 4.0, , ,
, NOBR.

3.8.
,
.
, Web ,
. -

3.7.

109

Java-, - ,
Adobe Acrobat, VRML ActiveX.
,
. 4 ,
Web-
HTML-. 5
, ,
.

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

J~y\:EJ^zJ


HTML-.
Netscape Corporation
Navigator 2.0, Microsoft Corporation
Internet Explorer 3.0.
HTML 3.2, Web-
, HTML 4.0. ,
HTML, )'
,
. .

,
(, ) .


Web-.
Web-.

Web-,

HTML- Java.

,
, ,
.

Web. .

112

4.

Web- ,
BACK FORWARD.


Web-.

URL
, URL ,
.

URL ,
(..
Web-
).

Print ( )
.
, .


Web-, .
, ,
,
, ,
.
HTML 4.0 TITLE
. 1,
. ,
, , CLASS, ID
STYLE. 5,

4 . 1 .
HTML- HEAD
BODY, , .
BODY ,
NOFRAMES, , .
BODY FRAMESET,
.
4.1. FRAMESET
FRAMESET, , FRAME,
URL , .
DOCTYPE.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0

Frameset//EN">

\ ^ .

4 . 2 .

113

4 . 1 .
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0 Frameset//EN">
<HTML>
<HEAD>
<TITLE>Document T i t l e < / T I T L E >
</HEAD>
<FRAMESET . . . >
<! FRAME and N e s t e d FRAMESET E n t r i e s >
<NOFRAMES>
<BODY>
< ! - - S t u f f f o r n o n - f r a m e s b r o w s e r s >
</BODY>
</NOFRAMES>
</FRAMESET>
</HTML>

4.2.
FRAMESET .

: <FRAMESET> ... </FRAMESET>


: ROWS, COLS, FRAMEBORDER (), BORDER (),
FRAME SPACING (), BORDERCOLOR (), ONFOCUS (
), ONBLUR (), ONLOAD, ONUNLOAD
FRAMESET .
FRAMESET ,
} . FRAMESET ROWS
COLS. ) FRAMEBORDER, BORDER, BORDERCOLOR, ONFOCUS ONBLUR-
, Netscape 4.x, Internet Explorer 4.x
.. FRAME SPACING
); Internet Explorer. ONLOAD ONUNLOAD
JavaScript-,
.

ROWS
ROWS (
FRAMESET) .
:
<FRAMESET ROWS="Rowl-Size,

...

RowN-Size">

</FRAMESET>
N .
(
), , }^ "%" (
),
"*". "*" " "; -

114

4 .

.
.
<FRAMESET

ROWS="50,10%,*f2*">

</FRAMESET>
.
50 . 10
. ,
, (
"*" 2).
. 4.1.
'

1 Ff1 ROV/S /^^^ inimn^

mRGi

""^"""|gi||

1 Frame Cell
1

i^-^

11

Frame Cell
Frame Cell
1 This is a sample HTML document to be used in frame cells.

^^

. 4.1. ,
" 5 0 , 10%, * , 2 * "

, )% ,
, . ,
,
. ,
ROWS ,
Netscape Web- . ,
(
Netscape).
<FRAMESET R O W S - " * " >

<FRAME SRC="CoreWebProgramming.html">
</FRAMESET>
!
FRAMESET
.

4 . 2 .

115

COLS
COLS (
FRAMESET) . ROWS, COLS
, ,
FRAMESET.
. FRAMESET FRAME
, , Web Netscape. FRAMESET
ROWS, COLS.

FIIAMEBORDER
FRAMEBORDER ,
. .
FRAMEBORDER=0
BORDER=0 FRAMESPACING=0,
. FRAMEBORDER FRAMESET
FRAMEBORDER FRAME
FRAMESET. Netscape 3.0, Internet Explorer 4.0, a
FRAMEBORDER YES, 1,
, , N0, ,
. 4.2 4.3
.
FRAMEBORDER.
. 4.2 4.3.

4.2. Frame-Borders.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0 F r a i n e s e t / / E N " >
<HTML>
<HEAD>
<TITLE>Frames w i t h B o r d e r s < / T I T L E >
</HEAD>
<FRAMESET ROWS="40%,60%">
<FRAME S R C = " F r a m e - C e l l . h t m l " >
<FRAMESET COLS="*,*">
<FRAME S R C = " F r a m e - C e l l . h t m l " >
<FRAME S R C = " F r a m e - C e l l . h t m l " >
</FRAMESET>
<NOFRAMES>
<BODY>
Your b r o w s e r d o e s n o t s u p p o r t f r a m e s . P l e a s e s e e
<A H R E F = " F r a m e - C e l l . h t m l " > n o n f r a m e s v e r s i o n < / A > .
</BODY>
</NOFRAMES>
</FRAMESET>
</HTML>

116

4.

:LJj^li'^lJi^J!PL^''Jl^Jli!ll>?flf^^
de d View Fvofkes lools

^ > ^ ., ^

'
[

Frame Cell
1 Tbs IS a sample HTML document to be used frame cells.

Frame Cell
1 Tbs IS a sample HTML document to be
1 used in frame cells.

Frame Cell
This is a sample HTML document to be
used in frame cells.

0] Done

1
|

i ^ My Cofflpii

. 4.2.
,

4.3. Frame-Borderless.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">
<HTML>
<HEAD>
<TITLE>Borderless Frames</TITLE>
</HEAD>
<FRAMESET ROWS="40%, 60%" FIU^MEBORDER=0

BORDER=0 FRAMESING=0>
<FRAME SRC="Frame-Cell.html">
<FRAMESET COLS="*,*">
<FRAME SRC="Frame-Cell.html">
<FRAME SRC="Frame-Cell.html">
</FRAMESET>
<N0FRAMES>
<BODY>
Your browser does not support frames. Please see
<A HREF="Frame-Cell.html">nonframes version</A>.
</BODY>
</NOFRAMES>
</FRAMESET>
</HTML>

4 . 2 .

I^Borderlet* Ftamex - Mictos<rfi fntetftet ExfiltMrei


; dft View Favorites Tods ^

i^

J J ^ ^ : i i J

-ii'

117

Bi^

^_^'

Frame Cell
1 This IS a sample HTML document to be iised m frame cells.

Frame Cell
1 This is a sample HTML document to be
1 used in frame cells.

^;^''"":;-

Frame Cell
This IS a sample HTML document to be
used in frame cells.

' f" ' ^^':

. 4.3.
FRAMEORDER

BORDER FRAMESPACING (Internet Explorer)


, Internet Explorer,
.
FRAMESET. 5.
BORDERCOLOR
BORDERCOLOR , Netscape,
Internet Explorer. .
, , .
)1
.
BORDERCOLOR FRAME
FRAMESET.
ONFOCUS O N B L U R
JavaScript, ,
.
,
JavaScript-, )^ o n F o c u s o n B l u r .
ONLOAD O N U N L O A D
JavaScript-,
, .
o n L o a d o n U n l o a d .

118

4 .

4.3.
: <FRAME SRC="..." ...> ( )
: SRC, NAME, FRAMEBORDER, BORDERCOLOR (), MARGINWIDTH,
MARGINHEIGHT, SCROLLING, NORESIZE, LONGDESC
FRAME HTML-,
. FRAME
FRAMESET. BORDERCOLOR ,
Netscape, Internet Explorer.
SRC
SRC URL , 1
. , HTML
4.0 .
Netscape SRC .
!
FRAME, NAME, SRC,

Netscape.

NAME
NAME . TARGET ,
AREA, BASE FORM >111
. )^ Java- showDocument,
.
, ,
.

FRAMEBORDER
FRAMEBORDER ,
. FRAMEBORDER FRAME
,
FRAMESET. ,
,
FRAMEBORDER. Netscape 3.0, Internet Explorer 4.0
FRAMEBORDER YES,
1, , , N0,
, !.
BORDERCOLOR
BORDERCOLOR .
,
RGB, (. . 1.1 1.6).
.

4.3.

119

MARGINWIDTH
MARGINWIDTH .

MARGINHEIGHT
MARGINHEIGHT .

SCROLLING
SCROLLING ,
. Netscape YES ,
. AUTO (
), ,
. Internet Ex
plorer YES ( ) , AUTO. N0
Netscape, Internet Explorer.
NORESIZE
,
. NORESIZE
.
LONGDESC
LONGDESC URI ,
. LONGDESC .

: <NOFRAMES> ... < / N O F R A M E S >


:
, , ,
NOFRAMES.
<NOFRAMES> </NOFRAMES>, ,
, .
Web-
.

, NOFRAMES.
<NOFRAMES>
Your b r o w s e r d o e s n ' t s u p p o r t
Get a < B > r e a l < / B > b r o w s e r .
</NOFRAMES>

frames.

HTML 4.0 NOFRAMES


, (ONCLICK, ONDBLCLICK,
0NKEYDOWN, ONKEYPRESS, ONKEYUP, ONMOUSEDOWN, ONMOUSEMOVE, ONMOUSEOUT,
ONMOUSEOVER, ONMOUSEUP). JavaScript 24. HTML 4.0
NOFRAMES DIR LANG ( L6).

120

4.

, 4.4, ;
, . . 4.4.
4 . 4 . Frame-Examplel.htinl
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">
<HTML>
<HEAD>
<TITLE>Frame Example 1</TITLE>
</HEAD>
<FRAMESET ROWS="55%,45%">
<FRAMESET COLS="*,^,*">
<FRAME SRC="Frame-Cell.html">
<FRAME SRC="Frame-Cell.html">
<FRAME SRC="Frame-Cell.html">
</FRAMESET>
<FRAMESET COLS="*,*">
<FRAME SRC="Frame-Cell.html">
<FRAME SRC="Frame-Cell.html">
</FRAMESET>
<NOFRAMES>
<BODY>
Your browser does not support frames. Please see
<A HREF="Frame-Cell.html">nonframes version</A>.
</BODY>
</NOFRAMES>
</FRAMESET>
</HTML>

\ Flame Exairade 1 Netscape


Re

<4(

View

go

jQommunicdJof

He^

'i 4 i^' r?l ^-^ : -i^ ^

Frame Cell

Frame Cell

Frame Cell

This IS a sample HTML


document to be used in frame
ceUs.

This IS a sample HTML


document to be used in
frame cells

This IS a sample HTML


document to be used in frame
cells

Frame Cell

Frame Cell

This IS a sample HTML document to be used


frame cells.

This IS a sample HTML document to be used in


frame cells.

.:^-:^...m..
. 4.4. ;
,

4.3.

121

, 4.5, .
, . . 4.5.
4.5. Frame-Example2 .html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">
<HTML>
<HEAD>
<TITLE>Frame Example 2</TITLE>
</HEAD>
<FRAMESET COLS="55%,45%">
<FRAMESET ROWS="*,*,*">
<FRAME SRC="Frame-Cell.html">
<FRAME SRC="Frame-Cell.html">
<FRAME SRC="Frame-Cell.html">
</FRAMESET>
<FRAMESET ROWS="*,*">
<FRAME SRC="Frame-Cell.html">
<FRAME SRC="Frame-Cell.html">
</FRAMESET>
<NOFRAMES>
<BODY>
Your browser does not support frames. Please see
<A HREF="Frame-Cell.html">nonframes version</A>.
</BODY>
</NOFRAMES>
</FRAMESET>
</HTML>

^ Fiaee EiMMiple * Netsoane


fie

View fio ^omrriurticaloi

|ie^

^.~ ^

^ a

Frame Cell

Frame Cell

This IS a sample HTML document to be used in


frame ceDs.

This IS a sample HTML document to be


used in frame cells.

Frame Cell
This is a sample HTML document.to be used in
frame cells.

Frame Cell

Frame Cell

This is a sample HTML document to be


used in frame cells.

This is a sample HTML document to be used in


frame cells.
i j ^ ri^J> :

DoctmwrA: Don*

jys- ^

^ ^

, L 3 ..^:.

. 4.5. .
,

122

4.

4.4.

Web- ,
, , ,
. , ,
TARGET,
. , , ,
. TARGET ,
, ,
. TARGET ,
,
TARGET. TARGET
, AREA, BASE FORM. Java- ,
g e t A p p l e t C o n t e x t () . s h o w D o c u m e n t .

,
.

, .
, .
.
,
. Web-, . 4.6.

21
1

Yiew

^^ ^

fio

Cownwiicala

fi^ ^^

^
Tnvpsring

TntTOfhirtio

Introduction
new breakthrough m cold fusion technology!
A ripe opportunity for the Kicky investor!
Accepted by the scientific community! Documented in The Journal of Irreproducible
'OocumentDone

:, v;^

Results

', '--^. ?1 *^

. 4.6. Web-, :
,

4.4.

123

Web- ,
.
)1 ( Main). 4.6 HTML-
.
4.6. Cold--Fusion.html
<!DOCTYPE xHTML PUBLIC "-//W3C//DTD HTML 4 . 0 F r a m e s e t / / E N " >
<HTML>
<HEAD>
< T I T L E > I n v e s t i n g i n Cold F u s i o n < / T I T L E >
</HEAD>
<FRAMESET ROWS="75,*">
<FRAME SRC="TOC.html" NAME="TOC">
<FRAME S R C = " I n t r o d u c t i o n . h t m l " NAME="Main">
<NOFRAMES>
<BODY>
T h i s p a g e r e q u i r e s F r a m e s . For a n o n - F r a m e s v e r s i o n ,
<A H R E F = " I n t r o d u c t i o n . h t m l " > t h e i n t r o d u c t i o n < / A > .
</BODY>
</NOFRAMES>
</FRAMESET>
</HTML>
) ^ . h t m l TARGET,
Main. ,
. ,
, 4.7.
4 . 7 . .html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0 T r a n s i t i o n a l / / E N " >
<HTML>
<HEAD>
<TITLE>Table of C o n t e n t s < / T I T L E >
</HEAD>
<BODY>
<TABLE WIDTH="100%">
<TR><TH><A H R E F = " I n t r o d u c t i o n . h t m l " TARGET="Main">
Introduction</A></TH>
<TH><A H R E F = " P o t e n t i a l . h t m l " TARGET="Main">
Potent ial</AX/TH>
<TH><A H R E F = " I n v e s t i n g . h t m l " TARGET="Main">
Investing</A></TH>
<TH><A HREF="References.html" TARGET="Main">
References</A></TH></TR>
</TABLE>
</BODY>
</HTML>

. , TARGET -

124

4 .

HEAD <BASE
TARGET="Main">. . 4.7
I n v e s t i n g . , TARGET,
HTML 4.0,
DOCTYPE. , ,
. h t m l , HTML 4.0
TARGET,
.

Web-
, ,
HEAD <BASE TARGET=". . . ">.


TARGET
: b l a n k , t o p , p a r e n t s e l f . ,
, ,
) )1. . 4.1
, .
4 . 1 .

_1


b l a n k , , ,

_top

t o p ,
, , .

, , Web-

_parent

_ p a r e n t ,
, FRAMESET,
. Web-
, _ p a r e n t
)^ _ t o p

_self


s e l f , .
_ s e l f ,
, ! BASE.
<BASE TARGET="_pea"> ,
, , ,

4.5. ...

125

4.5. ,


Web-. - ,
"Web-".

, , .


, Web-, .
U r l l . , ,
. U r l 2 . ,
U r l 2 .
, ( U r l 2 )
( U r l l ) . ,
Boormarks Favohties ( ) URL
, , URL
.
. ,
, . URL,
, .
Netscape Internet Explorer, Windows,
.
, .
1
, .
, ,
. , Web-
,
. -, ,
, ,
. -, ,
, URL . , Web- ,
. ,
. ,
, .
.
< HREF="http://some-site.com/some-page.html TARGET="_top">
http://some-site.com/some-page.html</A>.

126

4 .


HTML-,
,
.
. , , ,
. ,
, ,
, .

, , ,
Print,
, .
, ,
.

,
,
.
Internet Explorer 5.x .
Print File :

, ;

, .
Internet Explorer 5.x
. (
), .
Web- , ,
, .
o n C l i c k ( TARGET)
JavaScript-, .
JavaScript- 24.
, .
, Web- .


HTML
.
:

FRAME;

JavaScript.

4.5. ...

127

FRAME
, FRAMESET :
<FRAMESET ROWS="*,*, *">
<FRAME SRC="Top.html">
<FRAME SRC="Middle.html" NAME="MIDDLE">
<FRAME SRC="Bottom.html" NAME="BOTTOM">
</FRAMESET>
H T M L M i d d l e . h t m l
B o t t o m , h t m l . , .
<FRAMESET R0WS="*,2*">
<FRAME SRC="Top.html">
<FRAME SRC="Middle+Bottom.html" NAME="LOWER">
</FRAMESET>
M i d d l e + B o t t o r n , h t m l FRAMESET.
<FRAMESET ROWS="*,*">
<FRAME SRC="Middle.html" NAME="MIDDLE">
<FRAME SRC="Bottom.html" NAME="BOTTOM">
</FRAMESET>
LOWER, URL
, , , .
, ) Web-
. -, , ,
, -,
,
.
, , Web-
,
JavaScript.

JavaScript
, JavaScript-
o n C l i c k . ,
o n C l i c k , JavaScript,
top ._. location
= URL,
. )' ,
. ,
, JavaScript.
, JavaScript-, 24,
. 4.8 HTML- ,
.

128

4.

4.8. Multiple-Updates.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">
<HTML>
<HEAD>
<TITLE>Updating Multiple Frames Simultaneously</TITLE>
</HEAD>
<FRAMESET ROWS="75,*">
<FRAME SRC="Top-Frame.html">
<FRAMESET COLS="*,*^">
<FRAME SRC="Bottoml.html" NAME="Bottoml">
<FRAME SRC="Bottom2.html" NAME="Bottom2">
<FRAME SRC="Bottom3.html" NAME="Bottom3">
</FRAMESET>
</FRAMESET>
</HTML>


, JavaScript, B o t t o m l B o t t o m S .
, JavaScript-, 4.9.
u p d a t e C e l l s o n C l i c k
. . 4.7 4.8 Web-
.
4.9. Top-Frame.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Table of Contents</TITLE>
<SCRIPT TYPE="text/javascript">
<!
function updateCells() {
top.Bottoml.location = "Resultl.html";
top.Bottoms.location = "Result3.html";
}
// >
</SCRIPT>
</HEAD>
<BODY BGCOLOR="WHITE" TEXT="BLACK">
When selected on JavaScript-capable browsers,
<A HREF="Resultl.html" TARGET="Bottoml" OnClick="updateCells()">
this link</A> will update cell one and three below.
</BODY>
</HTML>

4.5. .

^
?! 1^ - 3 rii'^'ai <.!rf

129

jjj

When selected on JavaScript- able browsers, tins bi^:. will update ceil une and tliree below

Original
Bottom
Cell!

Original
Bottom
Celll
mp^'

Original
Bottom Cell
3
:- '^ J^:' en -.'. '

* Oone

. 4.7.
StflMrtteneoudly - Hetsdape

fie (* View Qomnurwc^arjd:^^:^^^^^^^

When selected on JavaScnpt-capable browsers, tins 1 will update cell one and three below.

Result Cell
1
*^,

Original
Bottom
Cell 2

;Docurnenit. Done

Result Cell
3
.>-':ii,A^-.

. 4.8.


,
Web- ,
.
HEAD <BASE T A R G E T = " t o p " > .
,
. JavaScript,
.
HEAD :
<SCRIPT TYPE="text/javascript">
<!

if

( t o p . f r a m e s . l e n g t h > 0)
top.location = document.location;

/ / >

</SCRIPT>
JavaScript-,
, ,
.

130

4 .


Internet Explorer 3.0
FRAME, NAME, SRC.
,
FRAMESET.
TARGET ,
, .
Netscape.
, , ,
, ..
.
, Web-
,
, .
Web- - , SRC
.
BODY.
!
Netscape ,
,
.

4 . 6 .
Internet Explorer Netscape
HTML- , .
, , , ,
Web-.
,
.
,
.
HTML 4.0, Internet Explorer Netscape 6.
Netscape ,
(layers), .
HTML 4.0, Netscape 6 ;
, Web-. h t t p : / / s i t e s .
n e t s c a p e . n e t / e k r o c k / s t a n d a r d s . h t m l ,

.
.
, , .

Web-. -

4.6.

131

, . ,
, .
4.10.
4.10.Contact-Info,html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
<HEAD>
<TITLE>Prof. Al Gore Ithim</TITLE>
</HEAD>
<BODY>
Prof. Al Gore Ithim<BR>
Computer Science Departinent<BR>
Podunk University<BR>
<A HREF="mailto:algy@podunk.edu"> algy@podunk.edu</A>
</BODY>
</HTML>

Web-
IFRAME. 4.11 Web-,
Computer Science 401.
4.11. CS-401.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
<HEAD>
<TITLE>Design and Analysis of Algorithms</TITLE>
</HEAD>
<BODY>
<Hl>Design and Analysis of Algorithms</Hl>
This course covers the techniques required to design and
analyze computer algorithms. The textbook is <I>Introduction
to Algorithms</I> by Gormen, Leiserson, and Rivest
(McGraw Hill, 1990, ISBN 0-07-013143-0).
<P>
Blah, blah, blah, algorithms. Yada, yada, yada, time. Blah,
blah, blah, space. Yada, yada, yada, iterative. Blah, blah,
blah, recurrences. Yada, yada, yard, data structures. Blah,
blah, blah, sorting. Yada, yada, yada, dynamic programming.
Blah, blah, blah, graph algorithms. Yada, yada, yada,
NP-Completeness.
<P>
<IFRAME SRC="Contact-Info.html" FRAMEBORDER=OX/IFRAME>
</BODY>
</HTML>

, Web- Internet Explorer, Web-, . 4.9 4.10.

132

4.

DesMin and Analysis of AlgofHhms - Miaosofl tr^efrtdt EnnAoft

ite *

Yivf* fflvra*e*

loot

Design and Analysis of Algorithms

This course covers the techniques required to design and analyze computer algorithms The textbook ^^
is Introduction to Algorithms by Cormen, Leiserson, and Rivest (McGraw Hill, 1990. ISBN 0-07- Iv
013143-0).
''
Blah, blah, blah, algorithms. Yada, yada, yada, time. Blah, blah, blah, space Yada, yada, yada,
iterative Blah, blah, blah, recurrences. Yada, yada, yard, data structures. Blah, blah, blah, sorting.
Yada, yada, yada, dynamic programming Blah, blah, blah, graph algorithms. Yada, yada, yada, N P Completeness
, My CornpUe

m^^

. 4.9. c s - 4 0 l . h t m l :

^ Design and Analysis of Algorithms - Microsoft Internet BtfAwm

ile Edit ifw

F^vontes

lock

Blah, blah, blah, algonthntis. Yada, yada, yada, time. Blah, blah, blah, space. Yada. yada, yada.
Iterative. Blah, blah, blah, recurrences. Yada, yada, yard, data structures Blah, blah, blah, sorting
Yada, yada. yada, dynamic programming Blah, blah, blah, graph algorithms. Yada, yada, yada. I n
completeness.

Prof. Al Gore Ithim


Computer Science Department
Podunk University
algy @P 0 dunk, e du

jd
; ^ Done""

i i ^ My Computer

. 4.10. c s - 4 0 1 . h t m l :

, ,
,
Web-.

: <IFRAME SRC="..." ..> ... </IFRAME>


: SRC, WIDTH, HEIGHT, ALIGN, NAME, FRAMEBORDER, MARGINWIDTH, MARGINHEIGHT,
SCROLLING, LONGDESC

I FRAME , , .
Internet Explorer 3.0 .
,
, .
, .
SRC
SRC URL ,
.

4.6.

133

WIDTH HEIGHT
.
. ,
.
ALIGN
ALIGN
. ALIGN
. LEFT, RIGHT, CENTER, TOP, BOTTOM
MIDDLE.

NAME
, ,
.
NAME.

FRAMEBORDER
): FRAMEBORDER ,
. FRAMEB0RDER=1 ,
, FRAMEBORDER=0
. )^1 .

MARGINWIDTH
MARGINWIDTH .

MARGINHEIGHT
MARGINHEIGHT )^ .

SCROLLING
SCROLLING ,
(SCROLLING="YES"), (SCROLLING="NO").
LONGDESC
LONGDESC URI
.

4.7.
HTML 4.0
. FRAMESET
, HTML-.
FRAME.
, Java- , ,
, .

134

4.

, ,
Web-
JavaScript-. ,
, .
H T M L 4.0 .

Web-. "",

. , ,
,
JavaScript-.
.

...
.
HTML-.
, ,
.
.
.
.
HTML-.
.
.
.
.

mamJ

M J ^ ^^^^^

^mmtammmmi^^ "^^

Web-.

, , ,
HTML-.
,
.
, "",
, , ,
)^ , Web-.
,
. ,
. CSS1
(Cascading Style Sheets, Level 1 , 1).
4.01 Netscape Internet Explorer,
. Internet Explorer 3.0 CSS1.
CSS1 World Wide Web Consortium CSS2,
. CSS2
, ,
, , ..
, CSS2 ,
, ,
, ..
.
, CSS.

Cascading Style S h e e t s , Level 1


http://www.w3.org/TR/REC-CSSl

138

5.

Cascading Style S h e e t s , Level 2


http://www.w3.org/TR/REC-CSS2
E x t e n s i b l e Stylesheet L a n g u a g e
http://www.w3.org/Style/XSL/

http://www.w3.org/Style/
CSS1.

5 . 1 .
HTML- .
,
LINK, HEAD .
HEAD HTML- Web. :

{ :

{ !:
002:

!;
2;

: ;

,
.
.
.
HTML- , ,
, ,
. .
HTML-, 5.L
. 5.L
5.1. F i z z i c s l . h t m l
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>New Advances in Physics</TITLE>
</HEAD>
<BODY>
<Hl>New&nbsp;Advances&nbsp;in&nbsp;Physics</Hl>
<H2>Turning Gold into Lead</H2>
In a startling breakthrough, scientist B.O. "Gus" Fizzics
has invented a <STRONG>practical</STRONG> technique for

5.1.

139

transmutation! For more details, please see


<A HREF="give-us-your-gold.html">our transmutation thesis</A>.
<H2>Perpetual Inactivity Machine</H2>
In a radical approach that turned traditional attempts to
develop perpetual motion machines on their heads, Prof.
Fizzles has developed a verified, bona-fide perpetual
<STRONG>inaction</STRONG> machine. To purchase your own for
only $99.00 (plus $43.29 shipping and handling), please see
<A HREF="rock.html">our order form</A>.
</BODY>
</HTML>

i j Mew Advances in Physics - Microsoft Internet Expio


f^i'o

PdJt View

Qo

Ffiwoiites

Help

m ^- :

New Advances in Physics

3!.

Turning Gold into Lead


In a startling breakthrough, scientist B.O. "Gus" Fimcs has invented a practical
technique for transmutation! For more details, please see our transmutation thesis.

Perpetual Inactivity Machine


In a radical approach that turned traditional attempts to develop perpetual motion
machines on their heads, Prof Fizzics has developed a verified bona-fide perpetual
inaction machine. To purchase your own for only $99.00 (plus $43.29 shipping and
handling), please see our order form.
HI
pone

. 5.1. F i z z i c s l . h t m l ,

HEAD ,
, . 5.2. ,
CSS, <STYLE> </STYLE>,
.
<STYLE TYPE="text/css">
<!
BODY { background: URL(images/confetti-background.jpg) }
HI { text-align: center;
font-family: Blackout }
H2 { font-family: MeppDisplayShadow }
STRONG { text-decoration: underline }
>
</STYLE>

140

5.

New Advances in Physics - Microsoft Internet Explorer


5

d'ft

yiew

iQo

Fisp*rt3rites

Jjelp

D a-

S-

"( @ < ^ 0 IL^s^


In a startling breakthrough, scientist B.O. "Gus" Fizzics has invented a practical
technique for transmutation! For more details, please see our transmutation thesis.

[p@i^l^tkaal] QiflaeMO^ (N^sx^iiiite


In a radical approach that turned traditional attempts to develop peetual motion
machines on their heads. Prof Fizzics has developed a verified bona-fide peetual
inaction machine. To purchase your own for only $99.00 (plus $43.29 shipping and
handling), please see our order fomi.

Done

. 5,2. F i z z i c s l . h t m l

5.2.
,
HTML-.
HTML- Web. .



, .
, WW4V-cepBep . ,
, HTML- LINK,
HEAD. REL STYLESHEET, HREF
, TYPE ( t e x t / e s s ) . ,
, S i t e - s t y l e . e s s ,
e s s . ,
LINK :
<LINK REL=STYLESHEET
HREF="http://www.oursite.com/css/Site-style.ess"
TYPE="text/css">
,
. 5.2. <STYLE> ,
TYPE LINK.
<STYLE> HTML-,
.

5 . 2 .

141


HTML' Web-ysne ,
.

^9

5.2.Sitestyle.ess
/* */
HI { text-align: center;
font-family: Arial
}'
H2 { color: #440000;
text-align: center;
font-family: Arial Black, Arial, Helvetica, sans-serif
}

HEAD HTML-,
<STYLE>.

: <STYLE TYPE="..." ...> ... </STYLE>


: TYPE (), MEDIA
STYLE
HEAD . STYLE
:
<STYLE TYPE="text/css">
<!
/* */

-->
</STYLE>
, ,
<STYLE>,
HTML-.

HTML-.
TYPE
TYPE . ,
. " t e x t / e s s " .
JavaScript TYPE " t e x t / j va s c r i p t " .

142

5.

MEDIA
MEDIA Netscape, Internet
Explorer. ,
. ,

. MEDIA ALL, AURAL,
BRAILLE, HANDHELD, HELD, PRINT, PROJECTION, SCREEN ( n o
), SPEECH, TTY TV.

STYLE JavaScript
" t e x t / e s s " , Netscape 4.x
" t e x t / j a v a s c r i p t " . JavaScript t a g s
JavaScript. , -. :
<STYLE T Y P E = " t e x t / c s s " >
HI { t e x t - a l i g n : c e n t e r ;
font-family: Arial }
>
</STYLE>

<STYLE T Y P E = " t e x t / j a v a s c r i p t " >


<!-tags.HI.textAlign="center";
tags.HI.fontFamily="Arial";
//>
</STYLE>
,
Netscape JavaScript
, . JavaScript 24.


CSS1
HTML. STYLE.
,
. :
<Hl>New Advances in Physics</Hl>
<P STyLE="margin-left: 0.5in;
margin-right: 0.Sin;
font-style: italic">
This paper gives the solution to three
previously unsolved problems: turning lead into gold,
antigravity, and a practical perpetual motion machine.

5.3.

143

, HEAD. ,
, , ,
.

5.3.
STYLE ,
:

{ !:

!;

...; :

,
HTML-
. , ,
. , , , ,
STRONG, , 50%
, :
STRONG { font-weight: bold; font-size: 150% }
HTML-.
,
.
:

HTML-;

, ;

, ;

, ,
CLASS, ID STYLE,
BASE, BASEFONT ( ID ), HEAD, HTML, , PARAM
( ID ), SCRIPT, STYLE TITLE. , HTML
4.0 SPAN,
.

HTML -
HTML- ,
BR , , .
, , ,
BODY , ,
, CODE .
. ,
. ,
,
, :

144

5.

BODY { c o l o r : b l u e }
HI { c o l o r : r e d }
,
. .
.
HI, 2, , 4, 5, { text-align: center;
font-family: sans-serif }
, ,
. , )^ :
BODY { color: blue }
HI { color: green }
EM { color: red }
c o l o r : b l u e , BODY,
HTML- (, UL, 0L, TABLE ..).
,
, .. HI . :
)' HI,
. ,
, , 1
.
HI { c o l o r :

green }

CSS , , Netscape
4.x , . , ,
1.
,

, .
!
Netscape 4.x
, HTML-,
Web-yaen.

,
1 .
-, . , ,
"" ,
. :
.abstract { margin-left: 0.5in;
margin-right: 0.5in;
font-style: italic }

5 . 3 .

145

, ,
CLASS . ,
"" , :
<Hl>New Advances in Physics</Hl>
<P CLASS="abstract">
This paper gives the solution to three previously unsolved
problems: turning lead into gold, antigravity, and a
practical perpetual motion machine.
CSS , HTML-.
. ,
,
:
.blue { color: blue; font-weight: bold }

This text is in the default color, but
<SPAN CLASS="blue">this text is blue.</SPAN>
.
<2 CLASS="blue">A Blue Heading</H2>
, , , Netscape
. , , Netscape
. b l u e _ f o n t .
!
Netscape ,

("_").

,
, , ,
.
, "#".
ID.
<HEAD>

<TITLE>...</TITLE>
<STYLE TYPE="text/css">
<!
#foo { color: red }
>
</STYLE>
</HEAD>
<BODY>
<P ID="foo">
</BODY>
.

146

5.


HTML
( , ),
,
. CSS1
. .
A:link, :link
,
. , ,
.
A:visited, rvisited
,
.
:active, :active
, (
).
Aihover, :hover
Internet Explorer. ,
.
. ,
,
:
.bizarre lactive { font-size: 300% }
,
. ,
.
:link IMG { border: solid green }

5.4.

, .
, .. ,
,
, .
() .
1. , "important" (),
.

5.5.

147

! i m p o r t a n t . ,
,
:
HI { c o l o r : b l a c k ! i m p o r t a n t ;
font-family: sans-serif }
! i m p o r t a n t .
2. , , ,
, .
, ,
, . ,
Web-, , ,
.
3. .
.

. HTML-,
. ,
, .
.
(big), .
, ,
, HTML-.
#foo { . . .
. b i g HI {
STRONG {
STRONG { . .

}
. . . }
.. . }
. }

4. , ,
, .

, , ,
, .

5.5.
CSS1 ,
,
.. Netscape ,
;
, .
, ;
t e x t - d e c o r a t i o n v e r t i c a l - a l i g n ,
.
. , ,
.

148

5.

font-weight
normal I lighter | bold | bolder 110012001... 1900
100
() 900 () 100. ,
: normal, l i g h t e r , bold b o l d e r . :
HI { font-weight : 200 }
2 { font-weight : bolder }

Netscape b o l d e r .
font-style
normal I italic | oblique
.
normal, i t a l i c o b l i q u e .
{ font-style
{ f o n t - s y t l e

: normal }
: italic }

Netscape o b l i q u e .
font-size
pt, pc, in, cm, mm | em, ex, px, % |
xx-large I x-large | large | medium | small | x-small | xx-small |
smaller | larger
.
(. . 5.1), .
( x x - l a r g e , x - l a r g e , l a r g e , medium,
s m a l l , x - s m a l l , x x - s m a l l ) ( s m a l l e r l a r g e r ) .
.
, , STRONG
50% :
STRONG { font-size: 150% }

f o n t - s i z e .
{ f o n t - s i z e : 14pt }
{ f o n t - s i z e : 1cm }
{ font-size: xx-large }
Netscape ,
, ..
" 14 t" "14 t".
font-family

. , 5.3
Web-; . 5.3.

5.5.

149

5.3. Web- Camp Bear Claw


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Cainp Bear Claw</TITLE>
</HEAD>
<BODY>
<Hl>Camp Bear Claw</Hl>
We have the following activities:
<H2>Archery</H2>
<H2>Arts and Crafts</H2>
<H2>Horseback Riding</H2>
<H2>Hiking</H2>
<H2>Campfire Song Times</H2>
<H2>C++ Prograiraning</H2>
</BODY>
</HTML>

Camp Bear Claw - Microsoft internet Expio


Die Edit yiew Qp Favorites

tjetp

Q a- ( ^

Camp Bear Claw

mm
"U

We have the following activities:

Archery
Arts and Crafts
Horseback Riding
Hiking
Campfire Song Times
C++ Programming
. 5.3. Web- Bear Claw

f o n t - f a m i l y (. 5.4 5.5),
-.
5.4. Web- Camp Bear Claw
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>

150

5.

<TITLE>Camp Bear Claw</TITLE>


<LINK REL^STYLESHEET HREF="CampBearClaw.ess" TYPE="text/ess">
</HEAD>
<BODY>
<Hl>Camp Bear Claw</Hl>
We have the following activities:
<H2 CLASS="archery">Archery</H2>
<H2 CLASS="arts">Arts and Crafts</H2>
<H2 CLASS="horseback">Horseback Riding</H2>
<H2 CLASS="hiking">Hiking</H2>
<H2 CLASS="campfire">Campfire Song Times</H2>
<H2 CLASS="java">Java Programming</H2>
</BODY>
</HTML>

5 . 5 . C a m p B e a r C l a w . c s s
HI { text-align: center;
font-family: Funstuff }
H2.archery { font-family: ArcheryDisplay }
H2.arts { font-family: ClampettsDisplay }
H2.horseback { font-family: Rodeo }
H2.hiking { font-family: SnowtopCaps }
H2.campfire { font-family: Music Hall }
H2.java { font-family: Digiface }

i j Camp Bear Clew - Microsoft Internet Expio

File dft View Qo fsyohtes

tlelp

. QD a ( m- 3 M 1
C^Xhf Bear CUw

"

We have the following activities:

aoodi raf fts

HORSEBACK: RIDIHC
111
JRVR PR05RRmmin5
Dom

^.

, 5.4. Web- Bear Claw


,

5.5.

151

, f o n t - f a m i l y
STYLE , ,
, . ,
, .
.
, . ,
"sanserif, . , ,
, .
, Web, intranet,
. Web, ,
.
1 ,
.
GIF- ,
, Web- . ,
, ,
, Web. CSS2
.
f o n t d e f f o n t - f a c e
Netscape Internet Explorer.
font-variant
normal I small-caps

. normal s m a l l - c a p s . Internet
Explorer s m a l l - c a p s . Netscape
.
font
f o n t f o n t - w e i g h t , f o n t - v a r i a n t ,
f o n t - s t y l e , f o n t - s i z e , l i n e - h e i g h t f o n t - f a m i l y .
, ,
.
f o n t - s i z e l i n e - h e i g h t , ("/")
,
{ f o n t - w e i g h t : demi-bold;
font-style: i t a l i c ;
f o n t - s i z e : 14pt;
l i n e - h e i g h t : 150%;
f o n t - f a m i l y : Times, s e r i f }

P { f o n t : demi-bold i t a l i c 14pt/150% Times, s e r i f }

152

5.

fontdef
CSSI.
HTML- .
Netscape f o n t d e f ,
<STYLE TYPE="text/css">
<!
@fontdef URL(http://.../font-file.pfr);
-->
</STYLE>
LINK, HEAD .
<LINK

REL="fontdef"
SRC="http://.../font-file.pfr">

. p f r
. Internet Explorer
p r f , Bitstream
ActiveX, Internet Explorer . p f r .
:
http://www.truedoc.com/webpages/intro/
http://www.bitstream.com/
.
font-face
Internet Explorer
f o n t - f a c e , Style Sheets, Level 2 ( h t t p : / / w w w . w 3 . o r g /
T R / R E C - C S S 2 / f o n t s . h t m l # f o n t - d e s c r i p t i o n s ) .
Internet Explorer, :
<STYLE TYPE="text/css">
<!
@font-face {
font-family: fontname;
font-style: normal;
font-weight: normal;
src: url(http://.../font-file.eot)
}
</STYLE>
, Internet Explorer Netscape
. Internet Explorer e o t , Netscape p f r .
. e o t Microsoft Web E m b e d d i n g Fonts
Tool (WEFT). Microsoft
http://www.microsoft.com/typography/
WEFT
Version 2.

5.6.

153

5.6.

,
, .
, , ,
, .
BGCOLOR, ,
.
color
_ \ #RRGGBB | #RGB | rgb(rrr, ggg, bbb) | rgb(rrr%, ggg%. bbb%)

. (. . 5.2).
c o l o r .

HI
2

{
{
{
{
{

color
color
color
color
color

blue }
#OOAABB }
#OAB }
rgb(255, 0, 0 ) } /* red -^f
rgb(0, 0, 255 ) } /^ blue */

background-color
transparent |
_ \ #RRGGBB | #RGB | rgb(rrr, ggg, bbb) | rgb(nT%, ggg%, b b b % )
.
, ,
,
transparent.
background-image
n o n e I \{_)
,
. ,
,
. :

2 { background-image: url(Bluedrop.gif);}
background-repeat
repeat | repeat-x | repeat-y | norepeat
r e p e a t , r e p e a t - x , r e p e a t - y
n o r e p e a t ,
, , ,
. b a c k g r o u n d repeat.

154

5.

BODY {
background-image: url(Bluedot.gif);
background-repeat: repeat-x;

background-attachment
scroll I fixed
,
( s c r o l l )
( f i x e d ) . Netscape.
background-position
[ top I center | bottom] [ left | center | right ] |
[ pt, pc, in, cm, mm ] [ pt, pc, in, cm, mm ] |
[ em, ex, px, % ] [ em, ex, px, % ]
b a c k g r o u n d - p o s i t i o n
.
, .
l e f t / c e n t e r / r i g h t , t o p / m i d d l e / b o t t o m ,
(. . 5.1). , , 50% ,
. 25
,
25 . ,
, ,
50%. "0% 0%".
, ,
.
background-position.
BODY { background-image: url(Marty.jpg);
background-position: 10% 10%; }
HI { background-image: Bluedrop.gif;
background-position: center; } /* 50% 50% */

Netscape b a c k g r o u n d - p o s i t i o n .
background
background b a c k g r o u n d - c o l o r , b a c k
ground-image, b a c k g r o u n d - r e p e a t , b a c k g r o u n d - a t t a c h m e n t b a c k g r o u n d p o s i t i o n .
5.6 5.7, Web. , .
. Web-
Netscape Communicator 4.7 . 5.5.

5.6.

5.6. Cabinets. html


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Joe's Cabinets</TITLE>
<LINK REL=STYLESHEET HREF="Cabinets.ess" TYPE="text/css">
</HEAD>
<BODY>
<CENTER>
<TABLE WIDTH=360 HEIGHT=199>
<TR><TD ALIGN="CENTER" CLASS="banner">Joe's Cabinets
</TABLE>
</CENTER>
<P>
Welcome to Joe's Cabinets. We specialize in
<UL>
<LI>Custom Cabinets
<LI>Kitchen Remodeling
<!-- Etc -->
</UL>
< ! Etc >
</BODY>
</HTML>

5.7. Cabinets.ess
.banner { background: url(images/boards.jpg) repeat-x;
font-size: 50pt;
font-family: Arial Rounded MT Bold }

ltki>'M^mail.,.nM.
Welcome to Joe's Cabinets. We specialize in
Custom Cabinets
Kitchen Remodebng

. 5.5.

155

156

5.

5.7.
.
, ,
.
word-spacing, letter-spacing
normal I + / - pt, pc, in, cm, m m | + / - em, ex, px
,
.
(. . 5.1) n o r m a l . )
(
), (
). w o r d - s p a c i n g Netscape, Internet
Explorer. , Netscape l e t t e r - s p a c i n g .
text-decoration
n o n e I underline | overline | line-through | blink
t e x t - d e c o r a t i o n .
, u n d e r l i n e , o v e r l i n e , l i n e - t h r o u g h
b l i n k . , ,
, , ,
:
:link { coloriblue; text-decoration: none }
P { text-decoration: underline }
, Internet Explorer b l i n k , a Netscape
o v e r l i n e .
vertical-align
top I bottom I baseline | middle | sub | super | text-top | text-bottom | %
. ,
( ),
. ,
.
t o p (
), b o t t o m (
), b a s e
l i n e (
), m i d d l e (
), s u b (
), s u p e r ( ), t e x t - t o p
( ), t e x t b o t t o m ( ).

5-7-

157

text-transform
n o n e I uppercase | lowercase | capitalize
,
( u p p e r c a s e ) , ( l o w e r c a s e )
( c a p i t a l i z e ) .
text-align
left I right I center [justify
, ,
.
text-indent
+ / - pt, , in, cm, mm | + / ~ em, ex, px, %
.
, m a r g i n - l e f t .

. 0.
, . :
{ text-indent: -25 } /* */
line-height
normal I \ pt, , in, cm, mm | em, ex, px, %

.
, . :
.double { line-height: 200% }
.triple { line-height: 3 } /* the font size */
DIV { line-height: 1.5em }
white-space
normal I pre | nowrap
w h i t e - s p a c e ,
, .
n o r m a l (
), p r e (
, PRE) n o w r a p (
BR). Netscape n o w r a p ; Internet
Explorer w h i t e - s p a c e .
Web-,
. Web- 5.8.
:
{ margin-top: 5 }
, ,
( r h e a d ) ( I h e a d ) . -

158

5.

( j u s t i f y ) . ,
( f o o t ) 60% .
. 5.6 , Internet
Explorer, Windows 2000.
5 . 8 . B a t e s . html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0 T r a n s i t i o n a l / / E N " >
<HTML>
<HEAD>
<TITLE>An Open L e t t e r t o t h e IRS</TITLE>
<LINK REL=STYLESHEET H R E F = " B a t e s . e s s " T Y P E = " t e x t / c s s " >
</HEAD>
<BODY BACKGROUND="images/bond-paper.jpg">
<P CLASS="rhead">
April 1, 2001
<HR>
<P CLASS="rhead">
William A. Bates<BR>
Macrosoft Corporation<BR>
Blumond, WA 12345
<P CLASS="lhead">
Internal Revenue Service<BR>
Philadelphia, PA 67890
<P>
<BR>
Dear Sirs,
<P CLASS="body">
I am writing to inform you that, due to financial difficulties,
I will be unable to pay my taxes this year.
<P CLASS="body">
You see, my company has had reduced profits this year. In fact
gross revenues have now dropped below the GDP of <B>twelve</B>
foreign countries! Given this intolerable situation, I am sure
you will understand.
<P CLASS="foot">
Sincerely,<BR>
William A. Bates
</BODY>
</HTML>

5.9. Bates. ess


P { margin-top: 5px }
P.rhead { text-align: right;
margin-right: O.Sin;
font-family: sans-serif }
P.lhead { font-family: sans-serif }
P.body { text-align: justify;
text-indent: 0.5in }
P.foot { margin-left: 60%;
line-height: 300% }

5.8.

^ ^iptxl

An Open Letter to the IRS - MkrosofI: MefneiCok^


Fte
*

Edit

View

- *

Favorites

- '^

i3

loot

159

Help

'3^Sedfch

; i j Favorites

^History

-^- ^

"3

April 1,2001
VViiliam A. Bates
Macrosoft
Blumood.WA 12345

Internal Revenue Service


Philadelphia, PA 67890
Dear Sirs,
I am writing to inform you that, due to financial difficulties, I wiD be unable to
pay ray taxes this year.
You see, my company has had reduced profits this year. In fact gross
revenues have now dropped bdow the GDP of twelve foreign countries! Given this
intolerable situation, I am sure you will understand
Sincerely,
Williain A. Bates

zl
i^Oone

( ^ My Computer

. 5.6.

5.8.
,
.
(box) ,
.
, , ,
.
.
,
. . ,
, , ,
, .
.
{ margin: 0 . 2 5 i n ;
border; 0.25in solid black;
padding: 0.25in;
background: URL(images/bond-paper.jpg) }
BODY { background: URL(images/bricks.jpg) }
Ha . 5.7 Web-, .
, ,
, .

160

5.

Baundift9
Jcjk

c8t

Box - MftcrosoftliAetiii^^
^ew

Fuvorltes

look

elp

^^^^^^!

-^Done

^ ^ My Computer

. 5.7. ,

,
.
.
margin-left, margin-right, margin-top, margin-bottom
auto I + / - pt, pc, in, cm, m m | + / - em, ex, px, %
, , .
(. . 5.1),
a u t o .
0. ,
.
.
{ m a r g i n - r i g h t : 5 }
HI { m a r g i n - t o p : 200% }
margin
, , ;
( ) .
, .
,
. ,
" ".

,
.
. ,
.

5.8.

161

border-left-width, border-right-width, border-top-width, border-bottom-width


none I thin | medium | thick |
pt, pc, in, cm, mm | em, ex, px
, ,
.
t h i n , medium, t h i c k none.
.
border-width
none I thin | medium | thick |
pt, pc, in, cm, mm | em, ex, px
b o r d e r - w i d t h top, b o r d e r - w i d t h - r i g h t , border-width-bottom b o r d e r - w i d t h - l e f t
( ).
, .
,
. ,
medium,
t h i n .
DIV { b o r d e r - w i d t h : medium t h i n }
border-color
_ \ #RRGGBB | #RGB | rgb(rrr, ggg, bbb) | rgb(rrr%, ggg%, bbb%)
. b o r d e r width, ,
, ,
. . 5.2. :
{ border-style: solid;
b o r d e r - c o l o r : b l a c k gray gray b l a c k ;
}

,
Netscape .
border-style
none I dotted | dashed | solid | double | groove | ridge | inset | outset
.
, , b o r d e r - w i d t h ,
, , .
, d o t t e d , dashed, s o l i d , double, groove, r i d g e , i n s e t
o u t s e t . , ,
.
dashed d o t t e d Netscape, Internet Explorer.
, Netscape b o r d e r - s t y l e ;
border. ,

162

5.

{ border-sytle: ridge }
Netscape; :
{ border: ridge }
Internet Explorer .
border-left, border-right, border-top, border-bottom
,
. , ,
,
, :
HI { c o l o r :

red;

border-top: lOpx solid blue;


border-bottom: lOpx solid blue }
border

,
. ,
, . 5.7, :
border: 0.25in s o l i d black



. ,
. .
padding-left, padding-right, padding-top, padding-bottom
pt, pc, in, cm, mm | em, ex, px, %
, ,
. ,
( BODY),
, , , ,
.
. 0.
.
padding
, ,
. padding
, .
,
. ,
, . 5.7, :
padding: 0.25in

5.9.

163


HTML- ,
.
, ,
. d i s p l a y
.
display
block I inline | list-item | none
,
, , PRE,
.
b l o c k , i n l i n e , l i s t - i t e m none. l i s t - i t e m
b l o c k , ,
.

5.9.
,
. ""
, .
width, height
auto I pt, pc, in, cm, mm | em, ex, px

. ,
, a u t o .
, "bullet" :
IMG.bullet { width: 50; height: 50 }
a u t o ,
, . ,
.
float
none I left I right

.
. , 5.10
, "" 75
. . 5.8.

164

5.

5.10. Psalm23.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>The 23rd Psalm</TITLE>
<STYLE>
<!
SPAN { float: left;
font-family: "Gushing Book";
font-size: 75pt }
-->
</STYLE>
</HEAD>
<BODY>
<H2 ALIGN="CENTER">
The 23rd Psalm (King James Version)</H2>
<SPAN>T</SPAN>he LORD is my shepherd; I shall not want.
He maketh me to lie down in green pastures: he leadeth me
beside the still waters. He restoreth my soul: he leadeth me
in the paths of righteousness for his name's sake. Yea,
though I walk through the valley of the shadow of death, I
will fear no evil: for thou art with me; thy rod and thy
staff they comfort me. Thou preparest a table before me in
the presence of mine enemies: thou anointest my head with oil;
my cup runneth over. Surely goodness and mercy shall follow me
all the days of my life: and I will dwell in the house of the
LORD forever.
</BODY>
</HTML>

file g(M ifiew

fio

ofwnunicioi

The 23rd Psalm


(King James Version)
he LORD is my
shepherd; I shall not
want. He maketh me to
lie down in green
pastures: he leadeth me
beside the still waters. He
restoreth my soul he
leadeth me in the paths of
righteousness for his name's sake
Yea, though I walk through the
of the shadow of death, I will

. 5.8. f l o a t

clear
none I left I right | both
,
. l e f t (
, ), r i g h t (

5.10.

165

, ), b o t h (
) ( ).
, Web- ( 5.10), . 5.8,
, .
<>,
, . 5.9,.

The 23 rd Psalm
(King James Version)

The 23rd Psalm


(King James Version)

he LORD is my
shepherd; I shall not
want.

()

He maketh me to lie
down m green pastures:
he leadeth me beside the
still waters. He restoreth my soul: he
leadeth me in the paths of
righteousness for his name's sake
Yea, though I walk through the

^^^

he LORD is my
shepherd; I shall not
want.

He maketh me to lie down in green


pastures: he leadeth me beside the
still waters He restoreth my soul: he
leadeth me in the paths of
nfihteousiifsb L r b s name': salce

z!

(6)

. 5.9. (a) , ,
; ()
,

< S T Y L E = " c l e a r : l e f t " > ,


Web- , . 5.9,6, ..
( "").

5.10.

(0L), (UL) (DL).
Internet Explorer 3, Netscape 4
l i s t - s t y l e - t y p e .
list-style-image
n o n e I \{_)
.
, , Internet Explorer.
URL .
l i s t - s t y l e - i m a g e .
,
d i a m o n d . g i f . s t a r ,
( s t a r . g i f ) .
UL { l i s t - s t y l e - i m a g e : u r l ( d i a m o n d . g i f ) }
UL.star { l i s t - s t y l e - i m a g e : u r l ( s t a r . g i f ) }

166

5.

GIF-,
. Netscape l i s t style-image.
list-style-type
n o n e I disc | circle | square | decimal | upper-alpha | lower-alpha | upper-roman |
lower-roman
,
l i s t - s t y l e - i m a g e ( 0L
DL). d i s c ( ), c i r c l e
( ), s q u a r e , d e c i m a l (1, 2, 3 ..), u p p e r - a l p h a (, ,
..), l o w e r - a l p h a (, , ..), u p p e r - r o m a n (I, II, III ..), l o w e r - r o m a n (i,
ii, iii ..) n o n e .
list-style-position
outside I inside
, o u t s i d e (
) i n s i d e , ,
( i n s i d e ) ( o u t s i d e ) . Netscape, Internet Explorer
l i s t - s t y l e - p o s i t i o n .
list-style
l i s t - s t y l e - i m a g e ,
t y p e l i s t - s t y l e - p o s i t i o n .

list-style-

5 . 1 1 .


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


,
, . 5.1.

5 . 1 .
cm

( )

em

( )

"" ( )

5.12.

167

. 5 . 1 .
in

( )

( )

; 6 ; 12 ( )

pt

; 72 ( )

( )

,
. 5.2.

5.2. CSS1


, . 1.1. Netscape Internet
Explorer X I 1

#RRGGBB

RR, GG
00 FF

#RGB


#RRGGBB. , #OAF
# OAAFF

rgb ( r r r , ggg,bbb)

r r r , ggg
b b b
255

r g b {rrr%, ggg%,bbb%)

r r r , g g g b b b
100

5.12.
Netscape 4 , .
,
.
, , ,
.
, ,
,
. JavaScript-,
.
24, ,
, .
( BODY) LAYER ILAYER. -

168

5.

HTML 4.0 Netscape 6 LAYER


ILAYER. Internet Explorer
.

Internet Explorer Netscape 6 LAYER
ILAYER. .

LAYER
/LAYER
: <LAYER ...> ... </LAYER>
<ILAYER ...> ... </110
: ABOVE, BACKGROUND, BELOW, BGCOLOR, CLIP, HEIGHT, ID, LEFT, ONBLUR,
ONFOCUS, ONLOAD, ONMOUSEOVER, ONMOUSEOUT, PAGEX, PAGEY, SRC, TOP, V I S I B I L I T Y ,
WIDTH,Z-INDEX

LAYER
)' . LAYER
: , .
, , NOLAYER.
LAYER, NOLAYER .

ABOVE, BELOW, Z-INDEX


, :
, .
, .
ABOVE, BELOW Z-INDEX.
Z-INDEX ,
.
. ABOVE BELOW
,
. . ,
<LAYER I D = " F o o " ABOVE="Bar"> , ,
, Foo, .
!
ABOVE BELOW , , , .
ID="currentLayer"

ABOVE="referencedLayer">

, currentLayer

<LAYER

referencedLayer.
) ABOVE BELOW 5.11.
. 5.10.

5 . 1 2 .

169

5 . 1 1 . ABOVE BELOW
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Using ABOVE and BELOW</TITLE>
</HEAD>
<BODY>
<Hl>Using <CODE>ABOVE</CODE> and <C0DE>BEL0W</C0DE></H1>
<LAYER ID="Top" LEFT=60 TOP=120
WIDTH=500 HEIGHT=100 BGCOLOR="#F5DEB3">
This layer is on top, even though it appears
first in the HTML document.
</LAYER>
<LAYER ID="Bottom" ABOVE="Top" LEFT=10 TOP=70
WIDTH=500 HEIGHT=100 BGCOLOR="gray">
This layer is on the bottom, even though it appears
second in the HTML document.
</LAYER>
</BODY>
</HTML>

f Using ABOVE a n d BELOW - NetsGdf

.:.."

:u^:-:'-^~-:,.<M^'Z^:'^^i^

File cW ^(ew 0 ommwrec*o

Si\

:'; ^' ~>r "'S rft *5^> ^ -S ^ Q

Using ABOVE and BELOW

1 1|"'"'^<^ layer is on top, even thougii it appears first in HTML docTjment

IQI*

-*.

;DOGUrfrtt D o n e

5.10.

..: ,:.^^*-,.. ...,. .,,i~

.:^:......,

ABOVE, BELOW Z - I N D E X

^.:

^-

BACKGROUND, BGCOLOR
. ,
. ,
( 5.10 . 5.10) BGCOLOR
. BGCOLOR ,
BACKGROUND ,
GIF-.

170

5.

CLIP
, ,
, . H T M L
, .
''_, _1,, _, _'
''_, _\
", ,
_^,
_\
WIDTH, HEIGHT
.
WIDTH HEIGHT , .
, WIDTH HEIGHT , .
,
. , 5.11
. 5.10, WIDTH HEIGHT .
ID
.
ABOVE BELOW JavaScript.
LEFT, T O P , PAGEX, PAGEY
, LAYER,
(LEFT, )
Web- (PAGEX, PAGEY). .
, Web. , 5.11 . 5.10, LEFT
.
(ILAYER) LEFT
Web-. 5.12
"Gently down the stream"
. 5.11.
5.12. I L A Y E R
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0 T r a n s i t i o n a l / / E N " >
<HTML>
<HEAD>
<TITLE>Row, Row, Row Your Boat</TITLE>
</HEAD>
<BODY>
<IMG S R C = " i m a g e s / R o w b o a t . g i f " ALIGN="RIGHT">
<HR>
<B>Row, Row, Row Your Boat</B><BR>
Row, row, row y o u r boat<BR>
Gently
<ILAYER TOP=10>down</ILAYER>
<ILAYER TOP=20>the</ILAYER>
<ILAYER TOP=30>streain<BR>

5-12.

171

Merrily, merrily, merrily, merrily<BR>


Life is but a dream<BR>
<HR>
</ILAYER>
</BODY>
</HTML>

te4iHHitHiffil'ff1
fe cft ^lew

^^?^

fio

omfnunical ^

11

ill *^- A ^^'-.if-

Row, Row, Row Your Boat


Row, row, row your boat
Gently
down
the
stream
Memly, memly, memly, merrily
Life IS but a dream

. 5.11. TOP i LAYER


SRC
URL HTML-,
. ,
.
, HTML-
, Web-,
, . , ,
Web-,
<LAYER S R C = " C o n t a c t - I n f o . h t m l " > < / L A Y E R >
</BODY>.

:
<Hl>Menu f o r J o e ' s D i n e r < / H l >
<ILAYER S R C = " B l u e - P l a t e - S p e c i a l . h t m l " > < / I L A Y E R >
<H2>Appetizers</H2> . . .
<H2>Main D i s h e s < / H 2 > . . .
<H2>Vegetables</H2> . . .

VISIBILITY
, .. ,
. SHOW, INHERIT
HIDDEN. SHOW , ,
INHERIT ,
HIDDEN .

172

5.

Web-,
JavaScript-.
ONBLUR, ONFOCUS, ONLOAD, ONMOUSEOVER, O N M O U S E O U T
JavaScript-,
.
24.


( ),
LAYER ILAYER.
SRC , , ,
PAGEX PAGEY,
. Netscape 4

LAYER
ILAYER. , ,
Web- , ..
, . ,
Netscape 6 LAYER ILAYER.

. ,
Netscape, Internet Explorer,
, .
,
, , <DIV STYLE=" . . . ">
( ) <SPAN STYLE=". . . "> ( ).
p o s i t i o n . ,
#11 { p o s i t i o n : absolutesl e f t : 50; t o p : 7 5;
. . .


<SPAN I D = " l a y e r l " >
</SPAN>
:
<LAYER I D = " l a y e r l " LEFT=50 =75
</LAYER>
,
#12

{ position: relative;
t o p : lOpx;
...

...>

5.12.

173


<SPAN I D = " l a y e r 2 " >
</SPAN>
, .
<ILAYER I D = " l a y e r 2 " =10

...>

</ILAYER>
, CSS1,
.
clip
, ..
ect {_,
_,
_,
_) a u t o ( ).
c l i p CLIP LAYER ILAYER. ,
, , ,
CSS. ,
LAYER ILAYER, , .
left, t o p

CSS. LEFT LAYER
ILAYER.
overflow
,
. ( )
, .
c l i p , s c r o l l ,
, .
position
a b s o l u t e , r e l a t i v e s t a t i c .
LAYER, ILAYER
, .
static.
visibility
, .
v i s i b l e , h i d d e n i n h e r i t .
, ,
.
JavaScript-.

174

5.

JavaScript- 24. 5.13


Web-, ,
. . Web . 5.12.
(. 5.13), ,
, . Internet Explorer Netscape ,

JavaScript- d i s p l a y .
5.13.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Changing Visibility Dynamically</TITLE>
<STYLE>
<!
#layerl { position: absolute; left: 0.25in; top: 1.5in;
color: black; background-color: #F5DEB3;
visibility: hidden }
#layer2 { position: absolute; left: 0.25in; top: l.Sin;
color: #F5DEB3; background-color: black;
visibility: hidden }
HI { text-align: center;
font-family: Arial }
FORM { text-align: center }
-->
</STYLE>
<SCRIPT TYPE="text/javascript">
<!
function display(valuel,value2){
if(document.layers) { // Netscape,
document.layers.layerl.visibility = valuel;
document.layers.Iayer2.visibility = value2;
} else {
document.all.layerl.style.visibility = valuel;
document.all.Iayer2.style.visibility = value2;
}
}
// >
</SCRIPT>
</HEAD>
<BODY BGCOLOR="WHITE">
<Hl>Changing Visibility Dynamically</Hl>
<FORM>
<INPUT TYPE="BUTTON" VALUE="Show Layerl"
onClick=!"display('visible' , 'hidden') ">
<INPUT TYPE="BUTTON" VALUE="Show Layer2"
onClick="display('hidden','visible')">
</FORM>
<DIV ID="layerl">
<Hl>This is layerl.</Hl>
</DIV>

5.12.

175

<DIV ID="layer2">
<Hl>This is Iayer2.</Hl>
</DIV>
</BODY>
</HTML>

' Changing visflbitily DfnanwcMiy - Nelcepe


file dit VJaw omniurceJ3r

Eaai

Changing Visibility
Dynamically

^!^:^^r

"" ^^*!*"'

. 5.12. Web-, JavaScript-

Changing Visibility
Dynamically
This is layeM.
^^-^ =jl^.- <

. 5. .

width, height
. ,
WIDTH HEIGHT LAYER ILAYER.
z-index
,
HTML-. z - i n d e x
. ,
.
. Z-INDEX LAYER
ILAYER.

176

5.

5.13.

Web-. H T M L 4.0
) . ,
, ,
. .
, ,
, .
Netscape
Internet Explorer.
, H T M L
, , ,
HTML, . Java
, Web- .
Java ,
Web-. Java .
Java- II .

-JlEJS^-.

JAVA
6. Java
7. - Java
8. Java
9.
10. Java 2D: Java 2
11. ,
12.
13. AWT
14. Swing
15. Swing
16.
17.


JAVA
...
Java. ,
.
Java: .

Java.

,
.

Java-.

Java-.

U~y\zJsJ:EJ

ava , C++. Java


, ,
WWW-,
.
, . IBM Oracle
Java ,
Enterprise Developer (. h t t p : //www-4 . i b m . com/
software/ad/certify/adedserv.html
http://education.oracle.com/ c e r t i f i c a t i o n / j avatrack.html).
Java .

,
Web.

- .

Java- Windows
" ", , Java
" ",
. Java ,
, , , ,
. , Java
Web.
, Java
,
. - Java, -

180

6. Java

, ,
. , ,
Java.
Java , . ,
"Java" "". Sun
Oak, . Java
.

6 . 1 . Java
Java,
. , Java ,
, .
. Java
( C/C++), (
) API .
Java.

Web
Web Java ,
Internet. ,
Web, Internet
, Java .

Java . Java
.
,
.
Java-, .
,
, ,
.
Web
Java- Netscape Internet
Explorer, ,
.
,
,
. , ,
,
. , ,
Web-,

6 . 1 . Java

181

. ,
, .
, Web- .
. 6.1 , Web.
.

. 6.1. , 1 NASA,

Java
Java
.
.
Java
Berkeley POSIX Transport Layer Interface. , Java
HTTP, Web
HTTP, . . 6.2 , -

182

6. Java

Web- Ethernet- Cisco Catalyst


6000. HTTP-, Catalyst,
, ,
.

. 6.2, Cisco OpenView, Ethernet-


Catalyst 6000 ( Cisco Systems, Inc.)

6 . 1 . Java

183


1995 . Sun
Java, . Java
RMI (Remote Method Invocation
), ,
. RMI Java-
. Java-, ,
,
. JDBC

, CGI. En
terprise JavaBeans, JavaServer Pages,
- .

Java
Java , ,
, , ..
. ? Java
.
Java -
Java- .
Java ,
Java (JVM Java Virtual
Machine). H a Java- .
( JVM),
J I T (Just In T i m e ) ,
, .
,
.
Borland Windows 2000,
Macintosh ,
Apple, Solaris , Sun.
. 6.3
StarOffice, Windows, Solaris Linux.
Web-
Java, Web- .
Java
,
, .

, . ,
,
, . Java
,
, Java Sun Microsystems AWT

184

6. Java

(Abstract Window Toolkit


), ,
. AWT
(, , , ,
..).
.
l i ^ S t a r t t f T t c e S ^ -iLrofiS-LanauaQedtittii:.-:;"
1 EdK i^iew

[rwert
A

8
__ 9 _
~ii"'

. B.

' Z

,; ""
: ^

_ 1

D . .

IRIT
0 62
0 46
0 43
0 38
0 33
0 32
0 22
0 19
0.18
0.12
0.08

U Tampere
0 68
0 53
0 43
0 33
0 28
0 26
0 19
0 16
0 13
0.1
0.07

CWI

.<3. ..J H ^

0 5
0 41
0 32
0 29
0 25
0 23
02
0 16
0.13
0.1
0.08

' 13 1
;

Cross Language Retrieval

; ; '^z

^ ': ^:^'v'' '#::';'V/::':<riiwi:iKyH^^^^^B

loots Cata tNp

JHU/APL T N O / U T w e n t e
0 68
0 58
0 63
0 51
0 54
0 47
0 51
0 41
0 47
0 36
0 43
0 32
0 37
026
0 33
0 22
03
021
0.2
0.14
n^6
0 1

0
0 1
0 2
0 3
0 4
0 5
06
0 7
08
0.9
1

V - J
76 ^\

; ;

'F^mA

liil

\ JHU/APL
' ^ , TNO/UTwente
VIRIT
UTartpere
''^CWI

"^

19
" 20
21

0.60 5O

0.4-

2
29'1
30
31
__33j

IMI

03020 1-

()

0.1

0.2

0.3

3%ii: f \ S h e e t i y Sheet2 / S h e e t s /

^^ J M

0,4

05

06

0.7

0.8

0.9

Recall

37
l^lCross-Lang...

'
if*

h2:36PM

. 6.3. StarOffice 5.2,


, Java. StarOffice"^^
Sun Microsystems, Inc.

Java 2, Sun Swing ,


AWT
. Swing
,
Web-. ,
Swing Netscape 6. Netscape Internet
Explorer .
. 6.4 ,
NASA.
Pathfinder ,
.

6 . 1 . Java

|^||

185

H^joixil
_J__T

;^^)^
~^

. ;-|3
v'^^.o>2t3isyT^>y^.:'?^^"^^^^^^

P^#Btfe^v#^^

m^\

:-:;;^=^^:;^|

nl4Q|||ffl|^|Al

Rovef:|fOcky7

Pointer Kicxfc

"^v;>;-

1:[^?1

Cyde;[l

Map:|Eteve(ion

. 6.4. Web-,
Jet Propulsion
Lab
Mars
Pathfinder

Java ,

Java ,
i n t , b o o l e a n d o u b l e . Java ,
. Java-
,
( Java
s i z e o f , /+-). Java
,
, .

186

6. Java

Java
Java C++, ,
C++. , Java- ,
make-, .
, , :
.

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

, .

Java- (,
), .
, , .
; ,
. Java,
, ,
.
, .
, , ,
,
Java. ,
C/C++, ,
Smalltalk Lisp.

- Java
Java - . "
", .

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

-
. , , , ,

6 . 1 . Java

187


, . Java, ,
, "" O b j e c t .
,
. Java ( i n t , d o u b l e ,
b o o l e a n , c h a r ..),
"" I n t e g e r , D o u b l e , B o o l e a n , C h a r a c t e r ..
.

Java
,
" / " ,
Java ,
:

( )
;

Java-;

Java-
Java, ,
. . 6.5.

. , ,
, ,
. , Java
,
. ,
Java. (.
7), (. 8).
Java .
Java , Java
.
,
Java. ,
,
AWT ( 13) Swing ( 14 15) ,
. , , . -

188

6. Java

Java, ,
, ,
,
Java API. , , ,
, , , ) , " ".
'!

;^^^1^<

'~& <2'^0$^^:

http //md dmso mil/melb(n/iava_query

??>f|%vlgj;?S:-.|;p^|j^
Mijipp!i(iH|irtii>jffMiij?i

J96.48

(W

''l*?i!iigWS^SW

3|23.039

WmaitJmjm X

RentMTalH.

j^fe^^^^^Ei
ClicK to start a ieeioti.

;^App$et3tdrtsd

\^i .'^'^

ir^

. 6.5. Java- Master Environmental Library ( M E L ) ~


. Java-

6.2. Java:
Java 1995 .,
.
Java ,
.

6.2. Java:

189

Java Web
Java
Java-. , Java-
Web-, , Java
Web. Java , ,
,
, Internet. , Java
Internet-.
, , Enterprise JavaBeans JavaMessaging Java .
,
-, Java,
Web. , Java
Web.

Java
Java
. , .
,
, .
, Java-.
J a v a - ,

e x e c R u n t i m e Java-
. , -
, Java .
Java- ,
,
. ,
Java ,
. "" Java.
- ,
, ,
,
, C++. ,
. ,
. ,
,
. , ,
,
"" Java-, .

190

6. Java


Java ,
.
.
. ,
, ,
. ,

.

,
.
,
. Solaris, Windows NT,
Macintosh
. ,
Java,
, .
-
Java ,

. ,
, , Macintosh
, , Windows 2000.
Abstract Window Toolkit
, , ,

.
, Sun
,
.
Java 2 Sun Swing,
.
, Swing,
. ,
Swing . AWT,
, .

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

6.2. Java:

191

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

.
, ,
. , ,
, "/"
. Java
. ? ,
, . ,
.
, Java .
, , Java
, Java .

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

Java

Java . --
. , Java
. UNIX

192

6. Java

, Windows- Visual Basic,


Web- JavaScript VBScript.
, ,

. ,

. Java
,
. ,
.

6.3. Java
Java 1.0 Sun Microsystems 1995 . 1996 .
Netscape Java Netscape 2.0.
, Java-.
Java 1.02;
Java 1.0. 1997 . Sun
Java 1.1, .

,
.

RMI (Remote Method Invocation )


.

JDBC (Java Database Connectivity) API


.

JavaBeans (Java- ActiveX).

, ,
( " ",
ActiveX).

Java 1.1 API,


Netscape 4.06 Internet Explorer 4.0,
.
, Java,
.
Java 2, JDK 1.2 (Java De
velopment Kit 1.2), 1998 .
, B J D K 1.2.

Swing,
Java.

Java 2D .

6.3. Java

193

Collection Framework ,
, .

. wav, , a i f f, . a u , . m i d i . rmf.

Java IDL API, Java CORBA.

2000 . Sun JDK 1.3.


API.
.

Java Naming and Directory Interface (JNDI) ,


().

RMI-IIOP ,
CORBA- .

, , , } , , JDK 1.2 JDK 1.3


Java 2, Standard Edition. Standard Edition Sun Java 2,
Enterprise Edition, .

Java- Jav2iServer Pages Sun Microsoft Active


Sei-ver Pages ColdFusion.

Enterprise JavaBeans -
, .

,
JDBC.

JavaMail
STP, IMAP4.

JAXP XML-.

Java Message Service


.


, , Java!
,
, .
)^ .

. Java Development Kit 1.1


(JDK 1.1, JDK 1.1.8_005). Netscape 4.06,
Internet Explorer 4.01
1.1
Java. Netscape 6, , ,
JDK 1.3. Internet, ,

194

6. Java

, ,
, , naJDK 1.1 API.

.
JDK 1.3, Java SDK, Standard Edition, Version 3.0.
,
, JDK
, .

, JDK 1.3,
naJDK 1.1 API .

Java
Java 2 .
, ,
Java.
7 8 Java. 9
, , 12 ,

AWT ( 13) Swing ( 14 15).

. -,
Internet (
17).
.
( ,
) 16.
, .
19 Java-, 20 JavaServer Pages.
cookie, JavaBeans.
JDBC 22. ,
23 XML JAXP - -.
,
Java, , Enterprise
JavaBeans, JNDI JavaMessaging.

6.4.
, .
, Java ,
. <> , ,
, . </>
, Java ,
, .
, , .

6.4.

195


. . ,
, .

Java.

Java.

Java API
Internet.

( ).

Java-.

Java
Java (,
OS/2, MacOS 10, Solaris 2.6), , Java
. ,
Windows MacOS, OS/2, Novell IntranetWare, Solaris, Irix, HP-UX, AIX, SCO
UnixWare, Linux, Amiga, BeOS .
, Java.
,
Sun
http://Java.sun.com/cgi-bin/java-ports.cgi
, , URL,
, h t t p : //www. corewebprogramming. com/.

Java SDK, Standard Edition, Version 1.3 (JDK 1.3)


Microsoft Windows
http://Java.sun.com/j2se/l.3/download~windows.html
Solaris SPARC/x86
http://Java.sun.com/j2se/l.3/download-solaris.html
Linux x86
http://Java.sun.com/j2se/l.3/download-linux.html

Java SDK, Standard Edition, Version 1.2 (JDK 1.2)


Microsoft Windows
http://Java.sun.com/products/jdk/1.2/download-windows.html
Solaris SPARC/x86
http://Java.sun.com/products/jdk/1.2/download-solaris.html

196

6. Java

L i n u x 86
http://Java.sun.com/products/jdk/1.2/download-linux.html

Java Development Kit, Version 1.1 (JDK 1.1)


Microsoft Windows
http://Java.sun.com/products/jdk/1.1/downlead-windows.html
Solaris SPARC/x86
http://Java.sun.com/products/jdk/1.2/download-jdk-solaris.html

Java
Java, Java-,
Web-, .. .
Java a p p l e t v i e w e r
"-", Web-
. .
Netscape Navigator Communicator, Microsoft
Internet Explorer, Hotjava Sun .
" ", , Web-
, , HTTP, .. .
,
Internet-. , FTP- Netscape.
N e t s c a p e Navigator
http://home.netscape.com/download/
Microsoft I n t e r n e t E x p l o r e r
http://www.microsoft.com/ie/download/
Hotjava
http://Java.sun.com/products/hotjava/

Java API
)^1, Java API,
( , p r i v a t e )
. ,
- . HTML- JDK 1.1, 1.2 1.3
Sun
. , Web-
Sun,
( 5-10 ).

6-4.

197

Java 2 SDK, Version 1.3 (JDK 1.3)


API
http://Java.sun.com/j2se/l.3/docs/api/
, API
http://Java.sun.com/j2se/l.3/docs.html

Java 2 SDK, Version 1.2 (JDK 1.2)


API
http://Java.sun.com/products/jdk/1.2/docs/api/
, API
http://Java.sun.com/products/jdk/1.2/download-docs.html

Java 1.1 (JDK 1.1)


API
http://Java.sun.com/products/jdk/1.1/docs/api/packages.html
, API
http://Java.sun.com/products/jdk/1.l/#docs
,
Sun h t t p : / / J a v a . s u n . c o m / p r o d u c t s / .


( )
Java-, , ,
, , ,
,
.
, , h t t p : / / J a v a ,
miningco . com/msub9 . htm. .
Borland JBuilder
http://www.boland.com/jbuilder/
IBM VisualAge
http://www-4.ibm.com/software/ad/vajava/

198

6. Java

Oracle J D e v e l o p e r
http://www.oracle.com/ip/develop/ids/jdeveloper.html
WebGain Visual Cafe
http://www.visualeafe.com/Products/VisualCafe_Overview.html
Sun Forte D e v e l o p e r

http://www.sun.com/forte/ffj/


( T e s t . J a v a ) ,
T e s t . , , ,
. ,
,
.
.

Windows UNIX j a v a c
Sun JDK, , j a v a c T e s t . J a v a .
Macintosh Java-.
, .
T e s t , c l a s s .

Java-
J a v a T e s t . , j a v a c , J a v a ,
, T e s t , T e s t . c l a s s . Mac
.
, Web-,
. , , Web- T e s t . h t m l ,
T e s t , c l a s s
<APPLET>. .

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

6 . 5 . J a v a -

199

Hello, World
Java- ( Java-)
Java-. , (
) .
main, p u b l i c s t a t i c void.
main , S t r i n g [ ] _
S t r i n g __[ ]. 6.1
, "Hello, world".
7. Java-
.
9, 13,
AWT.

SomeClass

SomeClass. Java. Windows


98/NT/2000
,
SOMECLASS. Java someclass.

Java.

6 . 1 . HeiioWorid.Java
public class HelloWorld {
public static void main(String[] args) {
System.out.println{"Hello, world.");
}
}
:
javac HelloWorld.Java
:
Java HelloWorld

:
H e l l o , world.


6.3 , ,
. , ,
, . S t r i n g
Java, Java- l e n g t h ,
.
C++, ,
8. , Macintosh -

200

6. Java

, , ,
; ,
, .
6 . 2 . S h o w A r g s . J a v a
p u b l i c c l a s s ShowArgs {
public s t a t i c void main(String[] args) {
f o r ( i n t i = 0 ; i < a r g s . l e n g t h ; i++) {
System.out.println("Arg " + i + " is

" + args[i];

}
}
}

:
javac

ShowArgs.Java

:
Java ShowArgs fee fie foe fum
:
Arg
Arg
Arg
Arg

0
1
2
3

is
is
is
is

fee
fie
foe
fum

Hello, World
, Web-
, . ,
, ,
m a i n .
i n i t , p a i n t . 6.3
Java-, "Hello, World
Wide Web". 6.4 HTML-, .
, HTML- ;
Java-.
.
9.
6 . 3 . HelloWWW. J a v a
import
import

Java.applet.Applet;
java.awt.*;

p u b l i c c l a s s HelloWWW e x t e n d s A p p l e t {
p r i v a t e i n t f o n t S i z e = 40;

6.5. Java-

public void initO {


setBackground(Color.black);
setForeground(Color.white);
setFont(new Font("SansSerif", Font.BOLD, fontSize));
public void paint(Graphics g) {
g.drawstring("Hello, World Wide Web.", 5, fontSize+5);

c 6.4. HelloWWW.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>HelloWWW: Simple Applet Test.</TITLE>
</HEAD>
<BODY BGCOLOR="WHITE">
<Hl>HelloWWW: Simple Applet Test.</Hl>
<P>
<APPLET CODE="HelloWWW.class" WIDTH=460 HEIGHT=50>
<B>Error! You must use a Java enabled browser.</B>
</APPLET>
</BODY>
</HTML>
:
javac HelloWWW.Java
:
HelloWWW. h t m l Web-.
:
. 6.6.
F^ HelloWWW: Simple Aopiet Tesl.
ile (A Yiew Qo Communcatc

Nfstscape

a
HelloWWW: Simple Applet Test.

Hello. World Wide Web.


Ci?''^'<'

^11^^|!|. Z

App{(s{netoWV,Vf<

. 6.6. ,
Netscape Navigator 4.7,
Windows 98

201

202

6. Java

,
,
. ,
PARAM, <APPLET
. . .>
</APPLET>. , g e t P a r a m e t e r . 6.5
HelloWWW, ,
. 6.6 HTML-,
, .
PARAM 9.

6.5. Message.java
import Java . a p p l e t . Appletsimport j a v a . a w t . * ;
p u b l i c c l a s s Message extends Applet {
private int fontSize;
p r i v a t e S t r i n g messagesp u b l i c void i n i t O {
setBackground(Color.black);
setForeground(Color.white);
/ / ,
/ / .
f o n t S i z e = g e t S i z e . h e i g h t - 10;
setFont(new F o n t ( " S a n s S e r i f " , Font.BOLD, f o n t S i z e ) ) ;
/ / ,
/ / HTML- PARAM.
message = getParameter("MESSAGE");
}

p u b l i c void p a i n t ( G r a p h i c s g) {
i f (message != n u l l ) {
g . d r a w s t r i n g ( m e s s a g e , 5, f o n t S i z e + 5 ) ;
}
}

6.6. Message.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>The Message Applet</TITLE>
</HEAD>
<BODY BGCOLOR="WHITE">
<Hl>The <CODE>Message</CODE> Applet</Hl>
<P>
<APPLET CODE="Message.class" WIDTH=325 HEIGHT=25>
<PARAM NAME="MESSAGE" VALUE="Tiny">

6.5. Java-

203

<B>Sorry, these exampl es require Java</B>


</APPLET>
<P>
<APPLET CODE="Message.cl ass" WIDTH=325 HEIGHT=50>
<PARAM NAME-"MESSAGE" VALUE="Small">
<B>Sorry, these exampl es require Java</B>
</APPLET>
<P>
<APPLET CODE="Message.cl ass" WIDTH=325 HEIGHT=75>
<PARAM NAME="MESSAGE VALUE="Medium">
<B>Sorry, these exampl es require Java</B>
</APPLET>
<P>
<APPLET CODE="Message.cl ass" WIDTH=325 HEIGHT=100>
<PARAM NAME="MESSAGE" VALUE="Giant">
<B>Sorry, these exampl es require Java</B>
</APPLET>
</BODY>
</HTML>
:
javac Message.Java
:
M e s s a g e . h t m l Web-.
:
. 6.7 Web-,
. APPLET
HEIGHT, PARAM VALUE.
JSIxJ
, Ete

1 *

>i-iBack '

iiew

Favorites

->- - . J J

'JU

lools

'i^Search

d
T h e Message A p p l e t

Small

Medium

Giant
i^jOone

; My Computer

. 6.7.
Explorer 5.5,
Windows 2000

204

6. Java

6.6.
Java
.
Java, , , ,
.
Java .
Java, Java Java API
.
,
. - ,
7. -
, ,
, Java -
. , C++,
8, Java,
. C/C++
, 8 . ,
, , , ,
Java-, JavaServer Pages .

JAVA
...
:
.
: .
: ,
.
: Java ,
.
Javadoc: .
:
.
: .
: .
CLASSPATH: .
:
.

Tly\:EJ^zJ

Java .
)' , )' Java, ,
.
, ,
8. -
, , .
, , .
. ,
,
. ,
;
.
7.7, Javadoc, 7.9,
, 7.10, ,
CLASSPATH JAR.

7 . 1 .
.
( ) new,
. ,
. :

Point 1 = new Point(2, 4);


Color red = new Color(255, 0, 0);
new
. , ,
new ,
, .
, , .

208

7. - .

OutputStream out = someSocket.getOutputStream();


Point pi = someWindow.location 0 ;
, ,
. ,
S t r i n g .
String stringl = new String("A String");
String string2 = "Another String";
, , Java .
, :
objectReference.variableName
,
.
7.1 S h i p l (
). m a i n
new S h i p l () S h i p l ,
. ,
"" , .
7 . 1 . T e s t l . j a v a
//
//
//
//
//

( ) :
X, , s p e e d , d i r e c t i o n name. , S h i p l
p u b l i c ,
, T e s t l . J a v a -
( p u b l i c ) .

class Shipl {
public double x, , speed, direction;
public String name;
}
// , ,
// main.
public class Testl {
public static void main(String[] args) {
Shipl si = new Shipl();
s1.X = 0.0;
si. = 0.0;
si.speed = 1.0;
si.direction = 0.0;
//
si.name = "Shipl";
Shipl s2 = new Shipl();
s2.x = 0.0;
s2.y = 0.0;
s2.speed = 2.0;
s2.direction = 135.0; // -
s2.name = "Ship2";
sl.x = sl.x + si.speed
* Math.cos(si.direction * Math.PI / 180.0);

7 . 1 .

si. = si. + si.speed


* Math.sin(sl.direction * Math.PI
s2.x = s2.x + s2.speed
'^ Math, cos (s2.direction * Math.PI
s2.y = s2.y + s2,speed
* Math.sin(s2.direction * Math.PI
System.out.println(si.name + " is at ("
+ si.X + "," + si.y +
System.out.println(s2.name + " is at ("
+ s2.x + "," + s2.y +

209

/ 180.0)
/ 180.0)
/ 180.0)
").");
").");

javac T e s t l . j a v a
Java T e s t l
:
Shipl is at (1,0).
Ship2 is at (-1.41421,1.41421).
, , ,
.
Java
(, s o m e S t r i n g , window, o u t p u t S t r e a m l ) ,
(. S t r i n g , Window,
O u t p u t S t r e a m ) . "",
"" (,
s o m e l n s t a n c e V a r i a b l e , S o m e C l a s s ) .
"" (,
someinstancevariable,
S o m e C l a s s ) . (, P I ) .
, ,
.


(myVar),
(myCLass).
, , 7.1,
. , ,
Math , P I ,
.
Math m a t h ? , Math ( Java
), . Java
iciacca, ,
.
s t a t i c ,
. ,

210

7. - ..

; ,
Math, M a t h . P I , ,
s t a t i c f i n a l () P I , Math.

7.2.

, .
)%
, ,
.
)^ , ,
. 7.2. , ,
, L i s p / C L O S , ( C++
-). , C++, Java
.
public double =0.0;

p u b l i c p r i v a t e , . )
, , p u b l i c
)' . p r i
v a t e , , .
7.2. T e s t 2 . j a v a
/ / S h i p move p r i n t L o c a t i o n ,
/ / p u b l i c
class Ship2 {
public double x=0.0, y=0.0, speed=1.0, direction=0.0;
public String name = "UnnamedShip";
private double degreesToRadians(double degrees) {
return(degrees * Math.PI / 180.0);
}
public void move() {
double angle = degreesToRadians(direction);
X = X + speed * Math.cos(angle);
= + speed * Math.sin(angle);
}
public void printLocation() {
System.out.println(name + " is at " +
" (" + X + ", " 4- + " ) . " ) ;
}
}
public class Test2 {

7 . 3 . this

211

public static void main(String[] args) {


Ship2 si = new Ship2();
si.name = "Shipl";
Ship2 s2 = new Ship2();
s2.direction = 135.0; // -
s2.speed = 2.0;
s2.name = "Ship2";
s1.move();
s2.move();
si.printLocation();
s2.printLocation();
}

:
javac Test2.java
Java Test2
:
Shipl is at (1, 0) .
Ship2 is at (-1.41421,1-41421).

7.3. this
, .
1 new C l a s s N a m e ( . . . ) . ,
,
. -, , , .
(, p u b l i c v o i d S h i p 2 ( . . . )
{...}),
,
.
!
,
.
.
. , Java
, ,
.
p u b l i c SomeClassO

{ }

,
. , ,
, ,
, .

212

7 . - . . .


, Java
.
,
.
S h i p 2 ,
. .
, ,
, ,
. ,
S h i p 3 , :
public Ship3(double , double , ...) {
//
}
:
. ,
, , .
public Ship3(double , double , ...) {
X = ;
= ;
}


.

.
public Ship3(double inputX, double inputY, ...) {
X = inputX;
= inputY;

t h i s .
t h i s .
, ,
. t h i s
, .
public void move() {
double angle = this.degreesToRadians(this.direction);
this.x = this.x + this.speed * Math.cos(this.angle);
this. = this. + this.speed * Math.sin(this.angle);
}
, :
public void move() {
double angle = degreesToRadians(direction);

7.3. this

213

X = X + speed * Math.cos(angle);
= + speed * Math.sin(angle);
}
t h i s
,
. , ,
.
7 . 3 . T e s t 3 . J a v a
/ / S h i p 3
/ / .

class Ship3 {
public double x, , speed, directionspublic String name;
public Ship3(double x, double y, double speed,
double direction, String name) {
this.x = x; // "this"
this. = ; // ,
this.speed = speed;
this.direction = direction;
this.name = name;
private double degreesToRadians(double degrees)
return(degrees * Math.PI / 180.0);
public void move() {
double angle = degreesToRadians(direction)
X = X + speed * Math.cos(angle);
= + speed * Math.sin(angle);
public void printLocation() {
System.out.println(name + " is at " +
" (" + X + ", " + + ") . ")

public class Tests {


public static void main(String[] args) {
Ships si = new ShipS(0.0, 0.0, 1.0,
0.0, "Shipl")
Ships s2 = new ShipS(0.0, 0.0, 2.0, 135.0, "Ship2")
s1.move();
s 2.move();
si.printLocation();
s2.printLocation();

214

7. - .

javac Test3.java
Java T e s t s
:
Shipl is at (1,0).
Ship2 is at (-1.41421,1.41421).

, ,
)[, , ,
,
s t a t i c .
,
. .
public class SomeClass {
int[] values = new int[12];
static {
for (int i=0; i<values . length; i--+) {
values[i] = 2 * i + 5;
}
}
int lastValue = values[11];

}

. .

7.4.
.
, Java
(, ).
" " ,
. ,
,
. ,
. ,
, . Java ,
. Java ,
. ,
. Java
: " " , ,

7-5-

215

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

. f i n a l i z e .
p r o t e c t e d void f i n a l i z e ( ) throws Throwable {
doSomeBookkeeping();
s u p e r . f i n a l i z e { ) ; / / f i n a l i z e r
/ / .
}

,
throws Java f i n a l i z e .
. ,
, doSomeBookkeeping
.

7.5.
C++ - , Java
.
. ,
i s B i g : "", ,
S t r i n g , ,
.
public boolean i s B i g ( S t r i n g s) {
r e t u r n ( s . l e n g t h 0 > 10);
}

public boolean i s B i g ( i n t n) {
r e t u r n ( n > 1000);
}

,
r e t u r n ( n > 1000);
, :
if ( > 1000) {
return(true);
} else {
return(false);
}

1 7.4 Ship4 move.


t h i s ( a r g s ) .
.
t h i s .

216

7. - .

public class SomeClass {


public SomeClass {
this(12); //
doSomething();
}
public SomeClass(int num) {
doSomethingWith(num);
doSomeOtherStuff();
}

move ""
. ,
, ,
.
move:
p u b l i c void move() {
double angle = d e g r e e s T o R a d i a n s ( d i r e c t i o n ) ;
X = X + speed * M a t h . c o s ( a n g l e ) ;
= 4- speed * Math, s i n (angle) ;
}

p u b l i c void move(int s t e p s ) {
for ( i n t 1=0; K s t e p s ; i++) {
move();
}
}

move ( i n t s t e p s ) ,
move ().
p u b l i c void move() {
double angle = d e g r e e s T o R a d i a n s ( d i r e c t i o n ) ;
X = X + speed * M a t h . c o s ( a n g l e ) ;
= + speed * M a t h . s i n ( a n g l e ) ;
}

p u b l i c void move2(int s t e p s ) {
double angle = d e g r e e s T o R a d i a n s ( d i r e c t i o n ) ;
X = X + ( d o u b l e ) s t e p s * speed * M a t h . c o s ( a n g l e ) ;
= + ( d o u b l e ) s t e p s * speed * M a t h . s i n ( a n g l e ) ;
}

,

. ; ,
.
.
.
.
:

7.5.

217

p u b l i c void move{) {
move(1);
p u b l i c void move{int s t e p s ) {
double angle = d e g r e e s T o R a d i a n s ( d i r e c t i o n ) ;
X = X + ( d o u b l e ) s t e p s * speed * M a t h . c o s ( a n g l e ) ;
= + ( d o u b l e ) s t e p s * speed * M a t h . s i n ( a n g l e ) ;
}

, ,

. , ,
move , .
7.4.
7 . 4 . T e s t 4 , j a v a
class Ship4 {
public double x=0.0, y=0.0, speed=1.0, direction=0.0;
public String name;
// .
public Ship4(double , double , double speed,
double direction, String name) {
this.x = x;
this. = ;
this.speed = speed;
this.direction = direction;
this.name = name;
// name,
// X, , speed direction .
public Ship4(String name) {
this.name = name;
private double degreesToRadians(double degrees) {
return(degrees * Math.PI / 180.0);
// .
public void move() {
move(1);
// N .
public void move(int steps) {
double angle = degreesToRadians(direction);
X = X + (double)steps * speed * Math.cos(angle);

218

7. - ...

= + (double)steps * speed * Math.sin(angle);


}
public void printLocation() {
System.out.println(name + " is at (" + x + "," + + " ) . " ) ;
}
}
public class Test4 {
public static void main(String[] args) {
Ship4 si = new Ship4("Shipl");
Ship4 s2 = new Ship4(0.0, 0.0, 2.0, 135.0, "Ship2")
s1.move();
s2.move(3);
si.printLocation();
s2.printLocation();
}
}

:
javac Test4.java
Java Test4
:
Shipl is at (1,0).
Ship2 is at (-4.24264,4.24264).

7.6.

, ,
, .
. ,
7.5 S h i p , 7.6 ,
.
, , ,
.
.
public

,
. , ,
p r i v a t e g e t X , g e t Y , s e t X
s e t Y ( ).
,
, .

7.6.

219

, )^
. , ,
,
, ,
.
,
, .
s e t X s e t Y ,
. ,
S h i p
. s e t X
s e t Y .

. , ,

P o i n t .
, .
1,
g e t X g e t Y .
javadoc
, " / * * " " * / " ,
j a v a d o c
,
p r i v a t e . j a v a d o c 7.7. ,
)1 , .
, . 7.1,
, S h i p . j a v a ( 7.5).
7 . 5 . S h i p . j a v a
/** ,
* J a v a .

* @author < H R E F = " m a i l t o : l a r r y @ c o r e w e b p r o g r a i r a n i n g . c o m " >


*
L a r r y Brown</A>
* @version 2.0
V
public class Ship {
//
private double x=0.0, y=0.0, speed=1.0, direction=0.0;
private String name;
//
/*^ Ship. */

220

7. - .

public Ship(double , double , double speed,


double direction, String name) {
setX(x);
setY(y);
setSpeed(speed);
setDirection(direction);
setName(name);
}
/** Ship
* (=0, =0, speed=1.0, direction=0.0).
public Ship(String name) {
setName(name);
}
/** .
* .
public void move() {
movelnternal(1);
}
/'^'^ N . */
public void move(int steps) {
movelnternal(steps);
private void movelnternal(int steps) {
double angle = degreesToRadians(direction);
X = X + (double)steps * speed ^ Math.cos(angle);
= + (double)steps * speed ^ Math.sin(angle);
}
private double degreesToRadians(double degrees) {
return(degrees * Math.PI / 180.0);
}
/** . */
public void printLocation() {
System.out.println(getName() + " is at (" + getX() +
"," + getYO + " ) . " ) ;
}
/** X. */
public double getX() {
return(x);
}
/k-k X. */
public void setX(double x) {

7.6.

this.x = ;
}
/** Y. */
public double getY() {
return();
/ . */
public void setY(double ) {
this. = ;
}
/** . */
public double getSpeedO {
return(speed);
}
/ . '^/
public void setSpeed(double speed) {
this.speed = speed;
}
/**
*
*
*

(=, 90=,
180=, 270=).
(0=, 90= ..) ,
.

V
public double getDirection() {
return(direction);
j-k-k (=, 90=,
* 180=, 270=).
public void setDirection(double direction) {
this.direction = direction;
}
/** .
* .
public String getName() {
return(name);
}
private void setName(String name) {
this.name = name;

221

222

?. - ...

It'Hn^ffiPi'illfffflllHWIWIl
File

Edk

View

Fjvofites

Tools

Help

[JiSIiJ Deprecated Help


eqCVClASS NCCrCtASS
SUMUA4V; 1 irgtD lC<;tUS^a ^'

OITAlL: riCiD ICOMSTB '

Class Ship
I
+Ship

public class $1
extends Object
Ship exunpk to demonstnte OOP in Java.

Itpj

&yow}t

Constructor Sununaiy
iSli4fi<<iovaji* X, doubi* y , doubit s p t d , doublt
S'ibSLljUiil )
Build a sbp with specified perametere.

dirtction,

:SMp<S':vin:t n*ike)
\
Build a ship with default values (, y-0, sped-l .0, diction-0.0).

Method Smmnary

d
; ^ My Compu

. 7.1. javadoc
Java

7.6. ShipTest.Java
p u b l i c c l a s s ShipTest {
p u b l i c s t a t i c void m a i n ( S t r i n g [ ^ args) {
Ship s i = new S h i p ( " S h i p l " ) ;
Ship s2 = new S h i p ( 0 . 0 , 0 . 0 , .Or 135.0, "Ship2");
s1.move();
s2.move(3);
si.printLocation();
s2.printLocation();
}
}
:
javac ShipTest.Java
Java ShipTest
j a v a c
S h i p . Java. Java-

7.7. Javadoc

223

. c l a s s , ,
( )')
. , Java
make-;
. , . c l a s s
, , . J a v a ,
.


Java -.
javac
.
:
Shipl is at (1,0).
Ship2 i s a t ( - 4 . 2 4 2 6 4 , 4 . 2 4 2 6 4 ) .

7.7.Javadoc
j a v a d o c JDK, a
.
, " / * * " " * / " .

, . j a v a d o c
, ,
p r i v a t e .

, .
j a v a d o c
. :
javadoc Foo.java
javadoc Foo.java Bar.Java
javadoc graphics.newWidgets
javadoc graphics.newWidgets math.geometry
j a v a d o c .
,
:
javadoc -author -version SomeClass.Java
javadoc -noindex -notree somePackage
7.10.
j a v a d o c HTML-
-. ,
HTML-. <
HREF=" . . . "> Web-
, IMG

224

7. - ...

, APPLET,
. javadoc- ,
,
j avadoc. , PRE, .
, ,
. )' j a v a d o c
:
Javadoc 1.3
http://Java.sun.com/j2se/l.3/docs/tooldocs/javadoc/
Javadoc Tool Reference Page
http://Java.sun.com/j2se/l.3/docs/tooldocs/solaris/javadoc.html
http://Java.sun.com/j2se/l.3/docs/tooldocs/win32/javadoc.html
API
http://Java.sun.com/j2se/l.3/docs/tooldocs/javadoc/overview.html
http://Java.sun.com/j2se/l.3/docs/tooldocs/javadoc/doclet/

javadoc
HTML j a v a d o c
,
. , , @param
, , @return ,
@see ,
)^ . ,
.
/** .
* @param degrees .
* @return .
* @see t r a d i a n s T o D e g r e e s .
p u b l i c double degreesToRadians(double degrees) {
r e t u r n ( d e g r e e s * Math.PI / 1 8 0 . 0 ) ;
}

.
,
.
,
. , , JDK 1.1
.

7.7. Javadoc

225

author
@ a u t h o r .
, " j a v a d o c - a u t h o r
. . .". @ a u t h o r HTML- ,
:
/** SomeClass
* @author < HREF="mailto:ellison@microsoft.com">
*
Larry Ellison</A>

V
deprecated
@ d e p r e c a t e d , ,
,
. ,
, .
{@docRoot}[Java 1.3]

^' .
,
;
, . ,
c o r e w e b p r o g r a m m i n g / S h i p . J a v a
,
<

href="{@docRoot}/license.html">


< href="../license.html">
,
corewebprograiraning.

licence.html

exception
,
, .
{@link}Uaval.2]
0 s e e , ,
"See Also" (. )
.
. , S h i p . J a v a
.
change the location of a ship use
{(Slink #move(int) move}.

226

7. - ...

:
change the location of a ship use
<a href="Ship.html#move(int)">move</a>.

@param
@param , (
). ,
.
return
, .
@see
@see .
"#".
, . :

* @see #getWidget
* @see Widget
* @see Frob#setWidget

V
public void setWidget(Widget w) { ... }

@serial[Java 1.2]
@serialData[Java 1.2]
@serialField[Java 1.2]
, ,
( S e r i a l i z a b l e ) . ,
. ObjectStream
F i e l d , E x t e r n a l i z a b l e .
h t t p : / / J a v a .
sun.com/j 2 s e / l . 3 / d o c s / g u i d e / s e r i a l i z a t i o n / s p e c / s e r i a l - a r c h . d o c 6 . h t m l .
since
"Since",
, .
,
, .
throwsljava 1.2]
@throws , .
,
.

7.7. Javadoc

227

version
A v e r s i o n
. j a v a d o c ,
: " j a v a d o c - v e r s i o n . . . ".

javadoc
j a v a d o c ,
. , @ a u t h o r @ v e r s i o n ,
,
.
javadoc -author -version -noindex -notree Class.Java
JDK l.S - 40
j a v a d o c . .
-author
) j a v a d o c ,
. .
-bottom[Java 1.2]
b o t t o m ,
) ^ . .
, .
-classpath
-sourcepath
j a v a d o c , . J a v a .
Solaris , Windows
. , CLASS PATH,
.
-d
HTML-.
.
, HTML- ,
. - d ,
i m a g e s , , .
-encoding
-docencoding

( - e n c o d i n g ) ( - d o c e n c o d i n g ) .

228

7. - ...

-link [Java 1.2]


-linkoffline [Java 1.2]
l i n k j a v a d o c ,
. ,
, j a v a . s u n . c o m ,
l i n k :
-link http://Java.sun.com/j2se/l.3/docs/api

j a v a d o c
p a c k a g e - l i s t , URL.
Internet p a c k a g e - l i s t
l i n k o f f l i n e .
JDK 1.3, Java- / r o o t / j d k l . 3 / d o c s /
a p i . Windows,
:
-linkoffline

http://Java.sun.com/j2se/l.3/docs/api
c:\jdkl.3\docs\api

-J
j a v a d o c no Java-. - J
Java. ,
, (24 )
1:
javadoc -J-ms24m . . .
-nodeprecated
-nodeprecatedlist [Java 1.2]
javadoc , ,
, .
d e p r e c a t e d - l i s t . h t m l
, , .
.
-noindex
j a v a d o c , AllNames . html
. .
.
-nonavbar [Java 1.2]
nonavbar
.
-notree
j a v a d o c , t r e e . h t m l
.

7.7. Javadoc

229

-public
-protected
-package
-private
, ,
. ,

. p r o t e c t e d ,
, p u b l i c p r o
t e c t e d . ,
, ,
, p r i v a t e .
-splitindex [Java 1.2]

. .
, ,
.
-verbose
j a v a d o c ,
, .
-version
v e r s i o n ,
@ v e r s ion. .
-windowtitle [Java 1.2]
HTML- ,
. ,
, < t i t l e > < / t i t l e >
HTML-. .
j a v a d o c JDK L3,
Windows 98, HTML-, . 7.L
>javadoc - a u t h o r - v e r s i o n -noindex - n o t r e e
-linkoffline
http://Java.sun.com/j2se/l.3/docs/api
c : \ j d k l . 3 \ d o c s \ a p i Ship.Java
! ,
. make javadoc. make- Windows ,
h t t p : / / j a v a . s u n . c o m / p r o d u c t s / j d k / j a v a d o c / m a k e f i l e s .
Javadoc Tool Reference
Page, h t t p : / / j a v a . s u n . e o m / j 2 s e / l . 3 / d o c s t o o l d o c s /
javadoc/index.html.

230

7. - .

7.8.
,
; .
e x t e n d s .
, ( C++
). , ,
, ( C++ ).

;
s u p e r . .
// ParentClass.Java: .
// , foo bar.
/ / .
public class ParentClass {
public int a;
private int b;
public ParentClass() { ... }
public ParentClass(double z) { ... }
public String foo(int x. String s) { ... }
private void bar() { ... }
}
//
//
//
//
//

ChildClass.Java: ParentClass.
a b, a foo bar.
,
baz. ChildClass
ParentClass.

public class ChildClass extends ParentClass {


public int c;
public ChildClass(double z) {
super(z); // ParentClass

p u b l i c void b a z ( b o o l e a n isReady)

,
s u p e r ,

. ,
, .
,
.
, .

7 . 8 .

231




super.
,
.

icTiaccoB. ,
, ,
.
. :
super.

___

(...)

s u p e r , s u p e r , ,
) , .
.
, p r o t e c t e d ,
p u b l i c .
: ,

s u p e r . ,
, ,
.. .
, , ;
s u p e r .


. super
,

.

, .
,
:
, .
.
. 7.7
S p e e d b o a t ,
p r i n t L o c a t i o n . ,
, 7.8.

232

7. - .

7.7. Speedboat.java
/** .
* 20 . */
public class Speedboat extends Ship {
private String color = "red";
/** Speedboat,
* . */
public Speedboat(String name) {
super(name);
setSpeed(20) ;
}
/** Speedboat . */
public Speedboat(double x, double y, double speed,
double direction. String name.
String color) {
super(x, y, speed, direction, name);
setColor(color);
}
/** . . */
public void printLocation() {
System.out.print(getColor().toUpperCase() + " " ) ;
super.printLocation0;
/** Speedboat. */
public String getColor() {
return(color) ;
j-k-k Speedboat. */
public void setColor(String colorName) {
color = colorName;

7.9.

233

7.8.SpeedboatTest.Java
/** , Speedboat Ship. */
public class SpeedboatTest {
public static void main(String[] args) {
Speedboat si = new Speedboat{"Speedboatl");
Speedboat s2 = new Speedboat(0.0, 0.0, 2.0, 135.0,
"Speedboat2", "blue");
Ship s3 = new Ship(0.0, 0.0, 2.0, 135.0, "Shipl");
s1.move();
s 2.move() ;
s 3.move();
si.printLocation()
s2.printLocation()
s3.printLocation()

:
javac -depend SpeedboatTest.Java
Java SpeedboatTest

S p e e d b o a t . j ava S h i p . j ava.

:
RED Speedboatl is at (20,0).
BLUE Speedboat2 is at (-1.41421,1.41421).
Shipl is at (-1.41421,1.41421).
C++ L i s p / C L O S , Java .
lOiacc , . Java
Smaltalk. ,
. Java
, ,
.

7.9.
, ,
, ,
. ,
,
, .
a b s t r a c t ,
.
7.9 S h a p e .
,
(getX, g e t Y ..), S h a p e .

234

7. - ...

7.9. Shape.java
/ . */
public abstract class Shape {
protected int x, y;
public int getX () {
return(x);
}
public void setX(int x) {
this.x = x;
public int getYO {
return(y);
}
public void setY(int y) {
this. = ;
}
}

Java ,
, .
public ReturnType methodName(Typel argl, Type2 arg2);
, ,
. ,
.
, ,
,
-.
)^ S h a p e ,
, . 7.10 7.11
S h a p e .
, ,
.
7 . 1 0 - C u r v e . j a v a
/ * , ( ) .
*
* .

public abstract class Curve extends Shape {}

7.9.

235

7.11.StraightEdgedShape.Java
/* ( ).
* Line, LineSegment,
* LinkedLineSegments Polygon.
public abstract class StraightEdgedShape extends Shape {}

, C i r c l e C u r v e ,
,
. ( a b s t r a c t )
g e t A r e . ,
,
. R e c t a n g l e

S t r a i g h t E d g e d S h a p e , .
, , ,
R e c t a n g l e C i r c l e ,
g e t A r e . , , ) ,
. C i r c l e [] ,
R e c t a n g l e [ ] . S h a p e [ ]
, ^ g e t A r e .
) , maxArea?
S h a p e ,
(, , \ ..). , ,
.
Java .
" " ,
. ,
. , ,
, ,
. 7.12.
7 . 1 2 . I n t e r f a c e l . j a v a
public interface Interfacel {
ReturnTypel methodl(ArgTypel arg)
ReturnType2 method2(ArgType2 a r g ) ;
}

c l a s s i n t e r f a c e ,
; (
). , p u b l i c ;
. ,
, 7.13.

236

7. 1- .

7.13.Classl.Java
// ,
// methodl method2.
public class Classl extends SomeClass
implements Interfacel {
public ReturnTypel methodl(ArgTypel arg) {
someCodeHere();
}
public ReturnType2 rnethod2(ArgType2 arg) {
someCodeHere0;

7.14.
7.14. Interf2.java
public interface Interface2 {
ReturnType3 methods( arg) ;

7.15 ,
.
7.15,Class2,java
// abstract,
// ,
// Interfacel Interf2.
public abstract class Class2 extends SomeOtherClass
implements Interfacel,
Interface2 {
}

7.9.

237

C l a s s 2 7.16.
7 . 1 6 . C l a s s 3 . j a v a
/ / ,
/ / methodl, methoci2 methods.
p u b l i c c l a s s Class3 extends Class2 {
p u b l i c ReturnTypel methodl(ArgTypel arg) {
someCodeHere() ;
}

public ReturnType2 method2{ArgType2 arg) {


someCodeHere();

public ReturnTypeS methods( arg)


someCodeHere() ;

,
. ( )
(
, ). ,
, .
, .
p u b l i c , s t a t i c f i n a l
, .
7.17.
7 . 1 7 . I n t e r f a c e s . J a v a
/ / .
/ / , .
p u b l i c i n t e r f a c e I n t e r f a c e s extends

Interfacel,
Interface2 {

i n t MIN_VALUE = 0;
i n t MAX VALUE = 1000;

Shape?
, ,
. Measurable, 7.18.

238

7. - .

7.18.Measurable.j ava
/** ,
* .
public interface Measurable {
double getAreaO;

Circle ,
Measurable ( 7.19).
7.19.Circle.Java
/ ( Circle). ,
* Circle Measurable.
public class Circle extends Curve implements Measurable {
private double radius;
public Circle(int x, int y, double radius) {
setX(x) ;
setY(y);
setRadius(radius);
}
public double getRadius() {
return(radius);
public void setRadius(double radius)
this.radius = radius;
}
/** Measurable. */
public double getAreaO {
returi> (Math. PI * radius * radius);

Measurable ,
, ,
. 7.20.

7.9.

239

7.20.MeasureUtil.Java
/** , ]^!
'^ Measurable.

V
public class MeasureUtil {
public static double maxArea(MeasuraUDle ml,
Measurable m2) {
return(Math.max(ml.getArea(), m2.getArea()));
}
public static double totalArea(Measurable[] mArray) {
double total = 0;
for(int i=0; i<mArray.length; i++) {
total = total + mArray[i].getArea0;
}
return(total);
}
}
,
M e a s u r a b l e , M e a s u r e U t i l .
7.21 7.22 P o l y g o n
. ,
,
.
7.21. Polygon.java
/ * * .

*/

p u b l i c a b s t r a c t c l a s s Polygon e x t e n d s StraightEdgedShape
implements Measurable {
p r i v a t e i n t numSides;
p u b l i c i n t getNumSides()
return(numSides);

protected void setNumSides(int


this.numSides = numSides;
}
}

numSides) {

240

7. - ..

7.22. Rectangle. java


/** Rectangle getArea,
* Measurable,
* .
public class Rectangle extends Polygon {
private double width, height;
public Rectangle(int x, int y,
double width, double height) {
setNumSides (2);
setX(x);
setY(y);
setWidth(width);
setHeight(height);
}
public double getWidth() {
return(width);
public void setWidth(double width) {
this.width = width;
}
public double getHeightO {
return(height);
public void setHeight(double height) {
this.height = height;
}
/** ,
* Measurable.

public double getAreaO {


return(width * height);
}
}

,
S h a p e .
M e a s u r a b l e , ,
, ,
" i m p l e m e n t s M e a s u r a b l e " .
M e a s u r e U t i l
, , ^ g e t A r e a .
M e a s u r e U t i l 7.2S.

7.9. 1

241

, Java, ,
(
), .
, ,
,
, , .
\ .
, (, C++,
Eiffel, L i s p / C L O S ) , , , , Java ,
.
7.23. MeasureTest.java
/**
*
*
*

MeasureUtil. ,
measurables ,
Measurable.
.

public class MeasureTest {


public static void main(String[] args) {
Measurable[] measurables =
{ new Rectangle(0, 0, 5.0, 10.0),
new Rectangle(0, 0, 4.0, 9.0),
new Circle(0, 0, 4.0) ,
new Circle(0, 0, 5.0) };
System.out.print("Areas:");
for(int i=0; i<measurables.length; i++)
System.out.print(" " + measurables[i].getArea());
System.out.println();
System.out.println("Larger of 1st, 3rd: " +
MeasureUtil.maxArea(measurables[0] ,
measurables[2]) +
"\nTotal area: " +
MeasureUtil.totalArea(measurables));

( M e a s u r e U t i l )
; ,
, .
.
, ,
, . , ,
, ,
, , d e b u g ,
, . Java,
,

(Debuggable).

242

7. - ...

,
, ,
. Java . ,
,
, , .

7.10. , CLASSPATH JAR-


Java ,
.
. , Ship
Shape , .
packagename
.
:
package packagename;

, ,
. , ,
import packagename.ClassName;

import packagename.*;

,
. , ( "*"
) )' .
import ,
CLASSPATH ( CLASSPATH
).
(". "). ,
, . , ,
Windows 2000 NT
: \ J a v a \ c l a s s e s . , ,
7.24-7.27,
.

packagel (: \ J a v a \ c l a s s e s \ p a c k a g e l ) C l a s s l .

package2 ( : \ J a v a \ c l a s s e s \ p a c k a g e 2 ) C l a s s 2 .

2 . ( C : \ J a v a \ c l a s s e s \ p a c k a g e 2 \ p a c k a g e 3 )
C l a s s 3 .

package4 (: \ J a v a \ c l a s s e s \ p a c k a g e 4 ) C l a s s l .

, p a c k a g e l package4
( c l a s s l ) . ,
i m p o r t _.
C l a s s l . . , ,

7.10. , CLASSPATH JAR-

243

A p p l e t
j a v a . a p p l e t . A p p l e t , a i m p o r t j a v a . a p p l e t .
A p p l e t ( i m p o r t J a v a , a p p l e t . *) A p p l e t .
, p r i n t l n f o
s t a t i c . ,
(, M a t h . c o s ) .
7 . 2 4 . : \ J a v a \ c l a s s e s \ p a c k a g e l \ C l a s s l . J a v a
package p a c k a g e l ;

public class Classl {


p u b l i c s t a t i c void p r i n t l n f o ( ) {
S y s t e m . o u t . p r i n t l n ( " T h i s i s C l a s s l in p a c k a g e l . " )
}
}

7.25. :\Java\classes\package2\Class2.java
package package2;
public class Class2 {
public static void printlnfo() {
System.out.println("This is Class2 in package2.");
}
}

7.26. :\Java\classes\package2\package3\Class3.java
package package2.;
public class Class3 {
public static void printlnfo() {
System.out.println("This is Class3 in " +
"package2..");
}
}

7.27.:\Java\classes\package4\Classl.java
package package4;
public class Classl {
public static void printlnfo() {
System.out.println("This is Classl in package4."),
}
}

244

7. - .

, (
7.28). : \ J a v a X c l a s s e s .
7.28.:\Java\classes\PackageExample.Java
import packagel.*;
import package2.Class2;
import package2.packages.*;
p u b l i c c l a s s PackageExample {
p u b l i c s t a t i c void m a i n ( S t r i n g [ ] args) {
Classl.printlnfo() .
Class2.printlnfo() ,
C l a s s 3 . p r i n t l n f o (),
package4.Classl.printlnfo(
}

:
j a v a c PackageExample.Java
Java PackageExample

.
:
This
This
This
This

is
is
is
is

Classl
Class2
Class3
Classl

in
in
in
in

packagel.
package2.
package2..
package4.

PackageExample. Java
, Example .
,
.
javac
javac
javac
javac

packagel/Classl.Java
package2/Class2.Java
package2/package3/Class3.Java
package4/Classl.Java

, ,
, .
1. ,
. , j a v a c p a c k a g e 2 / C l a s s 2 . Java,
C : \ J a v a \ c l a s s e s \ , C : \ J a v a \ c l a s s e s \
p a c k a g e 2 \ C l a s s 2 . Java, package2.

7.10. , CLASSPATH JAR-

245

2. , , ,
CLASSPATH
, . ,
,
CLASSPATH : \ J a v a \ c l a s s e s .

CLASSPATH
, Java-
. ,
. Java
. , .
;
. , , ,
, i m p o r t ,
. Java
JAR-.
.
. -,
j a v a c J a v a - c l a s s p a t h . -,
CLASSPATH.
. CLASSPATH ,
Java .
;
CLASSPATH, , (.).
(
) . , UNIX ( c s h , t c s h )
, CLASSPATH, :
setenv CLASSPATH

.:-/classes:/home/mcnealy/classes

Windows 9 8 / 2 0 0 0 / N T :
set CLASSPATH=.;:\BillGates\classes;D:\Java\classes
MacOS ,
, 'STR ). Java,
, .
,
Java-; .
, j a v a . l a n g . * .
, Netscape a p p l e t v i e w e r ,
, ,
CLASSPATH. .
- ,
, 1, ,
. ,
CLASSPATH .

246

7. - ...

CLASSPATH.

JAR-
CLASSPATH
, .
, , CLASS PATH
,
. , Java
Java- (JAR). JDK j a r ,
JAR-. ,
ZIP-.
, j .

JAR- .
f
f JAR-.
,
( ) ,
( JAR-, JAR-)
(manifest file). m f,
JAR- .
( ) ,
. ;
, JAR-.
h t t p : / / J a v a . s u n . c o m / d o c s / b o o k s / t u t o r i a l /
jar/basics/manifest.html.
t
JAR-.
u
JAR-,
.
V

V .

, JAR-.
, .

7 . 1 1 .

247

( "") JAR-.
,
C l a s s X . c l a s s , ,
JAR-.
:\Java\classes>jar

cfv e x a m p l e . j a r p a c k a g e l package2

package4

:
added manifest
adding: packagel/(in = 0) (out= 0)(stored 0%)
adding: packagel/Classl.class(in = 4 68)
(out= 326)(deflated 30%)
adding: package2/(in = 0) (out= 0)(stored 0%)
adding: package2/Class2.class(in = 4 68)
(out= 327)(deflated 30%)
adding: package2/package3/(in = 0) (out= 0)
(stored 0%)
adding: package2/package3/Class3.class(in = 486)
(out= 338)(deflated 30%)
adding: package4/(in = 0) (out= 0)(stored 0%)
adding: package4/Classl.class(in = 4 31)
(out= 298)(deflated 30%)
, , ,
. , e x a m p l e . j a r
.
, .
jar-
(? _.
jar-, CLASSPATH.
,
/ r o o t / j d k l . 3 / j r e / l i b / e x t / . JAR-, , Java
, , .

,

CLASSPATH, , -
/root/jdkl.3/jre/lib/ext/.
JAR-,

, .

7 . 1 1 .
,
: p u b l i c , p r i v a t e , p r o t e c t e d , s t a t i c .
,
.

248

7. - .


,
. ,
p u b l i c p r i v a t e
. C++, ,
, C++.

7.1.


public,

private

protected

( )

public
,
, .
, ;
j a v a d o c .
,

.
. S h i p
( 7.5); JavaBeans.
, ""
,
( ). ,
, ,
, .
J a v a . a w t . P o i n t ,
X , p u b l i c ,
, .

p u b l i c .

7 . 1 1 .

249




public.

p u b l i c ,
.
, .
private
,
. p r i v a t e
,
, .
protected
,
, .
, p r o t e c t e d , -
.
,
p r i v a t e , ,
.
( )
,
,
. .
.


static
,
. ,
s t a t i c , , . ,
, Foo b a r
f o o l f 2 , b a r
: f o o l . b a r , f 2 . b a r Foo , b a r .
.
( ) M a t h , c o s ,
Math , c o s .

.
, . 7.29

250

7. - ..

main.
s t a t i c M e t h o d , regularMethod
.
7.29. Statics.java
pmi
public class Statics {
public static void main(String[] args) {
StaticMethod{);
Statics si = new Statics();
si.regularMethod{) ;
public static void staticMethod() {
System.out.println("This is a static method.");
}
public void regularMethod() {
System.out.println("This is a regular method.");
}
}

final
f i n a l ,
.
. f i n a l
, ,
.
, , f i n a l , .
abstract
,
. a b s t r a c t
, .
synchronized
s y n c h r o n i z e d
. , s y n c h r o n i z e d ,
.
16.
volatile
Java
,
. (, long)

. v o l a t i l e
.

7 . 1 1 .

251

transient
, t r a n s i e n ,
.
native
, C++.

7.12.
Java -
. ,
Java. ,
( ) ( ).
, ,
. Java
,
, . ,
, j a v a d o c
.
, ,
Java .
, , ..
" ". ,
8, "" ;
Java. C++,
)^ , Java .

JAVA
...
.
,
.
.
.
.
, ,
Java.
.
.
.
.
.
.

Sl/\ZJ^ZJ

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

8 . 1 .

, , " ".
Java.
,
, ,
. Java (,
" / * " " * / " ) (,
" / / " ).
,
.
,
, . ,
)' .
Java-, , , .

254

8. Java

/* .
. . */
//
while (int i=l; i<=5; i++) {
if (i==2)
System.out.println("Tea for two.");
else
System.out.println("Not two.");
}

Bee .
Java
:
while(int i=l;i<=5;i++){if(i==2)
System.out.println("Tea for two.");else
System.out.println("Not two.");}

, : " ' i n t i'?" ,


: i n t i.
, , Java-
, , ,
. ,

.
.
1. . , While
WHILE w h i l e .
2. ( )
("_") ,
. , ,
"$", ,
.
, , ,
, .
. , ,
,
,
,
.
Java The Java Language Specification,
h t t p : / / j a v a . s u n . c o m / d o c s /
books/jls/.

8 . 2 .

255

8.2.
Java , , ,
. , , ,
, . Java :
b o o l e a n , c h a r , b y t e , s h o r t , i n t , l o n g , f l o a t d o u b l e . ,
v o i d , .
boolean
: t r u e f a l s e .
C/C++, Java . :
boolean
boolean
boolean
boolean

flagl
flag2
flag3
flag4

= false;
= (6 < 7 ) ; // true
= !true;
// false
=0;
// !

char
16- , Unicode.
,
unicode- (\uXXXX, X
) \ (Baskspace), \ t (), \ (
), \ f ( ) , \ ( ), \ ( ), \ '
( ), \ \ ( ). :
char
char
char
char
char

= 3 ;
1 = ' Q ' ;
2 = ' \uOOOO'; / /
= ' \ u F F F F ' ; / /
4 = ' \ ' ;
/ / Backspace

Unicode h t t p : //www. U n i c o d e . o r g / .
byte
8- .
.
b y t e -128 --127.
short
s h o r t 16- .
.
s h o r t -32768 +32767.
int
32- .
.
( 1, 10 100 1, 10 100),
( 1, 10 100 0 1 ,

256

8. Java

012 0144) ( 1, 10 100


0x1, 0x64). , 9,
, , , D, F.
i n t I n t e g e r .MIN_VALUE (-2 )
I n t e g e r . MAX_VALUE (2"' -1). :
int
int
int
int

iO
il
i2
13

=
=
=
=

0;
-12345;
OxCafeBabe; // "" .class
0777;
// ,
// 511

long
64- .
.
L, . 1
,
, 1 1.
,
. l o n g
L o n g . MIN_VALUE (-2"") Long . MAX_VALUE (2''-1). :
long
long
long
long

al
2

=
=
=
=

0L;
-123451;
OxBabeL; // ,
-067671;

c h a r , ( b y t e , s h o r t , i n t l o n g )
. C^-^-, Java
. , ( b y t e s h o r t ) ,
,
. , ,
, b y t e ,
, b y t e , 127.
s h o r t , i n t l o n g . , i n t
.
float
f l o a t 32- IEEE
754.
f F.
f ,
,
f l o a t .
float

fO = - 1 . 2 3 f ;

10 . ,
1 f l 6.02x10"^ ,
f 2 4.5x10 .

8.2.

257

float fl = 6.02E23F;
float f2 = 4.5e-17f;

F l o a t . MIN_VALUE (1.4x10"'") F l o a t .MAX_VALUE (3.410'').

. F l o a t
POSITIVE_INFINITY, NEGATIVE_INFINITy NaN (not-a-number
). NaN F l o a t . isNaN.
( F l o a t . NaN == F l o a t . NaN) f a l s e .
IEEE ,
NaN.
double
64- IEEE
754.
d D, .
.
double
double
double
double

dO
d2
d3
d4

=
=
=
=

1.23;
-4.56d;
6.02214E+23;
le-99;


D o u b l e . MIN_VALUE (4.910'''') D o u b l e .MAX_VALUE (1.710'"').
f l o a t ,
. D o u b l e
POSITIVE_INFINITY, NEGATIVE_INFINITY NaN.
D o u b l e . NaN D o u b l e . isNaN.



Java . :
2 t y p e 2 V a r =

(2)typelVar;

B ,
, , . :
int 1 = 3 ;
byte b = (byte)i; // i ;
//
long X = 123456L;
short s = (short); // short
//
, s ,
123456 16- .
,
.

258

8. Java

double d = 3.1416;
float f = (float)d; //
// 32-
short S = (short)f; // float short
int i = s; //
// ;
,
Math, .
, ,
. , ,
/ a f Language Specification,
h t t p : / / J a v a . s u n . c o m / d o c s / b o o k s / j I s / .

8.3. ,
(+, - , * ..),
( i f s w i t c h ) ( w h i l e f o r ) .

( ). , , C++
:
Point pl(3,4)f 2(1,3); // C++
1 += 2; // 1 2
Java .
, , .
1.translate(2);


. 8.1. , ,
, .
:
Math. , + .

8 . 1 .

+,

X = + 5;

, ,

i n t X = 3, = 2;
i n t Z = X / ;

/ /

/
/

i n t i = 1, j = 1 ;
^^^ ^ ^ i++/ / / = 1 ,
i n t = ++J; / / =2,

1=2
j=2

8.3. ,

259

. 8.1
/ / >

Scf

\f

i n t = 3;
int = X

2; / / 12

i n t = ~127; / / -128

And, Or,

i n t = 127 & 2; / / 2
i n t = 127 I 2; / / 127
i n t z = 127 ^ 2; / / 125

Java, C++, :
= ;

= ;
,
1=1+5;
X = X + 3;


1 += 5;
X += 3 ;


Java if, switch "? :",
. 8.2 . C++,
,
C/C++, ,
. ,
, . 8.3.

8.2.

if

if

{_)
;

(_)
!/
} else {
2;

if

?:

_? ! : 2;

260

8. Java

. 8.2
g^.^j^j^

s w i t c h () {
c a s e ! : !;
breaksc a s e 2 : 2;
2;
breaksd e f a u l t : ;
}

8.3.

==,

!=

< <= f >/


&&/
!

Ii

, . ,
== ,
>=

"", " ", "", "


",
AND, OR.

if {_:)
if {_)

! e l s e 2

i f ( b o o l e a n ) .
t r u e , ,
. f a l s e ,
, e l s e (
). i f ,
b o o l e a n , . Java
C++, , ,
t r u e . }' :
/ / . Math.max
public static int max2(int nl, int n2) {
if (nl >= n2)
return(nl);
else
return(n2);
}
i f - e l s e ,
. :

8.3. ,

261

public static int inax2Verbose(int nl, int n2) {


if (nl >= n2) {
System.out.println(nl + " is larger.");
return(nl);
} else {
System.out.println(n2 + " is larger.");
return(n2);
}
}
, else if,
else . :
public static int max3(int nl, int n2, int n3) {
if (nl >= n2)
if (nl >= n3)
return(nl);
else
return(n3);
else
if (n2 >= n3)
return(n2);
else
return(n3);
}

i f
e l s e . , i f
1, , ,
.
i f
, .
, .
/ /
p u b l i c SomeType someMethod(...) {
if {
statementl;
statementN
} else {
statementA;
statementZ;
}
}

/ /
p u b l i c SomeType someMethod(...)
{ if
{ statementl;
StatementN;
} else
{ StatementA;

262

8. Java
statementZ;
}
}

//
public SomeType someMethod(...)
{
if
{
statementl;
statementN;
}
else
{
statementA;
StatementZ;
}
}

, && ( ,
AND) | | ( , OR).
C/C++, " ".
, ,
,
. , ,
&& && f a l s e , f a l s e ;
&& . ,
, | |, t r u e ,
t r u e . :
public static int max3(int nl, int 2, int ) {
if ((nl >= n2) && (nl >= ))
return(nl);
else if ((n2 >= nl) && (n2 >= n3))
return(n2);
else
return(n3);
}
, & |,
, .
.
__ ? _1: _15
i f , Java ,
.

if (someCondition)
someVar = valuel;
else
someVar = value2;

8.3. ,

263

:
someVar = (someCondition ? valuel : value2);

,
, . , 2
:
public static int max2Short(int nl, int n2) {
return((nl >= n2) ? nl : n2);
}

switch {) { _ ]
s w i t c h ,
( c h a r , b y t e , s h o r t , i n t ,
long). s w i t c h
, ,
c a s e .
,
c a s e .
.
p u b l i c s t a t i c S t r i n g number(int d i g i t ) {
switch(digit) {
case 0: r e t u r n " z e r o " ) ;
case 1: r e t u r n ("one");
case 2: r e t u r n ("two");
case 3: r e t u r n ( " t h r e e " ) ;
case 4: r e t u r n ( " f o u r " ) ;
case 5: r e t u r n f i v e " ) ;
case 6: r e t u r n ( " s i x " ) ;
case 7: r e t u r n " s e v e n " ) ;
case 8: r e t u r n " e i g h t " ) ;
case 9: r e t u r n " n i n e " ) ;
default: return("Not a single d i g i t " ) ;


. ,
s w i t c h , ,
:
c a s e ,
c a s e , c a s e . ,
, s w i t c h
.
switch(val) {
case testl:
case test2:
actionForTestland2();
}

264

8. Java

, )^ c a s e ,
b r e a k r e t u r n .
, ,
:
// ,
// switch.
public static String numberVerbose(int digit) {
String resultsswitch (digit) {
case 0: System.out.println("zero") ;
result = "zero";
case 1: System.out.println("one");
result = "one";
case 2: System.out.println("two");
result = "two";
case 3: System.out.println("three");
result = "three";
case 4: System.out.println("four");
result = "four";
case 5: System.out.println("five");
result = "five";
case 6: System.out.println("six");
result = "six";
case 7: System.out.println("seven");
result = "seven";
case 8: System.out.println("eight");
result = "eight";
case 9: System.out.println("nine");
result = "nine";
default: System.out.println(
"Not a single digit");
result = "Not a single digit";
}
return(result)
c a s e ,
, .
n u m b e r V e r b o s e (5) :
five
six
seven
eight
nine
Not a single digit
, ,
c a s e , b r e a k , :
public static String numberVerboseFixed(int digit) {
String result;
switch(digit) {
case 0: System.out.println("zero");

8.3. ,

265

result = "zero";
break;
case 1: System.out.println("one");
result = "one";
break;
default: System.out.println("Not a single digit");
result = "Not a single digit";
}
return(result);
}

Java , C/C++: w h i l e , do f o r .
. 8.4
. , Java b r e a k c o n t i n u e ,

.

8.4.

while

w h i l e {_) {
_1,;
}
do {
^;
] w h i l e {_) ;

do

for

tor {1,;
_1;
}

_;

) {

while
w h i l e , , ,
1 t r u e , . ,
max:
p u b l i c s t a t i c v o i d l i s t N u m s l ( i n t max) {
i n t i = 0;
w h i l e ( i <= max) {
System.out.println("Number: " + i ) ;
i++;
}
}

l i s t N u m s 1 ( 5 ) :
0:
1:

zero
one

266

8. Java

2: two
3: three
4: four
do
do w h i l e ,
. ,
.
, do. l i s t N u m s 2 (5)
, , l i s t N u m s 2 ( - 5 ) ,
"Number : ". : l i s t N u m s l (-5)
. , do
, w h i l e
. l i s t N u m b e r (-5) .
public static void listNums2(int max) {
int i = 0;
do {
System.out.println("Number: " + i ) ;
i++;
} while (i <= max); //
}
,
: d o .
for

f o r . .
, , t r u e ,
.
l i s t N u m s 3 ,
, .
public static void listNums3(int max) {
for(int i=0; i<max; i++) {
System.out.println("Number: " + i ) ;
}
}
Java ( )
f o r . , ,
t r u e . :
for(;;)

{ / * */ }

while(true) { /* */ }
f o r ,
.
, r e t u r n b r e a k .

8.3. ,

267

while, do for ,
.
, .
for, ,
. while, ,
.
8.1 while.
while .
. , , ,
.
. DropBall 8.2.

8.1. DropBall.Java
/*
*
(550 ). ,
* , .

V
public class DropBall {
public static void main(String[] args) {
int time = 0;
double start = 550.0, drop = 0 . 0 ;
double height = startswhile (height > 0) {
System.out.println("After " + time +
(time==l ? " second, " : " seconds,") +
"the ball is at " + height + " feet.");
time++;
drop = freeFall(time);
height = start - drop;
}
System.out.println("Before " + time + " seconds could " +
"expire, the ball hit the ground!");
}
/** .
public static double freeFall (float time) {
// 32 / '^2.
return(16. * time * time); // 1/2 gt^2

268

8. Java

8.2. DropBall
Prompt> Java DropBall
After 0 seconds,the ball is at
After 1 second, the ball is at
After 2 seconds,the ball is at
After 3 seconds,the ball is at
After 4 seconds,the ball is at
After 5 seconds,the ball is at
Before 6 seconds could expire,

550.0 feet.
534.0 feet.
486.0 feet.
406.0 feet.
294.0 feet.
150.0 feet.
the ball hit the ground!

8.4. Math
Math ,
. s t a t i c ,
Math.

public static Hnal d o u b l e E


, .. 2.7182818284590452354.
public static final d o u b l e P I
, . .
3.14159265358979323846.


public static int abs(int n u m )
public static l o n g abs(long n u m )
public static float abs(float n u m )
public static d o u b l e a b s ( d o u b l e n u m )
.
public static d o u b l e c e i l ( d o u b l e n u m )
public static d o u b l e

floor(double

num)

c e i l d o u b l e - ,
. f l o o r d o u b l e , .
public static e x p ( d o u b l e n u m )
"""\

8.4. Math

269

public static double IEEEremainder(double fl, double f2)


f 1 f 2
IEEE 754.
public static double log(double num)
. Java
(, 10 2).
:
1() = 12() / 12(1)
p u b l i c s t a t i c double l o g ( d o u b l e num, double base) {
return(Math.log(num) / M a t h , l o g ( b a s e ) ) ;
}

public static int max(int numl, int num2)


public static long max(long numl, long num2)
public static float max(float numl, float num2)
public static double max(double numl, double num2)
public static int min(int numl, int num2)
public static long min(long numl, long num2)
public static float min(float numl, float num2)
public static double min(double numl, double num2)
(max) (min) .
public static double pow(double base, double exponent)
pow base^'^^^"'^"'.
public static double random()
0.0 ()
1.0 ( ).
j ava . u t i l . Random.
public static double rint(double num)
public static int round(float num)
public static long round(double num)
.
, .5. round
, r i n t
, IEEE 754. r i n t
,
)^1 .
public static double sqrt(double num)
num (
) Double . NaN NaN .

270

8. Java


public static double sin(double radians)
public static double cos(double radians)
public static double tan(double radians)
,
, .
public static double toDegrees(double radians)
public static double toRadians(double degrees)

. , , 60 :
Math, sin (Math. toRadians (60.0) )

public static double acos(double val)


public static double asin(double val)
public static double atan(double val)
,
. .

Biglnteger BigDecimal
Java : Java.math.
B i g l n t e g e r Java .math . BigDecimal. ,
, , , ,
.
,
, . ,
, B i g l n t e g e r ,
, . 8.3
B i g l n t e g e r N ! ( N,
.. N* (N-1) * (N-2) * . . . *1) N.
8.4.
8.3. F a c t o r i a l . j a v a
import

Java.math.Biglnteger;

/** B i g l n t e g e r .

*/

public class Factorial {


p u b l i c s t a t i c void m a i n ( S t r i n g [ ] args) {
f o r ( i n t i = l ; i<=256; i'^=2) {
S y s t e m . o u t . p r i n t l n ( i + "!=" + f a c t o r i a l ( i ) ) ;
}
}

8.5.

271

public static Biglnteger factorial(int n) {


if (n <= 1) {
return(new Biglnteger("1"));
} else {
Biglnteger bigN = new Biglnteger(String.valueOf(n));
return(bigN.multiply(factorial(n - 1) ) ) ;
}
}
}

8.4. F a c t o r i a l

Prompt> Java Factorial


1!=1
2! =2
4 !=24
81=40320
161=20922789888000
32 1=2 6313083 6933 693530167218012160000000
64 1=12 688 693218588 41641034 3338 93351614 808028 6551617 4 54 51921988018 94 375
2147 042 304 00000000000000
128 1=3856204 823 625804 217 3567 7 0 6592 34 63 64 0 617 4 9310 95902235 9027 882 8 4 0327
637 34 0257 516554 35 60 68 616858 8 507 3 61534 0300518 33058 91634 7 592172 9322 624 98
8577 66114 9552 4 503 9357 7 60034 64 4 7 0927 92 4 7 692 4 955852800000000000000000000
00000000000
2 561=8 57 8177 7 534 28 4 2 654119082271681232 62 5157 7 8152027 94 856198 5 9 655 65037
72 694 5255314 7 58 9377 4 4 02 913 604 514 08 4 5037 58 8534 233 658 4 30 615719 6834 693 69
4 7 532228 9288 4 97 4 2 602567 9 637 3325 633 687 8 64 4 2 67 5207 62 67 94 560187 968 8 67 9
2114 330770207752 664 64 514 6470 918732 610083287 6325702818 9807736717814 5417
0250523018 6084 953190 6813 8257 4 81070252817 5594 594 7 6987034 66571273813 928 6
205234 7568082188 607 01203 6110831520 9350194 7 4 3710 910172 69 682 628 616062 63 6
624 350228 4 0 94 41914 084 24 61593 600000000000000000000000000000000000000000
0000000000000000000000

!
java .math,
Biglnteger
BlgDeclmal, java. lang.Math. Math
. ,
.

8.5.
,
-.

272

8. Java


S y s t e m . o u t . p r i n t l n .
Java, , out
System, , ( P r i n t S t r e a m ) ,
p r i n t l n . p r i n t l n P r i n t S t r e a m
p r i n t . , p r i n t l n ,
. p r i n t l n ( p r i n t )
.
S t r i n g . valueOf, ,
S t r i n g , t o S t r i n g ,
.
-. p r i n t l n .
System.out.println(2 + '' + " ||

! " + new I n t e g e r ( 2 ) + "");

p r i n t l n p r i n t P r i n t S t r e a m f l u s h .
, , ,
. J a v a . i o . P r i n t S t r e a m
API.
, Java
, p r i n t f s p r i n t f .
J a v a . t e x t . DecimalFormat.
, .
format.
8.5, 8.6.
8.5. NumFormat. java
import

java.text.*;

/** DecimalFormat. */
public class NumFormat {
public static void main (String[] args) {
DecimalFormat science = new DecimalFormat("0.OOOEO");
DecimalFormat plain = new DecimalFormat("0.0000");
for(double d=100.0; d<140.0; d*=1.10) {
System.out.println("Scientific: " + science.format(d)
" and Plain: " + plain.format(d));
}
}

8.5.

273

8 . 6 . NumFormat

Prompt> Java NumFormat


Scientific: 1.000E2 and
Scientific: 1.100E2 and
Scientific: 1.210E2 and
Scientific: 1.331E2 and

Plain:
Plain:
Plain:
Plain:

100.0000
110.0000
121.0000
133.1000

D e c i m a l F o r m a t
S t r i n g , .
, , . . 8.5
, . , ,
, ### . ,
. 23767.82
23,767.8, 0.43 .4 ( ).
D e c i m a l F o r m a t
. D e c i m a l F o r m a t -
, p r i n t f .
h t t p : //www. acme . c o m / j a v a / s o f t w a r e / A c m e . Fmt. h t m l .
, S y s t e m , o u t ,
. ,
, , .
S y s t e m , s e t Out, P r i n t S t r e a m ,
.

8.5. ,

. ,

,
""

100


S y s t e m , o u t Java S y s t e m , e r r ,
.
P r i n t S t r e a m S y s t e m , o u t .
, S y s t e m . s e t E r .

274

8. Java


,
Java. , ,
,
.
, .
,
S y s t e m , i n Buf f e r e d R e a d e r :
BufferedReader keyboard =
new B u f f e r e d R e a d e r (
new I n p u t S t r e a i u R e a d e r ( S y s t e m , i n ) ) ;
r e a d L i n e
BufferedReader:

String line = keyboard.readLine();

8.6. , Java

, Java- ( Java-)
.
.
1. Runtime.
g e t R u n t i m e R u n t i m e .
Runtime r t

= Runtime.getRuntime();

2. . e x e c ,
P r o c e s s .

Process proc = rt.exec("someProgram");


,
. , e x e c
PATH,
. , e x e c ,
">" " I ", . , R u n t i m e
e x e c ,
S t r i n g ,
. :

String[] args = { "-1", "*.java" };


rt.exec{"Is", args); // .
3. ( ).
e x e c ,
, .
, .
e x e c .

8 . 6 . , Java

275

,
,
w a i t F o r .
proc.waitFor()/
, ,
j a v a c ,
J a v a . ,
. , w a i t F o r
, .
4. (
). ,
,
. , , ,
, , .
,
Buf f e r e d R e a d e r , :
try {

BufferedReader buffer =
new BufferedReader(
new InputStreamReader(proc.getInputStream()));
String s = null;
while ((s = buffer.readLine()) != null) {
System.out.println("Output: " + s);
}
buffer.close()/
} catch(Exception e) {
/* */
}
8.7
E x e c , e x e c , e x e c P r i n t e x e c W a i t . ,
, 8.8.

, . ,
, " " ,
.
!
.

, " ".

276

8. Java

.?. Exec. Java


import
/**
^
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*

java.io.*;

,
. :
<0L>
<LI><B>exec</B>:
, .
, .
<LI><B>execWait</B>:
, .
,

(, <CODE>javac</CODE> <CODE>java</CODE>).
<LI><B>execPrint</B>: ,
. UNIX
<CODE>ls</CODE>.
</0L>
, PATH ,
<></> . ,
. , UNIX

<0L>
<LI><PRE>Exec.exec("/usr/ucb/lpr Some-File");</PRE>
<LI><PRE>Exec.execWait("/usr/local/bin/javac Foo.java");
Exec.execWait("/usr/local/bin/Java Foo");</PRE>
<LI><PRE>Exec.execPrint("/usr/bin/ls -al");</PRE>
</0L>

public class Exec {


private static boolean verbose = true;
/** , Exec
* .
'^ true.
* @param verboseFlag true: , false: .
public static void setVerbose(boolean verboseFlag) {
verbose = verboseFlag;
}
/** Exec ? */
public static boolean getVerboseO {
return(verbose);
/** .
* ,
* .

8.6. , Java

*
*
*
*
*
*
*

0param command <></>


. (, "cd")
(, ">") .
@return false,
,
, .
true.

V
public static boolean exec(String command) {
return(exec(command, false, false));
}
/*"^ .
* , .
*
*
*
*
*
'^
*

@param command <></>


.
.
@return false,
. ( ,
, . )
true.

public static boolean execWait(String command) {


return(exec(command, false, true));
}
/** .
* , .

*
*
*
*
*
*
*

@param command <></>


.
.
(return false,
. ( ,
, .)
true.

V
public static boolean execPrint(String command) {
return(exec(command, true, false));
/**
*
*
*
*

Process Runtime.getRuntime.exec()
,
waitFor,
,
.

V
private static boolean exec(String command,
boolean printResults,
boolean wait) {

277

278

8. Java

if (verbose) {
printSeparator();
System.out.println("Executing '" + command + " ' . " ) ;
}
try {
// ; .
Process = Runtime.getRuntime().exec(command);
// .
// , ,
// ,
if(printResults) {
BufferedReader buffer = new BufferedReader(
new InputStreamReader(p.getlnputstream()));
String s = null;
try {
while ((s = buffer.readLine()) != null) {
System.out.println("Output: " + s ) ;
}
buffer.close() ;
if (p.exitValue0 != 0) {
if (verbose) {
printError(command + " -- p.exitValue() != 0")
}
return(false);
}
} catch (Exception e) {
// .
// , .
}
// , waitFor,
// .
} else if (wait) {
try {
System.out.println ( " " ) ;
int returnVal = p.waitFor();
if (returnVal != 0) {
if (verbose) {
printError(command);
}
return(false);
}
} catch (Exception e) {
if (verbose) {
printError(command, e ) ;
}
return(false);
}
}
} catch (Exception e) {
if (verbose) {
printError(command, e ) ;
}
return(false);

8.6. , Java

279

return(true);
}

private static void printError(String command,


Exception e) {
System.out.println("Error doing exec(" + command + " ) :
e.getMessage());
System.out.println("Did you specify the full " +
"pathname?");

" +

private static void printError(String command) {


System.out.println("Error executing '" + command + "'.")
private static void printSeparator() {
System.out.println

8.8 Exec UNIX,


8.9.
8.8. ExecTest.Java
/** Exec. */
public class ExecTest {
public static void main(String[] args) {
// , "&" ,
// .
// exec ,
//
// Netscape.
Exec.exec("/us/local/bin/netscape");
// , .
Exec.execPrint("/us/bin/Is");
Exec.execPrint("/usr/bin/cat Test.Java");
// .
/ / .
Exec.execWait("/usr/javal.3/bin/javac Test.Java");
// Test.class .
Exec.execPrint("/usr/bin/ls");
}
}

280

8. Java

8.9. ExecTest
Unix> Java ExecTest
Executing '/usr/local/bin/netscape'.
Executing '/usr/bin/ls'.
Output: Exec.class
Output: Exec.Java
Output: ExecTest.class
Output: ExecTest.Java
Output: Test.Java
Executing '/usr/bin/cat Test.Java'.
Output: public class Test {
Output:
boolean flag;
Output: }
Executing '/usr/javal.3/bin/javac Test.Java'
Executing '/usr/bin/ls'.
Output: Exec.class
Output: Exec.Java
Output: ExecTest.class
Output: ExecTest.Java
Output: Test.class
Output: Test.Java

8.7.
, , ..
( ), ,
. Java ,
. Java
, , ,
Java . ! ^^ ,
, . ,
, ,
, , ,
. Java , codej)Maiu,eu ,
, .
,
. , Java
,
. ,
. ,
, Java .
, ,
.

8.7.

281

8.10,
8.11.
. 10. ReferenceTest.Java
import Java . awt. Pointspublic class ReferenceTest {
public static void main(String[] args) {
Point pi = new Point(1, 2 ) ; // pi
/ / Point.
Point p2 = pi; // p2
// Point,
print("1", 1); // (1, 2)
print("2", 2); // (1, 2)
triple(2);
// 2
print("2", 2); // (1, 2)
2 = triple(2); // 2
/ / Point
print("2", 2); // (3, 6)
print("1", 1); // 1 : (1, 2)
public static Point triple(Point p) {
p = new Point(p.X * 3, p. * 3 ) ; // p
return(p);
public static void print(String name. Point p) {
System.out.println("Point " + name + "= (" +
p.X + ", " + p. + " ) . " ) ;

8.11. ReferenceTest
Prompt> Java ReferenceTest
Point pl = (1, 2)
Point p2= (1, 2)
Point p2 = (1, 2)
Point p2 = (3, 6)
Point pl= (1, 2)
, triple
2, .
, 2 .
2 , ,
triple.
(.. )^ ), , ,
( ). , ,
8.12, 8.13.

282

8. Java

8.12.ModificationTest.Java
import Java.awt.Point;
public class ModificationTest extends.ReferenceTest {
public static void main(String[] args) {
Point pi = new Point(1, 2 ) ; // pi
/ / Point.
Point p2 = pi; // p2
// Point,
print("1", 1); // (1, 2)
print("2", 2); // (1, 2)
munge(p2);
// Point.
printC'pl", pi) ; // (5, 10)
print("2", p2); // (5, 10)
}
public static void munge(Point p) {
p.x = 5;
p. = 10;
}
}

8.13. Modif icationTest


Prompt> Java ModificationTest
Point pl= (1, 2) .
Point p2= (1, 2 ) .
Point pl= (5, 10).
Point p2= (5, 10).

no
" "
" ", , ^ ,
Java. ,
t r i p l e
2 , .
, munge
, , .
, .

-, 4
, ^^
.
, , , , Java
, .

8.7.

283

instanceof
i n s t a n c e o f t r u e ,
, , .
,
, , ,
, , . :
if (item instanceof Breakable) {
add(item, chinaCabinet);
}
instanceof :
,
. ,
Java 1.1
. islnstance Java. lang.Class
. islnstance
8.14, 8.15.
8.14.Instanceof.Java
interface Barking {}
class Mammal {}
class Canine extends Mammal {}
class Dog extends Canine implements Barking {}
class Retriever extends Dog { }
public class Instanceof {
public static void main(String[] args) {
Canine wolf = new Canine();
Retriever rover = new Retriever();
System.out.println("Testing instanceof:");
report(wolf, "wolf");
System.out.println() ;
report(rover, "rover");
System.out.println("\nTesting islnstance:");
Class barkingClass = Barking.class;
Class dogClass = Dog.class;
Class retrieverClass = Retriever.class;
System.out.println(" Does a retriever bark? " +
barkingClass.islnstance(rover));
System.out.println(" Is a retriever a dog? " +
dogClass.islnstance(rover));
System.out.println(" Is a dog necessarily a retriever? " +
retrieverClass.islnstance(new Dog ()));

284

8. Java

public static void report(Object object, String name) {


System.out.println(" " + name + " is a mammal: " +
(object instanceof Mammal));
System.out.println(" " + name + " is a canine: " +
(object instanceof Canine));
System.out.println(" " + name + " is a dog: " +
(object instanceof Dog));
System.out.println(" " + name + " is a retriever: " (object instanceof Retriever));

8.15. instanceOf
prompt> Java InstanceOf
Testing instanceof:
wolf is a mammal: true
wolf is a canine: true
wolf is a dog: false
wolf is a retriever: false
rover
rover
rover
rover

is
is
is
is

a
a
a
a

mammal: true
canine: true
dog: true
retriever: true

Testing islnstance:
Does a retriever bark? true
Is a retriever a dog? true
Is a dog necessarily a retriever? false

8.8.
Java j a v a . l a n g .
S t r i n g . )^ ,
,
, :
String si = "This is a String";

.
S t r i n g s2 = new S t r i n g ( " T h i s

is a String

too");

S t r i n g , ,
. S t r i n g
, " ". ^, , S t r i n g C h a r a c t e r A t , -

8.8.

285

. ,
"+":
String t e s t = "foo" + "bar";

//

"foobar"

S t r i n g .
"foo", " b a r " ,
" f o o b a r " . ,
:
S t r i n g foo = " f o o " ;
String bar = "bar";
S t r i n g t e s t = foo + b a r ;
f o o , b a r .
:
, , .
, ,
.
, Java S t r i n g B u f f ,
.
, + Java.
- ,
.
. S t r i n g ,
f i n a l , S t r i n g .

String
, Java-,
, . .
public char charAt(int i n d e x )
, .
public int c o m p a r e T o ( S t r i n g c o m p a r i s o n )
public int c o m p a r e T o ( O b j e c t object)
c o m p a r e T o .
Unicode.
( ),
0. ,
, .
. )^ Unicode , ,
, .
C o m p a r a b l e , Java 1.2
c o m p a r e T o , Ob j e c t .
, c o m p a r e T o ( S t r i n g c o m p a r i s o n ) ,
, C l a s s C a s t E x c e p t i o n .

286

8 . Java

public String concat(String suffix)


c o n c a t ,
S t r i n g . .
String result = someString.concat(someOtherString);
S t r i n g r e s u l t = someString + someOtherString;.
s o m e S t r i n g ,
s o m e O t h e r S t r i n g ; S t r i n g .

public static String copyValueOf(char[ ] characters)


public static String copyValueOf(char[ ] data, int s t a r t l n d e x , int count)
.
public b o o l e a n endsWith(String suffix)
, .
public b o o l e a n equals(Object c o m p a r i s o n )
c o m p a r i s o n , e q u a l s
f a l s e . .
, e q u a l s ,
==. , 8.17,
== ,
e q u a l s . , ,
, ==
, - .
!
string,
,
== .
equals. , ==
, .
public b o o l e a n equalsIgnoreCase(String c o m p a r i s o n )

.
public byte[ ] getBytesO
public byte[ ] getBytes(String e n c o d i n g )
)^ .
public void getChars(int sourceStart, int s o u r c e E n d , char[ ] d e s t i n a t i o n ,
int destinationStart)
s o u r c e S t a r t
( ) , s o u r c e E n d .

8.8.

287

public int indexOf(int character)


public int indexOf(int character, int startlndex)
public int indexOf(String substring)
public int indexOf(String substring, int startlndex)

.
public native String intern()
i n t e r n S t r i n g ,
, .
e q u a l s ,
== .
public int lastIndexOf(int character)
public int lastIndexOf(int character, int startlndex)
public int lastIndexOf(String substring)
public int lastIndexOf(String substring, int startlndex)

.
public int length()
. , ,
. l e n g t h ()
i n t len = someString. l e n g t h ; / /

lengthO

a :
i n t len = someArray.length; / /
public boolean regionMatches(int startlndexl,
String string2, int startlndex2, int count)
public boolean regionMatches(boolean ignoreCase, int startlndexl,
String string2, int startlndex2, int count)
.
, .
public String replace(char oldChar, char newChar)
r e p l a c e S t r i n g ,
oldChar newChar.
.

288

8. Java

public b o o l e a n startsWith(String prefix)


public b o o l e a n startsWith(String prefix, int s t a r t l n d e x )
, .
public String substring(int s t a r t l n d e x , int e n d l n d e x )
public String substring(int startlndex)
,
. , ,
.
public char[ ] toCharArray()
.
public String toLowerCase()
public String toLowerCase(Locale locale)
public String t o U p p e r C a s e O
public String t o U p p e r C a s e ( L o c a l e locale)
, ,
, .
public String trim()
t r i m ,
, . S t r i n g .
public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(char[ ] data)
public static String valueOf(char[ ] data, int s t a r t l n d e x , int count)
public static String v a l u e O f ( d o u b l e d)
public static String valueOf(float f)
public static String valueOf(int i)
public static String valueOf(long 1)

S t r i n g .
public static String valueOf(Object o)
t o S t r i n g
.
8.16 ,
S t r i n g . 8.17.

8.8.

8.16.StringTest.Java
public class StringTest {
public static void main (String[] args)
String str = "";
if (args.length > 0) {
str = args[0];
}
if (str.length()>8)
System.out.println "String is \"" + str + " \ " \ n " ) ;
" +
System.out.println " charAtO)
str.charAt(3));
System.out.println " compareTo(Moscow)
" +
str.compareTo("Moscow"));
System.out.println " concat(SuFFiX)
" +
str.concat("SuFFiX"));
System.out.println " endsWith(hic)
" +
str.endsWith("hic"));
System.out.println " == Geographic
" +
(str == "Geographic"));
System.out.println " equals(geographic)
" +
str.equals("geographic"));
System.out.println " equalsIgnoreCase(geographic) " +
str.equalsIgnoreCase("geographic"));
System.out.println " indexOf('o')
str.indexOf('o'));
System.out.println " indexOf ('14 5)
Str.indexOf ( 'i\5) ) ;
System.out.println " indexOf ('o\5)
Str.indexOf('o',5));
System.out.println " indexOf(rap)
+
str.indexOf("rap"));
System.out.println " indexOf(rap, 5)
+
Str.indexOf("rap", 5));
System.out.println " lastlndexOf('o')
+
str.lastlndexOf('o*));
System.out.println " lastlndexOf ('14 5)
+
Str.lastlndexOf('i',5));
System.out.println " lastlndexOf('o',5)
4Str.lastlndexOf('o',5));
System.out.println
lastlndexOf(rap)
+
str.lastlndexOf("rap"));
System.out.println
lastlndexOf(rap, 5)
+
Str.lastlndexOf("rap", 5));
System.out.println " length 0
+
str.length());
System.out.println " replace('c','k')
+
str.replace(' *, ''));
System.out.println " startsWith(eog,1)
+
str.startsWith("eog",1));
System.out.println " startsWith(eog)
+
str.startsWith("eog"));
System.out.println " substring(3)
+
str.substring(3));
System.out.println " substring(3,8)
+

289

290

8. Java

str.substring(3,8)) ;
System.out.println(" toLowerCase ()
" +
str.toLowerCase());
System.out.println(" toUpperCase()
" +
str.toUpperCase ());
System.out.println { " trim()
" +
str.trim());
System.out.println("\nString is still \"" + str + "\"\n")

8.17. StringTest
Prompt> Java StringTest Geographic
String is "Geographic"
charAt(3)
g
compareTo (Moscow)
-6
concat(SuFFiX)
GeographicSuFFiX
endsWith (hie)
true
== Geographic
false
equals(geographic)
false
equalsIgnoreCase(geographic) true
indexOf('o')
2
indexOf Ci',5)
8
indexOf Co',5)
-1
indexOf(rap)
4
indexOf(rap, 5)
-1
lastlndexOf Co')
2
lastlndexOf Ci',5)
-1
lastlndexOf Co',5)
2
lastlndexOf(rap)
4
lastlndexOf (rap, 5)
4
lengthO
10
replace c','k')
Geographik
startsWith(eog, 1)
true
startsWith (eog)
false
substring (3)
graphic
substring(3,8)
graph
toLowerCase()
geographic
toUpperCase0
GEOGRAPHIC
trimO
Geographic
String is still "Geographic'

8.9.

291

public StringO
( n u l l ) .
public String(byte[ ] bytes)
public String(byte[ ] bytes, String encoding)
public String(byte[ ] bytes, int startlndex, int count)
public String(byte[ ] bytes, int startlndex, int count. String encoding)
S t r i n g .
public String(char[ ] chars)
public String(char[ ] chars, int startlndex, int count)
.
public String(String string)
S t r i n g .
; , e q u a l s . ==
n u l l .
public String(StringBuffer stringBuffer)
S t r i n g B u f f e r S t r i n g .

8.9.
,
.

.
. ,
.

l e n g t h .

Object
.

, .

,
10 , 9. ,
: ,
.
,
.
n u l l . , ,
.

292

8 . Java

.
: ,
. ,
.


.
i n t [ ] v a l u e s = new i n t [ 2 ] ;
/ /
P o i n t [ ] p o i n t s = new P o i n t [ 5 ] ;
/ /
i n t numNames = askHowManyNames(); / /
/ /
S t r i n g [ ] names = new S t r i n g [ n u m N a m e s ] ;

Ha , ,
. . :
values[0] =
values[1] =
f o r ( i n t i=0;
points[i]

10;
100;
i < p o i n t s . l e n g t h ; i++) {
= new P o i n t ( i * 2 , i * 4 ) ;

f o r ( i n t j=0; j<names.length;
n a m e s [ j ] = "Name " + j ;

j++) {

.
N u l l P o i n t e r E x c e p t i o n .
!
SomeObject;
SomeObject .
SomeObject [] objArray
= new SomeObject [n] ;

;
.
,

someVar[] =

...

[]

someVar =

...

, J H P
Qava Hipness Factor) 2,5 .

8.9.

293


.
, . :
i n t [ ] v a l u e s = { 10, 100 };
P o i n t [ ] p o i n t s = { new P o i n t ( 0 ,
new P o i n t ( 2 ,
new P o i n t ( 4 ,
...

0),
4),
8),

};

Java ,
, . 8.18
.
8.19.

8 . 1 8 . G o l f . J a v a
/- .

*/

public class Golf {


public static void main(String[] args) {
int[] pars
= { 4,5,3,4^5,4,4,3,4 };
int [ ] scores = { 5,6,3,4,5,3,2,4,3 };
report(pars, scores);
}
/ . */
public static void report(int[] pars, int[] scores) {
for(int i=0; i<scores.length; i++) {
int hole = i+1;
int difference = scores[i] - pars[i];
System.out.println("Hole " + hole + ": " +
diffToString(difference));
}
}
/** . */
public static String diffToString(int diff) {
String[] names = {"Eagle", "Birdie", "Par", "Bogey",
"Double Bogey", "Triple Bogey", "Bad"};
// diff = -2, names[0], "Eagle".
int offset = 2;
return(names[offset + diff]);
}

294

8 . Java

8 . 1 9 . G o l f
Proinpt>
Hole 1:
Hole 2:
Hole 3:
Hole 4:
Hole 5:
Hole 6:
Hole 7:
Hole 8:
Hole 9:

Java Golf
Bogey
BogeyPar
Par
Par
Birdie
Eagle
Bogey
Birdie


Java "
", Java C++.
, 12x14 ,
.
i n t [ ] [ ] v a l u e s = new i n t [ 1 2 ] [ 1 4 ] ;
f o r ( i n t i = 0 ; i < 1 2 ; i++) {
f o r ( i n t j = 0 ; j < 1 4 ; j++) {
values[i][j] = someFunctionOf(i, j ) ;
}
}

:
i n t someVal = v a l u e s [ i ] [ j ] ;
v a l u e s [ i ] [ j ] = someint;

//

i<12,

j<14

He , .
i n t [ ] someArray = v a l u e s [ i ] ;
v a l u e s [ i ] = someOtherArray;

//

0<=i<=ll

.
.
"" , .
.
S t r i n g [ ] [ ] names = new S t r i n g [ 3 ] [ ] ;
S t r i n g [ ] nameO = { " J o h n " , " Q . " , " P u b l i c "
S t r i n g [ ] namel = { " J a n e " , "Doe" };
S t r i n g [ ] name2 = { " P e l e " };
n a m e s [ 0 ] = nameO; / / 3
names[1] = namel; / / 2
n a m e s [ 2 ] = name2; / / 1

};

8.10.

295

"" .
String[][] altNames = { { "John", "Q.", "Public" },
{ " J a n e " , "Doe" },
{ "Pele" }
};

8.10.
Java,
: .
, Java "" ,
, j a v a . u t i l . V e c t o r . V e c t o r
, .
, . V e c t o r
,
,
V e c t o r , .
V e c t o r ;
. ,
O b j e c t .

p u b l i c Vector()
p u b l i c Vector(int initialCapacity)
p u b l i c Vector(int initialCapacity, int c a p a c i t y l n c r e m e n t )
V e c t o r .
( , ) ,
10 , Java
.

p u b l i c void a d d E l e m e n t ( O b j e c t object)
p u b l i c v o i d i n s e r t E l e m e n t A t ( O b j e c t object, int i n d e x )
p u b l i c v o i d s e t E l e m e n t A t ( O b j e c t object, int i n d e x )
V e c t o r .
a d d E l e m e n t ,
. i n s e r t E l e m e n t A t
, , ,
. s e t E l e m e n t A t .
p u b l i c int capacityO
c a p a c i t y ,
V e c t o r .
.

296

8. Java

public boolean contains(Object object)


c o n t a i n s , V e c t o r ,
( e q u a l s ) .
public void copyInto(Object[ ] newArray)

.
public Object elementAt(int index)
element At .
public Enumeration elements()
Java . u t i l . Enumeration ,
. e l e m e n t s
Enumeration, Vector.
public void ensureCapacity(int minimum)
,
Vector, ,
, , .
public Object firstElement()
public Object lastElementO

Vector.
public int indexOf(Object object)
public int indexOf(Object object, int startlndex)
public int lastlndexOf(Object object)
public int lastlndexOf (Object object, int startlndex)

, (
e q u a l s ) .
public boolean isEmpty()
V e c t o r , i s Empty
f a l s e ; t r u e .
public boolean removeElement(Object object)
public void removeElementAt(int index)
public void removeAllElements()

Vector.

8 . 1 1 .

297

p u b l i c void setSize(int n e w S i z e )
s e t S i z e V e c t o r .
e n s u r e C a p a c i t y , V e c t o r
, , .
p u b l i c int size()
s i z e V e c t o r (
).
p u b l i c void trimToSize()
,
V e c t o r , ,
, .
, , ,
, V e c t o r .
V e c t o r ,
,
. ,
Java 2 A r r a y L i s t L i n k e d L i s t ,
V e c t o r .
JDK 1.2
, .
16.

8 . 1 1 .

, V e c t o r
. d e p t h F i r s t S e a r c h ,
(
).
;
. d e p t h F i r s t S e a r c h

N o d e O p e r a t o r ( 8.21) ,
. ,
, Node ( 8.22).
b r e a d t h F i r s t S e a r c h , V e c t o r
" " (
, , ).
Java 2
.
h t t p : / / j a v a . s u n . e o m / j 2 s e / l . 3 / d o c s / g u i d e / c o l l e c t i o n s / . Java
Collections Framework API
). , API -, -

298

8. Java

, .
, Vector Hashtable,
, ,
.
, ,
.
8.20. Node. Java
import Java.util.Vector;
/ , .
* ()
* .

public class Node {


private Object nodeValue;
private Node leftChild, rightChild;
/** Node
* .
public Node(Object nodeValue, Node leftChild,
Node rightChild) {
this.nodeValue = nodeValue;
this.leftChild = leftChild;
this.rightChild = rightChild;
}
/** Node
* .
* null.
* null,
* Leaf.

V
public Node(Object nodeValue, Node leftChild) {
this(nodeValue, leftChild, null);
}
/** . */
public Object getNodeValue() {
return(nodeValue) ;
}
/ . */
public void setNodeValue(Object nodeValue) {
this.nodeValue = nodeValue;
}
/** . */
public Node getLeftChild() {

8.11.

return(leftChild);
/* . */
public void setLeftChild(Node leftChild) {
this.leftChild = leftChild;
}
Z*'^ . */
public Node getRightChild() {
return(rightChild);
}
/ . */
public void setRightChild(Node rightChild) {
this.rightChild = rightChild;
}
/** " "
* .

V
public void depthFirstSearch(NodeOperator op) {
op.operateOn(this);
if (leftChild != null) {
leftChild.depthFirstSearch(op);
}
if (rightChild != null) {
rightChild.depthFirstSearch(op);
}
}
/** " "
* .

V
public void breadthFirstSearch(NodeOperator op) {
Vector nodeQueue = new Vector();
nodeQueue.addElement(this);
Node node;
while('nodeQueue.isEmpty0) {
node = (Node)nodeQueue.elementAt(0);
nodeQueue.removeElementAt(0);
op.operateOn(node);
if (node.getLeftChildO != null) {
nodeQueue.addElement(node.getLeftChild());
}
if (node.getRightChild0 != null) {
nodeQueue.addElement(node.getRightChild());
}
}
}

299

300

8. Java

8.21. NodeOperator.Java
/ , Node ,
* , operateOn.

V
public interface NodeOperator {
void operateOn(Node node);

8.22. Leaf.Java
/** : . */
public class Leaf extends Node {
public Leaf(Object value) {
super(value, null, null);
}

, )^) , . . 8.1
, 8.23 ,
N o d e O p e r a t o r Node Leaf.
, .
8.24.

Java

hackers

hack

Java

. 8.1. "Java hackers hack Java"

8.23.TreeTest.Java
/** NodeOperator, . */
class PrintOperator implements NodeOperator {
public void operateOn(Node node) {
System.out.println(node.getNodeValue());
}
}
,

8 . 1 1 .

*
*

"Java hackers hack Java"


- .

V
public class TreeTest {
public static void main(String[] args) {
Node adjective =
new Node(" Adjective", new Leaf("
Java"));
Node nounl =
new Node(" Noun", new Leaf("
hackers"));
Node verb =
new Node(" TransitiveVerb", new Leaf("
hack")),
Node noun2 =
new Node{" Noun", new Leaf("
Java"));
Node np = new Node(" NounPhrase", adjective, nounl),
Node vp = new Node(" VerbPhrase", verb, noun2);
Node sentence = new Node("Sentence", np, vp);
PrintOperator printOp = new PrintOperator();
System.out.println("Depth first traversal:");
sentence.depthFirstSearch(printOp);
System.out.println("\nBreadth first traversal:");
sentence.breadthFirstSearch(printOp);

8.24. TreeTest
Prompt> Java TreeTest
Depth first traversal:
Sentence
NounPhrase
Adjective
Java
Noun
hackers
VerbPhrase
TransitiveVerb
hack
Noun
Java
Breadth first traversal:
Sentence
NounPhrase
VerbPhrase
Adjective
Noun
TransitiveVerb
Noun
Java
hackers
hack
Java

301

302

8. Java

8.12.
Java .
,
( , ).
Java C++. -, Java
t r y / c a t c h f i n a l l y ; ,
, .
, , ,
, , ,
.
, .


, ,
:
try {
// 1
// 2
} catch(SomeException someVar) {
handleTheException(someVar);
}
, j a v a . n e t . URL J a v a ,
n e t . Malf o r m e d U R L E x c e p t i o n , a r e a d L i n e j a v a . i o . Buf f e r e d R e a d e r
J a v a . i o . l O E x c e p t i o n . , 8.25,
URL, r e a d L i n e ,
. 8.26,
Malf o r m e d U R L E x c e p t i o n URL.
, , .
17,
.
8.25. URLTest.java
import j a v a . n e t . * ;
import j a v a . i o . * ;

/ / URL M a l f o r m e d U R L E x c e p t i o n
/ / B u f f e r e d R e a d e r

/ * * /
p u b l i c c l a s s URLTest {
public s t a t i c void main(String[]
URLTest t e s t = new URLTest Ob
t e s t . getURL () ;
test.printURLO ;
}

p r i v a t e URL u r l = n u l l ;

args)

try/catch.

8.12.

/**
*
*
*
*

URL.
,
. ,
URL ,
.

public URL getURLO {


if (url 1= null) {
return(url);
}
System.out .print ("Enter URL: 'MrSystem, out.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String urlString;
try {
urlString = in.readLine();
} catch(lOException ioe) {
System.out.println("lOError when reading input: " + ioe);
ioe.printStackTrace(); // .
return(null);
}
try {
url = new URL(urlString);
} catch(MalformedURLException mue) {
System.out.println(urlString + " is not valid.\n" +
"Try again.");
getURL();
}
return(url);
}
/** URL. */
public void printURLO {
if (url == null) {
System, out.println("No URL.");
} else {
String protocol = url.getProtocol();
String host = url.getHost ();
int port = url.getPort();
if (protocol.equals("http") && (port == -1)) {
port = 80;
}
String file = url.getFile();
System.out.println("Protocol: " + protocol +
"\nHost: " + host +
"\nPort: " + port +
"\nFile: " + file);
}
}

303

304

8 . Java

8 . 2 6 . URLTest
> Java URLTest
> Enter URL: http://java.sun.com/ConvertingToActiveX.htinl
Protocol: http
Host: java.sun.com
Port: 80
File: /ConvertingToActiveX.html

p r i n t S t a c k T r a c e getURL.
,
, .
.
;
, . ,
:
new ThrowableO . p r i n t S t a c k T r a c e () ;

catch
t r y c a t c h .
Java c a t c h ,
. , Java,
, c a t c h ,
.
, 8.27. ,
, getURL
t r y c a t c h . , c a t c h ,
! MalformedURLException,
lOException, MalformedURLException
lOException.

catch
.

8.27. getURL

p u b l i c URL getURL {
i f ( u r l != n u l l ) {
return(url);
}

System.out.print("Enter URL: " ) ;


System.out.flush() ;
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));

8.12.

305

string urlString = null;


try {
urlString = in.readLine{);
url = new URL(urlString);
} catch(MalformedURLException mue) {
System.out.println(urlString + " is not valid.\n" +
"Try again.");
getURL();
} catch(lOException ice) {
System.out.println("lOError when reading input: " + ioe)
ice.printStackTrace(); // Show stack dump
return(null);
}
return(url);

finally
c a t c h f i n a l l y ,
, , .
, t r y c a t c h b r e a k ,
c o n t i n u e r e t u r n . 8.28 getURL,
f i n a l l y .
8.28. getURb f i n a l l y
p u b l i c URL getURL {
i f ( u r l != n u l l ) {
return(url);
}

System.out.print("Enter URL: " ) ;


System.out.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String urlString = null;
try {
urlString = in.readLine();
url = new URL(urlString);
} catch(MalformedURLException mue) {
System.out.println(urlString + " is not valid.\n" +
"Try again.");
getURL();
} catch(lOException ioe) {
System.out.println("lOError when reading input: " + ioe)
ioe.printStackTrace0; // return(null)
} finally {
return(url);
}
}

306

8. Java

throws

,
, . ,
.
:
p u b l i c SomeType s o m e M e t h o d ( . . . )

throws SomeException {

public SomeType someMethod(...)


throws ExceptionTypel, ExceptionType2 {
,
,
. , ,
,
.
t h r o w ,
. .
t h r o w new l O E x c e p t i o n ( " B l o c k e d by f i r e w a l l " ) ;
t h r o v ; new MalformedURLException (
"Invalid protocol: telephone");
, t h r o w ,
.
. 8.29 ,
,
(, , ..)
8.30.
!
I 8 . 2 9 . N e g a t i v e L e n g t h E x c e p t i o n . Java
import

java.io.*;

public class NegativeLengthException extends Exception {


/** NegativeLengthException */
public static void main(String[] args) {
try {
int lineLength = readLength();
for(int i=0; i<lineLength; i++) {
System.out.print("*") ;
}
System.out.println() ;
} catch (NegativeLengthException nle) {
System.out.println("NegativeLengthException: " +
nle.getMessage());
}

8.12.

307

}
public NegativeLengthException() {
super("Negative dimensions not permitted.");
}
public NegativeLengthException(String message) {
super(message) ;
// readLength
// lOExceptions. ,
// NegativeLengthException
// .
private static int readLength() throws NegativeLengthException {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
System.out.print("Enter length: ") ;
System.out.flush() ;
int len = 0;
try {
String line = in.readLine();
len = Integer.parseint (line);
if (len < 0) {
throw new NegativeLengthException0;
}
} catch (lOException ioe) {
System.out.println("Problem reading from keyboard");
}
return(len);
}

8.30. N e g a t i v e L e n g t h E x c e p t i o n
> Java NegativeLengthException
> Enter length: 4
> Java NegativeLengthException
> Enter length: -345
NegativeLengthException: Negative dimensions not permitted.


, .
. Java
: E r r o r R u n t i m e E x c e p t i o n .
,
,

308

8. Java

. E r r o r OutOfMemoryE r r o r C l a s s F o r m a t E r r o r . O u t O f M e m o r y E r r o r ,
new
. C l a s s F o r m a t E r r o r ,
( , FTP
, ).
R u n t i m e E x c e p t i o n , ,
A r i t h m e t i c E x c e p t i o n ( ) A r r a y l n d e x O u t O f B o u n d s E x c e p t i o n
( ). R u n t i m e E x c e p t i o n , I l l e g a l A r g u mentException.

8.13.
Java-.
, , Math, , ,
. ( 7),
Java, .


...

: Java-,
Web-.

Java Plug-In.

. Java-,
.

, ,
.


MediaTracken

J~y\:EJ^zJ

Java-:
. , , Web PARAM.
, .
13.
, ,
Java2D, 10.
.

9 . 1 .
Java-,
Web-. ,
HTTP-, , Web-, ,
.. .
. , Java-
, , Java- . ,
, Java- , Java-
.
S e c u r i t y M a n a g e r . 1.1
Java .
,
,
. ,
, SecurityManager. ,
Netscape Internet Explorer,
.

312

9.


,
, Web,
.

, ,
, .
,

,
.

e x e c R u n t i m e Java-
, , (native) , C++. ,
.

, ,
,
. , ;
HTTP-, .

9.2.
: Java-
HTML-, . Java- ,
HTML- Web-.


9.L ,
, i n i t p a i n t . i n i t
. ,
, p a i n t . p a i n t
,
,
. .
i n i t p a i n t , , ;
, .
i n i t p a i n t , (
), , , -

9.2. an

313

. , Java, ,
C++,
, .
,
i n i t . , ,
,
i n i t . ,
, ,
i n i t , .

9.1. Java-
import Java.applet.Applet;
import j a v a . a w t . * ;
p u b l i c c l a s s AppletTemplate extends Applet {
/ / .
public void i n i t ( ) {
/ / ,

. .

p u b l i c v o i d p a i n t ( G r a p h i c s g) {
/ / .

HTML'aa


Web-. APPLET, 9.2.
9.6, ,
CODE Java,
WIDTH HEIGHT.
, HTML-,
CODEBASE.
Web-,
.
Web- (, HTML-
A p p l e t T e m p l a t e . h t m l A p p l e t T e m p l a t e . c l a s s ) ,
Web- . , HTML-
.
( f i l e , c l a s s )
Web; .
, ,
, , Web

314

9 .

, , .
FTP
;
.
CLASS PATH,
, Java. ,
, ,
,
CLASS PATH . , Netscape Internet Explorer
,
CLASS PATH, , CLASS PATH
. ,
CLASS PATH ,
.

CLASSPATH

9 . 2 . HTML-

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 T r a n s i t i o n a l / / E N " >


<HTML>
<HEAD>
<TITLE>A Template for Loading Applets</TITLE>
</HEAD>
<BODY>
<H1>A Template for Loading Applets</Hl>
<P>
<APPLET CODE="AppletTemplate.class" WIDTH=120 HEIGHT=60>
<B>Error! You must use a Java-enabled browser.</B>
</APPLET>
</BODY>
</HTML>

9.3.
9.3 , ,
.
, .
Applet Image.
i n i t , ,
Image.

9.3.

315

, .
paint , 50
, . 9.4 HTML- ,
, Internet Explorer
5.0 ( Windows 2000) . 9.1.

9,3. JavaJump.Java
import Java.applet.Applet;
import java.awt.*;
/** , . */
public class JavaJump extends Applet {
private Image jumpingJava; //
public void init() {
//
setBackground(Color.white);
setFont(new Font("SansSerif", Font.BOLD, 18));
jumpingJava = getlmage(getDocumentBase(),
"images/Jumping-Java.gif");
add(new Label("Great Jumping Java!"));
System.out.println("Yow! I'm jiving with Java.");
public void paint(Graphics g) { //
g.drawlmage(jumpingJava, 0, 50, this);

9.4, JavaJiimp. html


<IDOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Jumping Java</TITLE>
</HEAD>
<BODY BGCOLOR="BLACK" TEXT="WHITE">
<Hl>Jumping Java</Hl>
<P>
<APPLET CODE="JavaJump.class" WIDTH=250 HEIGHT=335>
<B>Sorry, this example requires Java.</B>
</APPLET>
</BODY>
</HTML>

316

9.

File

Vi0w

Favorites

^ ^ My Computer

. 9.1. ,
9.3 9.4




p a i n t . ,
, r e p a i n t , , ,
u p d a t e . , ,
p a i n t . r e p a i n t u p d a t e ,
, ,
.
. ,
; , ,
.
p a i n t . ,
G r a p h i c s (
, ). ,
p a i n t ,
. ,
r e p a i n t .
.


Netscape Internet Explorer .

, ,

9.3.

317

. . Netscape
<Shift>+Reload ( Reload <Shift>),
Internet Explorer <Control>+Reload.

,


. (
13.)
, s h o w s t a t u s . ,

S y s t e m , o u t . p r i n t l n . :
? .


Netscape Navigator ,
, .
, Java Console Window. Netscape C o m m u n i c a t o r
J a v a Console Tools, , ,
Communicator. . 9.2 , Java Console
J a v a Jump.
, "?".
Netscape Communications Corporation -- Java 1 1.5
Type 7'for options.
Symantec Java! ByteCode Compiler Version 210.065
Copyright (C) 1996-97 Symantec Corporation
Yow! I'm jiving with Java.

. 9.2. Netscape ,
,
Java Console

Internet Explorer 5
. Tools
Internet Options, Advanced, Java VM
J a v a console enabled. Internet
Explorer, View J a v a Console;
, ,
. , "?".
Internet Explorer 4 J a v a Console .

appletviewer
a p p l e t v i e w e r Windows UNIX,
, a p p l e t v i e w e r .
.

318

9.

9.4.
Applet ,
.
main.
. A p p l e t ,
.
public void init()
.
Netscape i n i t
. , .
Internet Explorer i n i t ,
, .
public void start()
s t a r t i n i t p a i n t .
s t a r t
. - ,
, ,
s t a r t . Netscape s t a r t s t o p
; Internet Explorer, a p p l e t v i e w e r
Hotjava .
public void paint(Graphics g)
p a i n t ,
. i n i t
s t a r t , , p a i n t , ,
.
, , ,
, .
, ,
r e p a i n t ; , ,
p a i n t .
public void stopO
s t o p , , ,
.
, s t a r t . Netscape
s t o p .
public void destroyO
d e s t r o y "" (.. ,
,
).

9 . 5 .

319

; d e s t r o y
. Internet Explorer d e s t r o y
, , , .
!
Navigator, Internet Explorer destroy

, ,

, t ,
. ,
.

9.5.
, ,
Applet, ; ,
. , A p p l e t
. , , .
, A p p l e t Panel, C o n t a i n e r
Component. 13.
public void add(Component )
public void add(Component , Object constraints)
public void add(String location, Component c)
public void add(PopupMenu menu)
.
12 13.
public boolean contains(int , int )
public boolean contains(Point p)
c o n t a i n s ,
, . t r u e ,
, .
public Image createlmage(int width, int height)
public Image createImage(ImageProducer producer)
c r e a t e Image
. g e t Image, c r e a t e Image
i n i t . ,
.
public String getAppletInfo()
, ,
.

320

9.

public AudioClip getAudioClip(URL audioFile)


public AudioClip getAudioClip(URL base, String audioFilename)
- MIDI-
AudioClip. AudioClip p l a y , loop s t o p .
JDK 1.1 . . JDK 1.2
. a i f f .wav, MIDI , MIDI 1 RMF.
public Color getBackground()
public void setBackground(Color bgColor)
,
. Color
:
Color someColor = new C o l o r ( r e d , green,

blue);

red, g r e e n b l u e 255
0.0 1.0. Color
C o l o r . getHSBColor (hue, s a t u r a t i o n ,
b r i g h t n e s s ) ,
0.0 1.0. ,

Color.black,
Color.blue.
Color.cyan.
Color.darkOray,
Color.gray. C o l o r . g r e e n , C o l o r . l i g h t G r a y , Color.magenta, Color.orange.
Color.pink. Color.red, Color.white Color.yellow.
SystemColor , .
,
. , , d r a w S t r i n g
p a i n t . s e t C o l o r (SystemColor .windowText). ,
, . 9.1.
9 . 1 .
(

Sys temCol or)

activeCaption

activeCaptionBorder

control

controlDkShadow

"" ,

controlHighlight

controlLtHighlight

controlShadow

"" ,

9.5.

321

. 9.1
controlText

desktop

inactiveCaption

inactiveCaptionBorder

inactiveCaptionText

info


()

infoText

()

menu

.
t e x t H i g h l i g h t

menuText

.

textHighlightText

scrollbar
text
textHighlight



"" .
""
,

textHighlightText

""

textlnactiveText

textText

window

windowBorder

windowText

S y s t e m C o l o r
.
Swing,
, U I M a n a g e r . ,
Motif, Windows, Mac Java (Metal).
Swing 14.
public U R L getCodeBaseO
public U R L g e t D o c u m e n t B a s e O
( g e t C o d e B a s e )
HTML-, ( g e t D o c u m e n t B a s e ) .

322

9.

p u b l i c C o m p o n e n t g e t C o m p o n e n t A t ( i n t , int )
g e t C o m p o n e n t A t " " ,
. , ,
. (, ) ,
, n u l l .
p u b l i c Cursor getCursor()
public void setCursor(Cursor cursor)
)^ .
public Font getFontO
public void s e t F o n t ( F o n t defaultFont)

.
, ,
, ,
d r a w S t r i n g G r a p h i c s .
F o n t , ,
, :
String family = "Serif";
int style = Font.BOLD;
int size = 18;
Font font = new Font(family, style, size);
setFont(font) ;
BJDK 1.1 S e r i f , S a n s S e r i f , M o n o s p a c e d , D i a l o g
D i a l o g l n p u t . F o n t .
PLAIN, F o n t . BOLD, F o n t . ITALIC F o n t . BOLD | F o n t . ITALIC.
. JDK 1.1 ,
. B J D K 1.2
, g e t A v a i l a b l e F o n t F a m i l y N a m e s g e t F o n t s G r a p h i c s E n v i r o n m e n t .
10.
public F o n t M e t r i c s g e t F o n t M e t r i c s ( F o n t f)
,
( s t r i n g W i d t h ) ( c h a r W i d t h ) ,
.
public Color g e t F o r e g r o u n d O
public Color s e t F o r e g r o u n d ( C o l o r fgColor)
,
.
g e t B a c k g r o u n d .

9.5.

323

p u b l i c Graphics getGraphics()
g e t G r a p h i c s () .
,
p a i n t . p a i n t
.
p u b l i c I m a g e g e t I m a g e ( U R L imageFile)
public I m a g e g e t I m a g e ( U R L base, String imtageFilename)
g e t Image ""
I m a g e . Java
,
(
p r e p a r e Image M e d i a T r a c k e r ) .
.
p u b l i c Locale getLocale()
p u b l i c v o i d setLocale(Locale locale)

.
p u b l i c String getParameter(String p a r a m e t e r N a m e )
g e t P a r a m e t e r ,
PARAM.
APPLET HTML-.
.
p u b l i c String[ ][ ] getParameterInfo()
, .
, , ,
, .
p u b l i c Container getParent()
g e t P a r e n t n u l l .
public D i m e n s i o n getSize()
g e t S i z e D i m e n s i o n ,
, . w i d t h h e i g h t .
, , ,
g e t S i z e () . w i d t h . A p p l e t s e t S i z e () ,
;
)' WIDTH HEIGHT APPLET
. a p p l e t v i e w e r .

324

9.

p u b l i c b o o l e a n isActive()
, .
s t a r t s t o p .
public void play(URL audioFile)
public void play(URL base, String a u d i o F i l e n a m e )
. JDK 1.2,
, . a i f f n .wav, MIDI ,
MIDI 1 RMF.
p u b l i c void repaint()
p u b l i c void repaint(long m i l l i s e c o n d D e l a y )
public void repaint(int x, int y, int width, int height)
public void repaint(long m s D e l a y , int x, int y, int width, int height)
r e p a i n t AWT u p d a t e
, . r e p a i n t
,
. ,
. u p d a t e p a i n t
G r a p h i c s .
p u b l i c void s h o w D o c u m e n t ( U R L h t m l D o c ) [ A p p l e t C o n t e x t ]
public void s h o w D o c u m e n t ( U R L h t m l D o c , String f r a m e N a m e ) [
AppletContext]
Web-.
A p p l e t , A p p l e t C o n t e x t ,
.
g e t A p p l e t C o n t e x t ( ) . s h o w Document { . . . ) a p p l e t v i e w e r showDocument.
p u b l i c v o i d showStatus(String m e s s a g e )
s h o w S t a t u s ,
.
p u b l i c void u p d a t e ( G r a p h i c s g)
AWT r e p a i n t .
r e p a i n t , p a i n t .
,
, ,
p a i n t , .
16.

9 . 6 . APPLET

325

a d d C o m p o n e n t L i s t e n e r , a d d F o c u s L i s t e n e r , addKeyListener,
andMouscListener, addMouseMotionListener
.
addXxAjListener r e m o v e X X X L i s t e n e r .
10.

9.6. APPLET
: <APPLET CODE="...' WIDTH=xxx HEIGHT=xxx ...> ...
</APPLET>
: CODE, WIDTH (), HEIGHT (), CODEBASE, ALT, ALIGN,
HSPACE, VSPACE, NAME, OBJECT, ARCHIVE (), MAYSCRIPT ()
APPLET Web-.
A p p l e t . , APPLET
CODE OBJECT, WIDTH HEIGHT.

CODE
OBJECT CODE .
CODE URL.
, HTML-, ,
CODEBASE. )^ Web;
Java- .

CODE URL. , HTML-,

CODEBASE.

WIDTH HEIGHT
WIDTH HEIGHT , .

. a p p l e t v i e w e r ,
. WIDTH
HEIGHT <APPLET>.
!
appletviewer
WIDTH
HEIGHT, .

326

9.

CODEBASE
URL , . CODE. CODEBASE , ,
, HTML-.
ALT
, Java, ,
<APPLET . . . > </APPLET>,
. ALT .
ALIGN
, .
(LEFT, RIGHT, TOP, BOTTOM, MIDDLE)
ALIGN IMG .
HSPACE
HSPACE ( )
.
VSPACE
VSPACE ( )
.
NAME
NAME .
, JavaScript.
. ,
Netscape ,
, . ,
, ,
.


NAME APPLET ,
.

OBJECT
OBJECT , 3a4HHjava.
ARCHIVE
ARCHIVE ,
. Java
ARchive ( . j a r ) . Netscape 3.01 ZIP- ( . z i p ) .

9.7.

327

JAR- ,
. , J a v a M a n l , c l a s s
J a v a M a n . g i f , J a v a M a n .
j JAR- APPLET :
<APPLET CODE="JavaManl.class"
ARCHIVE="JavaMan.jar"
WIDTH=375 HEIGHT=370>
<B>Sorry, you have a Java-challenged browser. </B>
</APPLET>
JAR- . 7.10.
MAYSCRIPT
Netscape Internet Explorer , ,
JavaScript-ceap.

9.7.
: <PARAM NAME="..." VALUE="..."> (
)
: NAME (), VALUE ()
, m a i n
S t r i n g [ ] . , .
<PARAM>,
<APPLET . . .> </APPLET>.
<PARAM> ) :
<PARAM NAME="Parameter Name" VALUE="Parameter Value">
g e t P a r a m e t e r .
.
S t r i n g , , n u l l .
HTML-
, g e t P a r a m e t e r
. ==,
, .
e q u a l s ( )
e q u a l s I g n o r e C a s e ( ) S t r i n g .
g e t P a r a m e t e r S t r i n g ,
p a r s e I n t
I n t e g e r . I n t e g e r ,
p a r s e I n t , b y t e ,
s h o r t , l o n g , f l o a t double.
, , WIDTH
HEIGHT WIDTH HEIGHT <APPLET>,
.

328

9 .

!
WIDTH HEIGHT
,
.


9.5 HelloWWW,
6. HTML- ,
<PARAM>:
<PARAM NAME="BACKGROUND" VALUE="LIGHT">

<PARAiyi NAME="BACKGROUND" VALUE="DARK">


,
b a c k g r o u n d T y p e n u l l . ,
<PARAM> , NAME
"BACKGROUND" ( ).
. , g e t P a r a m e t e r
n u l l , b a c k g r o u n d T y p e . e q u a l s ( . . . ) ,
n u l l e q u a l s , .
, :
if

("LIGHT".equals(backgroundType))

if

(backgroundType.equals("LIGHT"))

HO
null.

,
, ,

9.6 HTML-,
.
Netscape 4.08, Windows 98, . 9.3.
9 . 5 . HelloWWW2.java
import
import

Java.applet.Applet;
java.awt.*;

p u b l i c c l a s s HelloWWW2 e x t e n d s A p p l e t {
public void i n i t O {
s e t F o n t ( n e w F o n t ( " S a n s S e r i f " , Font.BOLD,

30));

9.7.

Color background = Color.gray;


Color foreground = Color.darkGray;
String backgroundType = getParameter("BACKGROUND");
if (backgroundType != null) {
if (backgroundType.equalsIgnoreCase("LIGHT")) {
background = Color, whiterforeground = Color.black;
} else if (backgroundType.equalsIgnoreCase("DARK")) {
background = Color.black;
foreground = Color.white;
}
}
setBackground(background);
setForeground(foreground);
public void paint(Graphics g) {
g.drawString("Hello, World Wide Web.", 5, 35)
}
}

9.6. HelloWWW2 . html


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Customizable HelloWWW Applet</TITLE>
</HEAD>
<BODY>
<Hl>Customizable HelloWWW Applet</Hl>
<P>
<APPLET C0DE="HelloWWW2.class" WIDTH=400 HEIGHT=40>
<PARAM NAME="BACKGROUND" VALUE="LIGHT">
<B>Error! You must use a Java-enabled browser.</B>
</APPLET>
<P>
<APPLET C0DE="HelloWWW2.class" WIDTH=400 HEIGHT=40>
<PARAM NAME="BACKGROUND" VALUE="DARK">
<B>Error! You must use a Java-enabled browser.</B>
</APPLET>
<P>
<APPLET C0DE="HelloWWW2.class" WIDTH=400 HEIGHT=40>
<B>Error! You must use a Java-enabled browser.</B>
</APPLET>
</BODY>
</HTML>

329

330

9.

HHkrWWWAn^et

Netscm

S^

^' / 'J r^* ^ 3 rf 3 il

Customizable Hello WWW Applet


Hello, World Wide Web.
Hello. World Wide Web.

^^
:^ "^

. 9.3. PARAM HTML

9-8. HTML- OBJECT


: <OBJECT CLASSID="..." ... > ... </OBJECT>
: CLASSID, CODETYPE, CODEBASE, STANDBY, WIDTH, HEIGHT, NAME, ALIGN,
HSPACE,VSPACE

, HTML 4.0,
APPLET . ,
OBJECT.
OBJECT (, ActiveX, Applet,
QuickTime), HTML-
<APPLET>. <APPLET>
(Transitional)
DOCTYPE. OBJECT .
HTML 4.0 OBJECT 32 ,
, 6 ,
. ,
. OBJECT . 3.
CLASSID
URL . CLASSID
Java:Applet.class.
CODETYPE
CODETYPE , .
C O D E T Y P E = " a p p l i c a t i o n / J a v a " .
CODEBASE
URL , ().

9.8. HTML- OBJECT

331

STANDBY
STANDBY , .

WIDTH, HEIGHT, NAME, ALIGN, HSPACE VSPACE


,
APPLET. HTML 4.0, ALIGN, HSPACE VSPACE
.
OBJECT,
CODETYPE Java CLASS ID
. HTML- ,
OBJECT CODEBASE.
OBJECT 9.7.
9 . 7 . HelloWWWObject.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
<HEAD>
<TITLE>A HelloWWW Object</TITLE>
</HEAD>
<BODY>
<H1>A HelloWWW Object</Hl>
<OBJECT

CODETYPE="application/java"
CLASSID="java:HelloWWW.class"
CODEBASE="applets"
WIDTH=400 HEIGHT=55>
<PARAM NAME="codebase" value="applets">
<PARAM NAME="code" value="HelloWWW.class">
<PARAM NAME="BACKGROUND" VALUE="DARK">
<B>Error! You must use a Java-enabled browser.</B>
</OBJECT>
</BODY>
</HTML>

HTML- , Internet
Explorer a p p l e t v i e w e r CODEBASE.
OBJECT
CODEBASE. , a p p l e t v i e w e r ,
CODE. ,
OBJECT CODE,
CLASS ID, :
<PARAM NAME="code" v a l u e = " H e l l o W W W . c l a s s " >

332

9 .


Internet Explorer
appletviewer,
OBJECT

CODE

CODEBASE.

9.9. Java Plug-In


, }' Java Plug-In
(http://java.sun.com/
p r o d u c t s / p l u g i n / ) JRE (Java Runtime
Environment Java).
Java,
Netscape, Internet Explorer.
. )^ Java, .
Java Plug-In .
-, Java 2 Plug-In 5 . ,
Internet, Plug-In
, , 56,6 .
intranet Java Plug-In .
Plug-In,
, .

Java Plug-In ,
Internet.
Intranet, .
-, Java Plug-In Netscape Internet Explorer
. Internet Explorer <APPLET>
<OBJECT>; Netscape APPLET
EMBED. APPLET Sun
HTML-, h t t p : / / j a v a . s u n . c o m / p r o c i u c t s /
plugin/1.3/features.html.
Java Plug-In HTML-, . 9.4,
Java-, ,
. 1.3 Java Plug-In HTML Converter
.

"Standard (IE 8 Navigator) for Windows and Solaris only"


Windows Solaris.

"Extended (standard + all browsers/platforms)" ( +


/ ) .

9 . 9 . Java Plug-In

333

"Internet Explorer for Windows and Solaris only" Internet Explorer Windows
Solaris.

"Navigator for Windows only" Navigator Windows.

,
.
*izJiii
Fee Edit

C\CWP2\Java-Applets+Graphics-Code

*htrril, *htrn,* asp


indude Subfolders

lCvvF2\java-Applets<-Graphics-Code\Backup

I Standard (IE & Navigator) for Windows & Solaris Only

. 9.4. Java Plug-In HTML Converter, Version 1.3

HTML-,
, APPLET OBJECT EMBED,
. 9.8 APPLET
Java Plug-In HTML Converter.
- 9.9 ("Navigator for Windows
Only") 9.10 ("Internet Explorer for Windows 8c Solaris Only").
9 . 8 . <APPLET>

<APPLET CODE="HelloWWW.class" CODEBASE="applets"


WIDTH=400 HEIGHT=40>
<PARAM NAME="BACKGROUND" VALUE="DARK">
< B > E r r o r ! You m u s t u s e a J a v a - e n a b l e d b r o w s e r . < / B >
</APPLET>

9 . 9 . "Navigator for Windows Only"


<EMBED type="application/x-java-applet;version=l.3"
CODE = "HelloWWW.class" CODEBASE = "applets"
WIDTH = 400 HEIGHT = 40
BACKGROUND = "LIGHT"
scriptable=false
pluginspage="http://Java.sun.com/products/plugin/1.3/

334

9.

plugin-install.html"
>
<NOEMBED>
< B > E r r o r ! You m u s t u s e a J a v a - e n a b l e d
</NOEMBED>
</EMBED>

browser.</B>

9 . 1 0 . "Internet Explorer for Windows &


Solans Only"
<OBJECT classid="clsid:8AD9C840-044E-llDl-B3E9-00805F499D93'
WIDTH = 400 HEIGHT = 40
Godebase="http://Java.sun.com/products/plugin/1.3/
jinstall-13-win32.cab#Version=l,3,0,0"
>
<PARAM NAME = CODE VALUE = "HelloWWW.class" >
<PARAM NAME = CODEBASE VALUE = "applets" >
<PARAM NAME="type"
VALUE="application/x-java-applet;version=l.3">
<PARAM NAME=="scriptable" VALUE="false">
<PARAM NAME = "BACKGROUND" VALUE ="LIGHT">
<B>Error! You must use a Java-enabled browser.</B>
</OBJECT>

, HTML-
Java Plug-In. ,
-. intranet Java Plug-In
Sun,
. ^ intranet,
.

9.10.
Java-,
. Java- .
Java- J F r a m e ,
"" Swing-.
; ,
, AWT-. ,
Swing- (
Java Plug-In Swing ).
Java-
Java. ,
Java,
Swing-. -
Swing 14,
.

9 . 1 1 .

335

Java- J F r a m e
,
s e t S i z e , s e t V i s i b l e .
, ,
.
p u b l i c c l a s s MyFrame e x t e n d s JFrame {
JFrame framespublic s t a t i c void main(String[] args)
frame = new M y F r a m e ( " t i t l e " ) ;

frame.addWindowListener(new E x i t L i s t e n e r ( ) ) ;
frame.setSize(width, height);
frame.setVisible(true) ;
}

,
,
(
). E x i t L i s t e n e r ,
, ,
S y s t e m . e x i t ( 0 ) . :
public class ExitListener extends WindowAdapter {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
}
14 Java-.
W i n d o w U t i l i t i e s ,
.

9 . 1 1 .
p a i n t .
G r a p h i c s .
G r a p h i c s g e t G r a p h i c s .
g e t G r a p h i c s ,
G r a p h i c s ,
p a i n t !^ . ,
, p a i n t G r a p h i c s .
, Swing, G r a p h i c s
. ,
, p a i n t ,
p a i n t C o m p o n e n t . "" Swing-,
J A p p l e t J F r a m e . ,
Swing J A p p l e t J F r a m e "" ,
J P a n e l .
10 14.

336

9 .

, , ,
, P a n e l , C a n v a s Frame.
13. , "" Swing, J P a n e l ,
Java 2D.
Java ,
, . ,
, . (0,0)
; ,
. , Java
, , ,
. ,
. )
, . ,
,
, .
AWT Graphics ,
( ) ).
Java 2 Java 2D API G r a p h i c s 2 D ,
, (
.) ,
. Java 2D 10
h t t p : / / J a v a , s u n , c o m / p r o d u c t s / j a v a - m e d i a / 2 D / .


Graphics.

Java 2D Graphcs2D (
Java Plug-In).
G r a p h i c s .


p u b l i c void clearRect(int left, int t o p , int width, int height)
c l e a r Re c t .
public void copyArea(int left, int t o p , int width, int height, int deltaX, int deltaY)
,
l e f t , t o p , w i d t h , h e i g h t , l e f t + d e l t a X , t o p + d e l t a Y ,
width, height.
public Graphics create()
public Graphics create(int left, int t o p , int width, int height)
! .
, ,

9 . 1 1 .

337

,
.
public v o i d draw3DRect(int left, int t o p , int width, int h e i g h t , b o o l e a n raised)
1 .
r a i s e d t r u e ,
, , ""
. r a i s e d f a l s e ,
, , ""
. ,
, .
public void fill3DRect(int left, int t o p , int width, int h e i g h t , b o o l e a n raised)
3D.
p u b l i c v o i d drawArc(int left, int t o p , int width, int height, int startAngle,
int deltaAngle)
d r a w A r c ) .
, . ,
;
, (3 ).
Math, , .
p u b l i c v o i d fillArc(int left, int t o p , int w i d t h , int h e i g h t , int startAngle,
int deltaAngle)
(. d r a w A r c ) .
public v o i d d r a w l m a g e ( l m a g e i m a g e , int left, int t o p , I m a g e O b s e r v e r observer)
.
g e t Image A p p l e t T o o l k i t . ,
g e t Image , d r a w l m a g e
g e t Image, , , . )^
I m a g e O b s e r v e r ( t h i s ) . :)
.
public void d r a w l m a g e ( l m a g e i m a g e , int left, int t o p , int width, int h e i g h t ,
I m a g e O b s e r v e r observer)
,
( l e f t , t o p , w i d t h , h e i g h t ) .
public void d r a w l m a g e ( l m a g e i m a g e , int left, int t o p . Color b g C o l o r ,
I m a g e O b s e r v e r observer) public v o i d d r a w l m a g e ( l m a g e i m a g e , int left, int t o p ,
int width, int h e i g h t . Color bgColor, I m a g e O b s e r v e r observer)

.
.

338

9.

public void drawLine(int x l , int y l , int x 2 , int 2)


d r a w L i n e 1 .
public void drawOval(int left, int t o p , int width, int height)
.
. , d r a w O v a l ( 7 5 , 7 5 , 5 0 , 50)
50 (100, 100).
public void fillOval(int left, int t o p , int width, int height)
f i l l O v a l ,
.
public void drawPolygon(int[ ] xArray, int[ ] , int n u m P o i n t s )
public void d r a w P o l y g o n ( P o l y g o n p o l y g o n )
,
, P o l y g o n (,
). .
, .
public v o i d fillPolygon(int[ ] , int[ ] , int n u m P o i n t s )
public void f i l l P o l y g o n ( P o l y g o n polygon)
.
) ;
.
p u b l i c void drawRect(int left, int t o p , int width, int height)
1 ( 1
). . drawBDRect d r a w R o u n d R e c t .
public void fillRect(int left, int t o p , int w i d t h , int height)
, \ .
AWT
, .
. f i l l 3 D R e c t f i l l R o u n d R e c t .
public void d r a w R o u n d R e c t ( i n t left, int t o p , int width, int h e i g h t , int arcWidth,
int arcHeight)
.
a r c W i d t h a r c H e i g h t . ( ) /!
/ . - ,
.
public void drawString(String string, int left, int bottom)
,
. , -

9 . 1 1 .

339

, .
c h a r b y t e d r a w C h a r s d r a w B y t e s .


p u b l i c Color getColorO
C o l o r , .

g e t B a c k g r o u n d
setBackground.
public v o i d setColor(Color color)
.
G r a p h i c s ,
. s e t C o l o r
G r a p h i c s . p a i n t
g e t G r a p h i c s G r a p h i c s ,
. s e t F o r e g r o u n d ,
G r a p h i c s ,
s e t F o r e g r o u n d .
public Font getFontO
F o n t ,
.
g e t F o n t s e t F o n t . Component ( ,
A p p l e t ) , G r a p h i c s g e t F o n t M e t r i c s ,
F o n t .
F o n t M e t r i c s
( c h a r W i d t h ) ( s t r i n g W i d t h ) ,
.
public void s e t F o n t ( F o n t font)
d r a w S t r i n g .
, s e t F o n t ,
p a i n t g e t G r a p h i c s .
s e t F o n t .


p u b l i c void s e t X O R M o d e ( C o l o r color)

XOR:
XOR
. , XOR, -

340

9.

. XOR
, XOR
,
. XOR,
.
, .
C o l o r . b l a c k ,

XOR .
, s e t P a i n t M o d e .
public void setPaintMode()
XOR ,
. . .


public void clipRect(int left, int t o p , int width, int height)

.
public R e c t a n g l e g e t C l i p B o u n d s ( )
,
. n u l l .
public Shape getClipO
g e t C l i p S h a p e , .
p u b i c void setClip(Shape c l i p p i n g R e g i o n )
.
public v o i d translate(int deltaX, int deltaY)
t r a n s l a t e .

9.12.
, Java,
GIF JPEG, GIF GIF89A.
.
g e t Image A p p l e t
T o o l k i t . d r a w Image
G r a p h i c s .
. ,
g e t Image . Java
, .

9 . 1 2 .

341

,
; . ,
- ,
, p r e p a r e l m a g e M e d i a T r a c k e r .
( p r e p a r e l m a g e ) ,
.
,
(, ). d r a w Image ,
, - . d r a w l m a g e
, ,
. p a i n t ( p a i n t C o m p o n e n t "" Swing) , ,
, d r a w l m a g e p a i n t ,
. ,
, .
, ,
, .. M e d i a T r a c k e r .

^
URL
A p p l e t g e t Image,
: URL ,
. URL , ,
g e t C o d e B a s e ( ,
) g e t D o c u m e n t B a s e ( ,
Web-). , g e t Image ,
. , g e t Image
i n i t . ^ Image . , ,
.
p r i v a t e Image myImage = g e t l m a g e ( . . . ) ;

//

!
nepei^etiy image
.
,
nt.
, '^^ d r a w l m a g e
G r a p h i c s . p a i n t (
G r a p h i c s ) ,
g e t G r a p h i c s .
drawlmage.

342

9.

drawlmage(image, left, top, window)

drawlmage(image,

left,

top, width,

height,

window)

.
)
. I m a g e O b s e r v e r ;
(). ,
p a i n t ,
d r a w l m a g e t h i s . 1 9.11 9.12
, i m a g e s ,
, . . 9.5.
9 . 1 1 . JavaManl. j a v a
import
import

Java.applet.Applet;
java.awt.*;

/ * * , ,
* URL.
V

p u b l i c c l a s s JavaManl e x t e n d s A p p l e t {
p r i v a t e Image javaMan;
public void i n i t O {
javaMan = g e t I m a g e ( g e t C o d e B a s e ( ) , " i m a g e s / J a v a - M a n . g i f " )
}

public void paint(Graphics g) {


g.drawlmage(j avaMan, 0, 0, thi s);
}

9.12. JavaManl. html


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>JavaManl</TITLE>
</HEAD>
<BODY BGCOLOR="WHITE">
<Hl>JavaManl</Hl>
<APPLET CODE="JavaManl.class" WIDTH=370 HEIGHT=365>
<B>Sorry, you have a Java-challenged browser.</B>
</APPLET>
</BODY>
</HTML>

9 . 1 2 .

343

'11||1-|11'

' ^ -/ 3 :^1 ^ iSi rf

JavaManl

. 9.5. ,

;fflg''=^

^-^ :5! ^,:.:

getlmage(getCodeBase(), path)
getlmage(getDocumentBase(), path)

,
URL

URL
URL, ,
URL. (
8.) , S e c u r i t y Manager ,
, URL
. , ,
, , HTML-
. URL .
9.13 9.14 HTML. . 9.6. ,
URL t r y / c a t c h . , ,
j a v a . n e t , URL M a l f o r m e d U R L E x c e p t i o n . .
URL ,
, .
, ,
.

344

9.

9.13. JavaMcm2. Java


import Java, applet .Appletsimport java.awt.*;
import java.net.*;
/** , ,
* URL. URL
* , .

V
public class JavaMan2 extends Applet {
private Image javaMan;
public void initO {
try {
URL imageFile = new URL("http://www.corewebprogramming.com" +
"/images/Java-Man.gif") ;
javaMan = getlmage(imageFile);
} catch(MalformedURLException mue) {
showStatus("Bogus image URL.");
System.out.println("Bogus URL");
}
}
public void paint(Graphics g) {
g.drawlmage(javaMan, 0, 0, this);
}

9.14. JavaMan2.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>JavaMan2</TITLE>
</HEAD>
<BODY BGCOLOR="WHITE">
<Hl>JavaMan2</Hl>
<APPLET C0DE="JavaMan2.class" WIDTH=370 HEIGHT=365>
<B>Sorry, you have a Java-challenged browser.</B>
</APPLET>
</BODY>
</HTML>

9 . 1 2 .

345

irft int^nei Exnfor^

A j j d t e s s j ^ 1/'/\^wwcofewebptogtarnrningcorn/JavaMan2htm|

J ^

^fi^So

JavaMan2

jd
|^Ap0!etterted

^M}>D3ipuJ

. 9.6.
URL
,
,

,
URL, .
g e t Image T o o l k i t . URL ,
Web-.
, , g e t Image ,
URL URL .
, ,
. T o o l k i t
, g e t T o o l k i t T o o l k i t . g e t D e f a u l t T o o l k i t .
, 9.15 J P a n e l ,
. ,
; System, g e t P r o p e r t y ( " u s e r . d i r " ) .

. . 9.7.
W i n d o w U t i l i t i e s , WindowList e n e r , 14.

, ,
, .

346

9.

9.15. JavaManS.Java
import java.awt.*;
import javax.swing.*;
/** ,
* . .
class JavaMan3 extends JPanel {
private Image javaMan;
public JavaMan3 () {
String imageFile = System.getProperty("user.dir") +
"/images/Java-Man.gif";
javaMan = getToolkitO .getImage(imageFile);
setBackground(Color.white);
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawlmage(javaMan, 0, 0, this);
}
public static void main(String[] args) {
JPanel panel = new JavaMan3();
WindowUtilities.setNativeLookAndFeel() ;
WindowUtilities.openlnJFrame(panel, 380, 390);
}

. 9.7.

getToolkitO .getlmage (arg)
Toolkit.getDefaultToolkit().getlmage(arg)

9.13.

347

9.13.
,
,
d r a w I m a g e . ,
,
. ,
. p r e p a r e Image

. p r e p a r e Image;
d r a w l m a g e .
preparelmage(image,

window)

preparelmage(image, width, height, window)


, ,
, , p r e p a r e l m a g e
. 9.16
, ,
. ,
, .
- p r e l o a d , p r e p a r e l m a g e .
. 9.8 ,
. . 9.9
, p r e l o a d
. , ,
. 9.8,
, , p r e p a r e l m a g e ,
.
,
9.16;
.
r e g i s t e r l m a g e , P r e l o a d .
9 . 1 6 . P r e l o a d . J a v a
import
import
import
import

java.awt.^;
Java.awt.event.*;
javax.swing.*;
java.net.*;

/** ,
*
"^ ( g e t l m a g e , p r e p a r e l m a g e drawlmage)
* ( g e t l m a g e and d r a w l m a g e ) .
*

<>

*
*

348

*
*
*

9.

,

.

public class Preload extends JPanel implements ActionListener {


private JTextField timeField;
private long start = 0;
private boolean draw = falserprivate JButton buttonsprivate Image platenpublic Preload(String imageFile, boolean preload) {
setLayout(new BorderLayout() K*
button = new JButton("Display Image"/,
button.setFont(new Font("SansSerif", Font.BOLD, 24));
button.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(button);
timeField = new JTextField(25);
timeField.setEditable(false);
timeField.setFont(new Font("SansSerif", Font.BOLD, 24));
buttonPanel.add(timeField);
add(buttonPanel, BorderLayout.SOUTH);
registerlmage(imageFile, preload);
}
/"** ,
* , ,
* .
^/
public void actionPerformed(ActionEvent event) {
draw = true;
start = System.currentTimeMillis0;
repaint();
}
// getImage ,
// , .
private void registerlmage(String imageFile, boolean preload) {
try {
plate = getToolkit().getlmage(new URL(imageFile));
if (preload) {
preparelmage(plate, this);
}
} catch(MalformedURLException mue) {
System.out.println("Bad URL: " + mue);
}
}
/** ,
* , , do nothing.
* .

9.13.

*/
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (draw) {
g.drawlmage(plate, 0, 0, this);
showTime();
}
}
// ,
private void showTime() {
timeField.setText("Elapsed Time: " + elapsedTime() +
" seconds.");
}
// .
private double elapsedTime() {
double delta = (double)(System.currentTimeMillis() - start);
return(delta/1000.0);
}
public static void main(String[] args) {
JPanel preload;
if (args.length == 0) {
System.out.println("Must provide URL");
System.exit(0);
}
if (args.length == 2 && args[1].equals("-preload")) {
preload = new Preload(args[0], true);
} else {
preload = new Preload(args [0], false);
}
WindowUtilities.setNativeLookAndFeel();
WindowUtilities.openlnJFrame(preload, 1000, 750);
}

349

350

9.

. 9.8. ,
. get image
drawimage, ,

. 9.9. p r e
pare image;

9.14. ...

351

9.14. :

,
, .
, , ,
,
. ,
9.17 9.18. i n i t ,
p a i n t .
Internet Explorer 5, Windows 98, . 9.10.
, -1.
9.17.ImageBox.Java
import
import

Java.applet.Applet/
java.awt.*;

/** ,
* .
* !
V
p u b l i c c l a s s ImageBox e x t e n d s A p p l e t {
p r i v a t e i n t imageWidth, imageHeight;
p r i v a t e Image i m a g e ;
public void i n i t O {
S t r i n g imageName = g e t P a r a m e t e r ( " I M A G E " ) ;
i f (imageName != n u l l ) {
image = g e t l m a g e ( g e t D o c u m e n t B a s e ( ) , imageName);
} else {
image = g e t l m a g e ( g e t D o c u m e n t B a s e ( ) , " e r r o r . g i f " ) ;
}

setBackground(Color.white);
/ / ,
/ / - 1 .
imageWidth = i m a g e . g e t W i d t h ( t h i s ) ;
imageHeight = i m a g e . g e t H e i g h t ( t h i s ) ;
p u b l i c v o i d p a i n t ( G r a p h i c s g) {
g . d r a w l m a g e ( i m a g e , 0, 0, t h i s ) ;
g . d r a w R e c t ( 0 , 0, i m a g e W i d t h , i m a g e H e i g h t ) ;
}

352

9.

9 . 1 8 . I m a g e B o x , h t m l
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0 T r a n s i t i o n a l / / E N " >
<HTML>
<HEAD>
<TITLE>ImageBox</TITLE>
</HEAD>
<BODY>
<Hl>ImageBox</Hl>
<APPLET C O D E = " I m a g e B o x . c l a s s " WIDTH=235 HEIGHT=135>
<PARAM NAME="IMAGE" V A L U E = " i m a g e s / s u r f i n g . g i f " >
S o r r y , you n e e d a < B > r e a l < / B > b r o w s e r .
</APPLET>
</BODY>
</HTML>

; fiie

gtU * Favorite

bxh

->

Ima geBox
1 .^-'

^
] Done

J^ MyCorapUa

. 9.10.
,

, M e d i a T r a c k e r .
,
a d d Image
( w a i t F o r l D w a i t F o r A l l ) .
M e d i a T r a c k e r , ,
, .
.

MediaTracker
public void a d d l m a g e ( l m a g e i m a g e , int id)
public void a d d l m a g ( l m a g e i m a g e , int id, int width, int height)

.
,
.
;
.

9.14. ...

353

public b o o l e a n checkAll()
public b o o l e a n c h e c k A l l ( b o o l e a n startLoading)
t r u e , ,
M e d i a T r a c k e r , .
f a l s e . s t a r t L o a d i n g
t r u e , ,
. C h e c k A l l
, w a i t F o r A l l ,
, .
public b o o l e a n c h e c k I D ( i n t id)
public b o o l e a n c h e c k I D ( i n t id, b o o l e a n startLoading)
c h e c k F o r A l l ,
.
p u b l i c Object[ ] getErrorsAnyO
p u b l i c Object[ ] getErrorsID(int id)
,
.
public b o o l e a n isErrorAnyO
public b o o l e a n isErrorID(int id)
t r u e ,
. f a l s e .
public void r e m o v e I m a g e ( I m a g e image)
public void r e m o v e I m a g e ( I m a g e i m a g e , int id)
public void r e m o v e I m a g e ( I m a g e i m a g e , int id, int width, int height)
.
public int statusAll()
public int statusID(int id, b o o l e a n startLoading)
,
.
M e d i a T r a c k e r : M e d i a T r a c
k e r . LOADING, MediaTracker.ABORTED, MediaTracker.ERRORED M e d i a T r a c
k e r . COMPLETE. , ,
. s t a r t L o a d i n g t r u e ,
, .

354

9.

public void waitForAllO


public boolean waitForAll(long milliseconds)
,
; ,
,
.
. I n t e r r u p t e d E x c e p t i o n ,
.
public void waitForID(int id)
public boolean waitForID(int id, long milliseconds)
,
.
,
, .
I n t e r r u p t e d E x c e p t i o n ,
.
9.19 9.20 ImageBox, ,
, .
. 9.11.
9.19.BetterImageBox.java
import Java, a p p l e t .Appletsimport j a v a . a w t . * ;
/** , ImageBox,
* MediaTracker.
* .
p u b l i c c l a s s BetterlmageBox extends Applet {
p r i v a t e i n t imageWidth, imageHeight;
p r i v a t e Image imagesp u b l i c void i n i t O {
S t r i n g imageName = getParameter("IMAGE");
i f (imageName != n u l l ) {
image = getlmage(getDocumentBase(), imageName);
} else {
image = getlmage(getDocumentBase(), " e r r o r . g i f " ) ;
}

setBackground(Color.white);
MediaTracker t r a c k e r = new M e d i a T r a c k e r ( t h i s ) ;
tracker.addlmage(image, 0 ) ;
try {
tracker.waitForAll();
} catch(InterruptedException i e ) {}

9.14. ...

355

if (tracker.isErrorAny) {
System.out.println("Error while loading image");
)
// .
imageWidth = image.getWidth(this);
imageHeight = image.getHeight(this);
}
p u b l i c v o i d p a i n t ( G r a p h i c s g) {
g . d r a w l m a g e ( i m a g e , 0, 0, t h i s ) ;
g . d r a w R e c t ( 0 , 0, i m a g e W i d t h , i m a g e H e i g h t ) ;
}

9 . 2 0 . B e t t e r I m a g e B o x . h t m l
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0 T r a n s i t i o n a l / / E N " >
<HTML>
<HEAD>
<TITLE>ImageBox</TITLE>
</HEAD>
<BODY>
<Hl>ImageBox</Hl>
<APPLET C O D E = " B e t t e r I m a g e B o x . c l a s s " WIDTH=235 HEIGHT=135>
<PARAM NAME="IMAGE" V A L U E = " i m a g e s / s u r f i n g . g i f " >
S o r r y , you n e e d a < B > r e a l < / B > b r o w s e r .
</APPLET>
</BODY>
</HTML>

1 1 ^

l^svoi lock U l " ^ 9 |

ImageBox

^
,JP3 Pone

^ My

. 9.11. MediaTracker,

M e d i a T r a c k e r
,
. 9.21 T r a c k e r U t i l
: w a i t F o r l m a g e w a i t F o r I m a g e s . w a i t F o r l m a g e
:

356

9.

someImage = getImage(...);
doSomeOtherStuff();
if (TrackerUtil.waitForlmage(somelmage, this))
// somelmage ,
else
// somelmage.
, , wait For Images,
imagel = getlmage(...);
image2 = getlmage(...);
imageN = getlmage(...);
doSomeOtherStuff() ;
Image[] images = { imagel, image2, ... , imageN };
if (TrackerUtil.waitForlmages(images, this))
// ,
else
/ / .
,
M e d i a T r a c k e r , i m a g e U p d a t e
. API.
9 . 2 1 . T r a c k e r U t i l , J a v a
import
/**
*
*
*
*
*
*
*/

java.awt.*;

,
.

, waitForlmage.
, ,
waitForImages;
.

public class TrackerUtil {


public static boolean waitForlmage(Image image. Component c) {
MediaTracker tracker = new MediaTracker(c);
tracker.addlmage(image, 0 ) ;
try {
tracker.waitForAll();
} catch(InterruptedException ie) {}
if (tracker.isErrorAny0) {
return(false) ;
} else {
return(true);
}
}
public static boolean waitForlmages(Image[] images.
Component c) {
MediaTracker tracker = new MediaTracker(c);
for(int i=0; i<images.length; i++) {
tracker.addlmage(images[i], 0 ) ;

9.15.

357

try {
tracker.waitForAll();
} catch(InterruptedException ie) {}
if (tracker.isErrorAny0) {
return(false);
} else {
return(true);
}

9.15.
, Web.
, .
j a v a . a p p l e t .Applet Web-
APPLET.
Swing, . ,
Swing, Java Plug-In Swing
. , Internet.
Java-, Web,
JFrame.
p a i n t . p a i n t Component
"" Swing; JFrame J P a n e l .
G r a p h i c s ,
. ,
,
Java 2D API, .

drawlmage, GIF JPEG,
g e t Image Applet T o o l k i t .
.
MediaTracker.
, .

JAVA 2D:

JAVA 2
...

20-.

.
.

J~y\ZJSJ^

, - ,
Abstract Windowing Toolkit (AWT),
, , G r a p h i c s .
, Sun AWT
Java World Wide Web. AWT
,
,
.
Java 2D , Java 2.
Swing-. Java 2D API

. Java 2D.

.
.

.
.

. ,
, .

.
, .

, .

, Java 2D API
Java Foundation Classes, Java 2. Swing, JDK 1.1, Java 2D
. 2D Java 2,
, Java 2 Java Plug-In,

360

10. Java 2D: Java 2

9. Java 2D API
h t t p : / / j a v a . s u n . c o m / p r o d u c t s / j a v a media/2D/. JDK 1.3 2D,
r o o t / j d k l . 3/demo/jf/Java2D/. Java 2D
; 15.

1 0 . 1 . Java 2D
Java 2 paintComponent Graphics2D,
, AWT G r a p h i c s .
Swing paintComponent
G r a p h i c s (Graphics2D Graphics). ,
, G r a p h i c s
Graphics2D. Java 2 , G r a p h i c s
( p a i n t , paintComponent, g e t G r a p h i c s ) , Graphics2D.
Java 1.1
10.1. AWT- Component p a i n t .
G r a p h i c s ,
. 10.2 Java 2D.
Swing- paintCompo
n e n t . Graphics2D p a i n t AWT,
G r a p h i c s 2D Java Foundations Classes,
Swing,
J P a n e l . 2D-pHCOBaHHe p a i n t
JFrame, J A p p l e t JWindow, ""
Swing- paintComponent.
10.1. Java 1.1
public void paint(Graphics g) {
// .
g.setColor(someColor);
g.setFont(someLimitedFont);
// .
g.drawstring(. . . ) ;
g.drawLine(...
g.drawRect(...
//
g.fillRect(...
//
g.drawPolygon( . . ) ;
//
g.fillPolygon( . . ) ;
//
g.drawOval(...
//
g.fillOvaK. . . ]
//

1 0 . 1 . Java 2 D

361

10.2. Java 2
public void paintComponent(Graphics g) {
// .
super.paintComponent(g);
// Graphics 6raphics2D.
Graphics2D g2d = (Graphics2D)g;
// .
g2d.setPaint(fillColorOrPattern);
g2d.setStroke(penThicknessOrPattern) ;
g2d.setComposite(someAlphaComposite);
g2d.setFont(anyFont);
g2d.translate(...);
g2d.rotate(...);
g2d.scale(...);
g2d.shear(...);
g2d.setTransform(someAffineTransform);
// .
SomeShape s = new SomeShape(...);
// .
g2d.draw(s); //
g2d.fill(s); //

Java 2D .
Graphics Graphics2D
paintComponent
paintComponent , Swing
p a i n t ComponentUI;
. , paintComponent
, Swing .
, Java 2- G r a p h i c s
Graphics2 D.
public void paintComponent(Graphics g) {
super.paintComponent(g) ;
Graphics2D g2d = (6raphics2D)g;
g2d.doSomeStuff(...);
}

> Swing-,

super.paintComponent.

( )
Shape, Graphics 2D.
(Graphics2D)
Shape.

362

10. Java 2D: Java 2

g2d.setPaint(fillColorOrPattern) ;
g2d.setStroke(penThicknessOrPattern);
g2d.setComposite(someAlphaComposite);
g2d.setFont(someFont);
g2d.translate(...);
g2d.rotate(...);
g2d.scale(...);
g2d.shear(...);
g2d.setTransform(someAffineTransform);
Shape
Rectangle2D.Double rect = ...;
Ellipse2D.Double ellipse = ...;
Polygon poly = ...;
GeneralPath path = ...;
// Shape.
SomeShapeYouDefined shape = ...;
Shape
Shape draw fill Graph ics2D.
, Graphics2D, ,
.
g2d.draw (someShape) ;
g2d.fill(someShape);
G r a p h i c s 2 D G r a p h i c s , ,
AWT, 9. ,
G r a p h i c s 2 D .
S h a p e
. , ,
, (, ,
), .

Graphics2D
G r a p h i c s 2 D .
public v o i d draw(Shape shape)
,
G r a p h i c s 2D.
( R e c t a n g l e ) , (0,0).
,
G r a p h i c s 2 D : r o t a t e , t r a n s f o r m , t r a n s l a t e .

1 0 . 1 . Java 2D

363

public b o o l e a n drawImage(BufferedImage i m a g e , B u f f e r e d l m a g e O p filter, int


left, int top)
Buf f e r e d l m a g e ,
( l e f t , t o p ) . ( f i l t e r ) .
Buf f e r e d l m a g e 10.3.
p u b l i c void drawString(String s, float left, float bottom)
,
.
. Java 2D API d r a w S t r i n g ,
d o u b l e , d r a w S t r i n g ( s , 2 . 0 , 3 . 0 )
. , ,
f l o a t , d r a w S t r i n g ( s , 2.Of,
3.0f).
Java 2D ,
.
Java 2D (User Coordinate
Space), .

(Device Coordinate Space).
72 1
.
.
p u b l i c v o i d fill(Shape shape)

G r a p h i c s 2D.
d r a w .
p u b l i c void rotate(double theta)
r o t a t e t h e t a
(0,0). r o t a t e ,
G r a p h i c s 2 D .
public v o i d rotate(double theta, d o u b l e x, d o u b l e y)
r o t a t e t h e t a
(,).
p u b l i c v o i d s c a l e ( d o u b l e x s c a l e , d o u b l e yscale)
.
, 1.0, , 1.0
. x s c a l e , -1,
.
y s c a l e -1, .

364

10. Java 2D: Java 2

public void setComposite(Composite rule)



.
, AlphaComposite:
A l p h a C o m p o s i t e . C l e a r , A l p h a C o m p o s i t e . D s t i n , AlphaComposite.DstOut,
AlphaComposite.DstOver, A l p h a C o m p o s i t e . S r c ,
AlphaComposite.Srcin,
AlphaComposite.SrcOut, AlphaComposite.ScrOver.
AlphaComposite, g e t I n s t a n c e
:
g2d.setComposite(AlphaComposite.SrcOver);

int type = AlphaComposite.SRC_OVER;


float alpha = 0.75f;
AlphaComposite rule =
AlphaComposite.getlnstance(type, alpha);
g2d.setComposite(rule);

a l p h a ,
. 1.0
( ). . (.
Porter) . (. Duff) "Compositing Digital Images" SIGGRAPH 84,
p. 253-259.
public void setPaint(Paint paint)
Graphics2D.
, P a i n t . ,
Java 2, Color, G r a d i e n t P a i n t
TexturePaint.
public void setRenderingHints(Map hints)
s e t R e n d e r i n g H i n t s . AWT
R e n d e r i n g H i n t s , Map
.
, ,
. ,
,
, .
RenderingHints hints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RengeringHints.VALUE_ANTIALIAS_ON);
hints.add(new RenderingHints(
RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY));
public void setStroke(Stroke pen)

G r a p h i c s 2D
S t r o k e . s e t S t r o k e S t r o k e ,

10.2.

365

. , ,
S t r o k e . AWT B a s i c S t r o k e ,
, .
public void transform(AffineTransform matrix)
,
Graphics2D. (. 10.7).
public void translate(double , double )
t r a n s l a t e .
, Graphics2D.
1/72 ,
. 300
600 dpi 4 9 .
public void setPaintModeO
setPaintMode Graphics.
(
XOR). Graphics2D setPaintMode
setComposite (AlphaComposite.SrcOver),
"" .
public void setXORMode(Color color)
setXORMode Graphics.
Graphics2D setXORMode
, . XOR
.
XOR ,
XOR. XOR ,
. ,
. .

10.2.
AWT drawXxx f illXxx
Graphics. Java 2D Shape,
draw f i l l Graphics2D. :
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
// , , diameter
// .
Ellipse2D.Double circle ss
new Ellipse2D.double(x, y, diameter, diameter);
g2d.fill(circle);

366

10. Java 2D: Java 2

Shape Shape. Double


Shape . F l o a t .
(Shape. Double),
(Shape. F l o a t ) . ,
, .
Graphics2D G r a p h i c s ,
drawXxx

Shape
, draw f i l l Graphics2D, Shape.
, Arc2D, Area, CubicCurve2D, E l l i p s e 2 D ,
G e n e r a l P a t h , Line2D, QuadCurve2D, Rectangle2D RoundRectangle2D.
J a v a , awt. geom. ,
Area, Polygon R e c t a n g l e , f l o a t double.
Polygon R e c t a n g l e , Java 1.1,
Shape. 9.
Shape .
public Arc2D.Float(float left, float top, float width, float height,
float startAngle, float deltaAngle, int closure)
public Arc2D.Double(double left, double top, double width,
double height, double startAngle, double deltaAngle,
int closure)
, ,
, ( l e f t , top).
() . .
, ,
45 ,
. c l o s u r e
Arc2D. CHORD, Arc2D. OPEN Arc2D. PIE.
public Area(Shape shape)
( Area) Shape.
, add,
s u b t r a c t , i n t e r s e c t exclusiveOr.
public CubicCurve2D.Float(float xStart, float yStart,
float pX, float pY,
float qX, float qY,
float xEnd, float yEnd)
public CubicCurve2D.Double(double xStart, double yStart,
double pX, double pY,
double qX, double qY,
double xEnd, double yEnd)

10.2.

367

C u b i c C u r v e 2 D ,
(), ( x S t a r t , y S t a r t ) (xEnd, yEnd).
(, pY) (qX, qY).
p u b l i c Ellipse2D.Float(float left, float t o p , float width, float height)
p u b l i c E l l i p s e 2 D . D o u b l e ( d o u b l e left, d o u b l e t o p , d o u b l e width, d o u b l e height)
,
w i d t h h e i g h t . E l l i p s e 2 D R e c t a n g u l a r S h a p e
, R e c t a n g l e 2 D R o u n d R e c t a n g l e 2 D .
p u b l i c GeneralPathO
G e n e r a l P a t h ,
S h a p e .
, c l o s e P a t h , c u r v e T o ,
l i n e T o , moveTo quadTo. G e n e r a l P a t h ,
moveTo,
I l l e g a l P a t h S t a t e E x c e p t i o n . G e n e r a l P a t h .
G e n e r a l P a t h p a t h = new G e n e r a l P a t h O ;
p a t h . m o v e T o ( 1 0 0 , 100) ;
p a t h . l i n e T o ( 3 0 0 , 205) ;
p a t h . q u a d T o ( 2 0 5 , 2 5 0 , 34 0 , 3 0 0 ) ;
p a t h . l i n e T o ( 3 4 0, 350) ;
path.closePath();
p u b l i c Line2D.Float(float xStart, float yStart, float x E n d , float yEnd)
p u b l i c L i n e 2 D . D o u b l e ( d o u b l e xStart, d o u b l e yStart, d o u b l e x E n d , d o u b l e yEnd)
Line2D,
, ( x S t a r t , y S t a r t ) (xEnd, yEnd).
p u b l i c Line2D.Float(Point p i . P o i n t p2)
p u b l i c L i n e 2 D . D o u b l e ( P o i n t p i . P o i n t p2)
L i n e 2 D ,
, 1 2 ( P o i n t ) .
public QuadCur-ve2D.Float(float xStart, float yStart,
float pX, float pY,
float x E n d , float yEnd)
public Q u a d C u r v e 2 D . D o u b l e ( d o u b l e xStart, d o u b l e yStart,
d o u b l e pX, d o u b l e pY,
d o u b l e x E n d , d o u b l e yEnd)
S h a p e , ,
( x S t a r t , y S t a r t ) (xEnd, yEnd). (, pY)
.

368

10. Java 2D: Java 2

public Rectangle2D.Float(float top, float left, float width, float height)


public Rectangle2D.Double(double top, double left, double width, double height)
Rectangle2D, ..
width h e i g h t , (top,
left).
public RoundRectangle2D.Float(noat top, float left,
float width, float height,
float arcX, float arcY)
public RoundRectangle2D.Double(double top, double left,
double width, double height,
double arcX, double arcY)
RectangleShape .
width h e i g h t ,
(top, l e f t ) . a r c Y
( ),
.
( E l l i s p s e 2 D ,
) (Rectangle2D) 10.3.
, .
Graphics 2D,
. . 10.1. g e t C i r c l e
, .
ShapeExample W i n d o w U t i l i t i e s ( 14.1)
E x i t L i s t e n e r ( 14.2).
, , Java-.
, :
import java.awt.*;
import javax.swing.*;
public class YourApplet extends JApplet {
public void initO {
JPanel panel new ChapterExample();
panel.setBackground(Color.white);
getContentPane().add(panel);
}
}
JApplet ,
JPanel, c o n t e n t JApplet.
JPanel. HTML- (
, JFrame)
a p p l e t viewer HTML- Java Plug-In.
Java Plug-In HTML- . 9.9.

10.2.

10.3.ShapeExample.Java
import javax.swing.*;
import java.awt.*;
import Java, awt .geom.""

// JPanel, .
// Graphics, .
// Ellipse2D, .

/** / Java 2D
* Java 1.2 .
public class ShapeExample extends JPanel {
private Ellipse2D.Double circle s=
new Ellipse2D.Double(10, 10, 350, 350);
private Rectangle2D. Dotible SG[uare
new Rectangle2D.Double(10, 10, 350, 350);
public void paintComponent(Graphics g) {
clear (g);
Graphics2D g2d = (Graphics2D)g;
g2d.fill(circle);

g2d.draw(sG[uare) ;
}

// no ,
. // super.paintComponent ,
protected void clear(Graphics g) {
super.paintComponent(g);
}
protected Ellipse2D.Double getCircleO {
return(circle);
}
public static void main(String[] args) {
WindowUtilities.openlnJFrame(new ShapeExample() 3 8 0 , 400)
}
}

. 10.1. () ,
Java 2D

369

370

10. Java 2D: Java 2

10.3.
S h a p e G r a p h i c s 2 D ,
P a i n t . C o l o r
( ), G r a d i e n t P a i n t ( ,
) T e x t u r e P a i n t ( ).
, P a i n t .
P a i n t ,
s e t P a i n t g e t P a i n t . , s e t P a i n t g e t P a i n t
s e t C o l o r g e t C o l o r ,
G r a p h i c s .


, s e t P a i n t G r a p h i c s 2 D ,
, g e t P a i n t , P a i n t .
P a i n t .

Color
C o l o r , AWT-,
,
. 4- ,
, ,
( a l p h a ) . 255,
. a l p h a 0.
C o l o r :
public Color(int r e d , int g r e e n , int blue)
public Color(float int, float g r e e n , float blue)
r e d , g r e e n b l u e
C o l o r . ( i n t )
255, ( f l o a t ) O.Of l.Of.
f l o a t i n t 255 .
public Color(int r e d , int g r e e n , int b l u e , int alpha)
public Color(float r e d , float g r e e n , float b l u e , float alpha)
C o l o r ,
a l p h a . r e d ,
g r e e n , b l u e , a l p h a .
, .
A l p h a C o m p o s i t e ,
G r a p h i c s 2 D s e t C o m p o s i t e .

10.3.

371

GradientPaint
G r a d i e n t P a i n t .
.
, .
, , , .

.
public GradientPaint(float xStart, float yStart,
Color colorStart, float x E n d , float yEnd,
Color colorEnd)
G r a d i e n t P a i n t ,
c o l o r S t a r t ( x S t a r t , y S t a r t ) c o l o r E n d
(xEnd, yEnd). ( ).
public GradientPaint(float xStart, float yStart,
Color colorStart, float x E n d , float yEnd,
Color c o l o r E e n d , b o o l e a n repeat)
, ,
r e p e a t
.

TexturePaint
T e x t u r e P a i n t ,
. T e x t u r e P a i n t , .
public T e x t u r e P a i n t ( B u f f e r e d I m a g e image, R e c t a n g l e 2 D tilesize)
T e x t u r e P a i n t Buf f e r e d l m a g e R e c t a n g l e 2 D
. Buf f e r e d l m a g e
GIF JPEG, .
Image

Buf f e r e d l m a g e , Buf f e r e d l m a g e .TYPE_INT_ARGB.


G r a p h i c s Buf f e r e d l m a g e ,
c r e a t e G r a p h i c s , Image Buf f e r e d l m a g e d r a w l m a g e .
10.4 .
( C o l o r , r e d ) (, 0)
( C o l o r . y e l l o w ) (185, 185) .
.
. 10.2.

372

10. Java 2D: Java 2

1 0 . 4 . GradientPaintEacample. j a v a
import

java.awt.^;

/** .
* , (0,0) (175,175).

V
public class GradientPaintExample extends ShapeExample {
private GradientPaint gradient =
new GradientPaint(0, 0, Color.red, 175, 175, Color.yellow,
true); // true
public void paintComponent(Graphics g) {
clear (g);
Graphics2D g2d = (Graphics2D)g;
drawGradientCircle(g2d);
}
protected void drawGradientCircle(Graphics2D g2d) {
g2d.setPaint(gradient);
g2d.fill(getCircle());
g2d.setPaint(Color.black);
g2d.draw(getCircle0);
}
public static void main(String[] args) {
WindowUtilities.openlnJFrame(new GradientPaintExample(),
380, 400);
}
}

. 10.2. , Java 2D

10.3.

373


,
( t i l e d ) , T e x t u r e P a i n t
s e t P a i n t G r a p h i c s 2 D ,
. T e x t u r e P a i n t
Buf f e r e d l m a g e R e c t a n g l e 2 D . Buf f e r e d l m a g e
, , R e c t a n g l e 2 D ,
.
. Buf f e r e d l m a g e
: Buf f e r e d l m a g e ,
, Buf f e r e d l m a g e .TYPE_INT_RGB,
c r e a t e G r a p h i c s
G r a p h i c s 2 D . :
int width =32;
int height=32;
Bufferedlmage bufferedlmage =
new Bufferedlmage(width, height
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufferedlmage.createGraphics();
g2d.draw(someShape);
TexturePaint texture =
new TexturePaint(bufferedlmage,
new Rectangle(0, 0, width, height));
G r a p h i c s 2 D , c r e a t e G r a p h i c s ,
Buf f e r e d l m a g e . G r a p h i c s 2 D
Buf f e r e d l m a g e . " "
32 ,
.
Buf f e r e d l m a g e . -,
Image M e d i a T r a c k e r , ,
. Buf f e r e d l m a g e ,
I m a g e . G r a p h i c s 2D
c r e a t e G r a p h i c s Image Buf f e r e d l m a g e .
g e t B u f f e r e d l m a g e I m a g e U t i l i t i e s ,
10.6.

10.5. . 10.3.
:
, ,
. ,
. R e c t a n g l e Buf f e r e d l m a g e
, .

374

10. Java 2D: Java 2

10.5. Tiledlmages.Java
import
import
import
import
/**
*
*
*

javax.swing.*;
java.awt.*;
Java.awt.geom.*;
Java.awt.image.*;

TexturePaint
.
Bufferedlmage
getBufferedlmage ImageUtilities.

V
public class Tiledlmages extends JPanel {
private String dir = System.getProperty("user.dir");
private String imageFilel = dir + "/images/marty.jpg";
private TexturePaint imagePaintl;
private Rectangle imageRect;
private String imageFile2 = dir + "/images/bluedrop.gif";
private TexturePaint imagePaint2;
private int[] xPoints = { 30, 700, 400 };
private int[] yPoints = { 30, 30, 600 };
private Polygon imageTriangle = new Polygon(xPoints, yPoints, 3)
public Tiledlmages() {
Bufferedlmage image =
ImageUtilities.getBufferedlmage(imageFilel, this);
imageRect = new Rectangle(235, 70, image.getWidth(),
image.getHeight() ) ;
imagePaintl = new TexturePaint(image, imageRect);
image = ImageUtilities.getBufferedlmage(imageFile2, this);
imagePaint2 =
new TexturePaint(image, new Rectangle(0, 0, 32, 32));
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(imagePaint2);
g2d.fill(imageTriangle);
g2d.setPaint(Color.blue);
g2d.setStroke(new BasicStroke(5) ) ;
g2d.draw(imageTriangle) ;
g2d.setPaint(imagePaintl);
g2d.fill(imageRect);
g2d.setPaint(Color.black);
g2d.draw(imageRect);
}
public static void main(String[] args) {
WindowUtilities.openlnJFrame(new Tiledlmages(), 750, 650);

10.3.

375

. 10.3. TexturePaint,

10.6.ImageUtilities.Java
import java.awt.*;
import Java.awt.image.*;
/**
*
*
*

,
, Bufferedlmage
MediaTracker
.

V
public class ImageUtilities {
/** Image
* Bufferedlmage.

V
piiblic static Bufferedlmage getBufferedlmage(String imageFile,
Component c) {
Image image = c.getToolkit().getImage(imageFile);
waitForImage(image, c ) ;
Bufferedlmage bufferedlmage =
new Bufferedlmage(image.getWidth(c), image.getHeight(c),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufferedlmage.createGraphics();
g2d.drawImage(image, 0 , 0 , c ) ;
return(bufferedlmage);
}
/**
*
*
*
*

Image, ,
.
,
; ,
.

376

10. Java 2D: Java 2

V
public static boolean waitForlmage(Image image, Component c) {
MediaTracker tracker = new MediaTracker(c);
tracker.addlmage(image, 0 ) ;
try {
tracker.waitForAll();
} catch(InterruptedException ie) {}
return(!tracker.isErrorAny());
}
/** , ,
* .
public static boolean waitForlmages(Image[] images. Component c) {
MediaTracker tracker = new MediaTracker(c);
for(int i=0; i<images.length; i++)
tracker.addlmage(images[i], 0 ) ;
try {
tracker.waitForAll();
} catch(InterruptedException ie) {}
return(!tracker.isErrorAny());

10.4.
Java 2D ( a l p h a ) ,
, , "''
.
A l p h a C o m p o s i t e , s e t C o m p o s i t e
G r a p h i c s 2D.

AlphaComposite

A l p h a C o m p o s i t e . g e t l n s t a n c e
, :
f l o a t alpha = 0.75f;
i n t t y p e = AlphaComposite.SRC_OVER;
AlphaComposite composite =
AlphaComposite.getlnstance(type, alpha);
A l p h a C o m p o s i t e API ,
"" A l p h a C o m p o s i t e . SRC_OVER.
,
. a l p h a O.Of (
) 1.Of ().
10.7 ,
, .
. 10.4 11 ,
. ,
.

10.4.

377

a l p h a O.Of;
1 .Of.
10.3,
.
Color.
p r i v a t e void drawSquares(Graphics2D g2d, f l o a t alpha) {
g2d.setPaint(Color.blue);
g2d.fill(blueSquare) ;
Color c o l o r = new Color(1, 0, 0, alpha); //
g2d.setPaint(color);
g2d.fill(redSquare) ;
}

, AlphaComposite.
SRCOVER. Graphics2D .
a l p h a AlphaComposite, Color,

alpha.
10.7. TransparencyExample.Java
import javax.swing.*;
import java.awt.*;
import Java.awt.geom.*;
/** AlphaComposite
* .

public class TransparencyExample extends JPanel {


private static int gap=10, width=60, offset=20,
deltaX=gap+width+offset ;
private Rectangle
blueSquare = new Rectangle(gap+offset, gap+offset, width,
width),
redSquare = new Rectangle(gap, gap, width, width);
private AlphaComposite makeComposite(float alpha) {
int type = AlphaComposite. SRC_OVER;
return(AlphaComposite.getlnstance(type, alpha));
}
private void drawSquares(Graphics2D g2d, float alpha) {
Composite originalComposite = g2d.getComposite();
g2d.setPaint(Color.blue);
g2d.fill(blueSquare);
g2d.setComposite(makeComposite(alpha));
g2d.setPaint(Color.red);
g2d.fill(redSquare);
g2d.setComposite(originalComposite);
}
public void paintComponent(Graphics g) {

378

10. Java 2D: Java 2

super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
for(int i=0; i<ll; i++) {
drawSquares(g2d, i*0.IF);
g2d.translate(deltaX, 0 ) ;
}
public static void main(String[] args) {
String title = "Transparency example: alpha of the top "
"(red) square ranges from 0.0 at the left '
"to 1.0 at the right. Bottom (blue) square
"is opaque.";
WindowUtilities.openlnJFrame(new TransparencyExample(),
ll*deltaX + 2*gap,
deltaX + 3*gap,
title, Color.lightGray);

^hw.'^l!li^rjlm{^lM[rj^fiMl^^lii,l[^^jlf^irl'^^^^^l^^^l^^l/ilf1^,lHl^^

. 10.4. , ,
, ""

10.5.

Java 2D , Java 1.1, : Serif


(. Times), SansSerif (, Helvetica Arial), Monospaced (,
Courier), Dialog, Dialoglnput. ,
, .
.
g e t A v a i l a b l e F o n t F a m i l y N a m e s g e t A l l F o n t s G r a p h i c s E n v i r o n m e n t .
G r a p h i c s E n v i r o n m e n t :
GraphicsEnvironment env =
GrapicsEnvironment.getLocalGraphicsEnvironment();

env.getAvailableFontFamilyNames

();

env.getAllFonts;

/ / !

API, ,
. , , -

1 0 . 5 .

379

, ,
, ,
.
!

, .

Font,

, g e t A l l F o n t s
Font, , ,
. ,
,
getAvailableFontFamilyNames.
getAvailableFontFamilyNames ,
. ,
, .
Font ,
, (SansSerif). 10.8 ,
, .
10.8. ListFonts.Java
import j a v a . a w t . * ;
/** . */
public class ListFonts {
p u b l i c s t a t i c void m a i n ( S t r i n g [ ] args) {
GraphicsEnvironment env =
GraphicsEnvironment.getLocalGraphicsEnvironment();
S t r i n g [ ] fontNames = env.getAvailableFontFamilyNames();
System.out.println("Available Fonts:");
f o r ( i n t 1=0; i<fontNames.length; i++)
S y s t e m . o u t . p r i n t l n ( " " + fontNames[i]);
}

, 10.9, , ,
"Java 2D" Goudy Handtooled .
. 10.5. Goudy
Handtooled , SansSerif.

380

10. Java 2D: Java 2

1 0 . 9 . F o n t E x a m p l e . J a v a
import

java.awt.*;

/**
* Java 2D.

V
public class FontExample extends GradientPaintExample {
public FontExample() {
GraphicsEnvironment env ==
GraphicsEnvironment.getLocalGraphicsEnvironment();
env. getAvailableFontFamilyNames () ;
setFont(new Font("Goudy Handtooled ", Font.PLAIN, 100))/
}
protected void drawBigString(Graphics2D g2d) {
g2d.setPaint(Color.black) ;
g2d.drawstring("Java 2D", 25, 215);
}
public void paintComponent(Graphics g) {
clear(g);
Graphics2D g2d = (Graphics2D)g;
drawGradientCircle(g2d) ;
drawBigString(g2d) ;
}
public static void main(String[] args) {
WindowUtilities.OpenlnJFrame(new FontExample(), 380, 400);
}

\ MHHBHHaiMiiHi'

nfava 211
ovi^fl^HHr

1
. 10.5. Java 2D
,

10.6.

381

10.6.
AWT drawXxx G r a p h i c s
1 . ,
(, d r a w R e c t d r a w P o l y g o n ) ,
. Java 2D
.
( ,
s e t P a i n t ) Java 2D ,
,
.
B a s i c S t r o k e , s e t S t r o k e G r a p h i c s 2 D ,
B a s i c S t r o k e .


, s e t S t r o k e ,
S t r o k e . B a s i c S t r o k e .
B a s i c S t r o k e .
p u b l i c BasicStrokeO
B a s i c S t r o k e 1.0.
CAPSQUARE
JOIN_MITER. ,
.
p u b l i c BasicStroke(float penWidth)
B a s i c S t r o k e .
, (CAP_SQUARE
JOIN_MITER).
p u b l i c BasicStroke(float p e n W i d t h , int capStyle, int joinStyle)
B a s i c S t r o k e ,
.
CAP_SQUARE (

; ), CAP_BUTT (
; )
CAP_ROUND (
, ).
JOIN_MITER ( ,
; ), JOIN_BEVEL
( ) JOIN_ROUND (
, ).

382

10. Java 2D: Java 2

public BasicStroke(float penWidth, int capStyle, int joinStyle, float miterLimit)


, , ,
,
( m i t e r L i m i t ) . m i t e r L i m i t ,
10.0, .
public BasicStroke(float penWidth, int capStyle, int joinStyle,
float miterLimit, float[] dashPattern,
float dashOffset)
,
. ,
. (dashOffset), 0.0,
.
.
( 10.10) 8 , ( 10.11)
. :
f l o a t [ ] d a s h P a t t e r n { 30, 10, 10, 10 };
.
30 , , .. 10 ,
10 10 .
. ,
, . 10.6 10.7.
10.10.StrokeThicknessExample.Java
import j a v a . a w t . * ;
/** .
p u b l i c c l a s s StrokeThicknessExample extends FontExample
p u b l i c void paintComponent(Graphics g) {
clear(g) ;
Graphics2D g2d = (Graphics2D)g;
drawGradientCircle(g2d) ;
drawBigString(g2d);
drawThickCircleOutline(g2d) ;
p r o t e c t e d void drawThickCircleOutline(Graphics2D g2d) {
g2d.setPaint(Color.blue);
g2d.setstroke(new B a s i c S t r o k e ( 8 ) ) ; / / 8
g2d.draw(getCircle());
}

p u b l i c s t a t i c void m a i n ( S t r i n g [ ] args) {
WindowUtilities.openlnJFrame(new StrokeThicknessExample(),
380, 400);
}

10.6.

383

. 10.6. ,
8

1 . 1 1 . DashedStrokeExample Java
import

java.awt.*;

/** .
public class DashedStrokeExample extends FontExample {
public void paintComponent(Graphics g) {
clear(g);
Graphics2D g2d = (Graphics2D)g;
drawGradientCircle(g2d);
drawBigString(g2d);
drawDashedCi rcleOutline(g2d);
protected void drawDashedCircleOutline(Graphics2D g2d) {
g2d.setPaint(Color.blue);
// 30 , 10 ,
// 10 , 10 .
float[] dashPattern = { 30, 10, 10, 10 };
g2d.setstroke(new BasicStroke(8, Basicstroke.CAP__BUTT,
BasicStroke . JOIN_JdITER, 10 ,
dashPattern, 0));
g2d.draw(getCircle());
}
public static void main(String[] args) {
WindowUtilities.openlnJFrame(new DashedStrokeExample()
380, 400);

384

10. Java 2D: Java 2

. 10.7, ,


10.12
,
. . 10.8 JOIN_MITER,
JOIN_BEVEL JOIN_ROUND, CAP_SQUARE, CAP_BUTT
ROUND.
10.12.LineStyles.j ava
import javax.swing.*;
import java.awt.*;
import Java.awt.geom.*;
/** .
* capStyle.
public class LineStyles extends JPanel {
private GeneralPath path;
private static int x = 30, deltaX = 150, = 300,
deltaY = 250, thickness = 40;
private Circle plLarge, plSmall, p2Large, p2Small,
p3Large, p3Small;
private int compositeType = AlphaComposite.SRC_OVER;
private AlphaComposite transparentComposite =
AlphaComposite.getlnstance(compositeType, 0.4F);
private int[] caps =
{ BasicStroke.CAP_SQUARE, BasicStroke.CAP_BUTT,
BasicStroke.CAP_ROUND };
private String[] capNames =
{ "CAP_SQUARE", "CAP_BUTT", "CAP_ROUND" };
private int[] joins =
{ BasicStroke.JOIN_MITER, BasicStroke.JOIN_BEVEL,
BasicStroke.JOIN_ROUND };
private String[] joinNames =
{ "JOIN MITER", "JOIN BEVEL", "JOIN ROUND" };

10.6.
public LineStylesO {
path = new GeneralPath();
path.moveTo(x, y ) ;
plLarge = new Circle(x, thickness/2);
plSmall = new Circle(x, 2);
path.lineTo(x + deltaX, - deltaY);
p2Large = new Circle(x + deltaX, - deltaY, thickness/2);
p2Small = new Circle(x + deltaX,
deltaY, 2 ) ;
path.lineTo(x + 2*deltaX, y ) ;
p3Large = new Circle(x + 2*deltaX,
thickness/2)
p3Small = new Circle(x + 2*deltaX,
2);
setFont(new Font("SansSerif", Font.BOLD, 20));
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.lightGray) ;
for(int i=0; i<caps.length; i++) {
BasicStroke stroke =
new BasicStroke(thickness, caps[i], joins[i]);
g2d.setStroke(stroke);
g2d.draw(path);
labelEndPoints(g2d, capNames[i], joinNames[i]);
g2d.translate(3*x + 2*deltaX, 0) ;
}
}

//
// .
private void labelEndPoints(Graphics2D g2d. String capLabel,
String joinLabel) {
Paint origPaint = g2d.getPaint();
Composite origComposite = g2d.getComposite();
g2d.setPaint(Color.black);
g2d.setComposite(transparentComposite);
g2d.fill(plLarge);
g2d.fill(p2Large);
g2d.fill(pBLarge);
g2d.setPaint(Color.yellow);
g2d.setComposite(origComposite);
g2d.fill(plSmall);
g2d.fill(p2Small);
g2d.fill(p3Small);
g2d.setPaint(Color.black);
g2d.drawstring(capLabel, x + thickness - 5, + 5 ) ;
g2d.drawstring(joinLabel, x + deltaX + thickness - 5,
- deltaY);
g2d.setPaint(origPaint);
}
public static void main(String[] args) {
WindowUtilities.openlnJFrame(new LineStyles(),
9*x + 6*deltaX, + 60)

385

386

10. Java 2D: Java 2

}
}

class. Circle extends Ellipse2D.Double {


public Circle(double centerX, double centerY, double radius) {
super(centerX - radius, centerY - radius, 2.0*radius,
2.0^radius);
}
}

JOIN_MITER

CAP SQUARE

JOIN.BEVEL

CAP_BUTT

gR

J |

JOIN_ROUND

CAP.ROUND

. 10.8.

10.7.
Java 2D : ,
( ).
,
. , ,
, ,
. ,
.
(shear) .
.
, .
, ,
: (
), .
.
,
. ,

.
, . ,
, .
( ) ;
.

10.7.

387

,
. , ,
, ,
.

. ,
, . (^,
2) (Xj, y j :

W
2
' =
1 J [l _

, !

2 =

0 0

m,oX,+m,,>;,+m,2
1

,
(,^). m^^g ,2
. (,,,,, mj, HIJ,, )
. ,
1. [0 0 1];
- ( z 0).
A f f i n e T r a n s f o r m
. API
, Aff i n e T r a n s f o r m .
:
Aff i n e T r a n s f o r m .
, Aff i n e T r a n s f o r m ,
, Aff i n e T r a n s f o r m G r a p h i c s 2 D ,
s e t T r a n s f o r m , ( S h a p e ) .
Aff i n e T r a n s f o r m S h a p e .
c r e a t e T r a n s f o r m e d S h a p e Aff i n e T r a n s f o r m .
,
Aff i n e T r a n s f o r m ,
.


Shape .
createTransformedShape
Shape,
Aff

Aff IneTransform

,

IneTransform.

, ,
t r a n s l a t e , r o t a t e , s c a l e s h e a r
G r a p h i c s 2D. , G r a p h i c s 2 D ,
; ,
, . ,
r o t a t e ( M a t h . P I / 2 ) , ,

388

10. Java 2D: Java 2

r o t a t e (Math. P I ) .
, G r a p h i c s 2D, getTransform,
, ,
oec)^ s e t T r a n s f o r m . :
/ / .
AffineTransform transform = g 2 d . g e t T r a n s f o r m ( ) ;
/ / ,
translate(...);
rotate(...);
/ /
/ / .
g2d.setTransform(transform);
10.13
.
"Java". . 10.9.
10.13.RotationExample.Java
import j a v a . a w t . * ;
/**
* .
public class RotationExample extends StrokeThicknessExample {
private Color[] colors = { Color.white, Color.black };
public void paintComponent(Graphics g) {
clear(g);
Graphics2D g2d = (Graphics2D)g;
drawGradientCircle(g2d);
drawThickCircleOutline(g2d);
// .
g2d.translate(185., 185.0) ;
for (int i=0; i<16; i++) {
// .
// .
g2d.rotate(Math.PI/8.0);
g2d.setPaint(colors[i%2]);
g2d.drawstring("Java", 0, 0 ) ;
}
}
public static void main(String[] args) {
WindowUtilities.openlnJFrame(new RotationExample(), 380, 400);

10.7.

389

. 10.9.


""
. -,
, . ,
-, 0.1, ,
10% . ,
X. - - .

. 10.14,
. 10.10. - 0.0
+0.8 . -
.
1 0 . 1 4 . S h e a r E x a m p l e . j a v a
import
import
import

javax.swing.^;
java.awt.*;
Java.awt.geom.*;

/ * * . * /
p u b l i c c l a s s ShearExample extends JPanel {
p r i v a t e s t a t i c i n t gap=10, width=100;
p r i v a t e R e c t a n g l e r e c t = new R e c t a n g l e ( g a p ,

gap, 100, 100);

p u b l i c void paintComponent(Graphics g) {
s u p e r . paintComponent (g). ;
Graphics2D g2d = (Graphics2D)g;
for ( i n t i = 0 ; i < 5 ; i++) {
g2d.setPaint(Color.red);
g2d.fill(rect) ;
// -
// - 0.2.

390

10. Java 2D: Java 2

g2d.shear(0.2, 0.0);
g2d.translate(2*gap + width, 0) ;
}
public static void main(String[] args) {
String title =
"Shear: x shear.ranges from 0.0 for the leftmost" +
"'square' to 0.8 for the rightmost one.";
WindowUtilities.openlnJFrame(new ShearExample(),
20*gap + 5*width,
5*gap + width,
title);
}

es from 0.0 for the ieftmust 'so

. 10.10. -
( ,
)

10.8. Java 2D
AWT Java 2D ,
.
, ,
.
(
) .
:
RenderingHints renderHints =
new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
renderHints.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
public void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHints(renderHints);
}

10.8.

Java 2 D

391



RenderxngHlnts,

(VALUEJMUTIALIASJDIH)

(VALUE_RENDER_QUALITY).

,
Java 2D. ,
,
.

( Composite CompositeContext).


i n t e r s e c t s Shape).

contains

( F o n t . d e r i v e F o n t ) .


( draw TextLayout).

,
( g e t O u t l i n e TextLayout).

Swing- (
15.5).

10.9.
Java 2D
. , Java 2D .

Shape.
draw f i l l Graphics2D.
Shape.

s e t P a i n t Graphics2D
(Color), ( G r a d i e n t P a i n t )
( T e x t u r e P a i n t ) .


. ,
AlhpaComposite, .

,
B a s i c S t r o k e ,
,
.

392

10. Java 2D: Java 2

Af f i n e T r a n s f o r m s e t T r a n s f o r m
G r a p h i c s 2 D , , (
) .


RenderingHints.
R e n d e r i n g H i n t s .

, Java 2D Java Foundation Classes


Java 2. "" Swing
Java Foundation Classes. Swing
14 15.
,
.
, .

, , .
.



...
.
.
.
.
.
processXxxEvent
.
" ".

S~y\zJ^zJ

, ,
, , .
Java
.
: " ,
, ".
,
, ,
. .
1. .
11 AWT,
. 1.1. , ,
. , K e y L i s t e n e r
, M o u s e L i s t e n e r
, F o c u s L i s t e n e r ,

. .
2. .

( M o u s e L i s t e n e r ,
K e y L i s t e n e r , F o c u s L i s t e n e r ..)
, .
, ,
, M o u s e L i s t e n e r ,
, .
, ,
.
, .
.

396

1 1 . ,

S. .
SomethingLlstener

addSom^/Am^Listener, .
, , , w,
, MyMouseL i s t e n e r , w . a d d M o u s e L i s t e n e r (new
MyMouseListener());.
, .
,
, ,
, .
.

1 1 . 1 .

, ,
Java- .
( , Java Console

Communicator Communicator/Tools Netscape View


Internet Explorer.) ,
. , , MouseListener
, M o u s e A d a p t e r ""
M o u s e L i s t e n e r . M o u s e L i s t e n e r ,
, m o u s e P r e s s e d
MouseEvent.
MouseEvent g e t X g e t Y ,
.
, , 11.1,
, 11.2.
. 11.1. HTML-, ,
h t t p : / / w w w . c o r e w e b p r o g r a m m i n g . c o m / .
1 1 . 1 . CiickListener.java
import

Java.awt.event.*;

/ * * , C l i c k R e p o r t e r .
p u b l i c c l a s s C l i c k L i s t e n e r e x t e n d s MouseAdapter {
p u b l i c void mousePressed(MouseEvent event) {
S y s t e m . o u t . p r i n t l n ( " M o u s e p r e s s e d a t (" +
event. getXO + " , " +
event.getY0 + " ) . " ) ;
}
}

*/

11.1. .

397

11.2. ClickReporter.Java
import Java, applet .Appletsimport java.awt.*;
/^* (
* ). .
public class ClickReporter extends Applet {
public void initO {
setBackground(Color.yellow);
addMouseListener(new ClickListener());

iS
fife

{fe

iiwupai'rrpummiffmi
Vtew

>-

F^vontes

J Jib

Tods

UJJ^'.&-^J-

Reporting Mouse Clicks

~3

l-.lii.lAJ.i!.

fifxil

JMouse p r e s s e d at ( 2 6 , 2 2 ) .
jMouse p r e s s e d at ( 6 5 , 6 3 ) ,
jMouse p r e s s e d at (110,106)
;House p r e s s e d
jMouse p r e s s e d

ac (160,137)
at ( 2 1 0 , 1 7 1 ) .

JKouse p r e s s e d at (275,211)
JHouse p r e s s e d at ( 3 6 7 , 2 7 4 ) .
Mouse pressed
JMouse p r e s s e d

J
; ^ iiwtel tarted

My CoTfipute

Li

Clear

at ( 3 9 0 , 3 2 5 ) .
at ( 4 2 6 , 3 2 7 ) .

_H
CJose

. 11.1. C l i c k R e p o r t e r , ^
Java Console ,
,


,
,
. G r a p h i c s paint :
g e t G r a p h i c s . ,
Applet , ,

398

1 1 . ,

g e t G r a p h i c s . g e t S o u r c e (
), ,
. Applet g e t G r a p h i c s . ,
, 11.3 11.4,
. 11.2.

event. getSource () ,
.

1 1 . 3 . C i r c l e L i s t e n e r . j a v a
import J a v a . a p p l e t . A p p l e t ;
import j a v a . a w t . * ;
import J a v a . a w t . e v e n t . * ;
/** , C i r c l e D r a w e r l .
* getSource.

V
p u b l i c c l a s s C i r c l e L i s t e n e r extends MouseAdapter {
p r i v a t e i n t r a d i u s = 25;
p u b l i c void mousePressed(MouseEvent event) {
Applet app = ( A p p l e t ) e v e n t . g e t S o u r c e 0 ;
Graphics g = app.getGraphics ( ) ;
g.fillOval(event.getX()-radius,
event.getY()-radius,
2*radius,
2*radius);

11.4. CircleDrawer.java
import Java.applet.Applet;
import java.awt.*;
/ ,
* . .

V
public class CircleDrawerl extends Applet {
public void initO {
setForeground(Color.blue);
addMouseListener(new CircleListener());
}
}

11.2. .

399

Using External Litefie(s fm Event Hanfng - Netscape

d
Using External Listeners for Event Handling
Click ill the applet to di aw circles.

If^ifMCdeOtaw1 tunn :.' -"^

- 3 ^ .'^^,

'

,^A

, 11.2.
,
. ,
getSource

11.2.


.
,
. ,
g e t S o u r c e
, )^ , . , ,
, .
, p r i v a t e p r o t e c t e d , .

. Java, ,
, M o u s e L i s t e n e r .
""
. , , M o u s e L i s t e n e r , m o u s e E n t e r e d ,
m o u s e E x i t e d , m o u s e P r e s s e d , mouseReleased m o u s e C l i c k e d .
11.5 , , ,
, , .

400

1 1 . ,

m o u s e P r e s s e d ,
g e t G r a p h i c s . , , ,
, .
1 1 . 5 . C i r c l e D r a w e r 2 . J a v a
import
import
import

Java.applet.Applet;
java.awt.*;
Java.awt.event.*;

/ * ,
* .
* .
public class CircleDrawer2 extends Applet
implements MouseListener {
private int radius = 25;
public void init() {
setForeground(Color.blue);
addMouseListener(this);
// , MouseListener.
public
public
public
public

void
void
void
void

mouseEntered(MouseEvent event) {}
mouseExited(MouseEvent event) {}
mouseReleased(MouseEvent event) {}
mouseClicked(MouseEvent event) {}

public void mousePressed(MouseEvent event) {


Graphics g = getGraphics();
g.fillOval(event.getX()-radius,
event.getY()-radius,
2*radius,
2^radius);
}

11.3.
icnaccoB
,
, A p p l e t
.
Java, - . ,
, A p p l e t . pea-

1 1 . 3 . . . .

401

M o u s e L i s t e n e r , , ""
, . ,
, .
, .
,
p r i v a t e . .
public c l a s s Outer {
p r i v a t e class Inner

{ ..,

p r i v a t e I n n e r t e s t = new I n n e r ( ) ;


. t h i s
. O u t e r . t h i s .
,
(, O u t e r $ I n n e r . c l a s s ) .
, ,

, .

, ,
,
.
11.6 C i r c l e D r a w e r ,
. g e t G r a p h i c s
, e v e n t . g e t Sou
.
M o u s e L i s t e n e r , ): M o u s e A d a p t e r .
""
mouseEntered, mouseExited,mouseReleased nmouseClicked.
1 1 . 6 . C i r c l e D r a w e r 3 . J a v a
import
import
import

Java.applet.Applet;
java.awt.*;
Java.awt.event.*;

/k-k ,
* .
* .
public class CircleDrawerS extends Applet {
public void initO {
setForeground(Color.blue);

402

1 1 . ,

addMouseListener(new CircleListener());
}
private class CircleListener extends MouseAdapter
private int radius = 25;
public void mousePressed(MouseEvent event) {
Graphics g = getGraphics();
g.fillOval(event.getX()-radius,
event.getY()-radius,
2*radius,
2*radius);
}
} .

11.4.

^! .
( , ),
;
.
, , ,
.
, .
.
C o l o r someColor = p i c k C o l o r O ;
add(new P a n e l ( ) {
p u b l i c Color o r i g C o l o r = someColor;
public void i n i t O {
setBackground(origColor);
}
});

K e y A d a p t e r myAdapter =
new K e y A d a p t e r 0 {
p u b l i c void keyPressed(KeyEvent event)

{ ...

};

addKeyListener(myAdapter);
11.7 , , ,
. , ,
.
.

11.5.

403

11.7.CircleDrawer4.java
import Java.applet.Applet;
import java.awt.*;
import Java.awt.event.*;
/ ,
* .
* .

public class CircleDrawer4 extends Applet {


public void initO {
setForeground(Color.blue);
addMouseListener
(new MouseAdapter() {
private int radius = 25;
public void mousePressed(MouseEvent event) {
Graphics g = getGraphics();
g.fillOval(event.getX()-radius,
event.getY()-radius,
2*radius,
2*radius); ,
}
});

11.5.
. 11.1 11 AWT,
. , ,
, add. ,
, a d d M o u s e L i s t e n e r M o u s e L i s t e n e r , a d d C o m p o n e n t L i s t e n e r C o m p o n e n t L i s t e n e r ..
a d d X x x L i s t e n e r r e m o v e X x x L i s t e n e r .
11 AWT, Swing ,
, Swing. ,
, ,
"" .
(,
, ), ,
, .

404

11. ,

11.1.

ActionListener

addActionListener

AdjustmentListener

addAdjustmentListener
ComponentAdapter

addComponentListener

ContainerListener

ContainerAdapter

addContainerListener

FocusListener

FocusAdapter

addFocusListener

KeyListener

KeyAdapter

addKeyListener

MouseListener

MouseAdapter

addMouseListener

MouseMotionListener

MouseMotionAdapter

addMouseMotionListene

ComponentListener

addltemListener

ItemListener

r
TextListener
WindowListener

addTextListener
WindowAdapter

addWindowListener

,
. ,
AWTEvent. AWTEvent :
consume ( ), i s C o n s u m e d ( ,
, ), g e t ID (
, ) g e t S o u r c e (
O b j e c t , ).
ActionListener
:
public void actionPerformed(ActionEvent event)
,
. ,
, . a c t i o n P e r f o r m e d
, , <Enter>,
, .
AWTEvent, A c t i o n E v e n t :
g e t A c t i o n C o m m a n d ( " "
String) g e t M o d i f i e r s ( ,
<Shift>, <Ctrl> .. " "
, ,
, .
g e t S o u r c e ,
, .

11.5.

405

AdjustmentListener
:
p u b l i c void adjustmentValueChanged(AdjustmentEvent

event)

, A d j u s t m e n t L i s t e n e r , .
,
a d j u s t m e n t V a l u e C h a n g e d ,
. AWTEvent Ad j u s t m e n t E v e n t
. , g e t A d j u s t a b l e
, g e t A d j u s t m e n t T y p e
UNIT_DECREMENT, UNIT_INCREMENT, BLOCK_DECREMENT, BLOCK_INCREMENT
TRACK; g e t V a l u e .
ComponentListener
C o m p o n e n t L i s t e n e r :
public
public
public
public

void
void
void
void

componentResized(ComponentEvent event)
componentMoved(ComponentEvent event)
componentShown(ComponentEvent event)
componentHidden(ComponentEvent event)

Java API C o m p o n e n t A d a p t e r , "''


. ,
.
, ,
, .
g e t C o m p o n e n t C o m p o n e n t E v e n t Component,
. g e t C o m p o n e n t ,
g e t S o u r , Component.
ContainerListener
:
public void componentAdded(ContainerEvent event)
public void componentRemoved(ContainerEvent event)
ContainerAdapter . ContainerListener
,
. ContainerEvent getContainer getChild
.
FocusListener
FocusListener :
public void focusGained(FocusEvent event)
public void focusLost(FocusEvent event)
"" F o c u s A d a p t e r .
F o c u s E v e n t i s T e m p o r a r y ,
, , .

406

1 1 . ,

ItemListener
:
public void itemStateChanged(ItemEvent

event)

, I t e m L i s t e n e r , .
Checkbox,
CheckboxMenuItem, C h o i c e L i s t . ,
. I t e m E v e n t : g e t l t e m S e l e c t a b l e
( ), g e t I t e m ( )
g e t S t a t e C h a n g e ( I t e m E v e n t . SELECTED
I t e m E v e n t . DESELECTED).
KeyListener
K e y L i s t e n e r :
p u b l i c void keyPressed(KeyEvent
p u b l i c void keyReleased(KeyEvent
p u b l i c v o i d keyTyped(KeyEvent

event)
event)

event)

K e y A d a p t e r "" , ,

. ,
, , P a n e l C a n v a s ,
, r e q u e s t F o c u s . k e y P r e s s e d
k e y R e l e a s e d )' ;
- <Shift>, <Ctrl> . .
, , consume
k e y P r e s s e d . , ,
. )
, keyTyped.
KeyEvent .
getKeyChar setKeyChar.
getKeyChar , s e t K e y C h a r
.
,
. KeyEvent g e t M o d i f i e r s
s e t M o d i f i e r s , -,
i s A c t i o n K e y ,
.
, I n p u t E v e n t : isAltDown,
i s C o n t r o l D o w n , isMetaDown i s S h i f tDown. ,
g e t K e y C h a r ,
, g e t K e y C o d e , getKeyText.
.
g e t K e y C o d e setKeyCode.
Component, )^ ,
getComponent, getWhen.

11.5.

407

MouseListener
:
p u b l i c void mouseEntered(MouseEvent
p u b l i c void mouseExited(MouseEvent

event)
event)

p u b l i c void mousePressed(MouseEvent
p u b l i c void mouseReleased(MouseEvent
p u b l i c void mouseClicked(MouseEvent

event)
event)
event)

m o u s e E n t e r e d m o u s e E x i t e d
, . m o u s e E n t e r e d
, , ,
m o u s e E x i t e d . , m o u s e E x i t e d
, ,
, . , ,
, ,
- , .
m o u s e E n t e r e d ( ,
), m o u s e E x i t e d ( ),
m o u s e E n t e r e d (
) , , m o u s e E x i t e d
( ). ,
, m o u s e E x i t e d , ;
, , m o u s e E x i t e d , .
m o u s e P r e s s e d , m o u s e R e l e a s e d
, m o u s e C l i c k e d , ^
. , ,
, , m o u s e P r e s s e d ,
m o u s e R e l e a s e d m o u s e C l i c k e d ( ).
, , ,
m o u s e P r e s s e d m o u s e R e l e a s e d ; m o u s e C l i c k e d .
( ) ,
, Mouse A d a p t e r .
(consume) m o u s e P r e s s e d ,
. ,
, g e t M o d i f i e r s . Java-
, (MacOS), (Windows) (Unix) ,
Java . , event.getModifiers(),
M o u s e E v e n t . Button2_MASK, ,
M o u s e E v e n t .Button3_MASK, .
M o u s e E v e n t . Button3_MASK ,
.
e v e n t . g e t M o d i f i e r s ()
.
(event.getModifiers

== event.ALT_MASK)

408

1 1 . ,

, :
((event.getModifiers

& event.ALT_MASK)

!= 0)

g e t C l i c k C o u n t .
,
, Java, .
m o u s e P r e s s e d :
, e v e n t . g e t C l i c k C o u n t , 1,
2. , ,
. ,
. g e t X , g e t Y g e t P o i n t
. i s P o p u p T r i g g e r
, , ,
, . KeyEvent,
MouseEvent I n p u t E v e n t ^ i s A l t D o w n , i s C o n t r o l D o w n ,
isMetaDown, i s S h i f t D o w n , g e t C o m p o n e n t getWhen.
MouseMotionListener
:
p u b l i c v o i d mouseMoved(MouseEvent e v e n t )
p u b l i c v o i d mouseDragged(MouseEvent e v e n t )
"" seMot i o n A d a p t e r .
, M o u s e M o t i o n L i s t e n e r ,
. M o u s e E v e n t M o u s e L i s t e n e r .
TextListener
:
public void textValueChanged(TextEvent event)
, TextListener, .
Text Area, Text Field
TextComponent. textValueChanged ,
, ,
(,
setText append).
WindowListener
WindowListener :
public
public
public
public
public
public
public

void
void
void
void
void
void
void

windowOpened(WindowEvent event)
windowClosing(WindowEvent event)
windowClosed(WindowEvent event)
windowlconifled(WindowEvent event)
windowDeiconifled(WindowEvent event)
windowActivated(WindowEvent event)
windowDeactivated(WindowEvent event)

11.6.

409

,
W i n d o w A d a p t e r , ""
. windowOpened
, w i n d o w C l o s i n g , ,
w i n d o w C l o s e d . w i n d o w I c o n i f i e d w i n d o w D e i c o n i f i e d
. w i n d o w A c t i v a t e d w i n d o w D e a c t i v a t e d ,
, .
getWindow WindowEvent Window, ^ ,
.

11.6.
, processX x x E v e n t , Mouse (.. p r o c e s s M o u s e E v e n t ) , Key,
F o c u s , A c t i o n .. ( . 11.2.) p r o c e s s X x x E v e n t ,
. ,
" ".
s s X x x E v e n t . , , ,
, ,
, p r o c e s s M o u s e E v e n t ,
, M o u s e L i s t e n e r . p r o c e s s X x x E v e n t , s u p e r . p r o c e s s X x x E v e n t ,
.
s u p e r . p r o c e s s X x x E v e n t
, .
p r o c e s s X x x E v e n t , ,
, s u p e r . p r o c e s s X x x E v e n t
.

processMouseEvent,

super.processMouseEvent.
,

processXxxEvent,
super. processXxxEvent.

., ^
^81^
^
^

p r o c e s s
X x x E v e n t , , .
, v e n t s )%
. AWTEvent. ,
p r o c e s s M o u s e E v e n t ,
, :
enableEvents(AWTEvent.MOUSE EVENT MASK);

410

1 1 . ,

, , :
enableEvents (AWTEvent .KEY__EVENT__MASK) ;
, :
enableEvents (AWTEvent. FOCUS__EVENT_MASK) ;

e n a b l e E v e n t s .
. :
enableEvents(AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.KEY_EVENT_MASK |
AWTEvent.FOCUS_EVENT_MASK);
p r s s X x x E v e n t ,
XxxEvent. , , s s M o u s e E v e n t
MouseEvent, p r o c e s s K e y E v e n t KeyEvent, p r o c e s s F o c u s E v e n t ~
FocusEvent, p r o c e s s I t e m E v e n t I t e m E v e n t , p r o c e s s A c t i o n E v e n t A c t i o n E v e n t
T. . : p r o c e s s M o u s e M o t i o n E v e n t , ,
p r o c e s s MouseEvent, MouseEvent. enableEvents
d i s a b l e E v e n t s ;
. , AWTEvent j a v a . awt, MouseEvent
j a v a . a w t . e v e n t . ,
, .
11.8 , p r o c e s s M o u s e E v e n t , )
, . p r o c e s s M o u s e M o t i o n E v e n t
,, .
. 11.3.
. 1 1 . 8 . M o u s e R e p o r t e r . J a v a
import
import
import

java.applet.Applet;
java.awt.*;
Java.awt.event.*;

/ * * , .
*
* p r o c e s s X x x E v e n t .

V
p u b l i c c l a s s MouseReporter extends Applet {
public void i n i t O {
s e t B a c k g r o u n d ( C o l o r . b l u e ) ; / /
enableEvents(AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE MOTION EVENT MASK);
p u b l i c void processMouseEvent(MouseEvent event) {
S y s t e m . o u t . p r i n t l n ( " M o u s e e n t e r / e x i t or c l i c k a t

(" +

11.6.

411

event.getXO + "," +
event.getYO + ").");
// MouseListener:
super.processMouseEvent(event);
}
public void processMouseMotionEvent(MouseEvent event) {
System.out.println("Mouse move/drag at (" +
event.getXO + ", " +
event.getYO + ").");
// MouseMotionListener:
super.processMouseMotionEvent(event);
}

t-4-l'i''IHJ-l'lU4'rl.H.H'NIHH.Ht4'-l
j^ -;; "3 -Ti ^- ,^ j ^ rf '^ -M

Mouse Event Reporter

Mouse enter/exit or click at (7.0).


Mouse move/drag at (7,0).
Mouse move/drag at (9.2).
Mouse move/drag at (11.4).
Mouse move/drag at (17.6).
Mouse move/drag at (23,14).
Mouse move/drag at (29.16).
Mouse move/drag at (31,18).
Mouse move/drag at (32,20)
Mouse move/drag at (34.22)
Mouse move/drag at (36.23).
Mouse move/drag at (38,24)
Mouse move/drag at (38,25).
Mouse enter/exit or click at (38.25)
Mouse enter/exit or click at (38.25)
Mouse enter/exit or click at (38.25)

_J^

;isg*;^j>r

Appiet Mo.isefi{

. 11.3. MouseReporter

, ,
. 11.2.
11.2.

processtionEvent
processAdjustmentEvent
prssComponentEvent
processContainerEvent
prssFocusEvent

ActionEvent
AdjustmentEvent
ComponentEvent
ContainerEvent
FocusEvent

enableEvents
(
AWTEvent)
ACTION_EVENT_MASK
ADJUSTMENT_EVENT_MASK
COMPONENT_EVENT_MASK
CONTAINER_EVENT_MASK
FOCUS EVENT MASK

412

11. ,

. 11.2
processItemEvent

ITEM_EVENT_MASK

ItemEvent

processKeyEvent

KeyEvent

KEY_EVENT_MASK

prccessMouseEvent

MouseEvent

MOUSE_EVENT_MASK

prssMouseMotionEvent

MouseEvent

MOUSE_MOTION_EVENT_MASK

processTextEvent

TextEvent

TEXT__EVENT_MASK

processWindowEvent

WindowEvent

WINDOW EVENT MASK

11.7.

11.9 ,
; .
: ,
( ,
), , ( )
), , , <Enter>
. (
k e y T y p e d K e y A d a p t e r ) ,

. <Enter> (
a c t i o n P e f o r m e d ,
A c t i o n L i s t e n e r )
, .
\' ( f o c u s G a i n e d F o c u s A d a p t e r )
. 11.10 ,
, . 11.4 .
1 1 . 9 .
import
import

LanguageField.Java

java.awt.^;
Java.awt.event.*;

/ * * T e x t F i e l d ,
*
*
.
V
public class LanguageField extends TextField {
private String[] substrings =
{ "", "J", "Ja", "Jav", "Java" };
public LanguageField() {
addKeyListener(new SpellingCorrector ());
addActionListener(new WordCompleter());
addFocusListener(new SubliminalAdvertiser());

11.7.

// .
private void setCaretO {
setCaretPosition(5);
}
// , .
private class SpellingCorrector extends KeyAdapter {
public void keyTyped(KeyEvent event) {
setLanguage();
setCaret();
}
// ,
// ,
// .
private void setLanguage() {
int length = getText().length();
if (length <= 4) {
setText(substrings[length]);
} else {
setText("Java");
}
setCaret();
}
// ,
// .
private class WordCompleter implements ActionListener {
// <Return> .
public void actionPerformed(ActionEvent event) {
setText("Java");
setCaret();
}
}
// , .
private class SubliminalAdvertiser extends FocusAdapter {
public void focusGained(FocusEvent event) {
String text = getText();
for(int i=0; i<10; i++) {
setText("Hint: Java");
setText(text);

413

414

1 1 . ,

11.10. JavaTextField. Java


import Java.applet.Applet;
import java.awt.*;
/'^* <></>
* .

public class JavaTextField extends Applet {


public void initO {
setFont(new Font("Serif", Font.BOLD, 14));
setLayout(new GridLayout(2, 1));
add(new Label("Enter a Good Programming Language",
Label.CENTER));
LanguageField langField = new LanguageField();
Font langFont = new Font("SansSerif", Font.BOLD, IE
langField.setFont(langFont);
add(langField);
}
}

H,tiHiflTlil'l'H'Hi'iika,

1^1-1|

Choose a Language, Any Language

J:
i^HyCompulef

. 11.4. JavaTextField
"C#"

11.8. " "


11.11 ,
. ,
, ,
, . ,
. 11.5 ,
, , .

11.8. " "

11.11.SimpleWhiteboard.Java
import Java.applet.Applet;
import java.awt.*;
import Java.awt.event.*;
/** , . */
public class SimpleWhiteboard extends Applet {
protected int lastX=0, lastY=0;
public void initO {
setBackground(Color.white) ;
setForeground(Color.blue);
addMouseListener(new PositionRecorder());
addMouseMotionListener(new LineDrawer());
protected void record(int x, int y) {
lastX = x;
lastY = y;
}
// ,
// .
private class PositionRecorder extends MouseAdapter {
public void mouseEntered(MouseEvent event) {
requestFocus();
record(event.getX(), event.getY());
}
public void mousePressed(MouseEvent event) {
record(event.getX(), event.getY());
}
}
//
// .
private class LineDrawer extends MouseMotionAdapter {
public void mouseDragged(MouseEvent event) {
int X = event.getX0;
int = event.getY0;
Graphics g = getOraphics();
g.drawLine(lastX, lastY, x, y) ;
record(x, y ) ;
}
}

415

416

1 1 . ,

1- SifMite Whiteboard Applet - Netscape

^' /

"^

"^

{!31

3 :0 .:^. ^1 1^^' 1 1'

SI

Simple Whiteboard Applet


I

[ID
^_

i # = ^

"'

Ai^JtetS^rfeWhfteboafdrynntnQ

^,. . ^ ........ J
; >,^

J ^

^/^

. 71.5.

'^ "
, . 11.5,
, ,
, . ( 11.12) .
keyTyped (
i n t ) , ,
. . 11.6.
11.12. Whiteboard.Java
import J a v a . a p p l e t . A p p l e t ;
import j a v a . a w t . * ;
import J a v a . a w t . e v e n t . * ;
/ '' "
* .
p u b l i c c l a s s Whiteboard extends SimpleWhiteboard
p r o t e c t e d FontMetrics fm;
p u b l i c void i n i t O {
super.init();
Font font = new F o n t ( " S e r i f " , Font.BOLD, 2 0 ) ;
setFont(font);
fm = g e t F o n t M e t r i c s ( f o n t ) ;
addKeyListener(new CharDrawer());

11-9.

417

private class CharDrawer extends KeyAdapter {


// , , ,
// .
public void keyTyped(KeyEvent event) {
String s = String.valueOf(event.getKeyChar0);
getGraphics().drawstring(s, lastX, lastY);
record(lastX + fm.stringWidth(s), lastY);
}

^WMeboarid Applet - Nelscape


Ede

<

Ytevv

^o

w!(Ttum:at.O(

1 :^ ^1 j^. ~s : ;3 13

Whiteboard Applet
1

Route
29

53|-\==.

Joluis Hopldits Road

Park
Here

Pond
- K-Ceiitei

A { 4 ^ V4)itbud {unnng

. 11.6. :

11.9.
, , ,
.
. ,
( , , .). ,
, , .
, , ,
, . 16
, .
,
. 13, AWT,
,
. ,
. 17.

...

.
FlowLayout.
BorderLayout.
GridLayout.
CardLayout.
GridBagLayout.
BoxLayout.

.
.

S1/\ZJ^:EJ

C o n t a i n e r
, (layout manager).

.
. , ,
,
. ,
Web- .
, ,
,
. ,
, ,
. ,

. Java ,
.

, s e t L a y o u t ( ,
), add
.
i n i t .
.
AWT: FlowLayout,
BorderLayout, GridLayout, CardLayout GridBagLayout, a
BoxLayout, Swing.

.

420

12.

1 2 . 1 . FlowLayout
F l o w L a y o u t
, .
, .. ,
. ,
.
,
. F l o w L a y o u t ,
, .
F l o w L a y o u t P a n e l , J P a n e l A p p l e t .
12.1 , .
, .
. 12.1, ,
, . F l o w L a y o u t
A p p l e t ,
s e t L a y o u t . , ,
s e t L a y o u t (new F l o w L a y o u t () ),
F l o w L a y o u t .
1 2 . 1 . FlowTGSt.Java

import J a v a . a p p l e t . A p p l e t ;
import j a v a . a w t . * ;
/** FlowLayout
.
V
p u b l i c c l a s s FlowTest extends Applet {
p u b l i c void i n i t O {
f o r ( i n t i = l ; i<6; i++) {
add(new Button ("Button " -f- i) ) ;
}
}
}

Ap0et
Button 1 I Button 2 1 Buttons I Button 4 I

. 12.1. FlowLayout
.
,

1 2 . 1 . FlowLayout

421

FlowLayout
public FlowLayoutO
F l o w L a y o u t ,
,
, .
public FlowLayout(int alignment)
F l o w L a y o u t
, .
F l o w L a y o u t .LEFT, F l o w L a y o u t . RIGHT
F l o w L a y o u t .CENTER.
.
public FlowLayout(int a l i g n m e n t , int hGap, int vGap)
F l o w L a y o u t
. hGap ,
vGap .

FlowLayout
F l o w L a y o u t )^ .
public int getAlignmentO
public void setAlignment(int alignment)
.
, F l o w L a y o u t .LEFT,
FlowLayout.RIGHT FlowLayout.CENTER.
public int getHgapO
public void setHgap(int hGap)
.
5.
public int getVgapO
p u b l i c void setVgap(int vGap)
.
5.
F l o w L a y o u t , P a n e l ,
( s t a t i c ) . ,
, .
,
F l o w L a y o u t , f i n a l , ,
. ,

422

12.

. , f i n a l ,
. ,
, :
P a n e l = new P a n e l ( ) ;
p.setLayout(new FlowLayout(FlowLayout.CENTER,10,5));
, , .
Panel = new Panel();
FlowLayout layout = (FlowLayout)p.getLayout();
layout.setHgap(10);
Ha , ,
F l o w L a y o u t .
, , ,
. , F l o w L a y o u t ,
10.

12.2. BorderLayout
B o r d e r L a y o u t
NORTH, SOUTH, EAST, WEST CENTER.
a d d , .
, ), ,
.
a d d ( b u t t o n F o r T o p , BorderLayout.NORTH);
a d d ( s c r o l l b a r F o r R i g h t S i d e , BorderLayout.EAST);
a d d ( p a n e l F o r R e m a i n i n g S p a c e , BorderLayout.CENTER);
.
, NORTH SOUTH,
:
, , . ,
, EAST WEST,
,
, , NORTH SOUTH.
, CENTER, ,
. B o r d e r L a y o u t
, 0.
B o r d e r L a y o u t Frame, D i a l o g
Window, J A p p l e t , J F r a m e , J D i a l o g JWindow.
12.2 ,
B o r d e r L a y o u t . , ,
. , , F l o w L a y o u t ,
.

1 2 . 2 . BorderLayout

423

12.2. BoiTderTest. Java


import Java, appl^it. Applet;
import j ava. awt. '';
/** BorderLayout.
public class BorderTest extends Applet {
public void initO {
setLayout(new BorderLayout());
add(new Button("Button 1"), BorderLayout.NORTH);
add(new Button("Button 2"), BorderLayout.SOUTH);
add(new Button("Button 3"), BorderLayout.EAST);
add(new Button("Button 4"), BorderLayout.WEST);
add(new Button("Button
), BorderLayout.CENTER);
}
}

^l4VI-)Hiyii;Hfr!l'!1tfPffiffMllirlgRl
ali$

B)toft4
'

8lton5

${)|

Applet started

. 12.2.
BorderLayout

BorderLayout .

add(component,BorderLayout.REGION);

add(component);

,
CENTER .
( ).
.
!
,
CENTER

, BorderLayout
.
.
, Panel
.

424

1 2 .


.
,
Panel
.

BorderLayout
public BorderLayoutO
B o r d e r L a y o u t ,
.
public BorderLayout(int h G a p , int vGap)
B o r d e r L a y o u t ,
WEST CENTER, CENTER EAST hGap. ,
NORTH CENTER, CENTER SOUTH vGap.

BorderLayout
Frame D i a l o g ,
, s e t H g a p
s e t V g a p , g e t L a y o u t .
, B o r d e r L a y o u t .
J F r a m e ,
JApplet,JWindow JDialog.
public int getHgapO
public void setHgap(int hGap)

.
public int getVgapO
public void setVgap(int vGap)

.
public float getLayoutAlignmentX(Container )
public float getLayoutAlignmentY(Container )
.
13.

12.3. GridLayout

425

12.3. GridLayout
G r i d L a y o u t ,
. , .
;
, . ,
. G r i d L a y o u t
.
12.3 .
; .
. 12.3.
12.3. G r i d T e s t . J a v a
i m p o r t J a v a , a p p l e t .Appletsimport ja'va.awt.*;
/ * * G r i d L a y o u t .

*/

public c l a s s GridTest extends Applet {


public void i n i t O {
s e t L a y o u t ( n e w G r i d L a y o u t ( 2 , 3 ) ) ; / / 2 rows, 3 c o l s
add(new B u t t o n ( " B u t t o n O n e " ) ) ;
add(new B u t t o n ( " B u t t o n T w o " ) ) ;
add(new B u t t o n ( " B u t t o n T h r e e " ) ) <
add(new B u t t o n ( " B u t t o n F o u r " ) ) ;
add(new B u t t o n ( " B u t t o n F i v e " ) ) ;
add(new B u t t o n ( " B u t t o n S i x " ) ) ;
}

i-Haii,!gy>"-'-'H
Applet
Buttor One

8<Jttftn Two

Button Four

Button Five

Button Three 1

Bunof) Stx

Applet started.

. 12.3.
G r i d L a y o u t

GridLayout
public GridLayout()
,
. .
public GridLayout(int rows, int cols)
G r i d L a y o u t ,
. -

426

12.

. rows c o l s ( )
0. rows , Java
,
( ) . , c o l s
, ,
.
, 12.4. ,
. 12.4, 11 ,
, .
W i n d o w U t i l i t i e s . Java 14.1.

1 2 . 4 . E l e v e n B u t t o n s . J a v a
import
import
/**
*
*
*
*
*

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

,
.
(
2), ,

.

public class ElevenButtons extends JPanel {


public ElevenButtons(int numRows) {
setLayout(new GridLayout(numRows, 0));
for(int i=0; i<ll; i++) {
add(new JButton("Button " + i));
}
}
public static void main(String[] args) {
int numRows = 2;
if (args.length > 0) {
numRows = Integer.parseint(args[0]);
}
String title = "11 Buttons using GridLayout(" +
numRows + " , 0 ) . " ;
WindowUtilities.setNativeLookAndFeel();
WindowUtilities.openlnJFrame(new ElevenButtons(numRows),
550, 200, title);

12.4. CardLayout

1 ^ 1 1 Button 1jsing G riciLwout(2>0l.

If
1
1
1
1 Sutton 0 1

427

ws-'^mmmi

Stittonl

Bvm\2

Button 3

&ulton4

Sutton r

e^ttons '

Buttond

. SuttonIO

BtittonS

SunonS

. 12.4.

,

public GridLayout(int rows, int c o l s , int hGap, int vGap)


,
,
hGap vGap. r o w s c o l s 0.
" " ,
.

GridLayout
public int getRowsO
p u b l i c void setRows(int rows)
.
public int getColumns()
p u b l i c void s e t C o l u m n s ( i n t cols)
.
p u b l i c int getHgapO
p u b l i c void setHgap(int hGap)
.
p u b l i c int getVgapO
public void setVgap(int vGap)
.

12.4. CardLayout
C a r d L a y o u t (
) ,
.
C a r d L a y o u t ,
.

428

12.

Panel cardPanel;
CardLayout layout;
layout = new CardLayout{);
cardPanel.setLayout(layout);
.
, , .
cardPanel.add(component1, "Card 1");
cardPanel.add(component2, "Card 2");
, .
, ,
. show,
, f i r s t , l a s t ,
p r e v i o u s n e x t . )^ )^
, , :
layout.show(cardPanel, "Card 1");
layout.first(cardPanel);
layout.next(cardPanel);
, 12.5. Panel, CardLayout, ,
. Panel CardPanel
( 12.6), , , Label
ImageLabel ( ImageLabel. Java
http://www.corewebprogramming.com/). ImageLabel
. ,
. . 12.5.
12.5.CardDemo.Java
import Java.applet.Applet;
import java.awt.*;
import Java.awt.event.*;
/^*
*
*
*
*
*

CardLayout.
Panel,
CardLayout
( CardPanel,
).
, .

public class CardDemo extends Applet implements ActionListener {


private Button first, last, previous, next;
private String[] cardLabels = { "Jack","Queen","King","Ace" };
private CardPanel[] cardPanels = new CardPanel[4];
private CardLayout layout;
private Panel cardDisplayPanel;

12.4. CardLayout

public void initO {


setBackground(Color.white);
setLayout(new BorderLayout());
addButtonPanel();
addCardDisplayPanel();
}
private void addButtonPanel() {
Panel buttonPanel = new PanelO;
buttonPanel,setLayout(new GridLayout(9^ 1));
Font buttonFont = new Font("SansSerif", Font.BOLD, 18);
buttonPanel.setFont(buttonFont);
for(int i=0; i<cardLabels.length; i++) {
Button button = new Button(cardLabels[i]);
button.addActionListener(this);
buttonPanel.add(button);
}
first = new ButtonC'First") ;
first.addActionListener(this);
last = new Button("Last");
last.addActionListener(this);
previous = new Button("Previous");
previous.addActionListener(this);
next = new Button("Next");
next.addActionListener(this);
buttonPanel. add (new Label ("
", Label. CENTER) )
buttonPanel.add(first);
buttonPanel.add(last);
buttonPanel.add(previous);
buttonPanel. add (next) .;
add(buttonPanel, BorderLayout.WEST);
}
private void addCardDisplayPanel() {
cardDisplayPanel = new PanelO;
layout = new CardLayout();
cardDisplayPanel.setLayout(layout);
String cardName;
for(int i=0; i<cardLabels.length; i++) {
cardName = cardLabels[i];
cardPanels[i] =
new CardPanel(cardName, getCodeBase(),
"images/" + cardName + ".gif");
cardDisplayPanel.add(cardPanels[i], cardName);
}
add(cardDisplayPanel, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent event) {
Button source = (Button)event.getSource();
if (source == first)
layout.first(cardDisplayPanel);
else if (source == last)
layout.last(cardDisplayPanel);
else if (source == previous)
layout.previous(cardDisplayPanel);
else if (source == next)

430

12.

layout.next(cardDisplayPanel);
else
layout.show(cardDisplayPanel, source.getLeUDel0);
return;
}
}

12.6.CardPanel.Java
import java.awt.*;
import java.net.*;
/**
*
*
*

, .
<></> CardLayout. CardPanel
^
CardLayout.

V
public class CardPanel extends Panel {
private Label name;
private ImageLabel picture;
public CardPanel(String cardName,
URL directory, String imageFile) {
setLayout(new BorderLayout());
name = new Label(cardName, Label.CENTER);
name.setFont(new Font("Sanserif", Font.BOLD, 50));
add(name, BorderLayout.NORTH);
picture = new ImageLabel(directory, imageFile);
Panel picturePanel = new Panel ();
picturePanel.add(picture);
add(picturePanel, BorderLayout.CENTER);
setSize(getPreferredSize());
}
public Label getLabelO {
return(name);
}
public ImageLabel getlmageLabel () {
return(picture);
}
}

12.4. CardLayout

431

\
Applet

__^
yiie^si

Jack
1

'1

King

AC

III ^^^ 1

first
Last

Prviii$
Nesd;

Ljji

Applet started.

. 12.5. CardLayout

CardLayout
public CardLayoutO
CardLayout,
.
public CardLayout(int sideMargins, int topMargins)
CardLayout,
.

CardLayout
CardLayout . ,
C o n t a i n e r , CardLayout, .
public void show(Container , String cardName)
,
.
public void first(Container )
public void last(Container )
,
.

432

12.

public void previous(Container )


public void next(Container )

. a d d ,
,
, .
public int getHgapO
public void setHgap(int hGap)
,
.
g e t S i d e M a r g i n s s e t S i d e M a r g i n s ,
, .
public int getVgapO
public void setVgap(int vGap)
,
.
g e t T o p M a r g i n s s e t T o p M a r g i n s , ,
.
public float getLayoutAlignmentX(Container )
public float getLayoutAlignmentY(Container )
.
13.2.

12.5. GridBagLayout
G r i d B a g L a y o u t
. ,
G r i d B a g L a y o u t .
, ,
.
.
1, G r i d B a g L a y o u t , .

G r i d B a g L a y o u t l a y o u t = new G r i d B a g L a y o u t ( ) ;
setLayout(layout) ;
G r i d B a g C o n s t r a i n t s
GridBagConstraints c o n s t r a i n t s =
new G r i d B a g C o n s t r a i n t s ( ) ;

12.5. GridBagLayout

433

G r i d B a g C o n s t r a i n t s
constraints.gridx = xl;
constraints.gridy = yl;
constraints.gridwidth = widthl;
constraints.gridheight = heightl;

add(component1, c o n s t r a i n t s ) ;

GridBagConstraints
, , G r i d B a g C o n s t r a i n t s , . )^ add
G r i d B a g C o n s t r a i n t s . add G r i d B a g C o n s t r a i n t s ,
Component .
Tiacce G r i d B a g C o n s t r a i n t s ; . GridBagConsta i n t s .
public int gridx
public int gridy
.
public int gridwidth
public int gridheight
, .
,
; GridBagLayout .
g r i d w i d t h g r i d h e i g h t G r i d B a g C o n s t r a i n t s .
RELATIVE, ,
. ,
G r i d B a g C o n s t r a i n t s . REMAINDER
. , 1.
public int anchor
f i l l G r i d B a g C o n s t r a i n t s .NONE, anchor
. ,
GridBagConstraints.CENTER. GridBagConstraints.NORTH, G r i d
B a g C o n s t r a i n t s .NORTHEAST, GridBagConstraints.EAST, GridBagConstra
i n t s .SOUTHEAST, GridBagConstraints.SOUTH, GridBagConstraints.SOUTH-

434

12.

WEST, GridBagConstraints.WEST GridBagConstraints.NORTHWEST



.
public int fill

. f i l l ,
, . GridBagConst
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 .VERTICAL , ,
. G r i d B a g C o n s t r a i n t s . BOTH ,
, .
public Insets insets
I n s e t s , .
I n s e t s ,
, [ .
p u b l i c I n s e t s ( i n t t o p , i n t l e f t , i n t bottom, i n t r i g h t )
public int ipadx
public int ipady
,
. .
public double weightx
public double weighty
,
X ,
. 0.0 ,
. 100.0 ,
,
100.0.

GridBagLayout
, . 12.6.
(JTextArea J t e x t f i e l d ) .
, , ,
.
, . ,
.
. ,
GridBagLayout.

12.5. GridBagLayout

435

\
0

V
1 [

^ (1

Z)\

(^ J (^ ) (^ ) |

. 12.6.
,

12.7 ,
.
G r i d B a g C o n t r a i n t s ,
G r i d B a g L a y o u t . G r i d B a g C o n t r a i n t s
,
. .
G r i d B a g L a y o u t G r i d B a g C o n s t r a i n t s
( ) H a s h t a b l e ,
p r i v a t e . Component.
,
GridBagContraints.

G r i d B a g L a y o u t . , , ,
G r i d B a g L a y o u t
, , ,
.

( "" ).
Box ( = 1 , =2). ,
, 1 .
Box 1 ,

. 2
3, Exit , . 12.8.
,
.
1 2 . 7 . G r i d B a g T e s t . J a v a
import
import
import
import
import
/'

java.awt.*;
Java.awt.event.*;
java.util.*;
javax.swing.*;
javax.swing.border.*;

, GridBagLayout

436

*
*

12.

^/
public class GridBagTest extends JPanel {
private JTextArea textArea;
private JButton bSaveAs, bOk^ bExit;
private JTextField fileField;
private GridBagConstraints c;
public GridBagTest0 {
setLayout(new GridBagLayout());
setBorder(BorderFactory.createEtchedBorder());
textArea = new JTextArea(12,40); // 12 rows, 40 cols
bSaveAs = new JButton("Save A s " ) ;
fileField = new JTextField("C:WDocument.txt");
bOk = new JButton("OK");
bExit = new JButton("Exit");
= new GridBagConstraints0;
// .
.gridx
= ;
c.gridy
= 0;
.gridwidth
= GridBagConstraints.REMAINDER;
.gridheight = 1;
.weightx
= 1.0;
.weighty
= 1.0;
.fill
= GridBagConstraints.BOTH;
c.insets
= new Insets(2,2,2,2); //t,l,b,r
add(textArea,c);
// Save A s .

.gridx
=
.gridy
=
.gridwidth =
.gridheight =
.weightx
=
.weighty
=
.fill
=
=
id(bSaveAs, c)

0;
1;
1;
1;
0. 0
0. 0
Gi
GridBagConstraints.VERTICAL;
ri<
.

// .
.gridx
= 1;
.gridwidth
= GridBagConstraints.REMAINDER;
.gridheight = 1;
.weightx
= 1.0;
.weighty
= 0.0;
c.fill
= GridBagConstraints.BOTH;
add(fileField, c) ;
// OK.
.gridx
= 2;
c.gridy++;

12.5. GridBagLayout

.gridwidth = 1;
c.gridheight = 1;
.weightx
= 0.0;
.weighty
= 0.0;
.fill
= GridBagConstraints.NONE;
add(bOk,c) ;
// Exit.
c.gridx
= 3;
c.gridwidth = 1;
c.gridheight = 1;
.weightx
= 0.0;
.weighty
= 0.0;
c.fill
= GridBagConstraints.NONE;
add(bExit,c);
// , ,
// 1 .
Component filler = Box.createRigidArea(new Dimension(1,1))
c.gridx
=1;
.weightx
= 1.0;
add(filler,c);
public static void main(String[] args) {
WindowUtilities.setNativeLookAndFeel();
JFrame frame = new JFrame("GrigBagLayout Test");
frame.setContentPane(new GridBagTest());
frame.addWindowListener(new ExitListener());
frame.pack();
frame.setVisible(true);
}

I^GiigBagLayoul Test

. :;: ;:;|12|

Save As

jCADocunfior.tM

Himfflfiffllff!

Save As

OK 1 P ^ 11
. 12.7. GridBag
Cons t r a i n t s ,

,

I CADocumentt4l

OK I
. 12.8.
GridBag
Layout, 1
Box

437

438

12.

GridBagLayout
p u b l i c GridBagLayoutO
G r i d B a g L a y o u t .
G r i d B a g
Constraints.

GridBagLayout
G r i d B a g L a y o u t .
p u b l i c GridBagConstraints g e t C o n s t r a i n t s ( C o m p o n e n t )
G r i d B a g C o n s t r a i n t s ,
.
public float getLayoutAlignmentX(Container )
public float getLayoutAlignmentY(Container )
.
13.2.
public int[ ][ ] getLayoutDimensionsO
g e t L a y o u t D i m e n s i o n s ,
.
p u b l i c P o i n t getLayoutOrigin()
G r i d B a g L a y o u t
.
public d o u b l e [ ][ ] getLayoutWeights()
g e t L a y o u t W e i g h t s w e i g h t x w e i g h t y .
public v o i d s e t C o n s t r a i n t s ( C o m p o n e n t c o m p o n e n t , GridBagConstraints
constraints)
.
,
. , ,

container.add(component);
layout.setConstraints(constraints);

container.add(component, constraints);

12.6. BoxLayout

439

12.6. BoxLayout
B o x L a y o u t , Swing.
( B o x L a y o u t . X A X I S )
( B o x L a y o u t . Y A X I S ) . B o x L a y o u t ,
:
.
.
B o x L a y o u t
( ) (
). ,
, B o x L a y o u t
. (
), B o x L a y o u t
, .
, B o x L a y o u t
. ,
BoxLayout .
,
, .
"" Swing-,
J C o m p o n e n t , O.Of
l.Of, 0.0 , ,
1.0 . ,
Component ,
: C o m p o n e n t . LEFT_ALIGNMENT (0.0), Component .CENTER_ALIGNMENT
(0.5), C o m p o n e n t . RIGHT_ALIGNMENT (1.0), Component .TOP_ALIGNMENT (0.0)
C o m p o n e n t . BOTTOM_ALIGNMENT (1.0). B o x L a y o u t ,
J C o m p o n e n t
, : .
JComponent.setAlignmentX(Component.Xxx_ALIGNMENT);
JComponent.setAlignmentY(Component.Xxx_ALIGNMENT);
Swing-
(Component .CENTER_ALIGNMENT). J B u t t o n ,
JComboBox, J L a b e l JMenu
( C o m p o n e n t . LEFT_ALIGNMENT).
B o x L a y o u t
( B o x L a y o u t . Y_AXIS) 12.8.

. .
,
(
r e v a l i d a t e ) . .

440

12.

12.8. BoxLayoutTest. Java


import java.awt.*;
import Java.awt.event.*;
import javax.swing.*;
/** BoxLayout. */
public class BoxLayoutTest extends Jpanel
implements ActionListener{
BoxLayout layout;
JButton topButton, middleButton, bottomButton;
public BoxLayoutTest() {
layout = new BoxLayout (this, BoxLayout .Y__AXIS) ;
s e tLayou t (1 ayou t) ;
JLabel label = new JLabel("BoxLayout

Demo");

topButton = new JButton("Left A l i g n m e n t " ) ;


middleButton = new JButton("Center A l i g n m e n t " ) ;
bottomButton = new JButton("Right A l i g n m e n t " ) ;
topButton.addActionListener(this);
middleButton.addActionListener(this) ;
bottomButton.addActionListener(this);
add(label);
add(topButton);
add(middleButton);
add(bottomButton);
setBackground(Color.white);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == topButton) {
refresh (Component. LEFT__ALIGNMENT) ;
} else if (event.getSource() == middleButton) {
refresh (Component. CENTER__ALIGNMENT) ;
} else if (event.getSource() == bottomButton) {
refresh(Component.RIGHT_ALIGNMENT);
}
}
private void refresh(float a l i g n m e n t ) !
topButton.setAlignmentX(alignment);
middleButton.setAlignmentX(alignment);
bottomButton. setAlignmentX (alignment) ;
revalidate();
System.out.println("x: "+layout.getLayoutAlignmentX(this));
}
public static void main(String[] args) {
WindowUtilities.setNativeLookAndFeel();
WindowUtilities.OpenlnJFrame(new BoxLayoutTest(), 300, 135,
"BoxLayoutTest");

12.6. BoxLayout

441

. 12.9 , B o x L a y o u t
Left Alignment Right Alignment.
, ,
.
. 12.9,
. . 12.9,6 ,
- .
,
;
. (0.0 1.0)
, "" .
0% ( 0.0)
100% ( 1.0). ""
,
. ,
. 12.9,
B o x L a y o u t .
^::.:].||>

llllllll^

BoxLayout Demo

BoxLayout Demo

|Lj-E!:^^?P'!*^j|
Center Mgnment

LeftAiignment

Center Alignment
f Rigiit Alignment '

Right ^ignment

()

(6)

. 12.9. (a) BoxLayout,


0.0 (
); ()
BoxLayout, 0.0,
1.0

B o x L a y o u t
. ,
(,
I n t e g e r . MAX_VALUE), .
,
( 0.0)
( 1.0), .

, .
,
B o x L a y o u t .
:
component.setMaximumSize(new Dimension(width,

height));

Bee
.

442

1 2 .

BoxLayout
BoxLayout .
public BoxLayout(Container container, int axis)
, ,
C o n t a i n e r , BoxLayout. C o n t a i n e r
, p r i v a t e ,
BoxLayout. , BoxLayout
. a x i s
: BoxLayout .XAXIS
( ), BoxLayout. Y_AXIS ( ).
!
,
BoxLayout
.

BoxLayout
BoxLayout.
public Dimension preferredLayoutSize(Container container)
public Dimension minimumLayoutSize(Container container)
public Dimension maximumLayoutSize(Container container)
,
, ,
.
public float getLayoutAlignmentX(Container container)
public float getLayoutAlignmentY(Container container)

( )
. O.Of l.Of.
13.2.
public void layoutContainer(Container container)

, s e t Bounds.
public void invalidateLayout(container container)
,
.

12.7.

443

, Swing Box,
BoxLayout. Box
BoxLayout .XAXIS
BoxLayout .YAXIS . Box
.

12.7.

. , ,
, . ;
, ,
. n u l l ,
.
s e t S i z e (width,
height),
s e t L o c a t i o n ( l e f t , top) s e t B o u n d s ( l e f t , t o p , w i d t h , h e i g h t ) .
, , Frame JFrame
s e t S i z e s e t Bounds.
s u p e r . s e t S i z e s u p e r . setBounds,
.

,
(, ),
.
12.9, . 12.10.
,
.
.
12.9. N u l l T e s t . J a v a
import J a v a . a p p l e t . A p p l e t ;
import j a v a . a w t . * ;
/**
*
*
*

,
<> </> .
,
setLayout n u l l .

public c l a s s NullTest extends Applet {


p u b l i c void i n i t O {
setLayout(null);
Button bl = new Button("Button 1")
Button b2 = new Button("Button 2")
Button b3 = new Button("Button 3")
Button b4 = new Button("Button 4")
Button b5 = new Button("Button 5")

444

12.

bl.setBounds(, , 150, 50);


b2.setBounds(150, , 75, 50);
b3.setBounds(225, , 75, 50);
b4.setBounds(25, 60, 100, 40);
b5.setBounds(175, 60, 100, 40) ;
add(bl)
add(b2)
add(b3)
add(b4)
add(b5)

Applet Viewer: NuliTest.class

Apple
Sutton 2

Applet started.

Button 3

. 12.10.
n u l l ,

12.8.


, ,
. Java-
, ,
. , , G r i d B a g L a y o u t
.
,
.

,

. " ".


.

,
.

12.8.

445


,
, .


,
, .

.

. G r i d B a g L a y o u t
, 12.10 ,
,
, .
. 12.11
. ,
, .

F l o w L a y o u t .

G r i d L a y o u t
.

B o r d e r L a y o u t NORTH SOUTH
, EAST WEST . CENTER
, .


, , . 12.11.
, )'
; .
.
,
. ,
B o r d e r L a y o u t , EAST, NORTH WEST .
, ,
J P a n e l G r i d L a y o u t ,
. 11 JPan3l,
.
J P a n e l , . Save As
( J B u t t o n )
J P a n e l . , ,
B o r d e r L a y o u t . F l o w L a y o u t , J P a n e l
, ,
. ,
J P a n e l F l o w L a y o u t F l o w L a y o u t .
RIGHT.

446

12.

. , ,
, , 12.7,
GridBagLayout.
. 12.12.

IBorderLayout
FlowLayout
GridLayout

. 12.11.

12.10.NestedLayout.Java
import
import
import
import
import
import

java.awt.*;
Java.awt.event.*;
java.util.*;
javax.swing.*;
javax.swing.border.*;
javax.swing.event.*;

/** ,
* 1^.
public class NestedLayout extends JPanel {
private JTextArea textArea;
private JButton bSaveAs, bOk, bExit;
private JTextField fileField;
public NestedLayout() {
setLayout(new BorderLayout(2,2));
setBorder(BorderFactory.createEtchedBorder0);
textArea = new JTextArea(12,40); // 12 , 40
bSaveAs = new JButton("Save A s " ) ;
fileField = new JTextField("C:WDocument.txt");
bOk = new JButton("OK");
bExit = new JButton("Exit") ;

12.8.

add(textArea,BorderLayout.CENTER);
//
/ / .
JPanel bottomPanel = new JPanelO;
bottomPanel.setLayout(new GridLayout(2,1));
JPanel subPanell = new JPanelO;
JPanel subPanel2 = new JPanelO;
siibPanell. setLayout (new BorderLayout ()) ;
subPanel2.setLayout(new FlowLayout(FlowLayout.RIGHT,2,2))
subPanell.add(bSaveAs,BorderLayout.WEST) ;
subPanell.add(fileField,BorderLayout.CENTER);
subPanel2.add(bOk) ;
subPanel2.add(bExit);
bottomPanel.add(subPanell);
bottomPanel.add(subPanel2);
add(bottomPanel,BorderLayout.SOUTH);

public static void main(String[] args) {


WindowUtilities.setNativeLookAndFeel();
JFrame frame = new JFrame("Nested Containers")
frame.setContentPane(new NestedLayout());
frame.addWindowListener(new ExitListener());
frame.pack();
frame.setvisible(true) ;
}

|11|||:||||:1.1|(1

;|

^^^jlljlll IMili ||1|

. 12.12.

447

448

12.



,
.
, , ,
,
( Label).
, 4 0 % (
). ,
Panel setBounds;
( 12.1).
Panel ,
(. 12.13).
12.11.ButtonCol.Java
import Java.applet.Applet;
import java.awt.*;
/*^
*
*
*
*
*


.
, .

, ,
.

public class ButtonCol extends Applet {


public void initO {
setLayout(null);
int widthl = getSize0 .width*4/10,
width2 = getSize0 .width - widthl,
height = getSize().height;
Panel buttonPanel = new Panel();
buttonPanel.setBounds(0, 0, widthl, height);
buttonPanel.setLayout(new GridLayout(6, 1));
buttonPanel.add(new Label("Buttons", Label.CENTER));
buttonPanel.add(new Button("Button One"));
buttonPanel.add(new Button("Button Two"));
buttonPanel.add(new Button("Button Three"));
buttonPanel.add(new Button("Button Four"));
buttonPanel.add(new Button("Button Five"));
add(buttonPanel);
Panel everythingElse = new Panel();
everythingElse.setBounds(widthl+1, 0, width2, height);
everythingElse.add(new Label("Everything Else"));
add(everythingElse);

12.8.

449

^.||.1.!||^!1!|1!'|!'1?||1.^.|'

Buttons

Everything Else

Button One

BirttonTwo

Button four

ByttonFw

. 12.13.
,


AWT G r i d B a g L a y o u t ,
,
. G r i d B a g L a y o u t
i n s e t s i p a d x i p a d y G r i d B a g C o n s t r a i n t s .
i n s e t s
I n s e t s
. ;
, . I n s e t s
. ,
C o n t a i n e r ,
, ,
I n s e t s , (,
P a n e l ) g e t l n s e t s .
C a n v a s B o x
AWT C a n v a s , ,
, ""
, . C a n v a s
F l o w L a y o u t ,
G r i d L a y o u t , G r i d B a g L a y o u t , B o x L a y o u t NORTH,SOUTH, EAST
WEST B o r d e r L a y o u t .
Swing-
Box. Box .

( B o x . c r e a t e R i g i d A r e a ) .

"" ,
, ( . C r e a t e H o r i z o n t a l S t r u t ) , ,
( B o x . C r e a t e H o r i z o n t a l S t r u t ) .

450

1 2 .

(Box. c r e a t e H o r i z o n t a l G l u e , B o x . c r e a t e V e r t i c a l G l u e ) ( B o x . c r e a t e G l u e )
, .

12.12 ,
"" .
J P a n e l s (
F l o w L a y o u t ) . .
. 12.14,
20x75 .
"" 60 .

, ,
F l o w L a y o u t Box.
, ,
B o x L a y o u t . , B o x L a y o u t ,
.
!

,

. ,
BoxLayout.

12.12.InvisibleComponentTest.Java
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class InvisibleComponentTest extends JPanel {
Component spacer;
public InvisibleComponentTest() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
//
// - 25
/ / 75 .
JPanel 1= new JPanel();
spacer = Box.createRigidArea(new Dimension(20,75));
setUpPanel(pi, "Rigid Area - 20x75 pixels", spacer);
// ""
// 60 .
JPanel 2= new JPanel();
spacer = Box.createHorizontalStrut(60);
setUpPanel(p2, "Horizontal Strut - 60 pixels", spacer);

12.8.

// :
// FlowLayout .
JPanel = new JPanelO;
spacer = Box.createHorizontalGlue;
setUpPanel(, "Horizontal Glue - FlowLayout", spacer);
//
// .
// FlowLayout,
// JPanel BoxLayout.
JPanel 4= new JPanelO;
4.setLayout(new BoxLayout(p4,BoxLayout.X-AXIS));
spacer = Box.createHorizontalGlue0;
setUpPanel(p4, "Horizontal Glue - BoxLayout", spacer);
add(pi);
add(p2);
add(p3);
add{p4);
}
//
/ / .
private void setUpPanel(JPanel p, String title,
Component spacer) {
p.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),title,
TitledBorder.TOP,TitledBorder.CENTER));
.setBackground(Color.white);
.add(new JButton("Left"));
.add(spacer);
.add(new JButton("Right"));
}
public static void main(String[] args) {
String title = "Using Invisible Components";
WindowUtilities.setNativeLookAndFeel();
WindowUtilities.openlnJFrame(new InvisibleComponentTest(),
350, 325, title);
}

||||"^|ri|x|
Rigid Area - 20x75 pixels

ILSLJI

^'sht 1

Horizontal Strut- 60 pixels

iM 1

. R^ j

Horizontal Glue - FlowLayout

Left 1

mm 1

Horizontal Glue - BoxLayout

Left 1

Right 1

. 12.14. Box

451

452

12.

Box
Box ,
.
public static Component createRigidArea(Dimension size)
.
public static Component createHorizontalStrut(int width)
public static Component createVerticalStrut(int height)

.
.
public static Component createHorizontalGlue()
public static Component createVerticalGlue()
public static Component createGlue()
,
,
. ,
.
, S h o r t .MAX_VALUE. ,
BoxLayout, ,
.

12.9.
.
, ,
.
FlowLayout, BorderLayout, GridLayout, CardLayout
GridBagLayout. Java 2
BoxLayout.
, ,
,
.

. - . 13
, ,
.

AWT
...

Component.

"" .

: P a n e l i A p p l e t , Frame D i a l o g .

Frame ,

Frame.

,
.

Jy\ZJ^ZJ

Abstract Window Toolkit (AWT),


Java,
,
. Java 2 AWT Swing ( 14, 15). ,
Netscape 6 Swing.
, Swing, Netscape
Internet Explorer, Java Plug-In
Swing- JAR- .
, AWT,
,
. Java 1.1 AWT API Netscape 4.06 Internet Explorer 4, a
.
AWT ,
: C a n v a s , P a n e l , A p p l e t , S c r o l l P a n e , Frame, D i a l o g ,
F i l e D i a l o g Window. (, P a n e l S c r o l l P a n e )
, . ,
Frame D i a l o g ,
. A p p l e t ;
AWT .
Frame. ,
Swing, Frame
Java-. , Frame
, .
,
, , ,
. ,
Component C o n t a i n e r , .

, ,

456

13. AWT

: ,
, , , ,
, .
, ,
; ,
. , L i s t ItemSel e c t i o n E v e n t , S c r o l l b a r AdjustmentEvent.
.
AWT .
;
p a i n t )^ .
, .
. ,
, ,
. , ,
,
.
AWT
Component. "
", .. .
p a i n t ,
. "" ,
, .

1 3 . 1 . Canvas
Canvas ,
. Canvas
, . Canvas
. Canvas
.
1. . ,
, .
,
Canvas. ,
, p a i n t .
2. . ,
, ,
Canvas.
Canvas.
.
G r a p h i c s , g e t G r a p h i c s , ,
u p d a t e p a i n t Canvas .
, Canvas, ,
, r e p a i n t Canvas.

1 3 . 1 . Canvas

457

paint. Graphics

Canvas
C a n v a s .
Canvas c a n v a s = new C a n v a s ( ) ;
/ / C a n v a s ,
c a n v a s . s e t S i z e ( w i d t h , h e i g h t ) ; / / ,
a d d ( c a n v a s ) ; / / Canvas .
/ / . . .
add(canvas, r e g i o n ) ;
C a n v a s 0x0 ,
, .
C a n v a s C e n t e r
B o r d e r L a y o u t .
!

Canvas.

,
Canvas
13.1 ,
C a n v a s . C a n v a s p a i n t ,
, ( 13.2), Java
. ,
C a n v a s .
C a n v a s .
. 13.1.
A p p l e t , .
. 12.
1 3 . 1 . C i r c l e . J a v a
import

java.awt.*;

/** Circle, Canvas. */


public class Circle extends Canvas {
private int width, height;
public Circle(Color foreground, int radius) {

458

13. AWT

setForeground(foreground);
width = 2*radius;
height = 2*radius;
setSize(width, height);
public void paint(Graphics g) {
g.fillOvaKO, 0, width, height);
public void setCenter(int x, int y) {
setLocation(x - width/2, - height/2);

13.2.CircleTest.Java
import java.awt.*;
import Java.applet.Applet;
/** , FlowLayout.
public class CircleTest extends Applet {
public void initO {
setBackground(Color.lightGray);
add(new Circle(Color.white, 30));
add(new Circle(Color.gray, 40));
add(new Circle(Color.black, 50));
}
}

Applet

Applet started.

. 13.1. Canvas

AWT
. , ;
. , 13.3,
. . 13.2, C a n v a s
. , ,
, ,
.
, .

1 3 . 1 . Canvas


AWT .

13.3. C i r c l e T e s t : 2 . j a v a
import java.awt.*;
import Java.applet.Applet;
/** ,
* . ,
* AWT- .

public class CircleTest2 extends Applet {


public void initO {
setBackground(Color.lightGray);
setLayout(null); // .
Circle circle;
int radius = getSize().width/6;
int deltaX = round(2.0 * (double)radius / Math.sqrt(2.0));
for (int x=radius; x<6*radius; x=x+deltaX) {
circle = new Circle(Color.black, radius);
add(circle);
circle.setCenter(x, x ) ;
}
}
private int round(double num) {
return((int)Math.round(num));
}

^ ^ A ^^- ^^ \

CircIeTest2

'i^^

"^)"

.
. 13.2. AWT

459

460

13. AWT

13.2. Component
AWT "" Component.
.
public v o i d a d d ( P o p u p M e n u m e n u )
public void r e m o v e ( M e n u C o m p o n e n t m e n u )
a d d PopupMenu.
; show PopupMenu.
r e m o v e .
public v o i d addNotifyO
public void removeNotifyO
a d d N o t i f y - ,
. - ,
- ,
s e t V i s i b l e .
s u p e r . a d d N o t i f y . r e m o v e N o t i f y -
.
. ,
createPeer destroyPeer.
public void addXxxListener(X)cxListener listener)
public v o i d removeXxxListener(Xxx;Listener listener)
.
: Component, F o c u s , I n p u t M e t h o d
(Java 2), Key, Mouse, M o u s e M o t i o n , P r o p e r t y C h a n g e (Java 2).
( ) . 11.5.
public b o o l e a n contains(int , int )
public b o o l e a n c o n t a i n s ( P o i n t p)
,
.
p r o t e c t e d final void d i s a b l e E v e n t s ( l o n g eventsToDisable)
p r o t e c t e d final void e n a b l e E v e n t s ( l o n g eventsToEnable)
d i s a b l e E v e n t s , a e n a b l e E v e n t s
. ()
AWT E v e n t .
public final void dispatchEvent(AWTEvent event)

.

13.2. Component

461

protected void firePropertyChange(String propertyName,


Object oldValue,
Object newValue) [Java 2]
f i r e P r o p e r t y C h a n g e PropertyChangeEvent
. P r o p e r t y C h a n g e Listener.
public float getAlignmentXO
public float getAlignmentYO

. O.Of , ( )
( ). 0.5f
. 1.Of , ( )
( ).

0.5f Component
: TOP_ALIGNMENT (O.Of), CENTER_ALIGNMENT (0.5f),
BOTTOM_ALIGNMENT (l.Of), LEFT_ALIGNMENT (O.Of) RIGHT_ALIGNMENT (l.Of).
public Color getBackgroundO
public void setBackground(Color bgColor)
getBackground , a setBackground
.
public Rectangle getBounds()
public void setBounds(int x, int y, int width, int height)
public void setBounds(Rectangle boundingRectangle)
getBounds Rectangle, .
R e c t a n g l e , , , width
h e i g h t . setBounds ,
. setBounds s e t S i z e s e t L o c a t i o n .
public Component getComponentAt(int x, int y)
public Component getComponentAt(Point p)
""
. ,
, .
, n u l l .
public
public

Cursor getCursor()
void setCursor(Cursor cursor)
g e t C u r s o r . s e t C u r s o r
. Cursor, -

462

13. AWT

C u r s o r . g e t P r e d e f i n e d C u r s o r ( t y p e ) ,
type


Cursor:
CROSSHAIR_CURSOR,
DEFAULT_CURSOR,
E_RESIZE_CURSOR,
HAND_CURSOR,
MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NW_RESIZE_CURSOR,
S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR,
W_RESIZE_CURSORWAIT_CURSOR.
public Font getFont()
public void s e t F o n t ( F o n t f)
g e t F o n t ,
s e t F o n t . G r a p h i c s ,
p a i n t u p d a t e , .
public F o n t M e t r i c s g e t F o n t M e t r i c s ( F o n t f)
g e t F o n t M e t r i c s F o n t M e t r i c s ,
. F o n t M e t r i c s
, .
public Color g e t F o r e g r o u n d ( )
public void s e t F o r e g r o u n d ( C o l o r fgColor)

. G r a p h i c s .
public Graphics getGraphics()
g e t G r a p h i c s G r a p h i c s ,
, .
G r a p h i c s , .
public P o i n t getLocationO
public void setLocation(int x, int y)
public void s e t L o c a t i o n ( F o i n t p)
g e t L o c a t i o n P o i n t ( x ),

.
g e t L o c a t i o n O n S c r e e n . s e t L o c a t i o n
,
. ,
.
public Point getLocationOnScreen()

. .
.

13.2. Component

463

public Dimension getMinimumSize()


p u b l i c D i m e n s i o n getMaximumSize()
p u b l i c D i m e n s i o n getPreferredSizeO
D i m e n s i o n ( , , w i d t h
h e i g h t ) , ,
. ,
.
p u b l i c Container getParent()
g e t P a r e n t (
Component , n u l l ) .

Frame

p u b l i c D i m e n s i o n getSize()
public void setSize(int w i d t h , int height)
p u b l i c void s e t S i z e ( D i m e n s i o n d)
g e t S i z e Dimension,
w i d t h h e i g h t . s e t S i z e ,
s e t B o u n d s . s e t B o u n d s
, .
p u b l i c Toolkit getToolkit()
T o o l k i t ,
( g e t l m a g e ) , ( g e t F o n t L i s t ) ,
( g e t S c r e e n S i z e ) , ( g e t S c r e e n R e s o l u t i o n ) ..
p u b l i c void invalidateO
p u b l i c void validateO
i n v a l i d a t e , ,

. v a l i d a t e
C o n t a i n e r
.
p u b l i c b o o l e a n isEnabled()
i s E n a b l e d , (.
s e t E n a b l e d ) .
p u b l i c b o o l e a n isFocusTraversable()
i s F o c u s T r a v e r s a b l e ,
<> <Shift+Tab>.
f a l s e , , ,
r e q u e s t F o c u s .

464

1 3 . AWT

public boolean isShowingO


public boolean isVisible()
i s Showing ,
, . i s V i s i b l e ,
. i s V i s i b l e
t r u e , ;
, .
public boolean isValid()
i s V a l i d , (.
v a l i d a t e i n v a l i d a t e ) .
public void list()
public void list(PrintStream stream)
public void list(PrintStream stream, int indentation)
public void list(PrintWriter writer)
public void list(PrintWriter writer, int indentation)
,
.
.
, , l i s t
, .

list
, ,

.

public void paint(Graphics g)


p a i n t r e p a i n t ,
.
p a i n t .
, G r a p h i c s ,
.
public void paintAll(Graphics g)
,
.

13.2. Component

465

public boolean preparelmage(lmage image,


ImageObserver observer)
public boolean preparelmage(lmage image, int width,
int height,
ImageObserver observer)
, Image.
.
( 9.) ,
,
, ,
p r e p a r e Image, . ,
, , t r u e ,
f a l s e .
public void print(Graphics g)
public void printAll(Graphics g)
G r a p h i c s P r i n t G r a p h i c s ,
.
, p a i n t p a i n t A l l .
public void processXjcxEvent(Xx3cEvent event)
) (.
e n a b l e E v e n t s ) . :
: Component, Focus, InputMethod (Java 2) Key, Mouse
MouseMotion. . .
public
public
public
public

void repaintO
void repaint(int x, int y, int width, int height)
void repaint(long milliseconds)
void repaint(long milliseconds, int x, int y, int width,
int height)
AWT , u p d a t e
. P a i n t E v e n t
. P a i n t E v e n t u p d a t e ,
, p a i n t .
, .
public void requestFocusO
. ,
r e q u e s t Focus ,
( Button)
TextField.

466

13. AWT

public v o i d s e t n a b l e d ( b o o l e a n enabledFlag)
s e t E n a b l e d AWT- ( t r u e )
( f a l s e ) .
, .
public v o i d setVisible(boolean visibleFlag)
s e t V i s i b l e AWT- ( t r u e )
(false).
public void transferFocus()
,
<>.
.
public void u p d a t e ( G r a p h i c s g)
AWT
r e p a i n t . ,
p a i n t ( g ) . u p d a t e , p a i n t
.
. 16
.

13.3. "" Java 1.1


Java 1.1 "" ,
Component,
. , p a i n t ,
, . 13.4
B e t t e r C i r c l e , .
C a n v a s ( 13.1), ,
g e t P r e f e r r e d S i z e g e t M i n i m u m S i z e , .

. 13.5 , B e t t e r C i r c l e , , , C i r c l e .
. 13.3, ,
.
""
p a i n t s u p e r . p a i n t ,
"" .

13.3. "" Java 1.1

1 3 . 4 . B e t t e r C i r c l e . J a v a
import

java.awt.*;

/ Circle,
* Canvas "" Java 1.1.
public class BetterCircle extends Component {
private Dimension preferredDimension;
private int width, heightspublic BetterCircle(Color foreground, int radius) {
setForeground(foreground);
width = 2*radius;
height = 2*radius;
preferredDimension = new Dimension(width, height);
setSize(preferredDimension);
}
public void paint(Graphics g) {
g.setColor(getForeground());
g.fillOval(0, 0, width, height);
}
public void setCenter(int x, int y) {
setLocation(x - width/2, - height/2);
}
/** ,
* BetterCircle
* .
*/
public Dimension getPreferredSize() {
return(preferredDimension);
}
/**

V
public Dimension getMinimumSize() {
return(preferredDimension);

467

468

13. AWT

13.5. BetterCircleTest.Java
import java.awt.*;
import java.applet.Applet;
/**
*
*
*

,
. 11 lightweight
""
Java 1.1.

public class BetterCircleTest extends Applet {


public void initO {
setBackground(Color.lightGray) ;
setLayout(null) ;
BetterCircle circle;
int radius = getSize().width/6;
int deltaX = round(2.0 * (double)radius / Math.sqrt(2.0));
for (int x=radius; x<6*radius; x=x+deltaX) {
circle = new BetterCircle(Color.black, radius);
add(circle);
circle.setCenter(x, x ) ;

}
}
private int round(double num) {
return((int)Math.round(num));
}

;ie dt> lifiew 0 !^tmMvu*ot

<

BetterCircleTest

gjj<ijj>r

. 13.3. Java 1.1 ""


13.4. Panel

469

""
,
. Swing
- . "" Swing-
14.

13.4. Panel
P a n e l ,
. C a n v a s , P a n e l
;
. Java- P a n e l .
1. . ,
,
P a n e l . ,
.
2. ,
.

: FlowLayout
, (.. ),
( L a y o u t M a n a g e r ) . .
,
.
F l o w L a y o u t
, , .
, ,
. , P a n e l
, . ,
P a n e l ,
F l o w L a y o u t ,
.

!
Panel , ^
FlowLayout,
.

470

13. AWT



P a n e l . P a n e l
, ,
. .
// Panel.
Panel panel = new Panel();
// .
panel.add(someComponent);
panel.add(someOtherComponent);
// .
// FlowLayout:
container.add(panel) ;
// BorderLayout:
container.add(panel,
region);

Panel

,
. ( 13.6) .
. 13.4, ,
. ,
,
. ( 13.7)
.
. 13.5.
1 3 . 6 . B u t t o n T e s t l . j a v a
import
import

Java.applet.Applet;
java.awt.'^;

/ * * ,
* F l o w L a y o u t , ,
* .
V
public class ButtonTestl extends Applet
public void init() {
String[] labelPrefixes = { "Start",
"Resume"
for (int i=0; i<4; i++) {
add(new Button(labelPrefixes[i] +
}
for (int 1=0; i<4; i++) {
add(new Button(labelPrefixes[i] +
}
}
}

{
"Stop", "Pause",
};
" Threadl"));
" Thread2"));

13.4. Panel

K3S3|
Fte

cW

V)rt4

^^^ -

Favortfes

Joote

HeJp

J J 'J a ^ J -' _* -^ J
Jl

ButtonTestl
Sfaft Threadi 1 StopThreadl | Pause Threadl | Reswio Thad1 | Slet | 3^|
Pause Thftad2 | Resume Ttyeacgj

A
^

Done

f^i My Conputef

. 13.4.
,

13.7.ButtonTest2.java
import J a v a . a p p l e t . A p p l e t ;
import j a v a . a w t . * ;
/** . */
p u b l i c c l a s s ButtonTest2 extends Applet {
p u b l i c void i n i t O {
S t r i n g [ ] l a b e l P r e f i x e s = { " S t a r t " , "Stop", "Pause",
"Resume" };
Panel p i = new P a n e l ( ) ;
for ( i n t i=0; i<4; i++) {
pi.add(new B u t t o n ( l a b e l P r e f i x e s [ i ] + " T h r e a d l " ) ) ;
}

Panel p2 = new P a n e l ( ) ;
for ( i n t i=0; i<4; i++) {
p2.add(new B u t t o n ( l a b e l P r e f i x e s [ i ]

+ " Thread2"));

add(pi);
add(p2);

Ftte

ck

View

Favof^es

Ttxrfs

-'

ButtonTest2
j

Staff Threadl j StopThreadl | Paute Threadl j Resume Threadl |


Start Thread^ | Stop Thfead2 | TNead2 | Retufw Tbead2 j

. 0 j statted

..J )-

. 13.5.

471

472

13. AWT

13.5. Container
P a n e l ~ Java,
. ,
, C o n t a i n e r . C o n t a i n e r
Component (
). , C o n t a i n e r
.
public C o m p o n e n t a d d ( C o m p o n e n t )
public C o m p o n e n t a d d ( C o m p o n e n t , Object constraints)


. B o r d e r L a y o u t ,
B o r d e r L a y o u t .NORTH, B o r d e r L a y o u t . SOUTH, B o r d e r L a y o u t .
EAST, B o r d e r L a y o u t . WEST B o r d e r L a y o u t .CENTER.
a d d , Component ,
.
API, j a v a . a w t .
Container.
public void a d d C o n t a i n e r L i s t e n e r ( C o n t a i n e r L i s t e n e r listener)
public void r e m o v e C o n t a i n e r L i s t e n e r ( C o n t a i n e r L i s t e n e r listener)
,
, .
C o n t a i n e r E v e n t ,
( C o n t a i n e r L i s t e n e r ) .
public int g e t C o m p o n e n t C o u n t O
, . , (.
i s V i s i b l e C o m p o n e n t ) .
public C o m p o n e n t g e t C o m p o n e n t ( i n t position)
g e t Component N- ,
(). .
,
g e t C o m p o n e n t C o u n t , A r r a y l n d e x O u t O f B o undsException.
public C o m p o n e n t [ ] g e t C o m p o n e n t s ( )
,
(). ; n u l l
.

13.5. Container

473

public LayoutManager getLayout()


,
, n u l l .
public Insets getlnsetsO
g e t l n s e t s I n s e t s ( t o p , bottom,
l e f t r i g h t ) , . s e t l n s e t s
. g e t l n s e t s ,
, ( - ), I n s e t s
, p u b l i c .
public boolean isAncestorOf(Component possibleSubComponent)
, -
.
public void paint(Graphics g)
public void print(Graphics g)
Component.
.
""
p a i n t p r i n t , s u p e r . p a i n t
s u p e r . p r i n t , .
, "" ,
p a i n t p r i n t
.
public void processContainerEvent(ContainerEvent event)
, , ,
. .
11.
public void remove(int Component)
public void remove(int position)
remove . N .
, getComponentCount () ~1 .
public void setLayout(LayoutManager manager)
. , ,
Frame BorderLayout FlowLayout
Applet , FlowLayout
10 5, .

474

13. AWT

13.6. Applet
A p p l e t Java-, Web. Java-,
P a n e l ,
A p p l e t . A p p l e t ,
P a n e l , F l o w L a y o u t . A p p l e t . 9.

13.7. ScrollPane
S c r o l l P a n e ,
,
. S c r o l l P a n e
P a n e l , .

ScrollPane
S c r o l l P a n e
, S c r o l l P a n e

. S c r o l l P a n e ,
: SCROLLBARS_ALWAYS,
SCROLLBARS_AS_NEEDED, SCROLLBARS_NEVER. S c r o l l P a n e ,
, ,
. ,
S c r o l l b a r .
/ / S c r o l l P a n e ,
/ / .
S c r o l l P a n e pane =
new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS);
/ / S c r o l l P a n e
/ / ,
.setSize(width, height);
add(pane);

ScrollPane,
, 100
13.8 , S c r o l l P a n e .
P a n e l , 100 . . 13.6
,
.

13.8. Frame

475

13.8.ScrollPaneTest-Java
import Java.applet.Applet;
import j ava.awt.*;
/*^ , 100 ,
* ScrollPane. ScrollPane ,
* .

public class ScrollPaneTest extends Applet {


public void initO {
setLayout(new BorderLayout());
ScrollPane pane = new ScrollPane();
Panel bigPanel = new PanelO;
bigPanel.setLayout(new GridLayout(10, 10));
for(int i=0; i<100; i++) {
bigPanel.add(new Button("Button " + i));
}
pane.add(bigPanel);
add(pane, BorderLayout.CENTER);
}

|.^^.f-ui;i!^u'i''iJii.^ffViffMPf?TWT^''^^^
Apptet
1 2

).

Button 4

Buttons

Sue

1 Button 12

Button 13

Bulton14

BtritonlS

ButtJ

1 Button 22

Sutton 23

Sutton 24

Button 25

ButtJ

1 Button 32

Button 33

Sutton 34

Bun36

Butt*

1 Button 42

Button 43

8un44

Button 46

Butt

1 Button $2

9053

Sutton S4

Button 56

Butt.

1 Button $2

Button S3

Sutton M

566

Butt*

1 Button 72 0 7 3

Suttdn74

Button 76

Btitt*
Butt*

1 Button $2 Button 83

Sulton?4

Button 6

1 Button 92 Button 93

Sutt8n94

Button 96

Lu
Applet started.

Butt*

^1
1

1. 13.6. S c r o l l P a n e ,
,

13.8. Frame
Frame .
, .
Frame . Frame
, , , . Frame
.

476

13. AWT

:
BorderLayout
B o r d e r L a y o u t : NORTH,
SOUTH, EAST, WEST CENTER.
; , ,
. , NORTH (SOUTH),
() .
(. p r e f e r r e d S i z e C o m p o n e n t ) ,
, ,
(. g e t l n s e t s
C o n t a i n e r ) . , EAST (WEST),
() ; ,
,
NORTH SOUTH.
CENTER. , Frame,
.
B o r d e r L a y o u t
F l o w L a y o u t , s e t L a y o u t .
B o r d e r L a y o u t . 12.

Frame
Frame, ,
, s e t S i z e , , Frame
.
, .
Frame :
/ / Frame.
Frame frame = new F r a m e ( t i t l e S t r i n g ) ;
/ / .
f r a m e . a d d ( s o m e P a n e l , BorderLayout.CENTER);
f r a m e . a d d ( o t h e r P a n e l , BorderLayout.NORTH);
/ / Frame.
/ / .
frame.setSize(width, height);
/ / , .
frame.setBounds(left, top, width, h e i g h t ) ;
/ / Frame.
frame.setVisible(true) ;
, Frame,
,
. f r a m e . a d d ( s o m e C o m p o n e n t ) ,
CENTER.
( s o m e O t h e r C o m p o n e n t ) , CENTER,
.

13.8- Frame

477

Frame,
, , ,
.
/ / Frame.
Frame frame = new F r a m e ( t i t l e S t r i n g ) ;
/ / Frame ( ).
frame.setLocation(left, top);
/ / .
frame.add(somePanel, BorderLayout.CENTER);
/ / Frame.
frame.packO ;
/ / Frame,
frame.setVisible(true);
pack, - Frame
(. addNotif Component),
.
.
Frame,
s e t R e s i z e a b l e ( f a l s e ) .
Frame , g e t S c r e e n S i z e ,
g e t T o o l K i t . Frame .
Toolkit t o o l k i t = frame.getToolkit();
Dimension s c r n S i z e = t o o l k i t . g e t S c r e e n S i z e ( ) ;
Dimension frameSize = f r a m e . g e t S i z e ( ) ;
frame.setLocation((scrnSize.width-frameSize.width)/2,
(scrnSize.height-frameSize.height)/2);
Frame,
"Unsigned Java Applet Window"
Netscape (. 13.7) "Warning: Applet Window" ( Internet
Explorer). .

. 13.7. Frame, ,

Frame
Frame. ,
13.9, Frame
main. Frame
( ),
. ( ,

478

13. AWT

) m a i n .
,
,
Frame.
1 3 . 9 . F r a m e E x a m p l e l . J a v a
import

java.awt.*;

p u b l i c c l a s s FrameExamplel {
public s t a t i c void main(String[] args) {
Frame f = new F r a m e ( " F r a m e Example 1")
f.setSize(400, 300);
f.setVisible(true);
}
}

'

Bo , 13.10,
.
Frame m a i n ,
. .
,
-
.
,
, m a i n ,
.
1 3 . 1 0 . F r a m e E x a m p l e 2 . j a v a
import

java.awt.*;

public class FrameExample2 extends Frame


public static void main(String[] args)
new FrameExample2();
}
public FrameExample2() {
superC'Frame Example 2 " ) ;
setSize(400, 300);
setVisible(true);
}

13.8. Frame

479

Frame
Frame ,
. ,
Frame
WindowListener. 13.11 CloseableFrame,
System.exit.

. Frame, (
Frame),
System, exit dispose. ,
. Frame
getlnsets, , ,
(, Panel) CENTER Frame
.
13.11.CloseableFrame.Java
import java.awt.*;
import Java.awt.event.*;
/** Frame, ,
*^
* Java 1.1.
public class CloseableFrame extends Frame {
public CloseableFrame(String title) {
super(title);
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
}
/
* (super.processWindowEvent).

V
public void processWindowEvent(WindowEvent event) {
super.processWindowEvent(event); // ,
if (event.getlDO == WindowEvent.WINDOW_CLOSING) {
// Frame ,
// dispose().
System.exit(0);
}
}

480

13. AWT

Frame ,
. MenuBar,
Menu. Menu
S t r i n g , Menu ( )
C h e c k b o x M e n u I t e m ( ).
MenuBar add, MenuBar
( ), s e t H e l p Menu ( ).
MenuBar Frame s e t M e n u B a r
.
A c t i o n L i s t e n e r . , ,
e v e n t . g e t A c t i o n C o m m a n d . 13.12 ,

Frame.
. 13.8.
1 3 . 1 2 . C o l o r M e n u . J a v a
import
import

java.awt.*;
Java.awt.event.*;

/ * * Frame
p u b l i c c l a s s ColorMenu e x t e n d s C l o s e a b l e F r a m e
implements A c t i o n L i s t e n e r {
p r i v a t e S t r i n g [ ] colorNames =
{ " B l a c k " , " W h i t e " , " L i g h t G r a y " , "Medium G r a y " ,
"Dark G r a y " };
private Color[] colorValues =
{ Color.black, Color.white, Color.lightGray,
C o l o r . g r a y , C o l o r . d a r k G r a y };
p u b l i c ColorMenu0 {
super("ColorMenu");
MenuBar b a r = new M e n u B a r ( ) ;
Menu ColorMenu = new M e n u ( " C o l o r s " ) ;
f o r ( i n t i = 0 ; i < 2 ; i++) {
ColorMenu.add(colorNames[i]);
}

Menu grayMenu = new M e n u ( " G r a y " ) ;


f o r ( i n t i = 2 ; i < c o l o r N a m e s . l e n g t h ; i++) {
grayMenu.add(colorNames[i]) ;
}

ColorMenu.add(grayMenu);
bar.add(ColorMenu) ;
setMenuBar(bar) ;
ColorMenu.addActionListener(this);
grayMenu.addActionListener(this);

1 3 . 8 . Frame

481

setBackground(Color.lightGray);
setSize(400, 200);
setVisible(true) ;
}
/** , Frame. */
public void actionPerformed(ActionEvent event) {
setBackground(colorNamed(event.getActionCoramand()));
repaint();
}
private Color colorNamed(String colorName) {
for(int i=0; i<colorNames.length; i++) {
if(colorNames[i].equals(colorName) ) {
return(colorValues[i]);
}
}
return(Color.white);
}
public static void main(String[] args) {
new ColorMenu();

. 13.8. Frame,

Frame
Frame.
Component C o n t a i n e r .
public void disposeO
- , Frame,
. System, e x i t ,
Frame, , WINDOW_DESTROY.

Frame, ,
System, exit dispose.

482

13. AWT

public Image getIconImage()


public void s e t I c o n I m a g e ( I m a g e icon)
,
Frame .
s e t l c o n l m a g e , g e t I c o n Image n u l l .
public MenuBar getMenuBar()
public void setMenuBar(MenuBar menuBar)
p u b l i c void r e m o v e ( M e n u C o m p o n e n t menuBar)
.
.
public String getTitleO
public void setTitle(String title)
,
.
public b o o l e a n isResizable()
public void s e t R e s i z a b l e ( b o o l e a n resizeFlag)

. s e t R e s i z a b l e ( f a l s e ) , .
i s Re s i z a b l e .
public void ()
Frame
.
public void toBack()
public void toFront()
Frame (.. ,
Frame, ).

13.9.
Java 1.1 .
Java-
. ( w r i t e O b j e c t )
Frame ,
, .
: ,
, , .
AWT. , S e r i a l i z a b l e .

13.9.

483

,
implements S e r i a l i z a b l e . ,
t r a n s i e n t .
(readObject).



. ,
Java.io.*.
try {
FileOutputStream fileOut =
new FileOutputStream("SaveFilename");
ObjectOutputStream out =
new ObjectOutputStream(fileOut);
out.writeObject(someWindow);
out.flush ();

out.close ();
} catch(lOException ioe) {
S y s t e m . o u t . p r i n t l n ( " E r r o r saving window: " + i o e ) ;
}

, GZIPOutputStream ( j a v a . u t i l . z i p ) F i l e O u t p u t S t r e a m
ObjectOutputStream.
.



.
try {
File saveFile = new File("SaveFilename");
FilelnputStream fileln =
new FilelnputStream(saveFile);
ObjectlnputStream in =
new ObjectInputStream(fileln);
someWindow = (WindowType)in.readObject();
doSomethingWith(someWindow); // , setVisible.
} catch(lOException ioe) {
System.out.println("Error reading file: " + ioe);
} catch(ClassNotFoundException cnfe) {
System.out.println("No such class: " + cnfe);
}
,
GZIPInputStream FilelnputStream ObjectlnputStream.

484

13. AWT

Frame,

13.13 Frame,
. ,
, Save
. . 13.9 ,
, ,
. SavedFrame
. Circle Panel ( 13.14)
Panel MouseListener,
, .
BetterCircle, 13.4.
13.13.SavedFrame.Java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
/** Frame .
* .
V
public class SavedFrame extends CloseableFrame
implements ActionListener {
/** ,
* .
* .
*/
public static void main(String[] args) {
SavedFrame frame;
File serializeFile new File(serializeFilename);
if (serializeFile.exists 0 ) {
try {
FilelnputStreeun fileln =
new FilelnputStream(serializeFile);
ObjectlnputStream in = new ObjectlnputStream(fileln);
frame = (SavedFrsune) in. readObject () ;
frame.setVisible(true);
} catch(lOException ioe) {
System.out.println("Error reading file: " + ioe);
} catch(ClassNotFoundException cnfe) (
System.out.println("No such class: " + cnfe);
}
} else {
frame = new SavedFrame();
}

13.9.

private static String serializeFilename ="SavedFrame.ser";


private CirclePanel circlePanel;
private Button clearButton, saveButton;
/** , CirclePanel . */
public SavedFrameO {
super("SavedFrame");
setBackground(Color.white) ;
setFont(new Font("Serif", Font.BOLD, 18));
circlePanel = new CirclePanel();
add("Center", circlePanel);
Panel buttonPanel = new Panel();
buttonPanel.setBackground(Color.lightGray);
clearButton = new Button("Clear");
saveButton = new Button("Save");
buttonPanel.add(clearButton);
buttonPanel.add(saveButton);
add(buttonPanel, BorderLayout.SOUTH);
clearButton.addActionListener(this);
saveButton.addActionListener(this);
setSizeOOO, 300) ;
setVisible(true);
}
/** Clear
* Save
* (, , .)

V
public void actionPerformed(ActionEvent event) {
if (event.getSource() == clearButton) {
circlePanel.removeAll();
circlePanel.repaint();
} else if (event.getSource() == saveButton) {
try {
FileOutputStream fileOut =
new FileOutputStreamC'SavedFraiae. ser") ;
ObjectOutputStream out =
new ObjectOutputStream(fileOut);
out.writeObject(this);
out.flush();
out.close 0 ;
} catch(lOException ioe) {
System.out.println("Error saving frame: " + ioe);
}
}

485

486

13. AWT

13.14. CirclePanel. Java


import java.awt.*;
import Java.awt.event.*;
import java.io.*;
/** , ,
* .
* <> .</>.
public class CirclePanel extends Panel {
class ClickAdapter extends MouseAdapter
implements Serializable {
public void mouseClicked(MouseEvent event) {
BetterCircle circle = new BetterCircle(Color.black, 25)
add(circle);
circle.setCenter(event.getX(), event.getY());
invalidate();
validate();
}
}
public CirclePanel()
:)
{
setLayout(null);
addMouseListener(new ClickAdapter());
}

. 13.9.


Frame.

13.10. Dialog
D i a l o g Frame,
, Frame.
D i a l o g .
1. ,
AWT , .
,
, .

13.10. Dialog

487

2. Frame ( ,
). , Frame,
.
D i a l o g B o r d e r L a y o u t ,
: NORTH, SOUTH, EAST, WEST CENTER.
B o r d e r L a y o u t . 12.

Dialog
D i a l o g Frame, ,
: Frame
b o o l e a n , , .
Dialog d i a l o g =
new D i a l o g ( p a r e n t F r a m e ,
Dialog modalDialog =
new D i a l o g ( p a r e n t F r a m e ,

titleString,

false);

titleString,

true);

,
g e t Frame, .
,
, .

:

13.5 ,
, .
. Yes
. No ,
. 13.16
WINDOWDESTROY ,
. . 13.10.
1 3 . 1 5 . C o n f i r m . J a v a
import
import

java.awt.*;
Java.awt.event.*;

/ Yes No.
* Yes
* . No
* .

c l a s s Confirm e x t e n d s Dialog implements A c t i o n L i s t e n e r {


p r i v a t e Button yes, no;
p u b l i c Confirm(Frame p a r e n t )

488

13. AWT
super(parent, "Confirmation", true);
setLayout(new FlowLayout());
add(new Label("Really quit?"));
yes = new Button("Yes");
yes.addActionListener(this);
no = new Button("No");
no.addActionListener(this);
add(yes);
add(no);
packO ;
setVisible(true);

}
public void actionPerformed(ActionEvent event) {
if (event.getSource0 == yes) {
System.exit(0);
} else {
dispose 0 ;
}
}

13.16.ConfirmTest.Java
import java.awt.*;
import j ava.awt.event.*;
/** Frame, Confirm
*
* .
*/
public class ConfirmTest extends Frame {
public static void main(String[] args) {
new ConfirmTest();
}
public ConfirmTest0 {
super("Confirming QUIT");
setSize(200, 200);
addWindowListener(new ConfirmListener());
setVisible(true);
}
public ConfirmTest(String title) {
super(title);
}
private class ConfirmListener extends WindowAdapter {
public void windowClosing(WindowEvent event) {
new Confirm(ConfirmTest.this);
}
}

1 3 . 1 1 . FileDialog

489

)^;|^^^

6^yeiy)i^

||^||^^|

. 13.10.

13.11. FileDialog
F i l e D i a l o g ,
. F i l e D i a l o g
, .
F i l e D i a l o g ,
. .
F i l e D i a l o g .
// FileDialog.
FileDialog fileLoader =
new FileDialog(frame, title, FileDialog.LOAD);
FileDialog fileSaver =
new FileDialog(frame, title, FileDialog.SAVE);
// .
fileLoader.setFile("*.txt");
// FileDialog.
fileLoader.show();
// .
String filename = fileLoader.getFile();


TextArea
13.17 , Frame.
( TextArea),
(. 13.11).
F i l e D i a l o g , . 13.11,
. F i l e l n p u t S t r e a m
(. 13.12).
1 3 . 1 7 . D i s p l a y F i l e . J a v a

import j a v a . a w t . * ;
import J a v a . a w t . e v e n t . * ;
import j a v a . i o . * ;
/** F i l e D i a l o g . */
p u b l i c c l a s s D i s p l a y F i l e extends CloseableFrame

490

13. AWT
implements ActionListener {

public static void main(String[] args) {


new DisplayFile0;
}
private Button loadButton;
private TextArea fileArea;
private FileDialog loaderspublic DisplayFile() {
super("Using FileDialog");
loadButton = new Button("Display File");
loadButton.addActionListener(this);
Panel buttonPanel = new Panel();
buttonPanel.add(loadButton);
add(buttonPanel, BorderLayout.SOUTH);
fileArea = new TextArea();
add("Center", fileArea);
loader ~ new FileDialog(this, "Browse", FileDialog.LOAD)
// : .Java.
loader.setFile("*.Java");
setSize(350, 450);
setVisible(true);
/**
* .
* .

V
public void actionPerformed(ActionEvent event) {
loader.show();
di splay File (loader .getFileO ) ;
}
public void displayFile(String filename) {
try {
File file = new File(filename);
FilelnputStream in = new FilelnputStream(file);
int fileLength = (int)file.length();
byte[] fileContents = new byte[fileLength];
in.read(fileContents);
String fileContentsString = new String(fileContents)
fileArea.setText(fileContentsString);
} catch(lOException ioe) {
fileArea.setText("lOError: " + ioe);
}
}

13.12. Window

import Java awt*,


I m p rt J ava. awt. eve nt.*.
import Java.io.*;

1?||^|
LoQkiK

491

[* Uses a FileDialog to choose the file to display */

^ Awt

J!*] BetterScrolbai lava


j j l BgReporter lava
e] BuHonExampte lava
jej Button! e$(1|ava
.<i| ButtonTesl2.iava
Checkboxes. Java

aJColorMenujava
] ColofPopupMenu
Mj Confirm. Java
jgjContirmTest.iava

^ Choice? e$J lava


a j Ccte lava
^ CclePanel.|ava
;^CcleTe$t|ava
i ^ CircleTestZiava
^ CioseabieFrdme.iava

Fjtejoome:

JDisplayFile.iava

FiwoTj**.

JAHFilesf"")

public static void main(StringQ args) {


nev^^DisplayFileO;

iMj FgRepoitet java


private Button loadButton;
private TextArea fileArea;
private FileDialog loader;

b]

public class DisplayFile extends CloseableFrame


implements ActionListener{

Qpn

public DisplayFileO{
superfUsing FileDialog^;
loadButton = new ButtonCDisplay File"),
loadButton.addActionListener(this);
Panel buttonPanel = nev^ PaneiQ,
buttonPanel add(loadButton),
add(buttonPanel, BorderLayout SOUTH).

gj^e^^f^l

. 13.11. Frame
TextArea.
F i l e D i a l o g

1^:
[pteggFjgi
. 13.12.
,
TextArea

13.12. Window
Frame Window. Window
, ,
.

:
BorderLayout
: NORTH, SOUTH, EAST,
WEST CENTER. B o r d e r L a y o u t . 12.

Window
Window ,
,
, .
Window ,
:
// Window.
Window window = new Window(parentFrame);
// .
window.add(somePanel, BorderLayout.CENTER);
// ,

492

13. AWT

window.setSize(width, height);
// ,
size.setBounds(left, top, width, height);
// Window,
window.setVisible(true);

Window,
, .
// Window.
Window window = new Window(parentFrame);
// ( ).
window.setLocation(left, top);
// .
winddow.add(somePanel, BorderLayout.CENTER);
// ,
window.pack();
// Frame,
window.setVisible(true);

Window BorderLayout,
,
. window, add (someComponent),
CENTER.
add (someOtherComponent) CENTER .

13.13.

,
.
. , , Button
ActionEvent, Checkbox ItemEvent. 10,
.
.

.
addXJcxListener, : ,
. ,
.

.
;
e n a b l e E v e n t s AWTEvent.
ssXxxEvent,
, .

,
AWTEvent. , ActionEvent
Button, L i s t , Menultem T e x t F i e l d -

13.13.

493

A c t i o n L i s t e n e r p r o c e s s A c t i o n E v e n t . ,
, Checkbox, CheckboxMenuItem,
Choice L i s t I t e m L i s t e n e r p r o c e s s l t e m Event.
(KeyEvent) (TextEvent); K e y L i s t e n e r
T e x t L i s t e n e r processKeyEvent p r o c e s s T e x t E v e n t .
AdjustmentEvent,
A d j u s t m e n t L i s t e n e r p r o c e s s A d j u s t m e n t E v e n t .
MouseEvent KeyEvent,
Menultem CheckboxMenuItem.
.

.
ActionEvent.
.
. 13.13 Frame .
.
,
.

, 13.13. :



,
. ,
. .
, ,
, .
,
, A c t i o n Event. , A c t i o n L i s t e n e r , a c t i o n P e r f ormed, -

494

13. AWT

A c t i o n E v e n t . ,
, a d d A c t i o n L i s t e n e r .
A c t i o n E v e n t .
13.18 13.19 ,
. B u t t o n
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 ,
A c t i o n E v e n t , .
a d d A c t i o n L i s t e n e r ( t h i s )
.
. i n v a l i d a t e v a l i d a t e

. ,
i m p o r t j a v a . a w t . e v e n t . * ; ,
.
1 3 . 1 8 . A c t i o n E x a m p l e l , Java
import

java.awt.*;

public class ActionExamplel extends CloseableFrame {


public static void main(String[] args) {
new ActionExamplel();
}
public ActionExamplel() {
super("Handling Events in Component");
setLayout(new FlowLayout());
setFont(new Font("Serif", Font.BOLD, 18));
add(new SetSizeButton(300, 200)),
add(new SetSizeButton(400, 300))
add(new SetSizeButton(500, 400))
setSize(400, 300);
setVisible(true);
}

13.19.SetSizeButton.Java
import Java.awt.*;
import j ava.awt.event,*;
public class SetSizeButton extends Button
implements ActionListener
private int width, height;
private Container parent;
public SetSizeButton(int width, int height) {
super("Resize to " + width + "x" + height);
this.width = width;
this.height = height;

13.13.

495

parent = getParentO;
addActionListener(this)
p\iblic void actionPerformed (ActionEvent event) {
parent.setSize(width, height);
parent.invalidate();
parent.validate();
}


, ,
, A c t i o n L i s t e n e r . ,
,
, .
a c t i o n P e r f ormed
A c t i o n L i s t e n e r , ,
.
13.20 .
.
, ActionEvent,
t i o n P e r f o r m e d , .
,
, updateLayout,
.

( 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 ,
,
.
. 11.3.
13.20. ActionExample2 , java
import j a v a . a w t . * ;
import j a v a . a w t . e v e n t . * ;
p u b l i c c l a s s ActionExample2 extends CloseableFrame
implements ActionListener {
p u b l i c s t a t i c void m a i n ( S t r i n g [ ] args) {
new ActionExample2();
}

p r i v a t e Button b u t t o n l , b u t t o n 2 , b u t t o n S ;
p u b l i c ActionExample2() {
super("Handling Events in Other O b j e c t " ) ;

496

13. AWT
setLayout(new FlowLayout());
setFont(new Font("Serif", Font.BOLD, 18))
buttonl = new Button("Resize to 300x200")
button2 = new Button("Resize to 400x300")
button3 = new Button("Resize to 500x400")
buttonl.addActionListener(this) ;
button2.addActionListener(this);
button3.addActionListener(this);
add(buttonl);
add(button2);
add(button3);
setSize(400, 300);
setvisible(true);

}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == buttonl) {
updateLayout(300, 200);
} else if (event.getSource0 == button2) {
updateLayout(400, 300);
} else if (event.getSource0 == button3) {
updateLayout(500, 400);
}
}
private void updateLayout(int width, int height) {
setSize(width, height);
invalidate();
validate();
}

13.14. Button
Button ,
. Java ,
.
(), , ,
.
, :
Button button = new Button("...");
add(button);

Button .
public ButtonO
public Button(String buttonLabel)
. ()
, s e t L a b e l .

13.14. Button

497

, ,
p r e f e r r e d S i z e , ,
. .
, p r e f e r r e d S i z e (
),
, ;
, .


13.21 , .
,
Button. add (new
Button ( . . . ) ) . ,
. . 13.14
, 13.21, Netscape 4.7,
Windows 98.
13.21. Buttons. Java
import j a v a . a p p l e t . A p p l e t ;
import j a v a . a w t . * ;
p u b l i c c l a s s Buttons extends Applet {
p r i v a t e Button b u t t o n l , b u t t o n 2 , b u t t o n s ;
p u b l i c void i n i t O {
b u t t o n l = new Button("Button One");
button2 = new Button("Button Two");
b u t t o n s = new Button("Button T h r e e " ) ;
add(buttonl);
add(button2) ;
add(buttons) ;
}

^
' ^ ^ a 5} ^, -1. iT :!i
di
Buttons
pOn

BietonTwo

Button Thfj

. 13.14. ,
Java- Windows 98

498

13. AWT

Button
B u t t o n .
public String getLabel()
g e t L a b e l ,
.
public v o i d setLabel(String newLabel)
s e t L a b e l .
, .
,
i n v a l i d a t e v a l i d a t e .
.
s o m e B u t t o n . s e t L a b e l ( " New L a b e l " ) ;
someButton.getParent().invalidate();
someButton.getParent().validate();
public v o i d addActionListener(ActionListener listener)
public void r e m o v e 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 listener)
a d d A c t i o n L i s t e n e r , a r e m o v e A c t i o n L i s t e n e r
, A c t i o n E v e n t .
.
public void processActionEvent(ActionEvent event)

, .

e n a b l e E v e n t s . , p r o c e s s A c t i o n E v e n t ,
s u p e r . p r o c e s s A c t i o n E v e n t .
.
, B u t t o n , ,
getForeground, setForeground, getBackground, setBackground,
getFont,
s e t F o n t Component.


, Java ,
, .
<Enter> ,
.
, , ,
. B u t t o n
, A c t i o n E v e n t :
enableEvents(AWTEvent.ACTION EVENT MASK);

13.14. Button

499

p r o c e s s A c t i o n E v e n t ,
.
super . p r o c e s s A c t i o n E v e n t ,
, . ,
. p r o c e s s A c t i o n E v e n t
13.19.
p u b l i c void processActionEvent(ActionEvent event) {
takeSomeAction(...);
s u p e r . p r o c e s s A c t i o n E v e n t ( e v e n t ) ; / / .
}

Button,
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 d d A c t i o n L i s t e n e r . actionPerformed,
, , .
13.20 A c t i o n L i s t e n e r ,
. , 13.22
, A c t i o n L i s t e n e r .
FgReporter ( 13.23),
FgReporter BgReporter ( 13.24), FgReporter, BgReporter
S i z e R e p o r t e r ( 13.25).
A c t i o n L i s t e n e r ,
. . 13.15,
, , 13.26.
13.22. ButtonExample. Java
import j a v a . a w t . * ;
import J a v a . a w t . e v e n t . * ;
p u b l i c c l a s s ButtonExample extends CloseableFrame {
p u b l i c s t a t i c void m a i n ( S t r i n g [ ] args) {
new ButtonExample();
}

p u b l i c ButtonExample() {
super("Using A c t i o n L i s t e n e r s " ) ;
setLayout(new FlowLayout());
Button bl = new Button("Button 1")
Button b2 = new Button("Button 2")
Button b3 = new Button("Button 3")
bl.setBackground(Color.lightGray);
b2.setBackground(Color.gray);
b3.setBackground(Color.darkGray) ;
FgReporter fgReporter = new F g R e p o r t e r ( ) ;
BgReporter bgReporter = new BgReporter();
SizeReporter s i z e R e p o r t e r = new S i z e R e p o r t e r ( ) ;
bl.addActionListener(fgReporter);
b2.addActionListener(fgReporter);
b2.addActionListener(bgReporter);

500

13. AWT

.addActionListener(fgReporter);
.addActionListener(bgReporter);
.addActionListener(sizeReporter)
add(bl)
add(b2)
add(b3)
setSize(350, 100) ;
setVisible(true);

13.23. FgReporter. Java


import Java.awt.event.*;
import java.awt.*;
public class FgReporter implements ActionListener {
public void actionPerformed(ActionEvent event) {
Component = (Component)event.getSource();
System, out. println( "Foreground: " -f c.getForeground () ) ;
}
}

13.24. BgReporter. Java


import java.awt.event.*;
import java.awt.*;
public class BgReporter implements ActionListener {
public void actionPerformed(ActionEvent event) {
Component = (Component)event.getSource();
System.out.println("Background: " + c.getBackground());
}
}

13.25.SizeReporter.Java
import Java.awt.event.*;
impo rt j ava.awt.*;
public class SizeReporter implements ActionListener {
public void actionPerformed(ActionEvent event) {
Component = (Component)event.getSource();
Dimension d = c.getSizeO;
System.out.println("Size: " + d.width + "x" + d.height);
}
}

13.15. Checkbox

501

. 13.15.

ActionListener
13.26. ButtonExample
Button 1, Button 2 Button 3 (
)
Foreground: J a v a . a w t . C o l o r [ r = 0 , g = 0 , b = 0 ]
Foreground: j a v a . a w t . C o l o r [ r = 0 , g = 0 , b = 0 ]
Background: j a v a . a w t . C o l o r [ r = 1 2 8,g=12 8,b=12 8]
Foreground: j a v a . a w t . C o l o r [ r = 0 , g = 0 , b = 0 ]
Background: J a v a . a w t . C o l o r [ r = 6 4 , g = 6 4 , b = 6 4 ]
S i z e : 59x23
AWT , ,
I m a g e B u t t o n C a n v a s .
I m a g e B u t t o n h t t p : //www. c o r e w e b p r o g r a m m i n g . com/.

13.15. Checkbox
,
. ,
,
(
). ,
( ) Checkbox
.
I t e m S e l e c t i o n E v e n t , ,
, g e t S t a t e . ,
, .
Checkbox cb = new C h e c k b o x ( " . . . " ) ;
somePanel.add(cb);

,
. ,
, .
public CheckboxO
public Checkbox(String checkboxLabel)
public Checkbox(String c h e c k b o x L a b e l , b o o l e a n state)

( ). .

502

13. AWT

Checkbox .
. ,
s e t S t a t e .
. t r u e , ,
f a l s e .


13.27 ,
. .
Windows 98 . 13.16.
13-27. Checkboxes. java

import j a v a . a w t . * ;
public class Checkboxes extends CloseableFrame
public static void main(String[] args) {
new Checkboxes();
}
public Checkboxes 0 {
super("Checkboxes");
setFont(new Font("SansSerif", Font.BOLD, 1 )) ,
setLayout(new GridLayout(0, 2));
Checkbox box;
for(int i=0; i<12; i++) {
box = new Checkbox("Checkbox " + i ) ;
if (i%2 == 0) {
box.setState(true);
}
add(box);
}
packO ;
setVisible(true);

' "'|i"ii 1 |i

F Checkbox p: Checkbox 1
F Checkbox 2 Checkbox 3
F Checkbox 4 Checkbox 5
F Checkbox 6 Checkbox 7
F Checkbox 8 Checkbox 9
F Checkbox 10 Checkbox 11

. 13.16.
Java-

Windows 98

13.15. Checkbox

503

Checkbox
C h e c k b o x .
p u b l i c b o o l e a n getState()
public void setState(boolean checkedState)
g e t S t a t e .
t r u e . f a l s e
. s e t S t a t e .
public String getLabel()
public void setLabel(String newLabel)
g e t L a b e l
, s e t L a b e l .
,
.
i n v a l i d a t e v a l i d a t e ,
.

(),
,

,

s o m e C h e c k b o x . s e t L a b e l ( " New L a b e l " ) ;


someCheckbox.getParent().invalidate();
someCheckbox.getParent().validate();
public v o i d a d d I t e m L i s t e n e r ( I t e m L i s t e n e r listener)
p u b l i c v o i d r e m o v e I t e m L i s t e n e r ( I t e m L i s t e n e r listener)
a d d l t e m L i s t e n e r I t e m L i s t e n e r ,
r e m o v e I t e m L i s t e n e r .
.
public v o i d p r o c e s s I t e m E v e n t ( I t e m E v e n t event)
.
p r o c e s s I t e m E v e n t , >
s u p e r . p r o c e s s I t e m E v e n t .
public Object[ ] g e t S e l e c t e d O b j e c t s O
, .
( ), n u l l (
).
, C h e c k b o x
Component.

Checkbox
C h e c k b o x A c t i o n E v e n t ,
I t e m S e l e c t i o n E v e n t .
, .

504

13. AWT

enableEvents(AWTEvent.ITEM EVENT MASK);


p r o c e s s I t e m E v e n t ,
I t e m E v e n t .
I t e m L i s t e n e r , p r o c e s s I t e m E v e n t s u p e r ,
p r o c e s s I t e m E v e n t . , AWTEvent,
I t e m E v e n t : g e t l t e m S e l e c t a b l e g e t S t a t e C h a n g e .
g e t l t e m S e l e c t a b l e I t e m S e l e c t a b l e
( I t e m S e l e c t a b l e C h e c k b o x ) . g e t S t a t e C h a n g e
ItemEvent.SELECTED, ItemEvent.DESELECTED.
,
a d d l t e m L i s t e n e r I t e m L i s t e n e r .
I t e m L i s t e n e r i t e m S t a t e C h a n g e d ,
I t e m E v e n t .

13.16.
C h e c k b o x C h e c k b o x G r o u p ,
,
. ;
.
.
HTML- ( 1), ,
, .

, P a n e l . ,
C h e c k b o x G r o u p ,
C h e c k b o x , . C h e c k b o x
, . ,
, .
CheckboxGroup cbGroup = new C h e c k b o x G r o u p ( ) ;
Checkbox c b l = new C h e c k b o x ( " . . . " , c b G r o u p , t r u e ) ;
add(cbl);
Checkbox cb2 = new C h e c k b o x ( " . . . " , c b G r o u p , f a l s e ) ;
add(cb2);

C h e c k b o x G r o u p C h e c k b o x .

CheckboxGroup
public CheckboxGroupO
C h e c k b o x G r o u p ,
, C h e c k b o x .
C h e c k b o x , C h e c k b o x G r o u p ,
.
.

13.16.

505

Checkbox
public Checkbox(String label, CheckboxGroup group, boolean state)
public Checkbox(String label, boolean state, CheckboxGroup group)
,
. s t a t e
. s t a t e
t r u e ,
. , ,
.

13.28 ,
Checkbox,
CheckboxGroup. ,
. . 13.17
Windows 98.

13.28.CheckboxGroups.Java
import java.applet.Applet;
import j ava.awt.*;
public class CheckboxGroups extends Applet {
public void initO {
setLayout(new GridLayout(4, 2));
setBackground(Color.lightGray);
setFont(new Font("Serif", Font.BOLD, 16));
add(new Label("Flavor", Label.CENTER));
add(new Label("Toppings", Label.CENTER));
CheckboxGroup flavorGroup = new CheckboxGroup();
add(new Checkbox("Vanilla", flavorGroup, true));
add(new Checkbox("Colored Sprinkles"));
add(new Checkbox("Chocolate", flavorGroup, false))
add(new Checkbox("Cashews"));
add(new Checkbox("Strawberry", flavorGroup, false)
add(new Checkbox("Kiwi"));
}
}

506

13. AWT

i ^ A p p l e t Viet: Checkboxfitaupt.oias

:::^:':&

Apptet

tm^

Flavor

F|Coioreassbidej|
^

Giocolate

Strawbeny

^^^:
.- -

FCasbews

Applet started.

. 13.17. ()
(),
Windows 98

CheckboxGroup Checkbox
CheckboxGroup
public Checkbox getSelectedCheckbox()
g e t S e l e c t e d C h e c k b o x
(Checkbox). ,
n u l l .
public void setSelectedCheckbox(Checkbox boxToSelect)
.
, , .
n u l l ,
.

Checkbox
, , Checkbox
, , .
public CheckboxGroup getCheckboxGroupO
g e t CheckboxGroup ,
.
public void setCheckboxGroup(CheckboxGroup newGroup)
.

CheckboxGroup
Checkbox
, .
.

g e t S t a t e .
g e t S t a t e ,
. g e t S e l e c t e d C h e c k b o x Check
boxGroup, Checkbox.

13.17. Choice

507

13.17. Choice
C h o i c e .
.
, .
, C h o i c e .
.
, .
C h o i c e ,
.
Choice choice = new Choice();
choice.addltem("...");
choice.addltem("...");
somePanel.add(choice) ;

icTiacce C h o i c e ,
.
public Choice()
.
a d d .


13.29 , Choice,
. Windows 98
. 13.18.
13.29.ChoiSt.Java
import java.applet.Applet;
import java.awt.*;
public class ChoiceTest extends Applet {
private Choice choice;
public void init{) {
setFont(new Font("SansSerif", Font.BOLD, 36))
choice = new Choice();
choice.addltem("Choice 1")
choice.addltem("Choice 2")
choice.addltem("Choice 3")
add(choice);
}

508

13. AWT

[Choice 1
IChoice 2
Ichoice 3

1
1

j
1

i Applet started.

. 13.18. c h o i c e Windows 98:


- - ;

Choice
Choice, .
public void addItem(String menultem)
public void add(String menultem)
.
. addltem add
. , ,
, ,
s e l e c t . remove
removeAll.
public void addItemLListener(ItemListener listener)
public void removeItemListener(ItemListener listener)
a d d l t e m L i s t e n e r I t e m L i s t e n e r ,
remove I t e m L i s t e n e .
public int getItemCount()
, Choice.
public String getltem(int itemlndex)
g e t I tern .
public int getSelectedlndexO
.
, -1.
public String getSelectedltemO
.

13.17. Choice

509

public Object[ ] getSelectedObjectsO


g e t S e l e c t e d O b j e c t s ,
. , n u l l .
public void insert(String menultem, int itemlndex)
i n s e r t .
add addltem, .
public void processItemEvent(Itemvent event)
, Choice
, p r o c e s s I t e m E v e n t .
public void remove(String menultem)
public void remove(int itemlndex)
public void removeAll()
.
public void select(int itemlndex)
public void select(String itemLabel)
.
, Java . s e l e c t ( S t r i n g
itemLabel) ,
. , .
, , , ,
, Component.

, Choice
, Choice,
Checkbox: p r o c e s s ItemEvent
a d d l t e m L i s t e n e r .
, ,
. ,
, , ,
. 13.30
ChoiceTest.
. ,
,
g e t S e l e c t e d i t e m g e t S e l e c t e d l n d e x .
13.30.ChoiceTest2.Java

import J a v a . a p p l e t . A p p l e t ;
import j a v a . a w t . * ;

510

13. AWT

import Java.awt.event.*;
public class ChoiceTest2 extends Applet
implements ItemListener {
private Choice choice;
public void initO {
setFont(new Font("SansSerif", Font.BOLD, 36));
choice = new Choice();
choice.addltem("Choice 1");
choice.addltem("Choice 2 " ) ;
choice.addltem("Choice 3");
choice.addltemListener(this);
add(choice);
}
public void itemStateChanged(ItemEvent event) {
Choice choice = (Choice)event.getSource();
String selection = choice.getSelectedltem();
if (selection.equals("Choice 1")) {
doChoicelAction();
} else if (selection.equals("Choice 2")) {
doChoice2Action();
} else if (selection.equals("Choice 3")) {
doChoice3Action();
}
private void doChoicelAction() {
System.out.println("Choice 1 Action");
private void doChoice2Action() {
System.out.println("Choice 2 Action");
}
private void doChoice3Action() {
System.out.println("Choice 3 Action");

13.18. List
( L i s t ) ,
.
Choice, : ,
.
L i s t l i s t = new L i s t ( ) ;
list.addltem("...");
list.addltem("...");
add(list);

13.18. List

511

L i s t .
public List()
public List(int rows)
public List(int rows, b o o l e a n multiSelectable)
,
. .
. ,
.
,
. ,
.
, . ,
.
C h o i c e , L i s t ;
a d d l t e m add. ,
, .
(
).

List
13.31 , L i s t .
,
. Windows 98
. 13.19.
1 3 . 3 1 . L i s t s . J a v a
import

java.awt.*;

public class Lists extends CloseableFrame {


public static void main(String[] args) {
new Lists();
public Lists() {
super("Lists");
setLayout(new FlowLayout());
setBackground(Color.lightGray);
setFont(new Font("SansSerif", Font.BOLD, 18));
List listl = new List(3, false);
listl.add("Vanilla") ;
listl.add("Chocolate");
listl.add("Strawberry");
add(listl);

512

13. AWT

List list2 s new List(3, true);


list2.add("Colored Sprinkles");
list2.add("Cashews");
list2.add("Kiwi");
add(list2);
packO;
setVisible(true);

Vanilla
ichocolate

Colored Sprinklesg
Cashews

. 13.19. ,
Windows 98

List
28 , ,
L i s t .

public v o i d add(String itemLabel)


public v o i d add(String itemLabel, int i t e m l n d e x )

. ;
, , .
public v o i d addActionListener(ActionListener listener)
public v o i d a d d I t e m L i s t e n e r ( I t e m L i s t e n e r listener)
public v o i d r e m o v e 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 listener)
public v o i d r e m o v e I t e m L i s t e n e r ( I t e m L i s t e n e r listener)
A c t i o n L i s t e n e r I t e m L i s t e n e r . I t e m E v e n t
. A c t i o n E v e n t ,
<Enter>,
. L i s t ,
.
public b o o l e a n isMultipleMode()
, ( f a l s e )
( t r u e ) .
public void removeAllO
.
public int g e t l t e m C o u n t O
g e t l t e m C o u n t .

13.18. List

513

public void remove(String m e n u l t e m )


public void remove(int i t e m l n d e x )
.
public void d e s e l e c t ( i n t i t e m l n d e x )
, , , d e s e l e c t
. , .
public String g e t l t e m ( i n t i t e m l n d e x )
public String[] g e t l t e m s O
,
.
.
public int getRowsO
,
.
g e t l t e m C o u n t , ,
. ,
.
public int g e t S e l e c t e d l n d e x O
public int[] g e t S e l e c t e d I n d e x e s ( )
, ,
.
, -1.
.
, ( n u l l ) .
public String g e t S e l e c t e d l t e m O
public String[ ] g e t S e l e c t e d I t e m s ( )
, ,
, .
,
n u l l .
. ,
, ,
. , (
n u l l ) .
public Object[ ] g e t S e l e c t e d O b j e c t s ( )
g e t S e l e c t e d O b j e c t s ,
. , n u l l .

514

13. AWT

public int getVisiblelndexO


,
m a k e V i s i b l e . m a k e V i s i b l e ,
.
public boolean isIndexSelected(int itemlndex)
, ,
.
public void makeVisible(int itemlndex)
m a k e V i s i b l e , ,
, .
public void processItemEvent(ItemEvent event)
public void processActionEvent(ActionEvent event)
, L i s t
, .
ItemEvent . ActionEvent

<Enter> , .
public void replaceItem(String newItemLabel, int itemlndex)
, .
public void select(int itemlndex)
, .
,
. Choice, L i s t
s e l e c t , .
public void setMultipleMode(boolean multipleSelectable)
setMultipleMode ( t r u e ) ( f a l s e )
.
L i s t Component,
.

List
L i s t , .
I t e m S e l e c t i o n E v e n t
. , s e l e c t
. ActionEvent
L i s t , .
,

13.18. List

515

<Enter>. L i s t
, ,
.
, L i s t
, , AWTEvent. ITEM_EVENT_MASK
AWTEvent. ACTION_EVENT_MASK, p r o c e s s l t e m E v e n t p r o c e s s A c t i o n E v e n t .
; .
I t e m L i s t e n e r a d d l t e m L i s t e n e r ,
A c t i o n L i s t e n e r a d d A c t i o n L i s t e n e r .
13.32.
, 13.33 (
I t e m L i s t e n e r ) 13.34 ( A c t i o n L i s t e n e r ) . . 13.20.
1 3 . 3 2 . L i s t E v e n t s . J a v a
import
import

java.awt.*;
Java.awt.event.*;

/** ,
* ,
* ActionEvent.

public class ListEvents extends CloseableFrame {


public static void main(String[] args) {
new ListEvents();
protected List languageList;
private TextField selectionField, actionField;
private String selection = "[NONE]", action;
/**
*
*
*

Frame,
.
,
- .

V
public ListEvents {
super("List Events");
setFont(new Font("Serif", Font.BOLD, 16));
add(makeLanguagePanel(), BorderLayout.WEST);
add(makeReportPanel(), BorderLayout.CENTER);
packO ;
setVisible(true);
// , List.
//
// Frame.
private Panel makeLanguagePanel() {

516

13. AWT

Panel languagePanel = new Panel();


languagePanel.setLayout(new BorderLayout());
languagePanel.add(new Label("Choose Language"),
BorderLayout.NORTH);
languageList = new List(3);
String[] languages =
{ "Ada", "C", "C++", "Common Lisp", "Eiffel",
"Forth", "Fortran", "Java", "Pascal",
"Perl", "Scheme", "Smalltalk" };
for(int i=0; Klanguages. length; i++) {
languageList.add(languages[i]);
}
showJava();
languagePanel.add("Center", languageList);
return(languagePanel);
}
//
//
//
//
//
//

Label
.
,
.
.
Panel Frame.

private Panel makeReportPanel() {


Panel reportPanel = new Panel();
reportPanel.setLayout(new GridLayout(4, 1));
reportPanel.add(new Label("Last Selection:"));
selectionField = new TextFieldO;
SelectionReporter selectionReporter =
new SelectionReporter(selectionField);
languageList.addltemListener(selectionReporter);
reportPanel.add(selectionField);
reportPanel.add(new Label("Last Action:"));
actionField = new TextFieldO;
ActionReporter actionReporter =
new ActionReporter(actionField);
languageList.addActionListener(actionReporter);
reportPanel.add(actionField);
return(reportPanel);
}
/** "Java". */
protected void showJava() {
languageList.select (7);
languageList.makeVisible(7);
}
}

13.33.SelectionReporter.Java
import java.awt.^;
import Java.awt.event.

13.18. List

517

/** ,
* SelectiorxReporter.
public class SelectlonReporter implements ItemListener {
private TextField selectionField;
public SelectionReporter(TextField selectionField) {
this.selectionField = selectionField;
}
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == event.SELECTED) {
List source = (List)event.getSource();
selectionField.setText(source.getSelectedItem());
} else
selectionField.setText("");
}

13.34. ActionReporter. Java


import j ava.awt.*;
import Java.awt.event.^;
f-k-k ,
^ ActionReporter.
public class ActionReporter implements ActionListener
private TextField actionField;
public ActionReporter(TextField actionField) {
this.actionField = actionField;
}
public void actionPerformed(ActionEvent event) {
List source = (List)event.getSource();
actionField.setText(source.getSelectedltem());
}

^List Event
Choose Language

Last Selection:
J Java

Pascal
Perl
Scheme

Last Action:
^Pascal

. 13.20.
"Pascal" "Java"

518

13. AWT

List , ,
. 13.35 ,
"Java" (
) "Java". ,
.
KeyAdapter . , ,
show Java Li stE vents,
protected.
13.35.ListEvents2.Java
import Java.awt.event.*;
public class ListEvents2 extends ListEvents {
public static void main(String[J-args) {
new ListEvents2();
}
/** ListEvents.
* , "JAVA" "Java",
* "Java".
public ListEvents2 () {
super ();
// KeyAdapter languageList.
// ,
// ,
// showJava ListEvent.
KeyAdapter javaChooser = new KeyAdapter() {
public void keyPressed(KeyEvent event) {
int key = event.getKeyChar0;
if ("JAVAjava".indexOf(key) != -1) {
showJava{);

languageList.addKeyListener(javaChooser)
}
}

13.19. TextField
T e x t F i e l d ,
.
TextArea, .
T e x t F i e l d ,
.

13.19. TextField

519

TextField lastNameField = new TextField(15) ;


add(lastNameField);
TextField langField = new TextField("Java");
add(langField);
TextField ,
, set Editable.
.
TextField temperatureField = new TextField(4);
temperatureField.setEditable(false);
statusPanel.add(temperatureField) ;
temperatureString = simulationTemperature("F");
temperatureField.setText(temperatureString);

T e x t F i e l d .
p u b l i c TextFieldO
public TextField(int numChars)
p u b l i c TextField(String initialString)
public TextField(String initialString, int numChars)
,
(
). ,
. ,

,
. ,
. ,
. ,
.
, .


13.36 , ,
.
. 13.21.
1 3 . 3 6 . t F i e l d s . J a v a
import
import

Java.applet.Applet;
java.awt.*;

/** T e x t F i e l d ,
*/

520

13. AWT

public class TextFields extends Applet {


public void init() {
add(new TextField());
add(new TextField(30));
add(new TextField("Initial String"));
add(new TextField("Initial", 30));
}
}
^iQjjdj
Apptet

1
Initial String
; j Initial
Applet started.

. 13.21. T e x t F i e l d ,

TextField
T e x t F i e l d T e x t C o m p o n e n t .
. g e t T e x t s e t T e x t
( T e x t F i e l d ) , s e t E d i t a b l e (
), g e t C o l u m n s s e t C o l u m n s (
T e x t F i e l d ) s e t E c h o C h a r ( "*"
; ).

TextComponent
p u b l i c v o i d a d d T e x t L i s t e n e r ( T e x t L i s t e n e r listener)
public v o i d r e m o v e T e x t L i s t e n e r ( T e x t L i s t e n e r listener)
a d d T e x t L i s t e n e r T e x t L i s t e n e r ,
r e m o v e T e x t L i s t e n e r . , Component,
, a d d K e y L i s t e n e r
r e m o v e K e y L i s t e n e r ,
, .
T e x t L i s t e n e r t e x t V a l u e C h a n g e d .
T e x t E v e n t .
, , g e t S o u r c e , .
T e x t C o m p o n e n t , g e t T e x t .
public int getCaretPosition()
public v o i d setCaretPosition(int i n d e x )

, .

13.19. TextField

521

public String getSelectedTextO


. ,
( n u l l ) .
public int getSelectionEnd()
public void setSelectionEnd(int startlndex)
g e t S e l e c t i o n E n d ,
. ,
' . s e t S e l e c t i o n E n d
.
public int getSelectionStart()
public void setSelectionStart(int endlndex)
g e t S e l e c t i o n S t a r t
. , .
s e t S e l e c t i o n S t a r t .
public String getTextO
public void setText(String newText)
g e t T e x t , .
, ( n u l l ) .
s e t T e x t , ,
. n u l l , " ".
public boolean isEditable()
public void setEditable(boolean editableStatus)
i s E d i t a b l e , ( t r u e )
( f a l s e ) . s e t E d i t a b l e ( t r u e )
( f a l s e ) .
public void processTextEvent(TextEvent event)
, s s TextEvent .
, , TextComponent )'
Component processKeyEvent. ,
, j ava . awt. e v e n t (import j ava . awt.
e v e n t . * ;) s u p e r . p r o c e s s T e x t E v e n t .
public void select(int startlndex, int endlndex)
, s t a r t l n d e x
, endlndex.
.
endlndex , ,
.

522

13. AWT

public void selectAll()


.

TextField
T e x t C o m p o n e n t T e x t F i e l d
.
public v o i d addActionListener(ActionListener listener)
public void r e m o v e 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 listener)
A c t i o n E v e n t ,
<Return> , T e x t F i e l d .
a d d A c t i o n L i s t e n e r ,
r e m o v e A c t i o n L i s t e n e r . ,
a d d T e x t L i s t e n e r r e m o v e T e x t L i s t e n e r (
T e x t C o m p o n e n t ) , a d d K e y L i s t e n e r r e m o v e K e y L i s t e n e r ( Component) .
public b o o l e a n echoCharIsSet()
, - (.
s e t E c h o C h a r ) .
public int getColumnsO
.
, ,
.
, .
public char getEchoChar()
public void setEchoChar(char echoChar)
g e t E c h o C h a r -.
, e c h o C h a r I s S e t t r u e .
s e t E c h o C h a r - ,
. )^'
g e t T e x t . -
"*".
public void processActionEvent(ActionEvent event)
A c t i o n E v e n t
<Enter> . ,
T e x t F i e l d ,
, AWTE v e n t .ACT ION_EVENT_MASK,
p r o c e s s A c t i o n E v e n t . ,
s u p e r . p r o c e s s A c t i o n
E v e n t (. a d d A c t i o n L i s t e n e r ) .

13.20. TextArea

523

public void s e t C o l u m n s ( i n t cols)


s e t C o l u m n s
T e x t F i e I d . ,
, .
T e x t F i e l d Component,
.

,
TextField
T e x t F i e l d
: , , \,
A c t i o n E v e n t . , ,
, . ,
, ,
, .
A c t i o n E v e n t , <Enter>
.
,
s e t T e x t ; . ,

T e x t F i e l d , p r o c e s s X x x E v e n t . ,
.
11.6.

13.20. TextArea
T e x t A r e a T e x t F i e l d , ,

A c t i o n E v e n t . , , .
T e x t A r e a i n p u t A r e a = new T e x t A r e a ( 4 , 1 5 ) ;
add(inputArea);
T e x t A r e a r e s u l t s A r e a = new T e x t A r e a ( " N o R e s u l t s Y e t " ,
resultsArea.setEditable(false) ;
add(resultsArea);

2,

10);

, T e x t A r e a ,
.
public TextAreaO
,
. one-

524

13. AWT

. ,
, .
public TextArea(int rows, int cols)

.
, . T e x t A r e a
.
p u b l i c TextArea(String initialString)
,

. , ,
( \ ) .
public TextArea(String initialString, int rows, int cols)

, .
.
public TextArea(String initialString, int rows, int c o l s , int scrollbar Type)

. s c r o l l b a r T y p e T e x t A r e a .
SCROLLBARS BOTH, ) 1,
. T e x t A r e a . SCROLLBARS_VERTICAL_ONLY,
.
, . T e x t A r e a .
SCROLLBARS_HORIZONTAL_ONLY !
. l i , , T e x t A r e a . SCROLLBARS_NEITHER
, .
.


13.37 , :
, .
Windows 98 . 13.22.
1 3 . 3 7 . T e x t A r e a s . J a v a
import
import

Java.applet.Applet;
java.awt.*;

p u b l i c c l a s s TextAreas extends Applet


public void i n i t ( ) {
setBackground(Color.lightGray);

13.20. TextArea

525

add(new TextArea(3, 10));


add(new TextArea("Some\nInitial\nText", 3, 10)

iiiiiiiifc'.'.'''jM^f
Apptel

Some
Initial
Text
i

J
Applet started

. 13.22, ,
Windows 98

TextArea
( T e x t C o m p o n e n t ) g e t T e x t ,
s e t T e x t , s e t E d i t a b l e , s e l e c t . , T e x t A r e a
, .
public void a p p e n d ( S t r i n g additionalText)
,
.
public int getColumns()
g e t C o l u m n s .
public int getRows()
g e t R o w s .
public void insert(String additionalText, int i n d e x )
,
. , ,
.
public void r e p l a c e R a n g e ( S t r i n g r e p l a c e m e n t , int s t a r t l n d e x , int e n d l n d e x )
r e p l a c e R a n g e ,
s t a r t l n d e x e n d l n d e x . ,
, .
, T e x t A r e a
Component.

526

13. AWT

TextArea
,
, , .
T e x t A r e a A c t i o n E v e n t .

1 3 . 2 1 . Label
L a b e l .
L a b e l ,
d r a w s t r i n g G r a p h i c s , , L a b e l ,
.
L a b e l , .
Label label = new Label("...");
add(label);
, L a b e l ,
.
F l o w L a y o u t ,
. L a b e l
. , L a b e l
.
P a n e l r e s u l t s P a n e l = new P a n e l ( ) ;
resultsPanel.setLayout(new BorderLayout());
L a b e l t i t l e = new L a b e l ( " R e s u l t s " , Label.CENTER);
t i t l e . s e t F o n t ( n e w F o n t ( " S a n s S e r i f " , Font.BOLD, 1 8 ) ) ;
r e s u l t s P a n e l . a d d ( t i t l e , BorderLayout.NORTH);
T e x t A r e a r e s u l t s A r e a = new T e x t A r e a ( ) ;
r e s u l t s P a n e l . a d d ( r e s u l t s A r e a , BorderLayout.CENTER);

L a b e l .
public Label()
public Label(String labelString)
public Label(String labelString, int alignment)
L a b e l .
, s e t T e x t .
, .
. a l i g n m e n t L a b e l . LEFT
( ), L a b e l . RIGHT L a b e l .CENTER. L a b e l
, F l o w L a y o u t ,
E a s t West B o r d e r L a y o u t ,

1 3 . 2 1 . Label

527

.
. L a b e l
NORTH SOUTH B o r d e r L a y o u t ,
G r i d L a y o u t G r i d B a g L a y o u t ,
.
, .

Label
13.38 Label,
. . 13.23.
13.38.Labels.Java
import Java.applet.Applet;
import java.awt.*;
public class Labels extends Applet {
public void initO {
setLayout(new GridLayout(4,1));
Label labell, label2, labelS, label4;
labell = new Label("Label 1");
label2 = new Label("Label 2", Label.LEFT);
label3 = new Label("Label 3", Label.RIGHT);
label4 = new Label("Label 4", Label.CENTER);
Font bigFont -= new Font ("Sanserif", Font.BOLD, 25);
label2.setFont(bigFont);
labels.setFont(bigFont);
label4.setFont(bigFont);

add(labell)
add(label2)
adddabelS)
add(label4) ,

r^LWHIiMMi'." -^
Applet
Label

Label 2
Label 3
Label 4
|
Applet started

. 13.23. Label

Label
L a b e l . ,
, .

528

13. AWT

public int getAlignment()


public v o i d setAlignment(int alignment)
.
L a b e l . LEFT, L a b e l .RIGHT L a b e l .CENTER.
.
public String getText()
public void setText(String newLabel)
g e t T e x t , L a b e l .
L a b e l ( n u l l ) .
s e t T e x t , L a b e l .
, .
,
invalidate validate.
someLabel.setText(" Different Label");
someLabel.getParent{).invalidate();
someLabel.getParent().validate();
C o m p o n e n t , L a b e l ,
, .

Label
L a b e l , ,
A c t i o n E v e n t . 13.39
, R e v e r s i b l e L a b e l
( 13.40). R e v e r s i b l e L a b e l ;
)^ , ,
. ,
. . 13.24
, . 13.25
R e v e r s i b l e L a b e l .
1 3 , 3 9 . R e v e r s e L a b e l s . J a v a
import

java.awt.*;

public class ReverseLabels extends ClcseableFrame {


public static void main(String[] args) {
new ReverseLabels();
public ReverseLabels () {
super("Reversible Labels");
setLayout(new FlowLayout());
setBackground(Color.lightGray);
setFont(new Font("Serif", Font.BOLD, 18))
ReversibleLabel labell =

13.21. Label

new ReversibleLabel("Black on White",


Color.white, Color.black);
add(labell);
ReversibleLabel label2 =
new ReversibleLabel("White on Black",
Color.black, Color.white);
add(label2);
packO ;
setVisible(true);

13.40.ReversibleLabel.Java
import java.awt.*;
import Java.awt.event.*;
/** Label,
* .

public class ReversibleLabel extends Label {


public ReversibleLabel(String text,
Color bgColor, Color fgColor) {
super(text);
MouseAdapter reverser = new MouseAdapter() {
public void mouseEntered(MouseEvent event) {
reverseColors();
}
public void mouseExited(MouseEvent event) {
reverseColors0; // mouseEntered(event);
addMouseListener(reverser);
setText(text);
setBackground(bgColor);
setForeground(fgColor);
}
protected void reverseColors()
Color fg = getForeground();
Color bg = getBackground();
setForeground(bg);
setBackground(fg);
}

529

530

13. AWT

Wliite on Black

. 13.24. R e v e r s i b l e L a b e l s

. 13.25. R e v e r s i b l e L a b e l s
,

13.22.

AWT
S c r o l l b a r . " "
,
F l o w L a y o u t . E a s t
S o u t h B o r d e r L a y o u t G r i d L a y o u t .
, S c r o l l b a r .
, Java- .
T e x t A r e S c r o l l .
Swing,
J S l i d e r .

S c r o l l b a r .
public ScroUbarO
.
( ) 10%
. (
) .
public Scrollbar(int orientation)

. o r i e n t a t i o n
Scrollbar.
HORIZONTAL S c r o l l b a r .VERTICAL.
10% .
( ) .

1 3 . 2 2 .

531

public Scrollbar(int orientation, int initialValue, int bubbleSize, int min, int max)
.
;
.
. , max min
5, 20% .
, (, MacOS)
.
,
( ) (
) .
,
. ,

. , ,
45;
25, 5.
new S c r o l l b a r ( S c r o l l b a r . H O R I Z O N T A L ,

25, 5,

50);

!
t ,

max, , - t .


. 13.41 ,
( S c r o l l b a r ,
). 100
, 50. .
Windows 98 . 13.26.
1 3 . 4 1 . S c r o l l b a r s . J a v a
import
import

Java.applet.Applet;
java.awt.*;

public c l a s s S c r o l l b a r s extends Applet {


public void i n i t O {
int i;
setLayout(new G r i d L a y o u t ( 1 , 2)) ;
P a n e l l e f t = new P a n e l ( ) , r i g h t = new P a n e l ( ) ;
left.setLayout(new GridLayout(10, 1 ) ) ;
f o r ( i = 5 ; i < 5 5 ; i=i-b5) {
l e f t . a d d ( n e w Scrollbar(Scrollbar.HORIZONTAL, 50, i ,
}

0,

100));

532

13. AWT

right.setLayout(new GridLayout(1, 10));


for (1=^5; i<55; 1=1 + 5) {
rlght.add(new Scrollbar(Scrollbar.VERTICAL, 50, 1, 0, 100)
}
add(left);
add(right);

1!111!,1-!1^

J.

dLi

H'^NKh

. 13.26. S c r o l l b a r

,

Scrollbar
, S c r o l l b a r , .
public v o i d a d d A d j u s t m e n t L i s t e n e r (AdjustmentListener listener)
public void r e m o v e A d j u s t m e n t L i s t e n e r ( A d j u s t m e n t L i s t e n e r listener)
a d d A d j u s t m e n t L i s t e n e r S c r o l l b a r
A d j u s t m e n t L i s t e n e r ,
. A d j u s t m e n t L i s t e n e r
a d j u s t m e n t V a l u e C h a n g e d ,
A d j u s t m e n t E v e n t . A d j u s t m e n t E v e n t g e t A d j u s t m e n t , : A d j u s t m e n t E v e n t . UN1T_INCREMENT ( ,
), A d j u s t m e n t E v e n t .UNIT_DECREMENT ( ,
), A d j u s t m e n t E v e n t . BLOCK_INCREMENT (
), A d j u s t m e n t E v e n t . BLOCK_DECREMENT ( )
A d j u s t m e n t E v e n t . TRACK ( ).
public int g e t U n i t l n c r e m e n t O
public void s e t U n i t I n c r e m e n t ( i n t i n c r e m e n t )
g e t U n i t I n c r e m e n t ,
,
.
s e t U n i t l n c r e m e n t , , 1.
, , JDK 1.1 Solans,
. ,

13.22.

533

. s e t U n i t I n c r e
m e n t
. .
public int getMaximum()
public void setMaximum(int maxValue)
getMaximum S c r o l l b a r .
,
, , g e t V i s i b l e Amount. setMaximum .
public int g e t M i n i m u m ( )
public v o i d s e t M i n i m u m ( i n t minValue)
g e t M i n i m u m , a s e t M i n i m u m
S c r o l l b a r .
public int getOrientation()
public void setOrientation(int orientation)
S c r o l l b a r .
S c r o l l b a r . HORIZONTAL
Scrollbar.VERTICAL.
public int g e t B l o c k I n c r e m e n t ( )
public void s e t B l o c k I n c r e m e n t ( i n t i n c r e m e n t )
g e t B l o c k l n c r e m e n t , a s e t B l o c k l n c r e m e n t

. .
Windows 98 10, Solaris .
public int getValueO
public void setValue(int value)
public void setValues(int value, int bubbleSize, int m i n , int max)

. ,
. ,
, ,
.
.
public int getVisibleAmount()
. , ^
.

534

13. AWT

public void processAdjustmentEvent(AdjustmentEvent event)


, S c r o l l b a r
,
:
enableEvents(AWTEvent.ADJUSTMENT_EVENT_MASK);
p r o c e s s A d j u s t m e n t E v e n t ,
A d j u s t m e n t E v e n t .
, s u p e r .
p r o c e s s A d j u s t m e n t E v e n t . .
S c r o l l b a r Component,
s e t F o r e g r o u n d s e t B a c k g r o u n d , s e t F o r e g r o u n d
. Windows 9 5 / N T s e t B a c k g r o u n d
. Solaris .
MacOS S c r o l l b a r .

Scrollbar
S c r o l l b a r p r o c e s s
A d j u s t m e n t E v e n t , A d j u s t m e n t L i s t e n e r .
p r o c e s s A d j u s t m e n t E v e n t ,
S c r o l l b a r . A d j u s t m e n t L i s t e n e r
.
A d j u s t m e n t E v e n t : g e t V a l u e g e t A d j u s t m e n t T y p e . g e t V a l u e
, S c r o l l b a r .
g e t A d j u s t m e n t T y p e : A d j u s t m e n t E v e n t .
UNIT_INCREMENT, AdjustmentEvent.UNIT_DECREMENT, A d j u s t m e n t E v e n t . B L O C K _
INCREMENT, AdjustmentEvent.BLOCK_DECREMENT A d j u s t m e n t E v e n t . T R A C K .
13.42
p r o c e s s A d j u s t m e n t E v e n t ,
.
, . ,
,
. s e t V a l u e
l a s t V a l u e
, s e t V a l u e
.
, Swing API J S l i d e r (
), S c r o l l b a r
. Swing
, , ,
, Java Plug-In.
1 3 . 4 2 . B e t t e r S c r o l l b a r . Java
import
import

java.awt.*;
Java.awt.event.*;

13.23.

/
*
*
*

535

.
,
.
.

public class BetterScrollbar extends Scrollbar {


private int lastValue;
public BetterScrollbar(int orientation,
int initialValue,
int bubbleSize,
int min,
int max) {
super(orientation, initialValue, bubbleSize, min, max);
enablGEvents (AWTEvent .ADJUSTMENT_EVENT_MASK) ;
lastValue = initialValue;

/** , .

V
public void processAdjustmentEvent(AdjustmentEvent e) {
int type = e.getAdjustmentType();
switch(type) {
case AdjustmentEvent.UNIT_INCREMENT:
setValue(lastValue + getUnitlncrement());
break;
case Adj ustmentEvent.UNIT_DECREMENT:
setValue(lastValue - getUnitlncrement());
break;
case Adj ustmentEvent.BLOCK_INCREMENT:
setValue(lastValue + getBlocklncrement());
break;
case Adj ustmentEvent.BLOCK_DECREMENT:
setValue(lastValue - getBlocklncrement());
break;
}
lastValue = getValueO;
super.processAdjustmentEvent (e);
}

http://www.corewebprograiraning.com/
Slider,
Scrollbar TextField.

13.23.
, .
, PopupMenu,

536

13. AWT

Menu I t em,
, i s P o p u p T r i g g e r .
show .
, A c t i o n E v e n t .

PopupMenu .
public PopupMenu()
public P o p u p M e n u ( S t r i n g title)
,
, , ,
Windows 9 5 / 9 8 / N T .


13.43 ,
.
. ,
ActionListener
. actionPerformed.
Windows 95 . 13.27.
13.43.lorPopupMenu.java
import Java . applet .Appletsimport java.awt.*;
import Java.awt.event.*;
/** . */
public class ColorPopupMenu extends Applet
implements ActionListener {
private String[] colorNames =
{ "White", "Light Gray", "Gray", "Dark Gray", "Black" };
private Color[] colors =
{ Color.white. Color.lightGray, Color.gray.
Color.darkGray, Color.black };
private PopupMenu menu;
/** PopupMenu Menultem. */
public void initO {
setBackground(Color.gray);
menu = new PopupMenu("Background Color");
enableEvents (AWTEvent.MOUSE_EVENT_MASK) ;
Menultem colorName;
for(int i=0; i<colorNames.length; i++) {
colorName = new Menultem(colorNames[i]);

13.23.

menu.add(colorName);
colorName.addActionListener(this);
menu.addSeparator() ;
}
add(menu) ;
/ MouseListener , Win95/98/NT
* isPopupTrigger mouseReleased,
* Solaris mousePressed.
^/
public void processMouseEvent(MouseEvent event) {
if (event.isPopupTrigger0) {
menu.show(event.getComponent(), event.getX(),
event.getY());
}
super.processMouseEvent(event);
}
public void actionPerformed(ActionEvent event) {
setBackground(colorNamed(event.getActionCommand()))
repaint();
}
private Color colorNamed(String colorName) {
for(int i=0;i<colorNames.length; i++) {
if(colorNames[i].equals(colorName)) {
return(colors[i]);
}
}
return(Color.white);

[^Applet

4ientrtJBk^apifMemJ^ti^

iPPPCfDfxr

Applet

^''V^f'''''', '''-;V'',','-'';

'^*''' ^'''''^

"^^'

p;' l''"' 'X '':'//, T'- ^^^^

^:[:!''!'''':'''-'-'

:<" ''/'"/.''-

' i'Zc-''^'<,?---'.1/!-''-- ^^^''-Wv'r:'''X'?^<''


Applet started

. 13.27. Windows 98

537

538

13. AWT


PopupMenu show,
. , , Menu,
Menu I t em .
public void a d d ( M e n u I t e m item)
public void add(String label)
.
,
M e n u l t e m , M e n u l t e m ( l a b e l ) .
A c t i o n L i s t e n e r .
public v o i d addActionListener(ActionListener listener)
M e n u l t e m ,
.
g e t A c t i o n C o m m a n d ( ) .
public void addSeparatorO
,
. . 13.27 .
public void setShortcut(MenuShortcut shortcut)
public M e n u S h o r t c u t getShortcut()
public void deleteShortcut()
JDK 1.1
.
M e n u S h o r t c u t :
MenuShortcut

shortcut

= new M e n u S h o r t c u t ( i n t

key);

M e n u l t e m
s e t S h o r t c u t . g e t S h o r t c u t M e n u S h o r t c u t ,
d e l e t e S h o r t c u t
.
public void s h o w ( C o m p o n e n t , int , int )

.
PopupMenu ,
.

13.23.

539

,

.
, .
.
,
, Java
i s P o p u p T r i g g e r M o u s e E v e n t .
(, Solaris)
, (, Windows 98 Windows NT)
, Mouse~
L i s t e n e r , p r o c e s s M o u s e E v e n t .
M o u s e L i s t e n e r ,
m o u s e P r e s s e d , m o u s e R e l e a s e d .
.
PopupMenu menu = new P o p u p M e n u ( " [ T i t l e ] " ) ;
e n a b l e E v e n t s (AWTEvent .MOUSE__EVENT__MASK) ;
public void processMouseEvent(MouseEvent event)
if
(event.isPopupTrigger())
menu.show(event.getComponent(),
event.getX(), event.getY());
super.processMouseEvent(event);

, ,
M e n u l t e m A c t i o n L i s t e n e r .
Menultem i t e m = new M e n u l t e m ( " [ L a b e l ] " ) ;
menu.add(item);
item.addActionListener(someListener);
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 ,
A c t i o n E v e n t . g e t A c t i o n C o m m a n d A c t i o n E v e n t
, M e n u l t e m .

13.24.
AWT ,
: C a n v a s , P a n e l , A p p l e t , S c r o l l P a n e ,
Frame, D i a l o g , F i l e D i a l o g Window.
, .
Java : B u t t o n ,
Checkbox (
). C h o i c e , L i s t , T e x t F i e l d , T e x t A r e a , L a b e l , S c r o l l b a r (
) PopupMenu. -

540

13. AWT

, , -, ,
, -,
,
. , ^
, ) , ( C h o i c e ,
L i s t , PopupMenu) "", .
, , , .
A c t i o n E v e n t , , ,
, , .
, ,
AWT .
, , , }^
Swing, Java 2,
. AWT
, , ,
Netscape Internet Explorer. Java 1.1 AWT API Netscape 4.06, Internet
Explorer 4.0 .

SWING
...
Swing.
.
.
..
HTML .
JCoiorChooser.
.
.
.
Web- Swing.

J~y\zJSJ:EJ

Swing
Java. Swing (
, ,
),
, .
Swing Java 2
AWT. Swing
.

,
, , ,
, HTML- RTF, , .

,
, .
.


. .

,
, , ,
, .

Swing .
, .
Swing
(Kim Topley) Core Java Foundation Classes Core Swing: Advanced Procamming.

544

14. Swing

1 4 . 1 . Swing
Swing Java 2, B J D K 1.1
. Swing JDK 1.1 h t t p : / / j a v a .
s u n . c o m / p r o d u c t s / j f c / d o w n l o a d . h t m l . Swing
. ,
Netscape 6.
Swing Java Plug-In ( Java Plug-In
9).

Swing WT
Swing AWT.


Swing "J"
J , . Swing-
J F r a m e , J P a n e l , J A p p l e t , J D i a l o g J B u t t o n . AWT-
Swing-. Swing
J C o m p o n e n t ,
, , , .

""
Swing "''. ,
Java-; . J F r a m e , J A p p l e t ,
JWindow J D i a l o g . ^'".
, , ,
"" AWT.

paintComponent
Swing p a i n t ,
p a i n t C o m p o n e n t . p a i n t C o m p o n e n t
, UI- (UI user interface),
. , UI-
.
p a i n t C o m p o n e n t ,
. ,
p a i n t C o m p o n e n t :
p u b l i c void paintComponent(Graphics
super.paintComponent(g);
/ / Swing . . .

g){

1 4 . 1 . Swing

545



Swing
paint, paintComponent.

super.

paintComponent.


Swing,
JFrame J A p p l e t .
( C o n t e n t P a n e ) .
Container content = getContentPane();
content.add(new JButton("Welcome"));
content.add(new JLabel("JavaOne");
JFrame J A p p l e t
.
, B o r d e r L a y o u t . Swing
J F r a m e J A p p l e t ( B o r d e r L a y o u t ) .
AWT, Frame
B o r d e r L a y o u t , A p p l e t F l o w L a y o u t .
, s e t C o n t e n t P a n e .

JFrame JApplet,

.


J P a n e l (
16). Swing ,
, R e p a i n t M a n a g e r .
p a i n t R e p a i n t M a n a g e r
. p a i n t
Component, . J P a n e l
p a i n t C o m p o n e n t
. p a i n t p a n e l .
g e t G r a p h i c s ( ) ,
.
, ,
. ,
, J F r a m e J A p p l e t ,
, Java- Swing
.

546

1 4 . Swing

"--"
"" Swing- "-" (MVC model-view-controller), . 14.1.
,
.
, , , ,
, , .
.
.
"" Swing
(UI), ComponentUI. UI
. UIManager ,
(LabelUI, TableUI, TreeUI ..),
(Windows, Motif, Java). UI ,
, .
MVC ,
,
. ,
. .
, ,
. .
Swing.
, , 15
JTree JTable.

. 14.1. "-" (MVC)

1 4 . 1 . Swing

547


MVC Swing.
Swing
Windows, Motif, MacOS Java ( Metal).
U I M a n a g e r UI-,
,
"" Swing.

.

Java ( Metal),
, Windows.

Motif , Windows
. ,
, , .


. S w i n g U t i l t i e s . U p d a t e C o m p o n e n t T r e e U I ,
UI-. :
try {

UIManager. setLoolcAndFeel (
"javax.swing.motif.MotifLookAndFeel");
} catch(Exception e) {
System.out.printlnC'LAF Error: " + e) ;
}
SwingUtilties.updateComponentTreeUI(
getContentPane());
,
.
J F r a m e , m a i n i n i t J A p p l e t .

,
, .
g e t S y s t e m L o o k A n d F e e l C l a s s N a m e U I M a n a g e r
U I M a n a g e r . s e t L o o k A n d F e e l .
s e t L o o k A n d F e e l ,
.
s e t N a t i v e L o o k A n d F e e l .

14.1 W i n d o w U t i l i t i e s .
, ,
, Java (Metal) Motif.
,
, Java (

548

14. Swing

JRE).
, .
WindowUtilities ,
JFrame. open In JFrame
JPanel JFrame. ExitListener
.
14.1. WindowUtilitiesava
import javax.swing.*;
import java.awt.*; // Color Container.
/** , Swing. */
public class WindowUtilities {
/** ,
.
Metal (Java).
*/
public static void setNativeLookAndFeel() {
try {
UIManager.setLookAndFeel(
UIManager. getSystemLookAndFeelClassName ()) ;
} catch(Exception e) {
System.out.println("Error setting native LAF: " + e ) ;
}
}
public static void setJavaLookAndFeel() {
try {
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting Java LAF: " + e ) ;
}

}
public static void setMotifLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.j ava.swing.plaf.motif.MotifLookAndFeel");
} catch(Exception e) {
System.out.println("Error setting Motif LAF: " + e ) ;
}
}
/** JPanel .
*
JFrame Container
*
.

V
public static JFrame openlnJFrame(Container content,
int width,
int height,
String title.
Color bgColor) {

1 4 . 1 . Swing

549

JFrame frame = new JFrame(title);


frame.setBackground(bgColor);
content.setBackground(bgColor) ;
frame.setSize(width, height);
frame.setContentPane(content);
frame.addWindowListener(new ExitListener());
frame.setVisible(true);
return(frame);
}
/** Color.white. */
public static JFrame openlnJFrame(Container content,
int width,
int height.
String title) {
return(openlnJFrame(content, width, height,
title. Color.white));
}
Z'^* Color.white ,
*
JFrame.

V
public static JFrame openlnJFrame(Container content,
int width,
int height) {
return(openlnJFrame(content, width, height,
content.getClass().getName(),
Color.white));
}

14.2.ExitListener.java
import java.awt.*;
import Java.awt.event.*;
/** ,
* JFrame , ,
* .

V
public class ExitListener extends WindowAdapter {
public void windowClosing(WindowEvent event) {
System.exit(0);
}

Java 2 JDK SwingSet2,


Swing. r o o t / j d k l . 3/demo/j f /
SwingSet2. . 14.2 14.4 ,
Windows, Motif Java.

550

14. Swing

kWf^f^

ill
Table D$mo | Source Code |
P Reprderlno fowed
P" Hoftz. Une&'
F Ven. Unes
Mtt^f'SdK ;:

-J

- Ssleefion mode
" Column seiettjon
jMuitiple ranges

P Row selection
Rowueight

^|

' Aterei2e mod

__j.

jSubsequent columns ;;^J

FgvoHte Kovie

first Name I UetNeme


Mike

Brazil

jMarK

:Curseotthe Demon

JBrian

|The Bluws Brothers

iLara

Airplane (the whole series)

Roger

The ManVvrno Kne^vToo Much

Brent

Bintie Runner (Director's Cut)

jMark

Brazil

jjeir

The Lady Vanishes

lEwan

A Bug's Life

[Anny

Reser\ruirDcg

I Fevortte Number I fvoirlte

. 14.2. SwingSet2 Windows

im

>0^

Table l>ew<?s
Selectkw wo<ie
J column sefecfeon

||^$ J' /1>

IS? Roweelec^cm
i ? we

Autore^is&rmjde

Rownelgbt

ir^r-teiupdesi$;: .

^1

I fmom i^gftNr

|Tt)^BHie8rpthers
iart ^ eerjes)
Who i^swTtHt^ imuth
|8lade * |^ ^>
[<11
0'

^ '^

. 14.3. SwingSet2 Motif

1 4 . 1 . Swing

fee

took&Feei
5

551

Themes

( * : *-;-:~'

mm

.-=^-\

TileOemoMir^.^1
! S^lfeCtmu mutie

. Reorctefbio alowed
v H o r k , Lines
!i Row Section
'< Veit.Unes

rAiitw$Jift?niMid8'"
c:3rrdlj^)br

First Name ; Last Name !


Mii-e

Albers

Favorite C(Hor

Favorite Movie

Favortte Number i

FgvorlteFood

sBrazil

Mark

Andrews

Curse of the Demon

Brian

Beck

The Blues Brothers

Lara

Bunni

Roger

Brinkley

Brent

Chnstian

Blade Runner (Director's Cut)

Mark

Davidson

Brazil

Jeff

Dinkins

The Lady Vanishes

Ewan

Dinkins

A Bug's Life

Amy

Fowler

Reservoir Dogs

[Airplane (the whole senes)


The Man Who Knew Too Much

P*fc. 14.4. SwingSet2 Java (Metal)


AWT Swing
AWT .
Java z-npuopumema, z-,
,
. , , z, z- .
z-
z-. -
z- .
Swing-
z-, . AWT
Swing.
.
, Swing-
AWT Button.
.

AWT, Swing.
Swing,
, j a v a x . s w i n g . S w i n g C o n s t a n t s
, . ,
LEFT, CENTER, RIGHT, TOP, BOTTOM, NORTH, EAST,
SOUTH, WEST, NORTH EAST, NORTH WEST, SOUTH EAST, SOUTH WEST, HORIZONTAL,

552

1 4 . Swing

VERTICAL, LEADING TRAILING.


,
( ).

14.2. JApplet
J A p p l e t Swing- AWT- A p p l e t .
J A p p l e t ,
Java 2 Platform Netscape 6.
Swing , Java 1.1,
, Swing,
Java 2. Swing- ,
Java 2 Plug-In, 9. Java Plug-In,
, 5 , Swing-
Internet . intranet,
Java Plug-In .
J A p p l e t Swing-,
A p p l e t . "" Swing,
J C o m p o n e n t . J A p p l e t
i n i t , s t a r t , s t o p d e s t r o y . J A p p l e t
Swing, A p p l e t .

J A p p l e t , .
, ,
.., .
g e t C o n t e n t P a n e .

J A p p l e t ( Frame JFrame)
B o r d e r L a y o u t . ,
A p p l e t FlowLayout.
, B o r d e r L a y o u t .

J a v a ( M e t a l ) .
,
.

p a i n t , p a i n t C o m p o n e n t .

J A p p l e t , J P a n e l ,
, p a i n t C o m p o n e n t J P a n e l
.


Applet, JApplet

BorderLayout.

14.3. JFrame

553

14.3 Swing-. ,
AWT-, ,
, Swing-
, , FlowLayout.
. 14.5 Netscape 6.
14.3. JApplGtExample.Java
import java.awt.'^;
import javax.swing.*;
/** ,
* JApplet Applet: ,
* Java (Metal),
*
* BorderLayout ( FlowLayout).

V
public class JAppletExample extends JApplet {
public void initO {
WindowUtilities.setNativeLookAndFeel();
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(new JButton("Button 1"))
content.add(new JButton("Button 2")),
content.add(new JButton("Button 3")),
}

File

Ed ^ i e w Search

Qp

Book'narks

lasks

jHelp

QiM>:200(XmM2S

. 14.5. Swing- J B u t t o n ,
Netscape 6,
Windows 98

14.3. JFrame
JFrame Swing- AWT- Frame. AWT,
JFrame .
JApplet, JFrame Swing-,
JComponent . JFrame
Frame. JFrame AWT- Frame
.

554

14. Swing

J F r a m e ;
, J F r a m e .
,
.
getContent.

Frame, J F r a m e
. ,
Java-.
J F r a m e
W i n d o w L i s t e n e r , S y s t e m , e x i t .
JDK 1.3 s e t D e f a u l t C l o s e O p e r t i o n
( E X I T O N C L O S E ) .
,
WindowListener.

Java (Metal).
,
.



, JFrame
WindowListener.
System, exit.
14.4 .
, AWT- Frame,
F l o w L a y o u t , .
. 14.6. W i n d o w U t i l i t i e s . J a v a
E x i t L i s t e n e r . J a v a .
, h t t p : / /www. c o r e w e b p r o g r a m m i n g . com/.
1 4 . 4 . JFrameExample. J a v a
import java.awt.*;
import javax.swing.*;
/** ,
* JFrame Frame: ,
* ,
* , Java (Metal).

V
public class JFrameExample {
public static void main(String[] args) {
WindowUtilities . setNativeLoolcAndFeel () ;
JFrame f = new JFrame("This is a test");
f.setSize(400, 150);
Container content = f.getContentPane();

14.4.

JLabel

555

content.setBackground(Color.white);
content.setLayout(new FlowLayout()) ;
content.add(new JButton("Button 1")),
content.add(new JButton("Button 2")),
content.add(new JButton("Button 3")),
f.addWindowListener(new ExitListener()
f.setVisible(true);

I LP-4^?!yj--'i

. 14.6. Swing- JFrame,


14.4. JLabel
L a b e l , J L a b e l .
, L a b e l , J L a b e l
. -,
, -, , , HTML-.

: ,
'

, J l a b e l ,
() Image I c o n .

s e t I c o n . J L a b e l ,
J B u t t o n , .

. J L a b e l
14.5.
J L a b e l J B u t t o n
, .
, , J l a b e l ,
. J L a b e l
J P a n e l , .
( 14.5).

HTML. ,
, "<html>",
, HTML-.
HTML- -

556

14. Swing

. HTML-
J B u t t o n . , HTML
.

HTML J L a b e l JDK L2.2, Swing


L L 1 . Java
, ,
, J L a b e l HTML-
.

JDK L2 HTML- J L a b e l
"<html>", "<HTML>". HTML-,
, B J D K L 3 .

BJDK L2 J L a b e l
Image I c o n J L a b e l s e t I c o n . HTML-
<img>. B J D K L3 HTML-
,
.

J L a b e l HTML-, JLabel- .

HTML. , , ,
, Serif
, Sans
Serif :
JLabel label =
new J L a b e l ( " < h t m l > B o l d T e x t < / h t m l > " ) ;
label.setFont(new Font("Serif",Font.BOLD,36))/

<>
<BR>. "" HTML, <BR> ,
<> <BR>.

-
. HTML- ,
, .
HTML- ,
.

JLabel
J L a b e l . ,
, .

14.4. JLabel

557

public JLabelO
public JLabel(String label)
public JLabel(Icon image)
public JLabel(String label, I c o n image, int hAlignment)
J L a b e l ,
J L a b e l , , J L a b e l .
, .
h A l i g n m e n t
"-" J L a b e l .
LEFT, CENTER, RIGHT, LEADING TRAILING.

JLabel
J L a b e l .
, , ,
(get-).
public void s e t H o r i z o n t a l A l i g n m e n t ( i n t alignment)
public void setVerticalAlignment(int alignment)

"-" J L a b e l .
, j a v a x . s w i n g .
S w i n g C o n s t r a i n t s : LEFT, CENTER, RIGHT, LEADING TRAILING
; TOP, CENTER BOTTOM .
public void s e t H o r i z o n t a l T e x t P o s i t i o n ( i n t alignment)
public void setVerticalTextPosition(int alignment)

.
"-".
public void s e t I c o n ( I c o n image)
public void s e t D i s a b l e d I c o n ( I c o n image)

J L a b e l . J L a b e l s e t E n a b l e d ( f a l s e ) .
public void setText(String label)
public void setFont(Font font)
s e t T e x t ,
J L a b e l . HTML-,
< h t m l > < / h t m l > . s e t F o n t J L a b e l .

558

14. Swing

JLabel 14.5.
. 14.7. JLabel
HTML- .
HTML-. HTML-
<UL>. .
, JPanel.
14.5. JLabels.java
import java.awt.*;
import javax.swing.*;
/** , JLabel,
* HTML ( Swing 1.1,1, Java 1.2.2
* ).

public class JLabels extends JFrame {


public static void main(String[] args) {
new JLabels();
public JLabels0 {
superC'Using HTML in JLabels");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
Font font = new Font("Serif", Font.PLAIN, 30);
content.setFont(font);
String- labelText =
"<htmlXFONT COLOR=WHITE>WHITE</FONT> and " +
"<FONT COLOR=GRAY>GRAY</FONT> Text</html>";
JLabel coloredLabel =
new JLabel(labelText, JLabel.CENTER);
coloredLabel.setBorder
(BorderFactory.createTitledBorder("Mixed Colors"));
content.add(coloredLabel, BorderLayout.NORTH);
labelText =
"<htmlXB>Bold</B> and <I>Italic</l> Text</html>";
JLabel boldLabel =
new JLabel(labelText, JLabel.CENTER);
boldLabel.setBorder
(BorderFactory.createTitledBorder("Mixed Fonts"));
content.add(boldLabel, BorderLayout.CENTER);
labelText =
"<html>The Applied Physics Laboratory is a division " +
"of the Johns Hopkins University." +
"<P>" +
"Major JHU divisions include:" +
"<UL>" +
" <LI>The Applied Physics Laboratory" +
" <LI>The Krieger School of Arts and Sciences" +
" <LI>The Whiting School of Engineering" +
" <LI>The School of Medicine" +

14.5. JButton

559

" <LI>The School of Public Health" +


" <LI>The School of Nursing" +
" <LI>The Peabody Institute" +
" <LI>The Nitze School of Advanced International Studies" +
"</UL>" +
"</html>";
JLabel fancyLabel =
new JLabel(labelText,
new Imagelcon("images/JHUAPL.gif"),
JLabe1.CENTER);
fancyLabel.setBorder
(BorderFactory.createTitledBorder("Fancy HTML"));
content.add(fancyLabel, BorderLayout.SOUTH);
packO ;
setVisible(true);
}

.rJPJXl
and :"./> TeKt
Bold and Italic Test
Fancy HTML

The Applied Physics Laboraloiy is a division of the Johns $ Umversity.


Wfejor JHU divisions include"

..0^^/*

The Appliei Physics Laboratory


The Kjriegcr School of Arts and Sciences
The Whrting School of Engineering
The School of Medicine
The School of Public Health
The School of Nursing
The Peabody kistitute
The School of Advanced Itatcrnational Studies

. 14.7. Swing
HTML-

14.5. JButton
Swing- J B u t t o n , AWT-
Button. JButton,
S t r i n g , .
Button; J B u t t o n a d d 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 .

: ,
tt

'

99

J B u t t o n AWT- Button
. Sing

560

14. Swing

Image I con, (JPEG,


GIF, GIF). JButton,
Imagelcon . J B u t t o n
.
1. ( ,
s e t Icon).
2. , ( s e t P r e s s e d l c o n ) .
3. ,
( s e t R o l l o v e r l c o n ; ,
setRolloverEnabled(true)).
4. ( s e t D i s a b l e d l c o n ) .
5. , ,
(setSelectedlcon).
6. , ,
(setDisabledSelectedlcon).
7. ,
( s e t R o l l o v e r S e l e c t e d l c o n ) .
( s e t S e l e c t e d l c o n , s e t R o l l o v e r S e l e c
t e d l c o n s e t D i s a b l e d S e l e c t e d l c o n ) B J D K 1.2;
JDK 1.3. ,
s e t S e l e c t e d ( t r u e ) .
ActionEvent. ,
JToggleButton (. API,
j a v a x . swing . JToggleButton), ,
.
,
"-", s e t H o r i z o n t a l Alignment s e t V e r t i c a l A l i g n m e n t ( ,
).

s e t H o r i z o n t a l T e x t P o s i t i o n s e t V e r t i c a l T e x t P o s i t i o n .
s e t l c o n T e x t G a p .
J B u t t o n " "
. setMnemonic. "
" , ,
<+>.

HTML'
JDK 1.2.2, Swing 1.1.1
HTML , J B u t t o n
JLabel. , ,

.

14.5. JButton

561

JButton
JButton :
public JButtonO
public JButton(String label)
public J B u t t o n ( I c o n image)
public JButton(String label, I c o n image)
public JButton(Action action)
J B u t t o n ,
J B u t t o n , J B u t t o n
J B u t t o n . B J D K 1.3.
A c t i o n ,
.

JButton AbstractButton
JButton .
, AbstractButton. . set-eo^^
, get-,
.
public void setAction(Action action)
public Action getAction()
JDK 1.3.
Action.
. , a c t i o n P e r f o r m e d .
A c t i o n
. ,
, A c t i o n
.
public void s e t H o r i z o n t a l A l i g n m e n t ( i n t alignment)
public void setVerticalAlignment(int alignment)
"" J B u t t o n .
, J L a b e l .
public void s e t H o r i z o n t a l T e x t P o s i t i o n ( i n t alignment)
public void setVerticalTextPosition(int alignment)

, .
J L a b e l .

562

14. Swing

public void setText(String label)


public void setFont(Font font)
s e t T e x t , ,
s e t Font .
HTML-, <html> </html>.
public void setIcon(Icon image)
public void setPressedIcon(Icon image)
public void setRolloverIcon(Icon image)
public void setDisabledIcon(Icon image)
, JButton.
,
, ,
, .
JButton, s e t E n a b l e d ( f a l s e ) .
public void setEnabled(boolean state)
s e t E n a b l e d ( t r u e ) ( f a l s e ) o)^
.
public void setMargin(Insets m^argins)
.
, 10
5 .
JButton button = new JButton("Continue");
button.setMargin(new Insets(10,5,10,5));
14.6 , :
, , .
. 14.8.
14.6.JButtons.Java
import java.awt.*;
import javax.swing.*;
/** , JButton.
* .

V
public class JButtons extends JFrame {
public static void main(String[] args) {
new JButtons{);
}
public JButtons0 {
super("Using JButton");
WindowUtilities.setNativeLookAndFeel();

14.6. JPanel

563

addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
JButton buttonl = new JButtonC'Java") /
content.add(buttonl) ;
Imagelcon cup = new Imagelcon("images/cup.gif");
JButton button2 = new JButton(cup);
content.add(button2);
JButton buttons = new JButton("Java", cup);
content.add(button3);
JButton button4 = new JButton("Java", cup);
button4.setHorizontalTextPosition(SwingConstants.LEFT);
content.add(button4);
packO ;
setVisible(true) ;

, / 4 . e . Swing- JButton
,

14.6. JPanel
J P a n e l , AWT- P a n e l .
, ,
. J P a n e l C a n v a s (
J C a n v a s ). J P a n e l
C a n v a s . -,
s e t P r e f e r r e d S i z e (
P a n e l J P a n e l ).
-, p a i n t p a i n t Component. , ,
p a i n t C o m p o n e n t , ,
s u p e r . p a i n t C o m p o n e n t .
public void paintComponent(Graphics g) {
super.paintComponent(g);

Swing Java 2, G r a p h i c s
G r a p h i c s 2 D Java 2D (
10).

564

14. Swing

JPanel
JPanel .
JPanel
s e t La o u t . .
J P a n e l JComponent,
. ( API.)
public JPanel()
public JPanel(LayoutManager manager)
public J P a n e l ( b o o l e a n i s D o u b l e B u f f e r e d )
public JPanel(LayoutManager manager, b o o l e a n isDoubleBuff ered)
J P a n e l ,
F l o w L a y o u t .

.

:
JPanel
. ,
J C o m p o n e n t , J P a n e l ,
. Swing : T i t l e d o r d e r , E t c h e d B o r d e r , B e v e l B o r d e r ( "" ). L i n e o r d e r , M a t t e B o r d e r , C o m p o u n d B o r d e r E m p t y B o r d e r .
.
s e t B o r d e r . B o r d e r
, B o r d e r F a c t o r y . :
J P a n e l = new J P a n e l ( ) ;
p.setBorder(BorderFactory.createTitledBorder("Java"));
, B o r d e r F a c t o r y
B o r d e r , , B o r d e r ,
B o r d e r F a c t o r y .

teXxxBorder

Border

BorderFactory.

BorderFactory
B o r d e r F a c t o r y 23 ,
. B o r d e r j a v a x .
s w i n g . b o r d e r . A b s t r a c t B o r d e r ,
B o r d e r . A b s t r a c t B o r d e r
EmptyBorder, T i t l e d B o r d e r , LineBorder, EtchedBorder, BevelBorder, Soft-

14.6. JPanel

565

B e v e l B o r d e r , M a t t e B o r d e r C o m p o u n d B o r d e r . 23 B o r d e r F a c t o r y , .
p u b l i e s t a t i c .
Border createEmptyBorder(int t o p , int left, int b o t t o m , int right)
E m p t y B o r d e r ,
.
Border c r e a t e L i n e B o r d e r ( C o l o r color)
B o r d e r createLineBorder(Color color, int thickness)
L i n e B o r d e r .
.
. L i n e B o r d e r
: c r e a t e B l a c k L i n e B o r d e r c r e a t e G r a y L i n e B o r d e r . ,
.
T i t l e d B o r d e r createTitledBorder(String title)
T i t l e d B o r d e r c r e a t e T i t l e d B o r d e r ( B o r d e r b o r d e r . String title)
T i t l e d B o r d e r ,
() .
"". ,
( ). T i t l e d B o r d e r
s e t T i t l e P o s i t i o n s e t T i t l e J u s t i f i c a t i o n .

: ABOVE_TOP, , BELOW_TOP, ABOVE_BOTTOM, BOTTOM BELOW_BOTTOM.
s e t T i t l e J u s t i f i c a t i o n
LEFT, CENTER RIGHT.
s e t T i t l e C o l o r , s e t T i t l e F o n t
BorderFactory.
Border createEtchedBorder()
Border c r e a t e E t c h e d B o r d e r ( C o l o r highlight, Color shadow)
LOWERED E t c h e d B o r d e r ,
2 .
.
, ,
, .
. ,
E t c h e d B o r d e r ,
RAISED.
B o r d e r F a c t o r y
, E m p t y B o r d e r , Border E t c h e d B o r d e r . , B o r d e r F a c t o r y
B e v e l B o r d e r ( c r e a t e B e v e l B o r d e r , c r e a t e R a i s e d B e v e l B o r d e r

566

14. Swing

C r e a t e L o w e r e d B e v e l B o r d e r ) M a t t e B o r d e r
( c r e a t e M a t t e B o r d e r ) ,
( c r e a t e C o m p o u n d B o r d e r ) .
14.7 J P a n e l L i n e B o r d e r
2 .
J P a n e l . 400 ,
( , WEST
B o r d e r L a y o u t ) . ,
, .
T i t l e d B o r d e r .
. 14.9.
1 4 . 7 . J P a n e l s . Java
import java.awt.*;
import javax.swing.*;
/** ,
* JPanel, .

V
public class JPanels extends JFrame {
public static void main(String[] args) {
new JPanels();
}
public JPanels0 {
superC'Using JPanels with Borders");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.lightGray);
JPanel controlArea = new JPanel(new GridLayout(3, 1));
String[] colors = { "Red", "Green", "Blue",
"Black", "White", "Gray" };
controlArea.add(new SixChoicePanel("Color", colors));
String[] thicknesses = { "1", "2", "3", "4", "5", "6" };
controlArea.add(new SixChoicePanel("Line Thickness",
thicknesses));
String[] fontSizes = { "10", "12", "14", "18", "24", "36" };
controlArea.add(new SixChoicePanel("Font Size",
fontSizes));
content.add(controlArea, BorderLayout.EAST);
JPanel drawingArea = new JPanel();
// ,
// WEST.
drawingArea.setPreferredSize(new Dimension(400, 0));
drawingArea.setBorder
(BorderFactory.createLineBorder (Color.blue, 2));
drawingArea.setBackground(Color.white);
content.add(drawingArea, BorderLayout.WEST);
pack () ;
setVisible(true) ;

14.7. JSlider

567

14.8.SixChoicePanel.Java
import java.awt.*;
import javax.swing.*;
/** Jpanel, JRadioButton.
public class SixChoicePanel extends JPanel {
public SixChoicePanel(String title. String[] buttonLabels) {
super(new GridLayout(3, 2));
setBackground(Color.lightGray);
setBorder(BorderFactory.createTitledBorder(title));
ButtonGroup group = new ButtonGroup();
JRadioButton option;
int halfLength = buttonLabels.length/2; // Assumes even length
for(int i=0; KhalfLength; 1++) {
option = new JRadioButton(buttonLabels[i]);
group.add(option) ;
add(option);
option = new JRadioButton(buttonLabels[i+halfLength]);
group.add(option) ;
add(option) ;
}
}

||^IHI,lipW!MJyiiffllfpi|^^
Color
pieifli

j
Black

(^ Green White
^

Blue

^ Gray

Line Thickness
r

r 5

^ 6

Font Size
^ 1 0
r
\^\^

12

^18
r 24
^ 36

. 14.9. JPanel

14.7. JSlider
AWT S c r o l l b a r :
,
. "" ,
. Swing
J S l i d e r .
J S l i d e r , S c r o l l b a r : -

568

14. Swing

pa, , ,
100 ,
50. ,
( J S l i d e r .HORIZONTAL
J S l i d e r .VERTICAL), .
J S l i d e r C h a n g e L i s t e n e r .
s t a t e C h a n g e d g e t V a l u e ,
J S l i d e r .

:
Swing- J S l i d e r
. ,
s e t P a i n t T i c k s ( t r u e ) .
j o r T i c k S p a c i n g s e t M i n o r T i c k S p a c i n g .
, ,
s e t S n a p T o T i c k s ( t r u e ) .
, s e t P a i n t L a b e l s ( t r u e ) .
(, Image I c o n ) .
D i c t i o n a r y I n t e g e r Component
, . D i c t i o n a r y
s e t L a b e l T a b l e .
J S l i d e r ,
, .. ( s e t l n v e r t e d ( t r u e ) ) ,
,
( g e t V a l u e I s Ad j u s t i n g () t r u e ) ,
.

JSlider
JSlider :
public JSliderO
public JSlider(int orientation)
public JSlider(int m i n , int max)
public JSlider(int m i n , int max, int initialValue)
public JSlider(int orientation, int m i n , int max, int initialValue)
J S l i d e r
, 100,
, 50. JSlider
. ,
(HORIZONTAL VERTICAL).
,
.

14.7. JSIider

569

JSIider
J S I i d e r 43 . ,
, . set- get-.
public void setMinimum(int min)
public void setMaximum(int max)
public void setValue(int initialValue)
public void setOrientation(int orientation)
,
, .
HORIZONTAL VERTICAL.
public void s e t P a i n t T i c k s ( b o o l e a n paint)
public void setMinorTickSpacing(int stepSize)
public void setMajorTickSpacing(int stepSize)
,
s e t P a i n t T i c k s ( t r u e )
( s e t M a j o r T i c k S p a c i n g )
(setMinorTickSpacing).



,
setPaintTicks
true.
public void s e t S n a p T o T i c k s ( b o o l e a n snap)
s e t S n a p T o T i c k s ( t r u e ) ,
.
, f a l s e ;
.
public void s e t I n v e r t e d ( b o o l e a n inverted)
s e t l n v e r t e d
.
public void setPaintLabels(boolean paint)
public void setLabelTable(Dictionary labels)
s e t P a i n t L a b e l s
. S t r i n g
I c o n . , .
J S I i d e r ,

570

1 4 . Swing

,
s e t L a b e l T a b l e .
Hashtable, "-" I n t e g e r
JComponent ( JComponent JLabel).

,

setPalntLahels
(true).

14.9 ,
: , ,
. . 14.10
. Windows,
Motif Java.
14.9. J S l i d e r s . J a v a
import j a v a . a w t . * ;
import j a v a x . s w i n g . * ;
/** , J S l i d e r s ,
* .
p u b l i c c l a s s J S l i d e r s extends JFrame {
p u b l i c s t a t i c void m a i n ( S t r i n g [ ] args) {
new J S l i d e r s ( ) ;
public J S l i d e r s 0 {
super("Using J S l i d e r " ) ;
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.white);
JSlider sliderl = new JSlider();
sliderl.setBorder(BorderFactory.createTitledBorder
("JSlider without Tick Marks"));
content.add(sliderl, BorderLayout.NORTH);
JSlider slider2 = new JSlider();
slider2.setBorder(BorderFactory.createTitledBorder
("JSlider with Tick Marks"));
slider2.setMajorTickSpacing(20);
slider2.setMinorTickSpacing(5);
slider2.setPaintTicks(true);
content.add(slider2, BorderLayout.CENTER);
JSlider sliderS = new JSlider();
slider3.setBorder(BorderFactory.createTitledBorder

14.8. JColorChooser

571

("JSlider with Tick Marks & Labels'


sliders.setMajorTickSpacing(20);
sliders.setMinorTickSpacing(5);
slider3.setPaintTicks(true);
sliderS . setPaintLcQ^els (true) ;
content.add(sliders, BorderLayout.SOUTH);
packO ;
setVisible(true) ;

JSB9rv^thdytTtekMart<$

gSiderwt&itlfcktilafks
JSIidJif ? k s

I11) > I )} f77TV77*7)


JSHder with Itafk? $, U N t s
I M ' ' I nT*77T7|
0 2Q 40 60 eC too

(a)

(6)

20

ifm

. 14.10. JSlider
: Windows; Java (Metal);
Motif

14.8. JColorChooser
J C o l o r C h o o s e r Swing. AWT
. J C o l o r C h o o s e r
. J C o l o r C h o o s e r
,
, , HSB (hue, saturation, brightness ,
, ) RGB.
J C o l o r C h o o s e r , J C o l o r C h o o s e r .
s h o w D i a l o g .
, ,
. :
JColorChooser.showDialog
(parent, " S e l e c t Background",

getBackground());

OK, Cancel Reset (. 14.11).


, C o l o r .
<Esc>
Cancel, n u l l .
J C o l o r C h o o s e r .
,
.
J C o l o r C h o o s e r J C o l o r C h o o s e r .
c r e a t e D i a l o g :

572

14. Swing

JColorChooser chooser
JDialog d i a l o g = new
this,
//
" S e l e c t Color",
//
true,
//
chooser,
//
okListener,
//
exitListener);
//

= new JColorChooser();
JColorChooser.createDialog(

, o k L i s t e n e r e x i t L i s t e n e r ,
A c t i o n L i s t e n e r .
, .
d i a l o g . s e t V i s i b l e ( t r u e ) ,
. JColorChooser JDialog,
, showDialog ! JColorChooser.

: JColorChooser.
public JColorChooser()
public JColorChooser(Color initialColor)
JColorChooser
C o l o r . w h i t e .
.

JColorChooser
JColorChooser.
public static Color shewDialog(Component parent, String title, Color initialColor)
,
JColorChooser. t i t l e i n i t i a l C o l o r
.
.
( Color) , ,
Cancel, n u l l .
public static JDialog createDialog(Component parent,
String title,
boolean modal,
JColorChooser chooser,
ActionListener okListener
ActionListener cancelListener)
JDialog, J c o l o r Chooser, .

14.8. JColorChooser

573

.
A c t i o n L i s t e n e r , ,
Cancel.
s e t C o l o r ,
s e t V i s i b l e . :
JColorChooser chooser = new JColorChooser();
JDialog d i a l o g = new J C o l o r C h o o s e r . c r e a t e D i a l o g ( . . . ) ;
chooser.setColor(someColor);
dialog.setVisible(true);
o k L i s t e n e r
getColor.
class okListener implements ActionListener {
public void actionPerformed(ActionEvent e)) {
Color color = chooser.getColor;
repaint();
}
}

public Color getColorO


public void setColor(Color color)
public void setColor(int red, int green, int blue)
public void setColor(int color)
(Color),
JColorChooser. s e t C o l o r ( i n t r e d ,
i n t g r e e n , i n t b l u e ) RGB,
0-255. s e t C o l o r ( i n t c o l o r )
,
i n t .
Color.
14.10 JFrame ,
JColorChooser.
JFrame.
JColorChooser . 14.11.
1 4 . 1 0 . J C o l o r C h o o s e r T e s t . J a v a
import j a v a . a w t . * ;
import J a v a . a w t . e v e n t . * ;
import j a v a x . s w i n g . * ;
/** , JColorChooser.
public c l a s s JColorChooserTest extends JFrame
implements A c t i o n L i s t e n e r {
p u b l i c s t a t i c void m a i n ( S t r i n g [ ] args) {
new J C o l o r C h o o s e r T e s t ( ) ;

*/

574

14. Swing

public JColorChooserTest () {
super("Using JColorChooser");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
JButton colorButton
= new JButton("Choose Background Color");
colorButton.addActionListener(this);
content.add(colorButton);
setSize(300, 100);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// ,
// .
Color bgColor
= JColorChooser.showDialog(this,
"Choose Background Color",
getBackgroundO ) ;
if (bgColor != null)
getContentPane().setBackground(bgColor);
}

^ C h o o s e Background Color
[Switches I 8 RGB

UJJJJJJJJ-

Recent:

dddi
"-"11;

^.

riiBlliH
D

Sample Text Sample Text

D
OK

Cancel

Reset

. 14.11.
JColorChooser

14.9.

575

14.9.
, Windows,
Microsoft PowerPoint, Corel Draw, Borland JBuilder Allaire HomeSite,
, (MDI
Multiple Document Interface). ,
, ,
. ,
.
.
MDI Swing . , J d e s k t o p , , . ,
J I n t e r n a l F r a m e , JFrame ,
JDesktopPane.
J I n t e r n a l F r a m e , ,
, ,
, , .
J I n t e r n a l F r a m e .
,
( ).
, z-: veToFront
moveToBack.

JInternalFrame
J I n t e r n a l F r a m e ,
. , ,
, .
public JInternalFrameO
public JInternalFrame(String title)
public JInternalFrame(String title,
boolean resizable,
boolean closeable,
boolean maximizable,
boolean iconifiable)
, ,
. , )'
, .
.

JInternalFrame

JInternalFrame , JFrame.
.

576

1 4 . Swing

public void setCloseable(boolean closeable)


public void setIconifiable(boolean iconifiable)
public void setMaximizable(boolean maximizable) public void
setResizable(boolean resizable)
. get set- isXxx,
. set P r o p e r t y V e t o E x c e p t i o n .
public String getTitleO
public void setTitle(String title)
g e t T i t l e ,
s e t T i t l e .
public void moveToBack()
public void moveToFrontO
z-
, .
public void show()
public void disposeO
show . ,
.
setBounds ( s e t L o c a t i o n , s e t S i z e ) ,
. , JLayeredPane,
, . d i s p o s e
INTERNAL_FRAME_CLOSED.


.

public void setFrameIcon(Icon image)


,
.
public void addInternalFrameListener(InternalFrameListener listener)
public void removeInternalFrameListener(InternalFrameListener listener)
J I n t e r n a l F r a m e s I n t e r n a l F r a m e E v e n t ,
WindowEvent. I n t e r n a l F r a m e L i s t e n e r
, ,
.

14.9.

internalFrameActivated

internalFrameClosed

internalFrameClosing

internalFrameDeactivated

internalFrameDeiconified

internalFramelconified

internalFrameOpened

577

a d d l n t e r n a l F r a m e L i s t e n e r ,
r e m o v e I n t e r n a l F r a m e L i s t e n e r .
JDesktopPane ,
J I n t e r n a l F r a m e , . g e t A l l F r a m e s
, .
g e t A l l F r a m e s I n L a y e r ( l a y e r )
JDesktopPane.
, 14.11,
, , , JFrame. ,
JDK 1.2 J I n t e r n a l F r a m e , ,
t r u e . JDK 1.3
f a l s e ,
s e t V i s i b l e ( t r u e ) . . 14.12, , . 14.12,6
.

JDK 1,2
true, JDK 1.3 false.

14.11. JlntemalFrames. Java


import java.awt.*;
import Java.awt.event.*;
import javax.swing.*;
/** , . */
public class JInternalFrames extends JFrame {
public static void main(String[] args) {
new JInternalFrames();
public JInternalFrames() {
super("Multiple Document Interface");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.white);

578

14. Swing

JDesktopPane desktop = new JDesktopPane();


desktop.setBackground(Color.white)/
content.add(desktop, BorderLayout.CENTER);
setSize(450, 400);
for(int i=0; i<5; i++) {
JInternalFrame frame
= new JInternalFrame(("Internal Frame " + i ) ,
true, true, true, true);
frame.setLocation(i*50+10, i*50+10);
frame.setSize(200, 150);
frame.setBackground(Color.white);
frame.setVisible(true);
desktop.add(frame)/
frame.moveToFront();
}
setVisible(true);

^ M u l t i p l e Document Interfac

^^^^

'^^.|^!^!^1<1
()

()

. 14.12. Swing- JFrames : ;

14.10. JOptionPane
, J O p t i o n P a n e ,
,
( J O p t i o n P a n e . s h o w M e s s a g e D i a l o g ) , ( J o p t i o n P a n e .
showConf i r m D i a l o g ) , ( J O p t i o n P a n e . ShowI n p u t D i a l o g ) , ( J o p t i o n
P a n e . s h o w O p t i o n D i a l o g ) . i n t , ,
, S t r i n g ,
.

14.10. JOptionPane

579

JOptionPane
J O p t i o n P a n e 26 , 7 59 .
,
.
. , ,
, .
. 14.1 ,
J O p t i o n P a n e .

1 4 . 1 . JOptionPane

PLAINMESSAGE
INFORMATION_MESSAGE
QUESTION_MESSAGE(no )
WARNING_MESSAGE
ERROR_MESSAGE

DE FAULTOPTI ON

OK_CANCEL_OPTION
YES_NO_OPTION
YES_NO_CANCEL_OPTION (no )
,

YES_OPTION
^ 0 OPTION

CANCEL_OPTION
CLOSED_OPTION
public static v o i d s h o w M e s s s a g e D i a l o g ( C o m p o n e n t parent,
Object m e s s a g e ,
String title,
int iconType)
,
, .
, s h o w M e s s s a g e D i a l o g .
, i c o n T y p e .
. 14.1.
, s h o w M e s s s a g e D i a l o g , . 14.13.

580

14. Swing

1)

O'JESUON^^MESSAGE

INFORMATION UBSSf-^""-

(6)1

()
^

showMessageOiidoe ^^!

W^J^N!NOMeSSAGC

()

6RR0P_WESSADEIC0R

oiol

()

. 14.13. ( Windows)
: ;
; ;

PLAINMESSAGE . ,
m e s s a g e S t r i n g .
( O b j e c t ) . J C o m p o n e n t
, I c o n
J L a b e l ,
t o S t r i n g S t r i n g .
public static int s h o w C o n f i r m D i a l o g ( C o m p o n e n t parent,
Object m e s s a g e ,
String title,
int o p t i o n T y p e ,
int i c o n T y p e )
showConf i r m D i a l o g
,
: YES_OPTION, NO_OPTION, CANCEL_OPTION CLOSE_OPTION.
o p t i o n T y p e ( . 14.1) ,
.
. 14.14.

DEFAULT_OPTN

OK_CANCH-_OPTION

()

()

'1?1!1?

YESJtOJ)PJ

I Yes :

()

'

YES_NO_CANCEl._OPTION
Yes

No

()

Cancel I
No

. 14.14. ( Java),
showConfirmDialog: ;
0/1; Yes/No; Yes/No/Cancel

14.10. JOptionPane

581


.
int response =

JOptionPane.showConfirmDialcg
(parentComponent,
"Do you l i k e J a v a ? " ,
"Confirm Dialog Example",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
i f ( r e s p o n s e == JOptionPane.YES_OPTION) {
/ / Y e s .
} e l s e i f ( r e s p o n s e == JOptionPane.NO_OPTION) {
/ / No.
} else {
/ / .
i c o n T y p e , .
p u b l i c static String s h o w I n p u t D i a l o g ( C o m p o n e n t parent,
Object m e s s a g e ,
String title,
int i c o n T y p e )
S h o w I n p u t D i a l o g ,
, , ,
Cancel. . 14.15.
Cancel.
S t r i n g , , .
Cancel,
n u l l . , ,
i c o n T y p e . . 14.1.

. 14.15. (
Motif), s h o w I n p u t D i a l o g

public static Object s h o w I n p u t D i a l o g ( C o m p o n e n t parent,


Object m e s s a g e ,
String title,
int i c o n T y p e ,
Icon icon,
Object[] s e l e c t i o n s .
Object initialSelection)
s h o w I n p u t D i a l o g
.
s e l e c t i o n s , -

582

14. Swing

. S t r i n g ,
, , t o S t r i n g .
20 ,
(. 14.16),
.
i n i t i a l S e l e c t i o n .
, t o S t r i n g .
Cancel,
n u l l . , ,
iconType.
; icon.

Message to appear intM coirAo box


Serulefs
[

OK

I ! CanceJ

. 14.16. (
Java)

public static Object showOptionDialog(Component parent,


Object message,
String title,
int iconType,
Icon image,
Object[] selections,
Object initialSelection)
showOptionDialog
OK Cancel (. 14.17). ,
s e l e c t i o n s JButton, i n i t i a l S e l e c t i o n
, .
s e l e c t i o n s S t r i n g ,
JButton. ,
s e l e c t i o n s :
Object[] s e l e c t i o n s = { "OK,
"Cancel";
new JButton("End Program")

};

s e l e c t i o n s JComponent.
showOptionDialog ,
. , ,
iconType. i c o n
.

?!1?1
Message to appear above options
|8utton1 ii

Bu11on2 1 Buttons |

. 14.17. (
Windows),

1 4 . 1 1 . JToolBar

583

,
s h o w O p t i o n D i a l o g showConf i r m D i a l o g .
, . ,
J P a n e l
J P a n e l .
, ,
J O p t i o n P a n e E x a m p l e s . J a v a .
h t t p : //www. c o r e w e b p r o g r a m m i n g . com/.

14.11. JToolBar
Swing ,
AWT, J T o o l B a r . J T o o l B a r ,

J P a n e l . J T o o l B a r
, "", ..
.
J T o o l B a r
. J T o o l B a r ,
"" , .
J T o o l B a r , (
)

J T o o l B a r . VERTICAL. NORTH
SOUTH , B o r d e r L a y o u t ,
EAST WEST .


NORTH SOUTH BorderLayout,

EAST WEST.

, J T o o l B a r ,
.
J b u t t o n , A c t i o n (
, A c t i o n L i s t e n e r
), J B u t t o n .
, ,
, J B u t t o n .
1. , ,
,
J B u t t o n . s e t M a r g i n ,
.
2. J B u t t o n ,
.
, s e t V e r t i c a l T e x t P o s i t i o n (BOTTOM) s e t HorizontalTextPosition(CENTER).

584

14. Swing

"" JToolBar . 14.18.

1^111||||

. 14.18. "" JToolBar,


JButton insets

14.12.ToolBarButton.Java
import java.awt.*;
import javax.swing.*;
/** , JToolBar.
* , JButton JToolBar
* { Action),
* .
* .
*
.
* JDK 1.3,
* Action, .

V
public class ToolBarButton extends JButton {
private static final Insets margins s=
new Insets(0, 0, 0, 0 ) ;
public ToolBarButton(Icon icon) {
super(icon);
setMargin(margins);
setVerticalTextPosition(BOTTOM);
setHorizontalTextPosition(CENTER);
}
public ToolBarButton(String imageFile) {
this(new Imagelcon(imageFile));
}
public ToolBarButton(String imageFile, String text) {
this(new Imagelcon(imageFile));
setText(text);
}
}

JToolBar
JToolBar :
public JToolBarO
public JToolBar(int orientation)
JToolBar,
.
: HORIZONTAL VERTICAL.

1 4 . 1 1 . JTooiBar

585

JTooiBar
JTooiBar 23 .
.
public JButton add(Action action)
,
, . 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 Performed, ActionEvent).
add A b s t r a c t A c t i o n (
, Action. A b s t r a c t A c t i o n
Icon S t r i n g , ,
. A b s t r a c t A c t i o n :
public class MyApplet extends JApplet{
public void init{
JTooiBar toolbar = new JTooiBar();
toolbar.add(new PrintAction());
getContentPane().add(toolbar,
BorderLayout.WEST);
}
// ,
class PrintAction extends AbstractAction {
public PrintAction() {
super("Print",new Imagelcon("print.gif"));
}
public void actionPerformed(ActionEvent evt) {
System.out.println("Print button selected.");
}
}

J B u t t o n A c t i o n L i s t e n e r
, add (someButton).
, C o n t a i n e r .
JDK 1.2 A c t i o n
, . JDK 1.3
. .

JDK 1.2 Action
, , JDK 1.3
.

^^^^^
|fl|HL
/^
^|||^

586

14. Swing

JDK 1.3 API A c t i o n


, A c t i o n ,
JToolBar.
JToolBar t o o l b a r = new J T o o l B a r ( ) ;
JButton b u t t o n = new J B u t t o n O ;
button.setAction(new PrintAction());
toolbar.add(button);
, .
public void addSeparator()
public void addSeparator(Dimension size)

.
. a d d S e p a r a t o r
Dimension,
.
public void setFloatable(boolean float)
public void setOrientation(int orientation)
s e t F l o a t a b l e , "",
s e t O r i e n t a t i o n . set-
get-, .
, 14.13 14.14,
JFrame,
JToolBar. JToolBar
Web-. ,
, ( JCheckBox).
J B u t t o n . . 14.19 ,
"" ,
"" . ,
, .
14.13.ToolBarExample.Java
import j a v a . a w t . * ;
import j a v a x . s w i n g . * ;
import J a v a . a w t . e v e n t . * ;
/** , JToolBar. */
p u b l i c c l a s s JToolBarExample extends JFrame
implements I t e m L i s t e n e r {
p r i v a t e BrowserToolBar toolbarsp r i v a t e JCheckBox labelBox;
p u b l i c s t a t i c void m a i n ( S t r i n g [ ] args) {
new JToolBarExample();

14.11. JToolBar

}
public JToolBarExample() {
super("JToolBar Example");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.white);
JPanel panel = new JPanel(new BorderLayout());
labelBox = new JCheckBox("Show Text Labels?");
labelBox.setHorizontalAlignment(SwingConstants.CENTER);
labelBox.addltemListener(this);
panel.add(new JTextArea(10,30), BorderLayout.CENTER);
panel.add(labelBox, BorderLayout.SOUTH);
toolbar = new BrowserToolBar();
content.add(toolbar, BorderLayout.NORTH);
content.add(panel, BorderLayout.CENTER);
packO ;
setVisible(true);
}
public void itemStateChanged(ItemEvent event) {
toolbar.setTextLabels(labelBox.isSelected());
packO ;
}
}

14.14,BrowserToolBar.Java
import java.awt.'^;
import javax.swing.*;
/** , JToolBar.
* ,
* Web-.
*
* JButton ToolBarButton. ,
* ,
* ,
* .

V
public class BrowserToolBar extends JToolBar {
public BrowserToolBar() {
String[] imageFiles =
{ "Left.gif", "Right.gif", "RotCCUp.gif",
"TrafficRed.gif", "Home .gif", "Print.gif", "Help.gif"
String[] toolbarLabels =
{ "Back", "Forward", "Reload", "Stop",
"Home", "Print", "Help" };

587

588

14. Swing

Insets margins = new Insets(0, 0, 0, 0 ) ;


for(int i=0; i<toolbarLabels.length; i++) {
ToolBarButton button =
new ToolBarButton("images/" + imageFiles[i] ;
button.setToolTipText(toolbarLabels[i]) ;
button.setMargin(margins);
add(button);
}
}
public void setTextLabels(boolean labelsAreEnabled) {
Component c;
int i = 0;
while((c = getComponentAtIndex(i++)) != null) {
ToolBarButton button = (ToolBarButton)c;
if (labelsAreEnabled) {
button.setText(button.getToolTipText())/
} else {
button.setText(null);
}
}
}

?
1#!&|11

ghSjJyfTiwtLab^^

Exampfe

#
WlfH'fflit'' '^'^-'1*'^^^^11

81Forwaml

\
?!

1>|@1|

" |>>5jexTub^s^

' ishowText Labels'^

. 14.19. JToolBar: "


" ; ""
; "" ;

14.12. JEditorPane

589

14.12. JEditorPane
J E d i t o r P a n e ,
.
J E d i t o r P a n e HTML RTF,
,
. ,
, s e t C o n t e n t T y p e , ,
, s e t E d i t o r K i t .
J E d i t o r P a n e ,
t e x t / h t m l , t e x t / r t f t e x t / p l a i n . ,
, t e x t / p l a i n .
J E d i t o r P a n e
HTML-. J T e x t F i e l d .

JEditorPane.
1. JEditorPane
URL S t r i n g , URL ( Java- URL
). , ,
URL, lOException,
t r y / c a t c h .
2. J E d i t o r P a n e ,
, s e t Page.
URL, S t r i n g ,
. J E d i t o r P a n e ,
s e t P a g e lOException.
,

.
3. J E d i t o r P a n e
s e t T e x t , S t r i n g ,
.
4. read,
I n p u t S t r e a m n HTMLDocument.
J E d i t o r P a n e
, ,
J E d i t o r P a n e .
s e t E d i t a b l e ( f a l s e ) ,
. Swing-, s e t E d i t a b l e ( f a l s e )
.
J E d i t o r P a n e .
String u r l = " h t t p : / / h o s t / p a t h / f i l e . h t m l " ;
try {
JEditorPane htmlPane = new J E d i t o r P a n e ( u r l ) ;
htmlPane.setEditable(false);

590

14. Swing

someWindow.add(new JScrollPane(htmlPane);
} catch(lOException ioe) {
System.err.println("Error displaying " + url);
}

no
, J E d i t o r P a n e
HTML-.
, ,
, J E d i t o r P a n e
.
H y p e r l i n k L i s t e n e r (, H y p e r l i n k L i s t e n e r , H y p e r L i n k L i s t e n e r ) , h y p e r l i n k U p d a t e .
a d d H y p e r l i n k L i s t e n e r .
g e t E v e n t
H y p e r l i n k E v e n t . E v e n t T y p e .ACTIVATED.
Swing, Java 1.2, ,
, .
, , .
public class SomeWindow extends JFrame
implements HyperlinkListener {
private JEditorPane htmlPane;

public void hyperlinkUpdate(HyperlinkEvent event) {


if (event.getEventType() ==
HyperlinkEvent.EventType.ACTIVATED) {
try {
htmlPane.setPage(event.getUIUi ()) ;
} catch(lOException ioe) {
//
}
}

JEditorPane
J E d i t o r P a n e :
public JEditorPaneO
public JEditorPane(String url)
public J E d i t o r P a n e ( U R L url)
public JEditorPane(String m i m e T y p e , String d o c u m e n t )
J E d i t o r P a n e
. URL URL String -

14.12. JEditorPane

591

HTML-,
J E d i t o r P a n e .
lOException. 1-
( t e x t / p l a i n , t e x t / h t m l t e x t / r t f ) .

JEditorPane
Knacca>JEditorPane.
getXxx setXxx.
public String getContentTypeO
public void setContentType(String mimeType)
g e t C o n t e n t T y p e , a s e t C o n t e n t T y p e MIME-.
t e x t / p l a i n , t e x t / h t m l t e x t / r t f .
public String getTextO
public void setText(String document)
, J E d i t o r P a n e ,
. MIME, .
public void replaceSelection(String newText)
r e p l a c e S e l e c t i o n
. ().
n u l l , .
, S t r i n g ,
. ,
. ,
s e t E d i t a b l e ( t r u e ) .
public URL getPageO
public void setPage(String page)
public void setPage(URL url)
g e t Page URL ,
J E d i t o r P a n e . .
URL
. URL.
lOException,
t r y / c a t c h .
public synchronized void addHyperlinkListener(HyperlinkListener listener)
public synchronized void removeHyperlinkListener(HyperlinkListener listener)
a d d H y p e r l i n k L i s t e n e r J E d i t o r P a n e
H y p e r l i n k L i s t e n e r ,
. r e m o v e H y p e r l i n k L i s t e n e r .

592

14. Swing

,
.
public void read(InputStream in, Object description)
JEdi t o r .
HTMLDocument
HTMLEditorKit, .
(JTextComponent)
.

Web-
JEdi tor URL ,
Web-. 14.15 14.16 ,
- .
http://www. corewebprogramming.
com/. . 14.20
(http: //www. jhuapl. edu/rc/).
14,15.Browser.Java
import
import
import
import
import
import

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

/ "Web-",
* Swing. URL, ,
* , ,
* .
V
public class Browser extends JFrame implements HyperlinkListener,
ActionListener {
public static void main(String[] args) {
if (args.length == 0)
new Browser("http://www.corewebprogramming.com/");
else
new Browser(args [0]);
}
private
private
private
private

JIconButton homeButton;
JTextField urlField;
JEditorPane htmlPane;
String initialURL;

public Browser(String initialURL) {


super("Simple Swing Browser");
this.initialURL = initialURL;
addWindowListener(new ExitListener()) ;

14.12. JEditorPane

WindowUtilities.setNativeLookAndFeel();
JPanel topPanel = new JPanelO;
topPanel.setBackground(Color.lightGray) ;
homeButton = new JIconButton("home.gif");
homeButton.addActionListener(this);
JLabel urlLabel = new JLabel("URL:");
urlField = new JTextField(30);
urlField.setText(initialURL) ;
urlField.addActionListener(this);
topPanel.add(homeButton);
topPanel.add(urlLabel);
topPanel.add(urlField);
getContentPane0.add(topPanel, BorderLayout.NORTH);
try {
htmlPane = new JEditorPane(initialURL);
htmlPane.setEditable(false);
htmlPane.addHyperlinkListener(this);
JScrollPane scrollPane new JScrollPane(htmlPane);
getContentPane().add(scrollPane, BorderLayout.CENTER)
} catch(lOException ioe) {
warnUser("Can't build HTML pane for " + initialURL
+ ": " + ioe);
}
Dimension screenSize = getToolkit().getScreenSize();
int width = screenSize.width * 8 / 10;
int height = screenSize.height * 8 / 10;
setBounds(width/8, height/8, width, height);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
String url;
if (event.getSource () == urlField) {
url = urlField.getText0;
} else { // Clicked "home" button instead of entering URL.
url = initialURL;
}
try {
htmlPane.setPage(new URL(url));
urlField.setText(url);
} catch(lOException ioe) {
warnUser("Can't follow link to " + url + ": " + ioe);
}
}
public void hyperlinkUpdate(HyperlinkEvent event) {
if (event.getEventType 0 ==
HyperlinkEvent.EventType.ACTIVATED) {
try {
htmlPane.setPage(event.getURL());
urlField.setText(event.getURL().toExternalForm());
} catch(lOException ioe) {
warnUser("Can't follow link to "

+ event.getUIUiO.toExternalForm0

+ ": " + ioe)

593

594

14. Swing

private void warnUser(String message) {


JOptionPane.ShowMessageDialog(this, message, "Error",
JOptionPane.ERROR_MESSAGE);
}

14.16.JIconButton.Java
import javax.swing.^;
/** JButton Imagelcon */
public class JIconButton extends JButton
public JIconButton(String file) {
super(new Imagelcon(file));
setContentAreaFilled(false);
setBorderPainted(false);
setFocusPainted(false);
}
}

Simple Swing Browser


URL' jhttp/Awwwjhuapl ecJu/rc/

The Milion S. Eisenhower

Research & Technology


Development Center

APL scientists work at the frontiers of many research fields to support


technical program needs. Research Is performed in all of APL's technical
departments. However, the Milton S. Eisenhower Research and Technology
Development Center (RTDC) Is dedicated to basic and applied research in
support of APL's mission. In addition to nurturing scientifically based,
in-house expertise In newly developing areas, the RTDC provides a window
into science for APL. The RTDC contains numerous highly specialized
laboratories and conducts research programs in a number of broad areas.

Jj

. 14.20. ,
Swing. JEditorPane HTML

14.13. Swing-

595

HTML JavaHelp
J E d i t o r P a n e
HTML 4.0. , ,
, HTML- J E d i t o r P a n e ,
.
, HTML-, .
J E d i t o r P a n e ,
HTML-,
. . Sun
JavaHelp,
. JavaHelp
h t t p : / / J a v a . s u n . c o m / p r o j e c t s / j a v a h e l p / .

14.13. Swing-
, ,
Swing-, AWT-: J C h e c k B o x ,
J R a d i o B u t t o n , J T e x t F i e l d J T e x t A r e a . ,
J F i l e C h o o s e r , .
(Kim
Topley) CoreJava Foundation Classes.

JCheckBox
Swing- JCheckBox (
JCheckBox) , AWT- Checkbox.
A c t i o n L i s t e n e r I t e m L i s t e n e r .
A c t i o n L i s t e n e r i s S e l e c t e d ,
. I t e m L i s t e n e r I t e m E v e n t
; JCheckBox,
g e t S t a t e C h a n g e
I t e m E v e n t . SELECTED I t e m E v e n t . DESELECTED. ,
JCheckBox ,
s e t C o n t e n t A r e a F i l l e d ( f a l s e ) . ,
, ( s e t l c o n ) . ,
,
( s e t S e l e c t e d l c o n ) . 14.17
I t e m L i s t e n e r A c t i o n L i s t e n e r .
.
J C h e c k B o x T e s t . J a v a . 14.21.

596

14. Swing

14.17. JCheclcBoxTest. Java


import javax.swing.*;
import java.awt.event.*;
public class JCheckBoxTest extends JPanel
implements ItemListener,
ActionListener{
JCheckBox checkBoxl, checkBox2;
public JCheckBoxTest0 {
checkBoxl = new JCheckBox("Java Servlets");
checkBox2 = new JCheckBox("JavaServer Pages");
checkBoxl.setContentAreaFilled(false);
checkBox2.setContentAreaFilled(false);
checkBoxl.addltemListener(this);
checkBox2.addActionListener(this);
add(checkBoxl);
add(checkBox2) ;
}
public void actionPerformed(ActionEvent event) {
System.out.println("JavaServer Pages selected; " +
checkBox2.isSelected() ) ;
}
public void itemStateChanged(ItemEvent event) {
JCheckBox checkbox = (JCheckBox)event.getltem();
if (event.getStateChange0 == ItemEvent.SELECTED) {
System, out .println (checkbox. getText () -f- " selected.");
} else {
System.out.println(checkbox.getText() + " deselected.");
}
}
public static void main(String[] args) {
JPanel panel = new JCheckBoxTest();
WindowUtilities.setNativeLookAndFeel();
WindowUtilities.openlnJFrame(panel, 300, 7 5 ) ;
}

. 14.21. JCheckBox

14.13. Swmg-

597

JRadioButton
Swing- JRadioButton AWT- Checkbox,
CheckboxGroup.
JRadioButtons, ButtonGroup.
, ButtonGroup, .
JCheckBox,
A c t i o n L i s t e n e r I t e m L i s t e n e r . , ,
ActionEvent ItemEvent, ,
, ItemEvent.
, JRadioButton ,
s e t C o n t e n t A r e a F i l l e d ( f a l s e ) . JCheckBox,
, ,
( s e t Icon). ,
( s e t S e l e c t e d l c o n ) .
, , 14.18,
. 14.22.
14.18. JRadioButtonTest. Java
import j a v a x . s w i n g . J R a d i o B u t t o n ;
import javax.swing.ButtonGroup;
import j a v a . a w t . * ;
import J a v a . a w t . e v e n t . * ;
import j a v a x . s w i n g . * ;
p u b l i c c l a s s JRadioButtonTest extends JPanel
implements I t e m L i s t e n e r
public JRadioButtonTest0 {
S t r i n g [ ] l a b e l s = {"Java Swing","Java S e r v l e t s " ,
"JavaServer Pages"};
JRadioButton[] b u t t o n s = new J R a d i o B u t t o n [ 3 ] ;
ButtonGroup group = new ButtonGroup();
f o r ( i n t i=0; i < b u t t o n s . l e n g t h ; i++) {
b u t t o n s [ i ] = new J R a d i o B u t t o n ( l a b e l s [ i ] ) ;
buttons[i].setContentAreaFilled(false);
buttons[i].addltemListener(this);
group.add(buttons[i]);
add(buttons[i]);
}

public void itemStateChanged(ItemEvent event) {


JRadioButton radiobutton = (JRadioButton)event.getltem();
if (event.getStateChange0 == ItemEvent.SELECTED) {
System.out.println(radiobutton.getText() + " selected.");
} else {
System.out.println(radiobutton.getText() + " deselected.")

598

14. Swing

public static void main(String[] args) {


JPanel panel = new JRadioButtonTest();
WindowUtilities.setNativeLookAndFeel();
WindowUtilities.openlnJFrame(panel, 400, 75);

Java Swing

^ SeryletS

javaServer Pages

. 14.22. J R a d i o B u t t o n

JTextField
Swing- J T e x t F i e l d
AWT- T e x t F i e I d .
, . T e x t F i e I d ,
J T e x t F i e l d , ,
s e t T e x t , s e t C o l u m n s s e t H o r i z o n t a l A l i g n m e n t .
J T e x t F i e l d . LEFT, J T e x t F i e l d . CENTER
J T e x t F i e l d . R I G H T . g e t T e x t .
<Enter> A c t i o n E v e n t ,
D o c u m e n t E v e n t . ^, J T e x t F i e l d
, J P a s s w o r d F i e l d .

JTextArea
Swing- J T e x t A r e a AWT- T e x t A r e a
. -, J T e x t A r e a
. Swing-,
J S c r o l l P a n e . -, J T e x t A r e a
J E d i t o r P a n e ,
. , J E d i t o r P a n e HTML- RTF.

JFileChooser
J F i l e C h o o s e r (. 14.23)
, .
J F i l e C h o o s e r
S t r i n g , ( "." )^ ).
, ( s e t S e l e c t e d F i l e ) , (
F i l e F i l t e r ).

14.13. Swing-

599

s e t D i a l o g T i t l e . ,
s h o w O p e n D i a l o g s h o w S a v e D i a l o g ,
. , ,
.
J F i l e C h o o s e r . APPROVEOPTION, ,
Cancel. ,
g e t S e l e c t e d F i l e . :
JFileChooser chooser = new JFileChooser(".");
int result = chooser.ShowOpenDialog(parent);
File file = chooser.getSelectedFile();
if (file != null &&
result == JFileChooser.APPROVE_OPTION) {
//
}
s e t M u l t i S e l e c t i o n E n a b l e d ( t r u e ) ,
. g e t S e l e c t e d F i l e s
F i l e .

[
LOOK in

\....> >

!J...J Allaire

" ^ MMi
"3

L J BACKUP
1, JBDK1.1
1 .iCDROM

i-J

111..^.1.-^1^^
Ftlenantic;

|t"-WP 2na-Edition

Fites of type

\>\\\ Fnes "i

d.

Canc^et 1

. 14.23. J F i l e C h o o s e r


JComponent B o r d e r ,
. s e t B o r d e r .
, ,
. ,
s e t T o o l T i p T e x t .

14-14.
Swing-,
AWT: J L a b e l , J B u t t o n , J S l i d e r , J P a n e l , J A p p l e t J F r a m e . ,
, Swing, J C o l o r C h o o s e r ,
J O p t i o n P a n e J I n t e r n a l F r a m e . Swing-, ,
Java-.
J F r a m e J A p p l e t J P a n e l ,
. J F r a m e J A p p l e t
BorderLayout.
Swing- .
, , -

600

14. Swing

. ,
. HTML-.

;
. JOpt ion
, ,
, .
JColorChooser .
Swing API.
J L i s t , JTree
JTable.
, . ,
, Java-
.


SWING
...

J L i s t
.

,
J L i s t .
JTree.

,
J T r e e .

JTable .

JTable.

Swing- .

Swing- .

J^y\zJsJ:J

,
: J L i s t , J T r e e J T a b l e . Swing
AWT- L i s t , ,
, J L i s t .
J T r e e J T a b l e AWT-. J T r e e
.
, .
J T a b l e .
*'--",
.
, , .
,
.
J L a b e l .
, ,
.
,
Swing,
.
: Swing
. G r a p h i c s 2D, 10,
. ,
,
, Swing-.
AWT Swing-
. Swing-
UI-,
. Swing- ,
.

604

15. Swing

Swing- , .
r u n R u n n a b l e
.
, ,
Java 2.
, Swing- JAR-,
Java Plug-In.

1 5 . 1 .

Swing-
. ;
, , ,
. Swing
. , Swing .
, ;
.
J L i s t , J T r e e J T a b l e
. , J L i s t S t r i n g
I c o n ,
t o S t r i n g , J L a b e l . . Swing

, J L i s t .
, ,
" ",
J L i s t , (, ,
).
J C o m p o n e n t .
,
J L i s t .
J T r e e J T a b l e .

15.2. JList
J L i s t ,
. J L i s t .
;
J L i s t .
, . ,
,
. , ,
, ,
J C o m p o n e n t .

15.2. JList

605

JList
J L i s t ,
. AWT- L i s t , J L i s t
.
ListModel, .

;
, .
S t r i n g [ ] o p t i o n s = { "Option 1", . . . , "Option N" };
J L i s t o p t i o n L i s t = new J L i s t ( o p t i o n s ) ;
s e t V i s i b l e RowCount. , J L i s t .
Swing, J S c r o l l P a n e .
optionList.setVisibleRowCount(4);
JScrollPane optionPane = new JScrollPane(optionList);
someContainer.add(optionPane);

J L i s t L i s t S e l e c t i o n E v e n t ,
L i s t S e l e c t i o n L i s t e n e r ,
valueChanged. ,
. ,
, ,
. g e t V a l u e l s A d j u s t i n g L i s t S e l e c t i o n
Event true,
, ,
f a l s e .
,
, g e t S e l e c t e d V a l u e g e t S e l e c t e d l n d e x .
JList ,
s e t S e l e c t i o n M o d e .
: SINGLESELECTION,
SINGLE_INTERVAL_SELECTION MULTIPLE_INTERVAL_SELECTION.
g e t S e l e c t e d V a l u e s
g e t S e l e c t e d l n d i c e s . J L i s t .
p u b l i c c l a s s SomeClass {
private JList optionList;
p u b l i c void someMethod() {
MyListListener l i s t e n e r = new M y L i s t L i s t e n e r ( ) ;
optionList.addListSelectionListener(listener);
}

p r i v a t e c l a s s MyListListener
implements L i s t S e l e c t i o n L i s t e n e r {
p u b l i c void v a l u e C h a n g e d ( L i s t S e l e c t i o n E v e n t event) {

606

15. Swing

//
//
//
if

.
getValuelsAdjusting
false,
(!event.getValuelsAdjusting) {
String selection =
optionList.getSelectedValue{);
doSomethingWith(selection);

}
}

,
, g e t V a l u e l s A d j u s t i n g L i s t S e l e c t i o n E v e n t
, f a l s e . ,
, , .



ListSelectionEvent.
, ,
getValuelsAdjusting
false.

JList
J L i s t :
p u b l i c JList()
p u b l i c JList(Object[] data)
p u b l i c JList(Vector data)
p u b l i c JList(ListModel m o d e l )
J L i s t , .
,
V e c t o r .
L i s t M o d e l , ,
.

JList
J L i s t 60 . ,
, .
public void clearSelection()
.
p u b l i c L i s t M o d e l getModel()
p u b l i c void s e t M o d e l ( L i s t M o d e l m o d e l )
g e t M o d e l , ,
. s e t M o d e l .

15.2. JList

607

public int getSelectedIndex()


public int[] getSelectedlndicesO
g e t S e l e c t e d l n d e x
. g e t S e l e c t e d l n d i c e s ,
.
public Object getSelectedValue()
public Object[] getSelectedValuesO
g e t S e l e c t e d V a l u e .
g e t S e l e c t e d V a l u e s Object,
.
public int getSelectionModeO
public setSelectionMode(int mode)
g e t S e l e c t i o n M o d e , a s e t S e l e c t i o n M o d e
. :
ListSelectionModel.SINGLE_SELECTION,
ListSelectionModel.SINGLE_INTERVAL_SELECTION
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION.

public boolean getValuelsAdjustingO


L i s t S e l e c t i o n E v e n t :
, (
) (
). g e t V a l u e l s A d j u s t i n g
t r u e , ( ,
) f a l s e .
public int getVisibleRowCountO
public void setVisibleRowCount(int rows)
getVisibleRowCount , a setVisibleRowCount
.
public boolean isSelectedIndex(int index)
t r u e , .
f a l s e .
15.1 , J L i s t ,
, .
, J L i s t ,
(. 15.1). W i n d o w U t i l i t i e s E x i t L i s t e n e r
14. , ,
, h t t p : //www. corewebprograrraning.com/.

608

15. Swing

15.1. JListSimpleExample. Java


import
import
import
import

java.awt.*;
javax.swing.*;
javax.swing.event.*;
javax.swing.border.*;

/** Simple JList example illustrating


* <UL>
* <LI>Coae JList;
* JList
* <LI> .
* </UL>
public class JListSimpleExample extends JFrame {
public static void main(String[] args) {
new JListSimpleExample0;
}
private JList sampleJList;
private JTextField valueField;
public JListSimpleExample() {
super("Creating a Simple JList");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
// JList, ,
//
// JScrollPane.
String[] entries = { "Entry 1", "Entry 2", "Entry 3",
"Entry 4", "Entry 5", "Entry 6" };
sampleJList = new JList(entries);
sampleJList.setVisibleRowCount(4);
sampleJList.addListSelectionListener(new ValueReporter());
JScrollPane listPane = new JScrollPane(sampleJList);
Font displayFont = new Font("Serif", Font.BOLD, 18);
sampleJList.setFont(displayFont);
JPanel listPanel = new JPanelO;
listPanel.setBackground(Color.white);
Border listPanelBorder =
BorderFactory.createTitledBorder("Sample JList");
listPanel.setBorder(listPanelBorder);
listPanel.add(listPane);
content.add(listPanel, BorderLayout.CENTER);
JLabel valueLabel = new JLabel("Last Selection:");
valueLabel.setFont(displayFont);
valueField = new JTextField("None", 7 ) ;
valueField.setFont(displayFont);
valueField.setEditable(false) ;
JPanel valuePanel = new JPanelO;
valuePanel.setBackground(Color.white);

15.2. JList

609

Border valuePanelBorder =
BorderFactory.createTitledBorder("JList Selection")
valuePanel.setBorder(valuePanelBorder);
valuePanel.add(valueLabel) ;
valuePanel.add(valueField) ;
content.add(valuePanel, BorderLayout.SOUTH);
packO ;
setVisible(true);
private class ValueReporter implements ListSelectionListener {
/**
* .
* , ,
* .
* getValuelsAdjusting
* true; .
public void valueChanged(ListSelectionEvent event) {
if (!event.getValuelsAdjusting()) {
Object value = sampleJList.getSelectedValue();
if (value != null) {
valueField.setText(value.toString());
}
}

Sample JList

Entry 1 '

Entry!
Entry 4jrj
JList Selection

Last Selection: JEntry 5

. 15.1. JList

JList
J L i s t ,
DefaultListModel, . D e f a u l t L i s t M o d e l
, j a v a . u t i l . Vector,
, .
, J L i s t .
DefaultListModel J L i s t .

610

15. Swing

J L i s t
. ,
V e c t o r . :
S t r i n g c h o i c e s = { "Choice 1", . . . , "Choice N " } ;
D e f a u l t L i s t M o d e l sampleModel = new D e f a u l t L i s t M o d e l ( ) ;
f o r ( i n t i = 0 ; i < c h o i c e s . l e n g t h ; i++) {
sampleModel.addElement(choices[i]);
}

J L i s t o p t i o n L i s t = new J L i s t ( s a m p l e M o d e l ) ;
a d d E l e m e n t , r e m o v e ( i n d e x )
.
,
, J L i s t , r e v a l i d a t e v a l i d a t e .
15.2 J L i s t
D e f a u l t L i s t M o d e l , .
J B u t t o n , A c t i o n L i s t e n e r ,
I t e m A d d e r . a c t i o n P e r f o r m e d
,
r e v a l i d a t e , J L i s t .
. 15.2.
1 5 . 2 . D e f a u l t L i s t M o d e l E x a m p l e . j a v a
import
import
import
import
/**
*
*
*
*
*
*
*

java.awt.*;
Java.awt.event.*;
javax.swing.*;
javax.swing.border.*;

J L i s t ,
<UL>
<LI>Coae JList DefaultListModel,

JList.
<LI>oaee
( , DefaultListModel)
</UL>

public class DefaultListModelExample extends JFrame {


public static void main(String[] args) {
new DefaultListModelExample0;
}
JList sampleJList;
private DefaultListModel sampleModel;
public DefaultListModelExample() {
super("Creating a Simple JList");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();

15.2. JList

string[] entries = { "Entry 1", "Entry 2", "Entry 3",


"Entry 4", "Entry 5", "Entry 6" };
sampleModel = new DefaultListModel();
for(int i=0; i<entries.length; i++) {
sampleModel.addElement(entries[i]);
}
sampleJList = new JList(sampleModel);
sampleJList.setVisibleRowCount(4);
Font displayFont = new Font("Serif", Font.BOLD, 18);
sampleJList.setFont(displayFont);
JScrollPane listPane = new JScrollPane(sampleJList);
JPanel listPanel = new JPanelO;
listPanel.setBackground(Color.white);
Border listPanelBorder =
BorderFactory.createTitledBorder("Sample JList");
listPanel.setBorder(listPanelBorder);
listPanel.add(listPane);
content.add(listPanel, BorderLayout.CENTER);
JButton addButton =
new JButton("Add Entry to Bottom of JList");
addButton.setFont(displayFont);
addButton.addActionListener(new ItemAdder());
JPanel buttonPanel = new JPanelO;
buttonPanel.setBackground(Color.white);
Border buttonPanelBorder =
BorderFactory.createTitledBorder("Adding Entries");
buttonPanel.setBorder(buttonPanelBorder);
buttonPanel.add(addButton);
content.add(buttonPanel, BorderLayout.SOUTH);
pack () ;
setVisible(true);
private class ItemAdder implements ActionListener {
/** ListModel
* . ,
* (, "Entry 10" "Entry 9"),
* .
* <1></1> .

V
public void actionPerformed(ActionEvent event) {
int index = sampleModel.getSize();
sampleModel.addElement("Entry " + (index+1));
((JComponent)getContentPane()).revalidate();
sampleJList.setSelectedlndex(index);
sampleJList.ensurelndexIsVisible(index);
}

611

612

15. Swing

Sample JLIst

Entry 1 0 ^
Entry 11
[Entry 12 I

Adding Entries

[ Add Entry to Bottom of J l i s t


I iTi T imi i-^mtri r

. 15.2. D e f a u l t L i s t M o d e l
J L i s t

JList

,
, .
,
. J L i s t ,
, ,
ListModel.

ListModel
public Object getElementAt(int index)
, .
public int getSizeO
.
public void addListDataListener(ListDataListener listener)
a d d L i s t D a t a L i s t e n e r ,
,
.
public void removeListDataListener(ListDataListener listener)
.
15.3 J L i s t ,
. J a v a L o c a t i o n ,
"Java".
JavaLocationModel,
15.4. ListModel
.
J L i s t , J l i s t CustomModel ( 15.3).

15.2. JList

613

J a v a L o c a t i o n C o l l e c t i o n ( 15.5)
J a v a L o c a t i o n ( 15.6). J a v a L o c a t i o n
"Java", ,
, , .
. 15.3.
15.3. JListCustomModel. Java
import
import

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

/** J L i s t ,
* ListModel,
* (JavaLocationListModel).
public class JListCustomModel extends JFrame {
public static void main(String[] args) {
new JListCustomModel0;
}
public JListCustomModel() {
superC'JList with a Custom Data Model");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
JavaLocationCollection collection =
new JavaLocationCollectionO ;
JavaLocationListModel listModel =
new JavaLocationListModel(collection);
JList sampleJList = new JList(listModel);
Font displayFont = new Font("Serif", Font.BOLD, 18);
sampleJList.setFont(displayFont);
content.add(sampleJList);
packO ;
setVisible(true);

15.4.JavaLocationListModel.Java
import javax.swing.*;
import javax.swing.event.*;
/** , ListModel.
* ,
* ,
* AbstractListModel
* .

V
public class JavaLocationListModel implements ListModel {

614

15. Swing

private JavaLocationCollection collection;


public JavaLocationListModel(JavaLocationCollection collection)
{
this.collection = collection;
}
public Object getElementAt(int index) {
return(collection.getLocations0 [index]);
}
public int getSizeO {
return(collection.getLocations().length);
}
public void addListDataListener(ListDataListener 1) {}
public void removeListDataListener(ListDataListener 1) {}

15.5. JavaLocationCollection.Java
/** , JavaLocation,
* , ,
* .
public class JavaLocationCollection {
private static JavaLocation[] defaultLocations =
{ new JavaLocation("Belgium",
"near Liege",
"flags/belgium.gif") ,
new JavaLocation("Brazil",
"near Salvador",
"flags/brazil.gif") ,
new JavaLocation("Colombia",
"near Bogota",
"flags/colombia.gif") ,
new JavaLocation("Indonesia",
"main island",
"flags/indonesia.gif") ,
new JavaLocation("Jamaica",
"near Spanish Town",
"flags/Jamaica.gif") ,
new JavaLocation("Mozambique",
"near Sofala",
"flags/mozambique.gif") ,
new JavaLocation("Philippines",
"near Quezon City",
"flags/philippines.gif") ,
new JavaLocation("Sao Tome",
"near Santa Cruz",
"flags/saotome.gif") ,

15.2. JList

new JavaLocation("Spain",
"near Viana de Bolo",
"flags/spain.gif"),
new JavaLocation("Suriname",
"near Paramibo",
"flags/suriname.gif"),
new JavaLocation("United States",
"near Montgomery, Alabama",
"flags/usa.gif"),
new JavaLocation("United States",
"near Needles, California",
"flags/usa.gif"),
new JavaLocation("United States",
"near Dallas, Texas",
"flags/usa.gif")
};
private JavaLocation[] locations;
private int numCountries;
public JavaLocationCollection(JavaLocation[] locations) {
this.locations = locations;
this.numCountries = countCountries(locations);
}
public JavaLocationCollection() {
this(defaultLocations);
}
public JavaLocation[] getLocations() {
return(locations);
}
public int getNumCountries() {
return(numCountries);
}
// , .
// , ,
private int countCountries(JavaLocation[] locations) {
int n = 0;
String currentCountry, previousCountry = "None";
for(int i=0;i<locations.length;i++) {
currentCountry = locations[i].getCountry();
if (IpreviousCountry.equals(currentCountry)) {
n++;
}
currentCountry = previousCountry;
}
return(n);

615

616

15. Swing

15.6.JavaLocation.Java
/** , : country,
* comment flagFile. ,
* ,
* "Java," ,
* ,
* .
* , ,
* , JList.

V
public class JavaLocation {
private String country, comment, flagFile;
public JavaLocation(String country. String comment.
String flagFile) {
setCountry(country);
setComment(comment);
setFlagFile(flagFile);
}
/ , */
public String toStringO {
return("Java, " + getCountryO

+ " (" + getComment() + ").")

/** ,
"Java." */
public String getCountryO {
return(country);
/** ,
"Java." */
public void setCountry(String country) {
this.country = country;
}
/**
*
*
*
*/

,

"Java".
" < >".

public String getComment() {


return(comment);
}
/** ,

"Java". */

15.2. JList

617

public void setCoiranent(String comment) {


this.comment = comment;
/**
. */
public String getFlagFile{) {
return(flagFile) ;
/**
. */
public void setFlagFile(String flagFile) {
this.flagFile = flagFile;
}

Java Belgimn (near Liege).


Java Brazil (near Salvador).
Java Colombia (near Bogota).
Java. Indonesia (hiain island).
Java Jamaica (near Spanish Town).
Java Mozambique (near Sofala).
Java HdUppines (near Quezon City).
Java Sao Tome (near Santa Cruz).
Java Spain (near Viana de Bolo).
Java Suriname (near Paramibo).
Java United States (near Montgomery, Alabama).
Java, United States (near Needles, California).
Java United States (near Dallas, Texas).

. 15.3. J L i s t ,
, ,
,

JList ,

J L i s t ,
, ,
.
J L a b e l ,
. Icon, J L a b e l
. , ,
,
L i s t C e l l R e n d e r e r ,
J L i s t .

618

15. Swing

ListCellRenderer
L i s t C e l l R e n d e r e r g e t L i s t CellRendererComponent.
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
g e t L i s t C e l l R e n d e r e r C o m p o n e n t ,
(value), ,
J L i s t . J L i s t .
, ,
(, ),
.
, , .. , ,
, .
, Java 2 Platform
Def a u l t L i s t C e l l R e n d e r e r , L i s t C e l l R e n d e r e r .
Def a u l t L i s t C e l l R e n d e r e r JLabel.

,
"Java". ,

, . 15.8 J a v a L o c a t i o n Renderer, L i s t C e l l R e n d e r e r . g e t L i s t C e l l
RendererComponent ,
J a v a L o c a t i o n , J L a b e l . J L i s t
s e t C e l l R e n d e r e r ( 15.7).
15.7.JListCustomRenderer.Java
import j a v a . a w t . * ;
import j a v a x . s w i n g . * ;
/** J L i s t ,
* ,
*
(JavaLocationRenderer).

V
p u b l i c c l a s s JListCustomRenderer extends JFrame {
p u b l i c s t a t i c void m a i n ( S t r i n g [ ] args) {
new J L i s t C u s t o m R e n d e r e r 0 ;
p u b l i c JListCustomRenderer() {
s u p e r ( " J L i s t with a Custom Cell Renderer")
WindowUtilities.setNativeLookAndFeel();

15.2. JList

619

addWindowListener(new ExitListener());
Container content = getContentPane();
JavaLocationCollection collection =
new JavaLocationCollection0;
JavaLocationListModel listModel =
new JavaLocationListModel(collection);
JList sampleJList = new JList(listModel);
sampleJList.setCellRenderer(new JavaLocationRenderer())
Font displayFont = new Font("Serif", Font.BOLD, 18);
sampleJList.setFont(displayFont);
content.add(sampleJList) ;
packO ;
setVisible(true) ;
}
}

,
, ..,
D e f a u l t L i s t C e l l R e n d e r e r ( L i s t C e l l R e n d e r e r )
J L a b e l ,
. , 15.8 , )^ J L a b e l ,
s u p e r . g e t L i s t C e l l R e n d e r e r , I c o n . ,
J L a b e l . ,
g e t L i s t C e l l R e n d e r e r C o m p o n e n t ,

, .

J L a b e l Image I c o n .
, -, Image I c o n
J a v a L o c a t i o n . J a v a L o c a t i o n
, Image I c o n , .
J L i s t ,
, , . 15.4.'
1 5 . 8 . J a v a L o c a t i o n R e n d e r e r . J a v a
import
import
import

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

/** .
* " " .
* ,
*
* . ,
* J L a b e l ,
* .
* <>
*

620

*
*
*
*
*
*
*
*
*
*
*
*
*

15. Swing

.
Imagelcon,
- Hashtable,
. ,
, .
<>
JDK 1.2 ,
, :
.
, Imagelcon,
JList .
, value
JavaLocation, .

public class JavaLocationRenderer extends


DefaultListCellRenderer {
private Hashtable iconTable = new Hashtable();
public Component getListCellRendererComponent(JList list.
Object value,
int index,
boolean isSelected,
boolean hasFocus) {
// JLabel, ,
// .
JLabel label =
(JLabel)super.getListCellRendererComponent(list,
value,
index,
isSelected,
hasFocus) ;
if (value instanceof JavaLocation) {
JavaLocation location = (JavaLocation)value;
Imagelcon icon = (Imagelcon)iconTable.get(value);
if (icon == null) {
icon = new Imagelcon(location.getFlagFile0);
iconTable.put: (value, icon) ;
}
label.setlcon(icon);
} else {
// ;
// JDK 1.2.
label.setlcon(null);
}
return(label);
}

15.3. JTree

621

Java, Belfiiini (near Liege).


^ Java, Brazil (near Salvador).
I M H J Java, Colombia (near Bogota).
Java, Indonesia (nniin island).
j ^ l Java, Jamaica (near Spanish Town).
N H H Java, Mozambique (near Sofala).
Java, Philippines (near Quezon City).
Java, Sao Tome (near Santa Cruz).
Java, Spain (near Viana de Bolo).
Java, Suriname (near Paramibo).
Java, United States (near Montgomery, Alabama).
Java, United States (near Needles, California).
Java, United States (near Dallas, Texas).

15.3.

. 15.4. JList

.
Swing-

JTree

J T r e e ()
. JTree,
, ,
, (,
), , ,
, , .

JTree
JTree
Def aultMutableTreeNode, .
, , .
, .
, De f a u l t t a b l e TreeNode , " ".
S t r i n g ,
t o S t r i n g .
, ,
parentNode . add (childNode).
JTree. -

622

15. Swing

( ), JTree
JScrollPane. , ,
.
DefaultMutableTreeNode root =
new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode childl =
new DefaultMutableTreeNode("Child 1"};
root.add(childl);
DefaultMutableTreeNode child2 =
new DefaultMutableTreeNode("Child 2 " ) ;
root.add(child2);
JTree tree = new JTree(root);
someWindow.add(new JScrollPane(tree));
,
.
, , ,
.

DefaultMutableTreeNode
D e f a u l t M u t a b l e T r e e N o d e :
public D e f a u l t M u t a b l e T r e e N o d e ( )
public D e f a u l t M u t a b l e T r e e N o d e ( O b j e c t data)
public D e f a u l t M u t a b l e T r e e N o d e ( O b j e c t data, b o o l e a n allowChildren)
Bee .
"" , .
.
, .
.
D e f a u l t M u t a b l e T r e e N o d e
D e f a u l t M u t a b l e T r e e N o d e 50 ,
,
.
.
public void a d d ( M u t a b l e T r e e N o d e child)
public void r e m o v e ( M u t a b l e T r e e N o d e child)

.
public E n u m e r a t i o n children()
c h i l d r e n E n u m e r a t i o n ,
. ,
n u l l .

1 5 , 3 . JTree

623

public int getChildCountO


g e t C h i l d C o u n t
.
public TreeNode getParent()
public TreeNode getRoot()
g e t P a r e n t , .
, n u l l .
getRoot , .
public boolean isLeaf()
public boolean isRoot()
,
.
public void removeAllChildrenO
r e m o v e A l l C h i l d r e n .
15.9 , ,
, .
p r o c e s s H i e r a r c h y .
( i n s t a n c e o f O b j e c t [ ] ) ,
p r o c e s s H i e r a r c h y . . 15.5,
, . 15.5,6 .

15.9.SimpleTree.Java
import j ava . awt.''^;
import j a v a x . s w i n g . * ;
import j a v a x . s w i n g . t r e e . * ;
/** ,
DefaultMutableTreeNode. */
p u b l i c c l a s s SimpleTree extends JFrame {
p u b l i c s t a t i c void m a i n ( S t r i n g [ ] args) {
new S i m p l e T r e e ( ) ;
}

p u b l i c SimpleTree0 {
s u p e r ( " C r e a t i n g a Simple J T r e e " ) ;
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new E x i t L i s t e n e r ( ) ) ;
Container c o n t e n t = g e t C o n t e n t P a n e ( ) ;
Object[] h i e r a r c h y =
{ "javax.swing",
"javax.swing.border",
"javax.swing.colorchooser",

624

15. Swing

"j avax.swing.event",
"javax.swing.filechooser",
new Object[] { "javax.swing.plaf",
"javax.swing.plaf.basic",
"javax.swing.plaf.metal",
"javax.swing.plaf.multi" ) ,
"javax.swing.table",
new Object[] { "javax.swing.text",
new Object[] { "javax.swing.text.html".
j avax.swing.text.html.parser" },
"javax.swing.text.rtf" },
"javax.swing.tree"
"javax.swing.undo" };
DefaultMutableTreeNode root processHierarchy(hierarchy);
JTree tree = new JTree(root);
content.add(new JScrollPane(tree), BorderLayout.CENTER);
setSize(275, 300);
setVisible(true);

}\
/** ,
* .
* ,
* .
* , , , .

V
private DefaultMutableTreeNode processHierarchy(
Object[] hierarchy) {
DefaultMutableTreeNode node =
new DefaultMutableTreeNode(hierarchy[0]);
DefaultMutableTreeNode child;
for(int i=l; i<hierarchy.length; i++) {
Object nodeSpecifier = hierarchy[i];
if (nodeSpecifier instanceof Object[]) { //Node with children
child = processHierarchy((Object[])nodeSpecifier);
} else {
child = new DefaultMutableTreeNode(nodeSpecifier); //Leaf
}
node.add(child);
}
return(node);

15.3.JTree

625

|fflflHI'l,ll.|[|IHIilMli>mtM^Msi
:1J javax. swing
' javax.swing.border
javax svvlng.colorchooser
' javax.swing.event
[ javax.8wing.filechooser
if lJi9vax.swing.plaf
I javaxswing.table
s- _I;j javax.swing.text
i javax.swlng.tree
' javaxswlng.undo

(a)

. J javax swing
javax.swing.border
lavaxswing.coiorchooser
javax swing.event
% javax.swJng.mechooser
1 javax.8wing.plaf
javax.swingplafbasic
javax.swing.plafmetal
javax.swlng.plafmulti
# javaxswing.table
- ^ javax.swing.text
f javax.swing.lext.html
javax.swlng.text.html.parser
Javax.swing,text,rtf
javax swing.tree
Javax.8wing.undo

(6)

. 15.5. Jtree: a ;

,
JTree.

JTree
lOiacc JTree . ,
, . ,
Vector Hash t a b l e .
JTree ,
, Sun,
.
public JTree(TreeNode root)
public JTree(TreeModel model)
,
. ,
.

JTree
JTree .
.
TreeExpansionEvent. API,
j a v a x . swing. JTree.

JTree
, ,
JTree T r e e S e l e c t i o n L i s t e n e r . T r e e S e l e c t i o n L i s t e n e r
valueChanged.
T r e e S e l e c t i o n E v e n t
t r e e . g e t L a s t S e l e c t e d P a t h C o m p o n e n t .

626

15. Swing

( Def aultMutableTreeNode). ,
, getUserObject.
, , toString ,
tree . getLastSelectedPathComponent.
15.10 , .
. JTree
TreeSelectionListener. ,
, , ,
toString (. 15.6).
15.10.SelectableTree.Java
import
import
import
import

java.awt.*;
javax.swing.*;
javax.swing.tree.*;
javax. swing, event.'^;

/** JTree ,
* in JTextField.
public class SelectableTree extends JFrame
implements TreeSelectionListener {
public static void main(String[] args) {
new SelectableTree0;
private JTree tree;
private JTextField currentSelectionField;
public SelectableTree() {
superC'JTree Selections");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
DefaultMutableTreeNode root =
new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode child;
DefaultMutableTreeNode grandchild;
for(int childlndex=l; childlndex<4; childlndex++) {
child = new DefaultMutableTreeNode("Child " + childlndex);
root.add(child);
for(int grandChildIndex=l; grandChildIndex<4;
grandChildIndex++) {
grandchild =
new DefaultMutableTreeNode("Grandchild " + childlndex +
"." + grandChildlndex);
child.add(grandchild);
}
}
tree = new JTree(root);
tree.addTreeSelectionListener(this);
content.add(new JScrollPane(tree), BorderLayout.CENTER);
currentSelectionField =

15.3. JTree

627

new JTextField{"Current Selection: NONE");


content.add(currentSelectionField, BorderLayout.SOUTH);
setSize(250, 275) ;
setVisible(true) ;
public void valueChanged(TreeSelectionEvent event) {
Object selection = tree.getLastSelectedPathComponent();
if (selection != null) {
currentSelectionField.setText
("Current Selection: " + selection.toStringO);
}

\^

Htfflwmw
J Root

JRoot
- J Child 1
Grandchild
Grandchild
# Grandchild
% Child 2
Grandchild

* . ? Child 1
^
I Child 2
+ . I Child 3

(a)

{Current Selection NONE

(6)

Grandchild
<5 Child 3
# Grandchild
Grandchild
Grandchild

11
12
1.3

2.1

il

23

::

il

31
32
3.3

jCurrent Selection Grandchild 2.2

1. 15.6. J t r e e : a ; 6

T r e e E x p a n s i o n E v e n t
. T r e e E x p a n s i o n E v e n t s
J T r e e T r e e E x p a n s i o n L i s t e n e r .
( t r e e E x p a n d e d t r e e C o l l a p s e d ) ,
. T r e e E x p a n s i o n E v e n t
g e t P a t h , ,
. P a t h .
g e t L a s t P a t h C o m p o n e n t P a t h .

, ,

J T r e e T r e e M o d e l .
J L i s t , .
, .
J L i s t .
T r e e M o d e l
,
. ,
, T r e e M o d e l , -

628

15. Swing

, TreeNode. ,
DefaultMutableTreeNode,
.
D e f a u l t M u t a b l e
TreeNode , ,
DefaultMutableTreeNode.

DefaultMutableTreeNode
DefaultMutableTreeNode 50 ,
. Vector,
. , , .
public void add(MutableTreeNode child)
public void remove(MutableTreeNode child)
.
( Vector).
public void insert(MutableTreeNode child, int index)
public void remove(int index)
i n s e r t ;
index. , ,
.
Vector. ,
, getChildCount. remove
, .
, ArraylndexOutOf BoundsException.
public Enumeration children()
Enumeration,
.
public TreeNode getChildAt(int index)
public int getIndex(TreeNode child)
g e t C h i l d A t ,
. ,
, ArraylndexOutOfBoundsException.
g e t Index , ,
-1, .
public int getChildCountO
getChildCount .
public TreeNode getParent()
g e t P a r e n t .
, n u l l .

15.3.JTree

629

public T r e e N o d e [ ] getPath()
g e t P a t h ,
.
public T r e e N o d e getRoot()
.
public b o o l e a n isLeaf()
public b o o l e a n isRoot()
i s L e a f t r u e , (..
); f a l s e .
i s R o o t t r u e ,
; f a l s e .
, , , ..
. ,
, Def a u l t M u t a b l e T r e e N o d e .
, ,
.
, .
15.11 , ,
.
1, 1.1, 1.2, 1.3 ..
1.1.1, 1.1.2 ..
.
J T r e e
g e t C h i l d C o u n t . ,
. g e t C h i l d C o u n t , f a l s e ,
.
( ) ,
, i s Leaf,
f a l s e . 15.12,
.
. 15.7.
1 5 . 1 1 . DynamiCTree. Java

import
import

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

/** ,
* .
* O u t l i n e N o d e .
V
p u b l i c c l a s s DynamicTree e x t e n d s JFrame {
public s t a t i c void main(String[] args) {
i n t n = 5; / / .

630

15. Swing

if (args.length > 0) {
try (
n = Integer.parseint(args[0]);
} catch(NumberFormatException nfe) {
System.out.println(
"Can't parse number; using default of " + n ) ;
}
}
new DynamicTree(n);
}
public DynamicTree(int n) {
super("Creating a Dynamic JTree");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
JTree tree = new JTree(new OutlineNode(1, n ) ) ;
content.add(new JScrollPane(tree), BorderLayout.CENTER);
setSize (300, 475);
setVisible(true);
}

15.12.OutlineNode.Java
import java.awt.^;
import javax.swing.*;
import javax.swing.tree.*;
/**
*
*
*
*
*
*
*
*
*

TreeNode,
.

getChildCount. ,
getChildCount .
<>
,
"" .
"", - ".",
".1", ".2" ".".
<>

public class OutlineNode extends DefaultMutableTreeNode {


private boolean areChildrenDefined = falserprivate int outlineNum;
private int numChildren;
public OutlineNode(int outlineNum, int numChildren) {
this.outlineNum = outlineNum;
this.numChildren = numChildren;

public boolean isLeaf() {


return(false);

15.3.JTree

public int getChildCount() {


if (!areChildrenDefined) {
defineChildNodes0;
}
return(super.getChildCount());
}
private void defineChildNodes() {
// "add"
// , .
// , getChildCount
// .
areChildrenDefined = true;
for (int i=0; KnumChildren; i++) {
add(new OutlineNode(i+l, numChildren));
}
}
public String toStringO {
TreeNode parent = getParentO;
if (parent == null) {
return(String.valueOf(outlineNum));
} else {
return(parent.toString() + "." + outlineNum);
}
}

^Creating a Dynamic JTree


11
1
2
.*~_I1 3

11 4
i141
J 1 4 2
1143
1144
^ J1 4 4 1
_J 1 4 4 2

443
- 11444
* _j 1 4 4 4 1
+ J14442
+
n 4443
- ^ 1 4444
+ _ J 1 4 4.4.4.1
+
M 4 4.4.4.2
+
;1 4 4.4.4.3
+
14 4.4.4.4

+
1 4 4.4.4.5
+
M 4445
' J1 4 4 5
45
5

(6)
. 15.7. TreeNode, ,
: ; 6 ,

631

632

15. Swing


JTree ,
, , .
Image Icon, JTree,
DefaultTreeCellRenderer setOpenlcon, setClosedlcon
setLeaf Icon, Icon, null,
. Image Icon
, . Default
TreeCellRenderer setCellRenderer.
15.13 , .
, ,
, ,
. . 15.8.
15.13.Customlcons.Java
import
import
import
import

java.awt.*;
Java.awt.event.*;
javax.swing.*;
javax.swing.tree.*;

/** JTree
, . */
public class Customlcons extends JFrame {
public static void main(String[] args) {
new Customlcons();
private Icon customOpenlcon =
new Image I con (" image s/Circle__l. gif ") ;
private Icon customClosedlcon =
new Imagelcon("images/Circle_2.gif");
private Icon customLeafIcon =
new Imagelcon("images/Circle_3.gif");
public Customlcons() {
super("JTree Selections");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setLayout(new FlowLayout());
DefaultMutableTreeNode root =
new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode child;
DefaultMutableTreeNode grandchild;
for(int childlndex=l; childlndex<4; childlndex++) {
child = new DefaultMutableTreeNode("Child " + childlndex);
root.add(child);
for(int grandChildIndex=l; grandChildIndex<4;
grandChildIndex++) {
grandchild =

15.3. JTree
new DefaultMutableTreeNode("Grandchild " +
childlndex +
"." + grandChildlndex);
child.add(grandchild);
}
)
JTree treel = new JTree(root);
treel.expandRow(1); //
// .
JScrollPane panel = new JScrollPane(treel);
panel.setBorder(
BorderFactory.createTitledBorder("Standard Icons")
content.add(panel);
JTree tree2 = new JTree(root);
// .
tree2.expandRow(2);
DefaultTreeCellRenderer renderer2 =
new DefaultTreeCellRenderer0;
renderer2.setOpenlcon(null);
renderer2.setClosedlcon(null);
renderer2.setLeafIcon(null);
tree2.setCellRenderer(renderer2);
JScrollPane pane2 = new JScrollPane(tree2);
pane2.setBorder(
BorderFactory.createTitledBorder("No Icons"));
content.add(pane2);
JTree treeS = new JTree(root);
// .
tree3.expandRow(3);
DefaultTreeCellRenderer rendererS =
new DefaultTreeCellRenderer0;
rendererS.setOpenlcon(customOpenlcon);
rendererS.setClosedlcon(customClosedlcon);
rendererS.setLeafIcon(customLeafIcon);
treeS.setCellRenderer(rendererS);
JScrollPane = new JScrollPane(tree3);
.setBorder(
BorderFactory.createTitledBorder("Custom Icons"));
content.add();
packO ;
setVisible(true);
}

633

634

15. Swing

iHPiffuwffiimi
standard icons

No (cons

' Custom teos

, s Root
- jChildl
Grandchild i 1
Grandchild 1 2
Grandchild 1 3
_ J Child 2
* J Child 3

Root
Child 1
- Child 2
Grandchild 21
Grandchild 2 2
Grandchild 2 3
.+ Child 3

( f ) Root
+ 2) Child 1
+ ^ r ) Child 2
- M Child 3
(3) Grandchild 3 1
f i } Grandchild 3 2
( ? ) Grandchild 3.3

. 15.8.
JTree

15.4. JTable
J T a b l e ,
. Swing API. J T a b l e
: ,
. ,
,
( ).
.
j a v a x . s w i n g , t a b l e .
, , , .

(Kim Topley) CoreJava Foundation Classes.

JTable
J T a b l e
, ,
, . ,
, N :
String[][]

data = { { "Cell

(1,1)",

--

"Cell

( 1 , N ) " },

{ " C e l l ( M , l ) " , . . . , " C e l l (M,N)" } };


S t r i n g [ ] columnNames = { "Column 1 " , . . . , "Column N" };
J T a b l e t a b l e = new J T a b l e ( d a t a , columnNames);

Obj e c t ,
J L a b e l , t o S t r i n g .
J L i s t J T r e e , .
, .
,
450x400 . -

15.4. JTable

, D i m e n s i o n
S c r o l l a b l e V i e w p o r t S i z e J T a b l e .

635

setPreferred-

Ha
JTable ,
JScrollPane,

JTable
J T a b l e .
, n u l l .
, (, ,
, , , , ...). J T a b l e
. , ,
D e f a u l t T a b l e M o d e l , D e f a u l t C o l u m n M o d e l D e f a u l t L i s t S e l e c t i o n M o d e l .
public JTableO
Def a u l t
T a b l e M o d e l , D e f a u l t C o l u m n M o d e l D e f a u l t L i s t S e l e c t i o n M o d e l .
addRow addColumn.
.
public JTable(int rows, int c o l u m n s )
, , ,
(
n u l l ) .
public JTable(Object[][] data, Object[] c o l u m n N a m e s )

.
J L a b e l . ,
t o S t r i n g .
, ,
B o o l e a n , Image I c o n Number.
public JTable(Vector data. Vector c o l u m n N a m e s )

V e c t o r . ,
, V e c t o r , .
public JTable(TableModel m o d e l )
J T a b l e ,
T a b l e M o d e l .
A b s t r a c t T a b l e M o d e l Def a u l t T a b l e M o d e l ;
T a b l e M o d e l E v e n t . D e f a u l t
ColumnModel D e f a u l t L i s t S e l e c t i o n M o d e l .

636

15. Swing

JTable
J T a b l e 125 ,
, J T a b l e : T a b l e M o d e l , T a b l e C o l u m n Model L i s t S e l e c t i o n M o d e l . J T a b l e ,
p r o t e c t e d , J T a b l e
.
J T a b l e .
public T a b l e M o d e l getModel()
public v o i d s e t M o d e l ( T a b l e M o d e l tableModel)
g e t M o d e l , a s e t M o d e l T a b l e Model. T a b l e M o d e l , J T a b l e .
public T a b l e C o l u m n M o d e l g e t C o l u m n M o d e l ( )
public s e t C o l u m n M o d e l ( T a b l e C o l u m n M o d e l c o l u m n M o d e l )
g e t ColumnModel , a s e t C o l u m n M o d e l
T a b l e C o l u m n M o d e l .
.
, . T a b l e C o l u m n
Model .
T a b l e C o l u m n M o d e l API,
j avax.swing.table.
public L i s t S e l e c t i o n M o d e l g e t S e l e c t i o n M o d e l ( )
public void s e t S e l e c t i o n M o d e l ( L i s t S e l e c t i o n M o d e l s e l e c t i o n M o d e l )
g e t S e l e c t i o n M o d e l , a s e t S e l e c t i o n M o d e l
. L i s t S e l e c t i o n M o d e l J T a b l e , J L i s t
, .
L i s t S e l e c t i o n E v e n t
v a l u e C h a n g e d .
g e t S e l e c t e d R o w g e t S e l e c t e d R o w s .
TableColumnModel L i s t S e l e c t i o n M o d e l
. L i s t S e l e c t i o n M o d e l
API, j a v a x . swing.
public int getRowHeightO
public void s e t R o w H e i g h t ( i n t height)
public int g e t R o w H e i g h t ( i n t row)
public void s e t R o w H e i g h t ( i n t row, int height)

. 16 . JDK
1.3 ,
.

15.4. JTable

637

public int getRowMarginO


public void setRowMargin(int margin)
getRowMargin , a setRowMargin
.
.
setColumnMargin TableColumnModel.
public void setShowGrid(boolean show)
public boolean getShowHorizontalLines()
public void setShowHorizontalLines(boolean show)
public boolean getShowVerticalLines()
public void setShowVerticalLines(boolean show)
setShowGrid
.
UI-.

.
, 15.14, JTable,
4 15 . ,
. ,
.
. J T a b l e . 15.9.
15.14. JTableSimpleExample . Java
import j a v a . a w t . * ;
import j a v a x . s w i n g . * ;
/** JTable,
^ S t r i n g

public c l a s s JTableSimpleExample extends JFrame {


p u b l i c s t a t i c void m a i n ( S t r i n g [ ] args) {
new JTableSimpleExample0;
p r i v a t e f i n a l i n t COLUMNS = 4;
p r i v a t e f i n a l i n t ROWS = 15;
p r i v a t e JTcuDle sample JTable;
p u b l i c JTableSimpleExample() {
s u p e r ( " C r e a t i n g a Simple J T a b l e " ) ;
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new E x i t L i s t e n e r ( ) ) ;
Container content = g e t C o n t e n t P a n e ( ) ;
S t r i n g [ ] columnNames = buildColumnNames (COLUMNS)

638

15. Swing

string[][] tableCells = buildTableCells(ROWS, COLUMNS);


sampleJTable = new JTable(tableCells, columnNames);
JScrollPane tablePane = new JScrollPane(sampleJTable);
content.add(tablePane, BorderLayout.CENTER);
setSize(450,150);
setVisible(true);
}
private String[] buildColumnNames(int columns) {
String[] header = new String[columns];
for(int i=0; i<columns; i++) {
header[i] = "Column " + i;
return(header)
}

p r i v a t e S t r i n g [ ] [ ] b u i l d T a b l e C e l l s ( i n t rows, i n t columns) {
S t r i n g [ ] [ ] c e l l s = new S t r i n g [ r o w s ] [ c o l u m n s ] ;
f o r ( i n t i=0; i<rows ; i++) {
f o r ( i n t j=0; j<columns; j++ ) {
c e l l s [i] [j] = "Row " + i + ", Col " + j ;
}
}

return(cells);

1
0
JRowO, Col 0
|Row1,ColO
IROW 2, Col 0

|Row3, ColO
^Row4, Col 0
I R O W S , Col 0

iRow 6. Col 0
|Row7, Col 0
lRow8, Col 0

1
Column 1
RowO. Col 1
R o w l , Col 1
Row 2, Col 1
Row 3. C o l l
Row 4, Col 1
Row 5, Col 1
Row 6. Col 1
Row 7. Col 1
Row 8. C O M

Cs^lunw ^

RowO. Col 2
Row 1. Col 2
Row 2, Col 2
Row3. Col 2
Row 4, Col 2
Row 5, Col 2
Row 6, Col 2
Row 7. Col 2
Row 8. Col 2

RowO, Col 3
R o w l . Col 3
Row 2, Col 3
Row 3, Col 3
Row 4, Col 3
Row 5, Col 3
Row 6, Col 3
Row 7, Col 3
Row 8, Col 3

\
1MI
"-; 1
,
^

. 15.9. JTable,

,
JTable
JTable , ,
. ,
TableModel.
,
,
.
TableModel, A b s t r a c t T a b l e M o d e l ,
. A b s t r a c t T a b l e M o d e l
, TableModelEvent.
A b s t r a c t T a b l e M o d e l ,
:

15.4. JTable

639

p u b l i c i n t getRowCount()
p u b l i c i n t getColumnCount()
p u b l i c Object g e t V a l u e A t ( i n t row, i n t column)

.
A b s t r a c t T a b l e M o d e l setValueAt
. s e t V a l u e A t
, i s C e l l E d i t a b l e f a l s e .
Swing API DefaultTableModel,
A b s t r a c t T a b l e M o d e l
. DefaultTableModel Vector.
Vector,
. , ,
DefaultTableModel, Vector.
, DefaultTableModel
. i s C e l l E d i t a b l e DefaultTableModel
t r u e ,
.

IsCellEditable
false;

AbstractTableModel
DefaultTableModel

tJTue.

DefaultTableModel
DefaultTableModel . ,
, .
public DefaultTableModel(Object[][] data, Object[] columnNames)
DefaultTableModel,
d a t a ; ,
columnNames .
S t r i n g .

(, .)public DefaultTableModel(Vector data, Vector columnNames)
Vector.
d a t a
, . columnNames
.
public DefaultTableModel(Vector columnNames, int numRows)
DefaultTableModel
.

640

15. Swing

, .
n u l l .

DefaultTableModel
D e f a u l t T a b l e M o d e l ,
, .
.
public void a d d C o l u m n ( O b j e c t c o l u m n N a m e )
public v o i d a d d C o l u m n ( O b j e c t c o l u m n N a m e , Object[] columnData)
public void a d d C o l u m n ( O b j e c t c o l u m n N a m e , Vector columnData)

. n u l l .
,
.
public void addRow(Object[] rowData)
public void addRow(Vector rowData)
public void insertRow(int row, Object[] rowData)
public void insertRow(int row. Vector rowData)
addRow ;
. .
I n s e r t R o w ,
. r o w D a t a n u l l , cipoKa
n u l l .
, , IndexOutOfBoundsException.
public void removeRow(int row)
r e m o v e Row .
, ,
A r r a y l n d e x O u t O f B o u n d s E x c e p t i o n .
public int getColumnCount()
public int getRowCount()
g e t C o l u m n C o u n t [ , a g e t R o w C o u n t
.
public String g e t C o l u m n N a m e ( i n t c o l u m n )
,
t o S t r i n g . n u l l ,
,
(, , , ..., , , , ...). , -

15,4. JTable

641

, ,
A r r a y l n d e x O u t O f B o u n d s E x c e p t i o n .
public Object getValueAt(int row, int c o l u m n ) public
setValueAt(Object value, int row, int c o l u m n )
g e t V a l u e A t ^, a s e t V a l u e A t
, .
s e t V a l u e A t T a b l e M o d e l E v e n t ,
.
,
ArraylndexOutOfBoundsException.
public b o o l e a n isCellEditable(int row, int c o l u m n )
Def a u l t T a b l e M o d e l i s C e l l E d i t a b l e
t r u e , . Def a u l t
T a b l e M o d e l .
15.15 Def a u l t T a b l e M o d e l .
J a v a L o c a t i o n C o l l e c t i o n ,
15.5. J a v a L o c a t i o n
, , "Java": ,
, (GIF-) ,
. ""
Def a u l t T a b l e M o d e l ; addColumn
.
; getRowData,
, J a v a L o c a t i o n , addRow,
. ,
( I m a g e I c o n ) ,
, , .
. 15.10. ,
.
,
Image I c o n B o o l e a n
.
1 5 . 1 5 . D e f a u l t T a b l e E x a m p l e . J a v a
import
import
import

Java.util.Vector;
javax.swing.*;
javax.swing.table.*;

/** J T a b l e , D e f a u l t T a b l e M o d e l
* .
V
p u b l i c c l a s s D e f a u l t T a b l e E x a m p l e e x t e n d s JTable {

642

15. Swing

private String[] columnNames =


{ "Flag", "City", "Country", "Comment", "Visited" };
piiblic DefaultTableExample () {
this(new DefaultTableModel);

public DefaultTableExample(DefaultTableModel model) {


super(model);
JavaLocationCollection collection =
new JavaLocationCollection0;
JavaLocation[] locations = collection.getLocations();
// .
int i;
for(i=0; i<columnNames.length; i++ ) {
model.addColumn(columnNames[i]);
}
for(i=0; i<locations.length; i++) {
model.addRow(getRowData(locations[i]));
}
}
private Vector getRowData(JavaLocation location) {
Vector vector = new Vector();
' vector.add(new Imagelcon(location.getFlagFile()) ) ;
vector.add("Java");
vector.add(location.getCountry());
vector.add(location.getComment());
vector.add(new Boolean(false));
return(vector) ;
}

p u b l i c s t a t i c void m a i n ( S t r i n g [ ] args) {
WindowUtilities.setNativeLookAndFeel();
WindowUtilities.openlnJFrame(
new JScrollPane(new D e f a u l t T a b l e E x a m p l e ( ) ) , 600, 150,
"Using a DefaultTableModel");
}

l o u s i n g a OefauRTableM idel

Flag

;flags/beigium gif
Iflags/brazil gif
[flags/colombia gif
Itlags/indonesia gif
Iflags/jamaica gif
;flags/tnorambiqcie
flags/philippines gif

1
Java
Java
Java
Java
Java
Java
Java

cm

-:1
1

Coun^

Belgium
Brazil
Colombia
Indonesia
Jamaica
Mozambique
Philippines

Comment

near Liege
near Salvador
near Bogota
mam island
near Spanish Town
nearSofala
near Quezon City

1false
false
false
false
false
false
false

vi'stted

1
j4

Ji

. 15.10. ,
>
DefaultTableModel

15.4. JTable

643



J L a b e l . Java 2 Platform
,
.
.

B o o l e a n J C h e c k B o x .

D a t e J L a b e l ,
D a t e F o r m a t .

Image I c o n J L a b e l .

Number N u m b e r F o r m a t
J L a b e l .

Ob j t t o S t r i n g J L a b e 1.

,
g e t C o l u m n C l a s s D e f a u l t T a b l e M o d e l ,
, . g e t C o l u m n
C l a s s O b j e c t . c l a s s ,
J L a b e l .
, ,
, ,
D e f a u l t T a b l e M o d e l . g e t C o l u m n C l a s s ,
. :
p u b l i c C l a s s g e t C o l u m n C l a s s ( i n t column) {
return (getValueAt(0, column).getClass());
}

,
.
, , ,
,
g e t C o l u m n C l a s s .
.
15.16 C u s t o m T a b l e E x a m p l e ,
D e f a u l t T a b l e E x a m p l e .
C u s t o m T a b l e E x a m p l e ,
C u s t o m T a b l e M o d e l ( 15.17) .
C u s t o m T a b l e M o d e l D e f a u l t T a b l e M o d e l
g e t C o l u m n C l a s s . , C u s t o m T a b l e M o d e l
i s C e l l E d i t a b l e ; ,
Comment V i s i t e d .
. 15.11.
,
, s e t M i n W i d t h , s e t M a x W i d t h
s e t P r e f e r r e d W i d t h .

644

1 15. Swing

75 , 15 .
, :
TableColumn column = table.getColumn(columnName);
column.setPreferredWidth(numPixels);
J D K .
,
:
table.sizeColumnsToFit(JTable.AUTO_RESIZE_OFF);
TableColumn setWidth, ,
, .
15.16.CustomTableExample.Java
import javax.swing.*;
import javax.swing.table.*;
/** JTable, CustomTableModel
* ,
* .

V
public class CustomTableExample extends DefaultTableExample {
public CustomTableExample() {
super(new CustomTableModel());
setCellSizes();
}
private void setCellSizes () {
setRowHeight(50);
getColumn("Flag").setMaxWidth(55);
getColumn("City").setPreferredWidth(60);
getColumn("Country").setMinWidth(80);
getColumn("Comment").setMinWidth(150);
//
// ( ).
SizeColumnsToFit(JTable.AUTO_RESIZE_OFF);
}
public static void main(String[] args) {
WindowUtilities.setNativeLookAndFeel();
WindowUtilities.openlnJFrame(
new JScrollPane(new CustomTableExample()), 525, 255,
"Using a CustomTableModel");
}

15.4.JTable

645

15.17. CustomTableModel. Java


import javax.swing.table.*;
/** DefaultTableModel,
* ,
* .
'^ Comment Visited.

V
public class CustomTableModel extends DefaultTableModel {
public Class getColumnClass(int 1) {
return(getValueAt(0, column).getClass());
}
// "Comment" "Visited",
public boolean isCellEditable(int row, int column) {
return(column==3 || column==4);

Usma a {JmAimTeMeiiodel
Fiag

11
E
E
@

Coia^

Crty

Cemment

1 Java

Belgium

inear Liege

1 Java

Braz.l

inear Salvador

J Java

Colombia

Inear Bogota

4;Java

Indonesia

imain island

_rJ

. 15.11.



, J T a b l e .
: T a b l e M o d e l , T a b l e C o l u m n M o d e l
L i s t S e l e c t i o n M o d e l . ,
, T a b l e M o d e l L i s t e n e r T a b l e M o d e l .
T a b l e M o d e l L i s t e n e r t a b l e C h a n g e d ,
(
<Enter> ).
T a b l e M o d e l E v e n t . ,
, g e t C o l u m n ,
g e t F i r s t R o w g e t L a s t R o w . , D e f a u l t T a b l e M o d e l
i s C e l l E d i t a b l e , t r u e ,
, ,
.

646

15. Swing

<Enter>
, T a b l e M o d e l E v e n t .
T a b l e M o d e l T a b l e M o d e l L i s t e n e r .
:
tablemodel.addTableModelListener(
new TableModelListner() {
public void tableChanged(TableModelEvent event) {
int row = event.getFirstRow0;
int column = event.getColumn0;
}
});
, ,
, g e t V a l u e A t ( r o w , c o l u m n ) ,
s e t V a l u e A t ( r o w , c o l u m n ) . g e t V a l u e A t
O b j e c t ; .
, .
J T a b l e
TableModelEvent.
A b s t r a c t T a b l e M o d e l , T a b l e M o d e l ,
, .
: f i r e T a b l e C e l l U p d a t e d ( r o w , c o l u m n ) ,
, f i r e T a b l e D a t a C h a n g e d () , .
Java 2 Platform T a b l e C o l u m n M o d e l E v e n t
T a b l e C o l u m n M o d e l L i s t S e l e c t i o n E v e n t
ListSelectionModel.
15.18 , ,
, .
j a v a x . s w i n g . e v e n t .
, T a b l e M o d e l L i s t e n e r
T a b l e M o d e l E v e n t .
T a b l e M o d e l E v e n t ,
.
. 15.12.

.
D e c i m a l F o r m a t , API,
j ava.text.DecimalFormat.
1 5 . 1 8 . J T a b l e E v e n t s o a v a
import
import
import
import
import

java.awt.*;
Java.text.DecimalFormat;
javax.swing.*;
j avax.swing.event.*;
javax.swing.table.*;

/** JTable,

15.4. JTable
* TableModelEvent
* , .

V
public class JTableEvents extends JFrame {
private final int COL_COST = 1;
private final int COL_QTY = 2;
private final, int COL_TOTAL = 3;
private final int ROW_LAST = 5;
private DecimalFormat df = new DecimalFormat("$####.##");
private JTable sampleJTable;
private DefaultTableModel tableModel;
public static void main(String[] args) {
new JTableEvents();
}
public JTableEvents() {
super("Using TableEvents");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
String[] columnNames = { "Book", "Cost", "Qty", "Total" };
final Object[][] data = {
{"Core Web Programming", "$ 0.99", "0", "$0.00"},
{"Core Servlets and JavaServer Pages",
"$34.39", "0", "$0.00"},
{"Core Swing", "$39.99", "0", "$0.00"},
{"Core Java, Volume I", "$31.49", "0", "$0.00"},
{"Core Java, Volume II", "$34.39", "0", "$0.00"},
{null, null, "Grand:", "$0.00"} };
tcdDleModel = new DefaultTableModel (data, columnNames);
tcibleModel. addTableModelListener (
new TableModelListener0 {
int row, col;
int quantity;
float cost, subTotal, grandTotal;
public void tableChanged(TcUDleModelEvent event) {
row = event.getFirstRowO ;
col = event.getColumn();
// ,
if (col == COL_QTY) {
try {
cost = getFormattedCellValue(row, COL_COST);
quantity = (int)getFormattedCellValue(row, COL_QTY);
subTotal = quantity * cost;
// .
tableModel.setValueAt(df.format(subTotal),
row, COL_TOTAL);
// .
grandTotal =0;
for(int row=0; row<data.length-1; row++) {

647

648

15. Swing

grandTotal += getFormattedCellValue(row, COL TOTAL)


}

tableModel.setValueAt(df.format(grandTotal),
ROW__LAST, COL_TOTAL) /
tableModel.fireTableDataChanged()/
} catch (NumberFormatException nfe) {
// .
JOptionPane,showMessageDialog(
JTableEvents.this,
"Illegal value entered!");
}

private float getFormattedCellValue(int row, int col) {


String value = (String)tableModel.getValueAt(row, col)
return(Float.parseFloat(value.replace('$',' ')));
}
});
sampleJTable = new JTable(tableModel);
setColumnAlignment(sampleJTable.getColumnModel());
JScrollPane tablePane = new JScrollPane(sampleJTable);
content.add(tablePane, BorderLayout.CENTER);
setSize(460,150);
setVisible(true);
// Bee , ,
// .
private void setColumnAlignment(TableColumnModel tcm) {
TableColumn column;
DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer*();
for(int i=l; i<tcm. getColumnCount () ; i+-b) {
column = tcm.getColumn(i);
renderer.setHorizontalAlignment(SwingConstants.RIGHT);
column.setCellRenderer(renderer);
}
}

Using TdbleEvenU

Core Servlets and JavaSetver Pages


:Core Swing
Core Java. Volume 1
iCore Java, Volume II

$34
$39
$31
$34

39
99
49
39

$10317
$39 99
$31 49
$34 39
$213 99

. 15.12. ,

15.5. Swing-

649

15.5. Swing-
Java 2 ,
J a v a . a w t . p r i n t .
Swing- .
G r a p h i c s 2 D
. JDK 1.2,
. JDK 1.3

JComponent p r i n t .
,
JDK 1.2. B J D K 1.3.


:
.


.
P r i n t e r J o b , P r i n t a b l e s e t P r i n t a b l e ,
p r i n t D i a l o g , ,
, p r i n t P r i n t e r J o b .
Windows 98 . 15.13. ,
, Cancel,
p r i n t , p r i n t D i a l o g .

EQI

Pfinter
Najr.e

H d

Status

Ready

Type;

H P LaserJet 4000 Senes

Where-

128.244128 247.RAW

Comment.

4000 If! Stev/e Dtan.r.r-. i, -,(, ? 51

Eroperties

'

Print range

f'

(^ Ah
f" Page 6

tiorrr p

"^

to 1 '
r

1"" OK

Collate

Cancel

1
. 15.13. ,
p r i n t D i a l o g

650

15. Swing

, ,
:
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog0)
try {
printJob.print();
} c a t c h ( P r i n t e r E x c e p t i o n pe) {
System.out.println("Error printing: " + pe);
}


P r i n t a b l e , s e t P r i n t a b l e ,
p r i n t ,
. p r i n t :
Graphics PageFormat, page Index. p r i n t
P r i n t e r Job
. page Index
. P r i n t e r Job p r i n t
page Index, 0. ,
PAGEEXISTS. N0 SUCH_PAGE
, .
Java p r i n t ,
; ,
NO_SUCH_PAGE. , ,
.
,
PAGEEXISTS,
- NO_SUCH_PAGE.
,
, . Swing- ,
, ,
.
Graphics Graphics2D,
p a i n t ,
Graphics2D . Graphics2D
10.
, , .
public int print(Graphics g,
PageFormat pageFormat,
int pagelndex) {
if (pagelndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getlmageableX{),
pageForitiat .getlmageableY () ) ;

15.5. Swing-

651

// JDK 1.
//
// ,
// . JDK 1.3
// :
// componentToBePainted.print(g2d).
setDoubleBufferEnabled(false);
componentToBePrinted.paint(g2d);
setDoubleBufferEnabled(true);
return(PAGE EXISTS);
}
}
g e t l m a g e a b l e X g e t l m a g e a b l e Y
, .
, , Printer.


Swing- .

,
p a i n t C o m p o n e n t .
. ,
.
, p a i n t .
,
.
, Swing-
, .
, J P a n e l ,
p a i n t s e t D o u b l e B u f f a r e d ( f a l s e ) ,
s e t D o u b l e B u f f a r e d ( t r u e ) .
,
, .
. :
RepaintManager currentManager =
RepaintManager.currentManager(theComponent);
currentManager.setDoubleBufferingEnabled(false);
p a i n t )
D o u b l a B u f f e r i n g E n a b l e d ( t r u e ) .

. ,
, ,
. JDK 1.3
,
.

652

1 5 . Swing


JDK 1.2
,

.


Swing p r i n t
G r a p h i c s ,
. , p r i n t
, . ,
, P r i n t a b l e , p r i n t
,
.
p r i n t ,
p a i n t .
p r i n t C o m p o n e n t , ,
.


Swing-,
,
,
Printable.
15.19 P r i n t U t i l i t i e s ,
Swing-. ,
, )' P r i n t U t i l i t i e s . p r i n t C o m p o n e n t .
15.20 P r i n t U t i l i t i e s B J D K 1.2.
1 5 . 1 9 . P r i n t U t i l i t i e s . J a v a
import
import
import
/**
*
*
*
*
*
*
*

java.awt.*;
javax.swing.*;
Java.awt.print.*;

, ,
JDK 1 . 2 ,
.
P r i n t U t i l i t i e s . p r i n t C o m p o n e n t . ,
,
p r i n t .

.

<>

*
*
*

,
,
:

15.5. Swing-

* <PRE>
*
PrintUtilities printHelper =
*
new PrintUtilities(theComponent);
* </PRE>
* a printHelper.print().
*
'*' PrintUtilities . printComponent (componentToBePrinted)

V
public class PrintUtilities imiplements Printable {
protected Component componentToBePrinted;
public static void printComponent(Component c) {
new PrintUtilities(c).print();
public PrintUtilities(Component componentToBePrinted) {
this.componentToBePrinted = componentToBePrinted;
}
public void print 0 {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog0)
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);

// JDK 1.2.
// JDK 1.3
// PrintUtilities2.
public int print(Graphics g, PageFormat pageFormat,
int pagelndex) {
if (pagelndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getlmageableX(),
pageFormat.getlmageableY());
disableDoubleBuffering(componentToBePrinted);
componentToBePrinted.paint(g2d);
enableDoubleBuffering(componentToBePrinted);
return(PAGE_EXISTS);
}
}
/**
*
*
*

,
,
.
JDK 1.2.

V
public static void disableDoubleBuffering(Component ) {

653

654

15. Swing

RepaintManager currentManager =
RepaintManager.currentManager();
currentManager.setDoubleBufferingEnabled(false);
}
/**
* JDK 1.2.

V
public static void enableDoubleBuffering(Component ) {
RepaintManager currentManager =
RepaintManager.currentManager();
currentManager.setDoubleBufferingEnabled(true);
}

15.20 , .
,
PrintUtilities .printComponent.
DrawingPanel ( 15.21), paintComponent.
"Java 2D" .
. 15.14.
Graphics2D . 10.
15.20. PrintExample. java
import
import
import
import
/**
*
*
*
*
*

java.awt.*;
javax.swing.*;
Java.awt.event.*;
Java.awt.print.*;

, Java 1.2.
Java 1.2 <></> ,
,
( )
printComponent PrintUtilities
.

public class PrintExample extends JFrame


implements ActionListener {
public static void main(String[] args) {
new PrintExample();
}
public PrintExample() {
super("Printing Swing Components in JDK 1.2");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
JButton printButton = new JButton("Print");
printButton.addActionListener(this);
JPanel buttonPanel = new JPanelO;

15.5. Swing-

buttonPanel.setBackground(Color.white)/
buttonPanel.add(printButton);
content.add(buttonPanel, BorderLayout.SOUTH);
DrawingPanel drawingPanel = new DrawingPanel();
content.add(drawingPanel, BorderLayout.CENTER);
packO ;
setVisible(true);
public void actionPerformed(ActionEvent event)
PrintUtilities.printComponent(this);
}
}

15.21.DrawingPanel.Java
import java.awt.*;
import javax.swing.*;
import Java.awt.geom.*;
/**
*
*
*
*
*

paintComponent.
,
,
.
printComponent PrintUtilities
.

V
public class DrawingPanel extends JPanel {
private int fontSize = 90;
private String message = "Java 2D";
private int messageWidth;
public DrawingPanel() {
setBackground(Color.white);
Font font = new Font("Serif", Font.PLAIN, fontSize);
setFont(font);
FontMetrics metrics = getFontMetrics(font);
messageWidth = metrics.stringWidth(message);
int width = messageWidth*5/3;
int height = fontSize*3;
setPreferredSize(new Dimension(width, height));
/

" '

public void paintComponent(Graphics g) {


super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
int X = messageWidth/10;
int = fontSize*5/2;
g2d.translate(x, y ) ;
g2d.setPaint(Color.lightGray);
AffineTransform origTransform = g2d.getTransform();

655

656

1 5 . Swing

g2d.shear(-0.95, 0) ;
g2d.scale(1, 3 ) ;
g2d.drawstring(message, 0, 0 ) ;
g2d.setTransform(origTransform);
g2d.setPaint(Color.black);
g2d.drawstring(message, 0, 0) ;

l-^<Jllil'lilil'.H'!'4liilll.H.llli!l>i4H

Java 2D

. 15.14. JButton
p r i n t ,
Graphics2D

JDK 1.3
O T J D K 1.2, JDK 1.3
. JDK 1.3 J C o m p o n e n t
p r i n t , . p r i n t
IS_PRINTING p a i n t . p a i n t J C o m p o n e n t
, , p r i n t Component, p r i n t B o r d e r p r i n t C h i l d r e n , p r o t e c t e d ,
.
JDK 1.3
setDoubleBufferEnabled(false);
componentToBePrinted.paint(g2d);
setDoubleBufferEnabled(true);

componentToBePrinted.print(g2d);

JDK 1.3
print (Graphcs2d g2d). JDK 1.3

.
15.22 P r i n t U t i l i t i e s 2 ,
JDK 1.3.
P r i n t U t i l i t i e s (. 15.19) p r i n t ,

15.5. Swing-

657

paint print .
:
PrintUtilities2 .printCoinponent {componentToBePrinted) ;
componentToBePrinted Swing-,
.
15.22.PrintUtilities2.java
import java.awt.*;
import javax.swing.*;
import Java.awt.print.* ;
/**
^
*
*
*
*
*
*
*
*
*

,
JDK 1.3.
JDK 1.3,
, JComponent
print ;
,
. , paint
printComponent, printBorder printChildren.
,
PrintUtilities2.printComponent(componentToBePrinted)

V
public class PrintUtilities2 extends PrintUtilities {
public static void printComponent (Comiponent c) {
new PrintUtilities2(c) .print 0 ;
public PrintUtilities2(Component componentToBePrinted) {
super(componentToBePrinted);
}
// JDK 1.3.
// JDK 1.2
// PrintUtilitiesl.
public int print(Graphics g, PageFormat pageFormat,
int pagelndex) {
if (pagelndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getlmageableX(),
pageFormat.getlmageableY());
componentToBePrinted.print(g2d);
return(PAGE_EXISTS);
}
}

658

15. Swing

15.6. Swing
Swing AWT
.
,

.
1. ,
,
.
, .
2. Swing-
.
, ,
1 ,
"" .
,
, ,
. ,
Start,
, J L a b e l , (
, " T r a n s f e r r i n g
f i l e n a m e . . . " ) . a c t i o n P e r f o r m e d ,
Start, :
/ / ,
/ / S t a r t ,
p u b l i c void actionPerformed(ActionEvent e v e n t ) {
/ / JLabel ,
/ / .
label.setText("Transferring " + filename);
/ / -
/ / .
transferFile(filename);
/ / JLabel ,
/ / ,
label.setText("Transfer completed.");
}

, JLabel,
, s e t T e x t .
.
s e t T e x t PropertyChangeEvent.
,
a c t i o n P e r f o r m e d . ,
J L a b e l , .

15.6. Swing

659

JLabel ,
"Transferring . . .".
,
actionPerformed.
.

JLabel .
,
, JLabel.
actionPerformed.
// . ,
// , ,
public void actionPerformed(ActionEvent event) {
// JLabel ,
// .
ladDel.setText("Transferring " + filename);
// ,
// .
// .
Thread t = new FileTransfer(filename, label);
t. start 0 ;
}
FileTransfer.
//
// Swing.
public class FileTransfer extends Thread {
private String filename;
private JLabel = label;
public FileTransfer(String filename, JLabel label) {
this.filename = filename;
this.label = label;
}
public void run() {
// .
// .
doTransf(...);
// JLabel .
// .
IcUDel. setText ( "Transfer complete. ") ;
}
}

. , J L a b e l
F i l e T r a n s f e r , , Swing-
, .
"" J L a b e l

660

15. Swing

, .


.
Swing : i n v o k e L a t e r
i n v o k e A n d W a i t , R u n n a b l e ,
Swing-. R u n n a b l e
, r u n .
, J L a b e l .
R u n n a b l e 16.


Swing ,
,
Runnable Runnable
SwlngUtilitles:
InvokeLater

InvokeAndWal

t.

SwingUtilities
S w i n g U t i l i t i e s ,
R u n n a b l e . ,
Swing , ,
r u n R u n n a b l e .
public static void invokeLater (Runnable object)
i n v o k e L a t e r R u n n a b l e
.
, r u n
. i n v o k e L a t e r
, , .
public static void invokeAndWait(Runnable object)
throws I n t e r r u p t e d E x c e p t i o n , I n v o c a t i o n T a r g e t E x c e p t i o n
i n v o k e A n d W a i t R u n n a b l e
r u n R u n n a b l e .
, Swing-
, , , ,

. i n v o k e A n d W a i t ,
.
, ,
i s E v e n t D i s p a t c h T h r e a d . i n v o k e A n d W a i t
I n v o c a t i o n T a r g e t E x c e p t i o n ,
J a v a . l a n g . r e f l e c t .

15.6. Swing

661

Swing-
Runnable. ,
, JLabel .
,
, ,
, , , Swing .
"".
a c t i o n P e r f o r m e d F i l e T r a n s f e r .
JLabel .
/ / , . ,
/ / ,
/ / , Swing
/ / Runnable,
/ / .
p u b l i c void actionPerformed(ActionEvent event) {
/ / , ,
/ / .
Thread t = new FileTransfer(filename, l a b e l ) ;
t.start 0 ;
}
}

FileTransfer JLabel,
. run
Runnable: JLabel
, JLabel .
Runnable .
. 10.
// FileTransfer.
// ,
public class FileTransfer extends Thread {
private String filenamesprivate JLabel label;
public FileTransfer(String filename, JLabel label) {
this.filename = filename;
this.label = label;
}
public void run() {
try {
// Runnable,
// JLabel, .
// invokeAndWait
// , .
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
label.setText("Transferring " + filename);
}
});

662

15. Swing

} catch(InvocationTargetException ite) {
} catch(InterruptedException ie) { }
// ( ).
doTransfer(...);
//
// Runnable. invokeLater.
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
IcUDel. setText ("Transfer completed") ;
}
});
}
}
R u n n a b l e
i n v o k e An d W a i t . ,
J L a b e l " T r a n s f e r r i n g . . .".
R u n n a b l e .
i n v o k e L a t e r . ,
, .
r u n , J L a b e l
'*Transf c o m p l e t e d " .
, ,
Swing-
.
, ,
RMI, Web-
. ,
, i n v o k e L a t e r i n v o k e A n d W a i t .

15.7.
,
Swing-.
,
. Swing,
,
.
J L i s t , J T r e e J T a b l e
( ) .
,
,
. ,
Swing-,
, .

15.6. Swing

663

,
p r i n t . ;
.
Swing- ,
. invokeAndWait i n v o k e L a t e r
.

...
Thread.

, ,
.
.
Thread.

.
.
.
.

J~y\ZJ^ZJ

ava

T h r e a d . " ";
, "" (heap),
. , ,
.

, .
, , .
, 12 ,
, , 1
. , 5 13 = 65
. ,
12 + 5 = 17 .
, Java
( . 9).

,
. ,
.
.

.
, HTTP- .
,
. , -

666

16.

.
. 17
HTTP-, .
,
,
. ,
, , ,
. ,
,
. ,
.
, Java.

1 6 . 1 .
Java :
T h r e a d , , ,
T h r e a d .

Thread
,
T h r e a d , r u n ,
s t a r t .
16.1 16.2.
1 6 . 1 . D r i v e r C l a s s . J a v a
public class DriverClass extends

SomeClass

public void startAThread() {


/ / T h r e a d .
T h r e a d C l a s s t h r e a d = new T h r e a d C l a s s ( ) ;
/ / ,
thread.start();
}
}

16.2.ThreadClass.Java
public class ThreadClass extends Thread {
public void run() {
// .
}
}

1 6 . 1 .

667

Thread, s t a r t ,
run .
run .
run, s t a r t .
run, ,
. , ,
run ,
p r i v a t e . ,
. , run
, p u b l i c .
!
run .
, .
C o u n t e r ,
16.3. N,
. ,
( 16.4),
C o u n t e r . 16.5.
16.3. Counter.java
/** Thread, N,
* .
V
p u b l i c c l a s s Counter e x t e n d s Thread {
p r i v a t e s t a t i c i n t totalNum = 0;
p r i v a t e i n t currentNum, l o o p L i m i t ;
p u b l i c C o u n t e r ( i n t loopLimit) {
t h i s . l o o p L i m i t = loopLimit;
currentNum = totalNum++;
}

p r i v a t e void p a u s e ( d o u b l e seconds) {
t r y { Thread, s l e e p (Math, round (100.0. O*seconds) ) ; }
c a t c h ( I n t e r r u p t e d E x c e p t i o n ie) {}
}

/** run
* .
public void run() {
for(int i=0; i<loopLimit; i++) {
System.out.println("Counter " + currentNum + ": " + i) ;
pause(Math.random()); // ""
// 1 .
}
}

668

16.

16.4.CounterSt.Java
/** Counter. */
public class CounterTest {
public static void main(String[] args) {
Counter cl = new Counter(5);
Counter c2 = new Counter (5);
Counter c3 = new Counter(5);
cl.start 0 ;
c2.start();
c3.start 0 ;

16.5. CounterTest
Counter
Counter
Counter
Counter
Counter
Counter
Counter
Counter
Counter
Counter
Counter
Counter
Counter
Counter
Counter

0:
1:
2:
1:
2:
1:
0:
0:
1:
2:
0:
1:
0:
2:
2:

0
0
0
1
1
2
1
2
3
2
3
4
4
3
4

,
Runnable

.
, R u n n a b l e ,
T h r e a d , T h r e a d
R u n n a b l e , s t a r t T h r e a d .
r u n R u n n a b l e ; r u n
T h r e a d . r u n
( R u n n a b l e ) .
( r u n R u n n a b l e r u n T h r e a d ) , ,
. T h r e a d
R u n n a b l e , s t a r t r u n .
16.6.

1 6 . 1 .

669

16.6.ThreadedClass.Java
public c l a s s ThreadedClass extends AnyClass implements Runnable {
public void run() {
/ / .
}

p u b l i c void s t a r t T h r e a d ( ) {
Thread t = new Thread(this);
t . s t a r t O ; / / run ,
/ / , .

run , Runnable,
. run
, .

. ,
, Thread. c u r r e n t T h r e a d ().
16.7
. , ,
16.8, s t a r t Counter2,
Counter2 Thread s t a r t .
16.9 ,
, Counter.
16.7. Counter2.java
/** Runnable, N,
* .

public c l a s s Counter2 implements Runnable {


p r i v a t e s t a t i c i n t totalNum = 0;
p r i v a t e i n t currentNum, loopLimit;
p u b l i c C o u n t e r 2 ( i n t loopLimit) {
t h i s . l o o p L i m i t = loopLimit;
currentNum = totalNum++;
Thread t = new Thread(this);
t.startO ;
p r i v a t e void pause(double seconds) {
t r y { Thread.sleep(Math.round(1000.O*seconds));
c a t c h ( I n t e r r u p t e d E x c e p t i o n ie) {}
p u b l i c void run() {

670

16.

for(int i=0; i<loopLimit; i++) {


System.out.println("Counter " + currentNum + ": " + i ) ;
pause(Math.random()); // ""
// 1 .
}
}
}

16.8. Covinter2Test. Java


/** Counter2.
public class Counter2Test {
public static void main(String[] args) {
Counter2 cl = new Counter2(5)
Counter2 c2 = new Counter2(5)
Counter2 c3 = new Counter2(5)
}
}

16.9. Counter2Test
Counter
Counter
Counter
Counter
Counter
Counter
Counter
Counter
Counter
Counter
Counter
Counter
Counter
Counter
Counter

0:
1:
2:
1:
1:
0:
1:
2:
0:
0:
1:
2:
2:
0:
2:

0
0
0
1
2
1
3
1
2
3
4
2
3
4
4

, ,
, Thread. , , Java
, -
(, Applet), Thread.
, run
. Thread
.
, s t a r t .

16.2. ""

671

16.2. ""
, Runnable,
. , ,
, . ,
, run.
, , ,
,
. 16.10
. , run
, )' .
16.10. BuggyCounterApplet. Java
import J a v a . a p p l e t . A p p l e t ;
import j a v a . a w t . * ;
/** run
* .
* , !
V
public c l a s s BuggyCounterApplet extends Applet
implements Runnable{
p r i v a t e i n t totalNum = 0;
p r i v a t e i n t loopLimit = 5;
/ / s t a r t Thread s t a r t
/ / Applet,
/ / i n i t .
p u b l i c void s t a r t {
Thread t ;
for(int i=0; i<3; i++) {
t = new Thread(this);
t. start 0 ;
}
}
private void pause(double seconds) {
try { Thread.sleep(Math.round(1000.O*seconds)); }
catch(InterruptedException ie) {}
}
public void run() {
int currentNum = totalNxom;
System.out.printlnCSetting currentNum to " + currentNum);
totalNum = totalNum + 1;
for(int i=0; i<loopLimit; i++) {
System, out .printlnC Counter " + currentNijm + ": " + i) ;
pause(Math.random());
}
}

672

16.

16.11. BuggyCounterApplet
> appletviewer BuggyCounterApplet.html
Setting currentNuin to 0
Counter 0: 0
Setting currentNum to 1
Counter 1: 0
Setting currentNum to 2
Counter 2 0
Counter 2 1
Counter 1 1
Counter 0 1
Counter 2 2
Counter 0 2
Counter 1 2
Counter 1 3
Counter 0 3
Counter 2 3
Counter 1 4
Counter 2 4
Counter 0 4
(
16.11), ,
.
, , r u n
t o t a l N u m , .
, , "
" t o t a l N u m .
, 16.12.
16.12. BuggyCounterApplet,

> appletviewer BuggyCounterApplet.html
Setting currentNum to 0
Counter 0: 0
Setting currentNum to 1
Setting currentNum to 1
Counter 0: 1
Counter 1: 0
Counter 1: 0
Counter 0: 2
Counter 0: 3
Counter 1: 1
Counter 0: 4
Counter 1: 1
Counter 1: 2
Counter 1: 3
Counter 1: 2
Counter 1; 3
Counter 1: 4
Counter 1: 4

16.3.

673

"" ,
t o t a l N u m .
public void run() {
i n t currentNum = totalNiim++;
S y s t e m . o u t . p r i n t l n ( " S e t t i n g currentNum t o " +
currentNum);
f o r ( i n t i = 0 ; i < l o o p L i m i t ; i++> {
S y s t e m . o u t . p r i n t l n ( " C o u n t e r " + currentNum +
": " + i) ;
p a u s e (Math. random () ) ;
}
}

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

16.3.
.

. ,
.
, ,
.
.
O b j e c t ,

, .


,
, s y n c h r o n i z e d .
synchronized(someObject) {
//
}

674

1 6 .

s y n c h r o n i z e d , ,
, ,
, ,
w a i t . ,
.
.
, , ,
.
, , .
,
. s o m e O b j e c t ,
; s y n c h r o n i z e d
. -
"" ,
.
, s y n c h r o n i z e d .
. ,
,
s o m e O b j e c t , ,
s o m e O b j e c t , . ,
.

synchronized6noKHpyeT

, .
#


,
s y n c h r o n i z e d .
p u b l i c s y n c h r o n i z e d v o i d someMethodO {
/ / .
}

someMethod,
(.. t h i s ) .
someMethod,
,
( t h i s ) . ,
.
p u b l i c s y n c h r o n i z e d v o i d someMethodO
/ / .
}

p u b l i c v o i d someMethodO {
synchronized(this) {
/ / .
}
}

1 6 . 3 .

675

"",
, .
,
.
r u n .

.
, s y n c h r o n i z e d , ,
, .
s y n c h r o n i z e d , , ,
, ,
synchronized.
!
,
synchronized.

T h r e a d , .
t h i s ,
.
, S o m e T h r e a d e d C l a s s s o m e S h a r e d O b j e c t ,
s t a t i c .
. 'YOHOK"
, ,
d o S o m e O p e r a t i o n s y n c h r o n i z e d .
, d o S o m e O p e r a t i o n ?
p u b l i c c l a s s SomeThreadedClass e x t e n d s Thread {
p r i v a t e s t a t i c RandomClass s o m e S h a r e d O b j e c t ;
p u b l i c synchronized void doSomeOperation()
accessSomeSharedObject();

public void run() {


while(someCondition) {
doSomeOperation0;
/ / .
d o S o m e O t h e r O p e r a t i o n ( ) ; / / .
}
}
}

, s y n c h r o n i z e d
synchronized(this){

676

16.

S o m e T h r e a d e d C l a s s t h i s
. do SomeO p e r a t i o n .
, t h i s .



, .
} - .
, ,
.
p u b l i c void doSomeOperation() {
synchronized(someSharedObject)
accessSomeSharedObject();

Class
C l a s s .
Java C l a s s .
.
public void doSomeOperation() {
synchronized(SomeThreadedClass.class) {
accessSomeSharedObject();
}
}
,
t h i s , C l a s s .



, ,
s t a t i c . :
p u b l i c c l a s s SomeThreadedClass e x t e n d s Thread {
p r i v a t e s t a t i c O b j e c t l o c k O b j e c t = new O b j e c t ( ) ;
p u b l i c void doSomeOperation()
synchronized(lockObject) {
accessSomeSharedObject();

,
. ,
,
.

16.4.

677

, , t h i s
, ,
R u n n a b l e . r u n .

t h i s . , ,
, s y n c h r o n i z e d .

16.4.
, , , ,
. ,
.
,
. , ,
, ,
, .
,
, .
: ,
R u n n a b l e ,
, .
, .

: ,
, )'.

;
v o i d .


( ,
), "". , '
.
,
, "".
,
HTTP- SMTP-.
, .
S o m e C l a s s f o o ,
R a n d o m C l a s s r a n d o m A r g . f o o , . .
.
,
f o o .
p u b l i c c l a s s T h r e a d e d S o m e C l a s s e x t e n d s SomeClass
implements Runnable {
/ / foo v o i d , . .
/ / ,
p u b l i c v o i d f o o ( R a n d o m C l a s s randomArg) {

678

16.

MyThread t = new M y T h r e a d ( t h i s ,
t.start 0;

randomArg);

p u b l i c void run() {
MyThread t = ( M y T h r e a d ) T h r e a d . c u r r e n t T h r e a d ( ) ;
RandomClass randomArg =
(RandomClass)t.getValueSavedEarlier();
super.foo(randomArg);
}
}

, f o o ( s u p e r . f o o )
, f o o ,
.
MyThread :
p u b l i c c l a s s MyThread e x t e n d s T h r e a d {
p r i v a t e Object d a t a ;
p u b l i c MyThread(Runnable r u n n a b l e , Object d a t a )
super(runnable);
this.data = data;

public Object getValueSavedEarlier() {


return data;
}
}
f o o , randomArg, MyThread
MyThread,
"". r a n d o m A r g )' f o o
"", randomArg
s u p e r , f o o . f o o
,
. , ,
f o o .
MyThread , f o o
"" R a n d o m C l a s s R a n d o m C l a s s
(, , S t r i n g , I n t e g e r ,
F l o a t , D o u b l e .) MyThread
randomArg. , MyThread
.
this.data = data.clone();
c l o n e RandomClass "" ,
.. ( ).
,
, 16.13 16.14. RSAKey
c o m p u t e Key,
, RSA.
, .
RSA, N S y s t e m , o u t .
h t t p : / / c o r e w e b p r o g r a m m i n g . com/.

16.4.

16.13. RSAKey. Java


import Java.math.Biglnteger;
/** RSA, .

public class RSAKey {


private static final Biglnteger ONE = new Biglnteger("1");
//
//
//
//
//

.
,
R = ^ mod N.
R = R'^d mod N,
, a d .

public void computeKey(String strNumDigits) {


Biglnteger p, q, n, m, encrypt, decrypt;
int numDigits = Integer.parseint(strNumDigits);
if (numDigits%2==l) {
numDigits++;
}
do {
p = Primes.nextPrime(Primes.random(numDigits/2));
q = Primes.nextPrime(Primes.random(numDigits/2));
n = p.multiply(q);
m = (p.subtract(ONE)).multiply(q.subtract(ONE));
// .
encrypt = Primes.nextPrime(Primes.random(numDigits));
while (!encrypt.gcd(m).equals(ONE)) {
encrypt = Primes.nextPrime(encrypt);
}
// .
decrypt = encrypt.modlnverse(m);
//
// (numDigits).
}while ((decrypt.toString().length() != numDigits) ||
(encrypt.toString().length() != numDigits) ||
(n.toString().length() != numDigits));
System.out.println("\nN
=> " + n ) ;
System.out.println("public => " + encrypt);
System.out.println("private => " + decrypt);

679

680

16.

1 6 . 1 4 . ThreadedRSAKey. Java
import
/**
*
*
*

java.io.*;

,

.
computeKey.

public class ThreadedRSAKey extends RSAKey implements Runnable {


// strNumDigits
// "".
public void computeKey(String strNumDigits) {
RSAThread t = new RSAThread(this, strNumDigits);
t.start 0 ;
}
// strNumDigits .
// ,
public void run() {
RSAThread t = (RSAThread)Thread.currentThread();
String StrNumDigits = t.getStrDigits();
super.computeKey(StrNumDigits);
public static void main(String[] args){
ThreadedRSAKey key = new ThreadedRSAKey()
for (int i=0; i<args.length ; i++) {
key.computeKey(args[i]);
}
}
}
class RSAThread extends Thread {
protected String strNumDigits;
public RSAThread(Runnable rsaObject, String strNumDigits) {
super(rsaObject);
this.StrNumDigits = strNumDigits;
}
public String getStrDigits () {
return(StrNumDigits);

, ,
,
c o m p u t e K e y
. ThreadedRSAKey computeKey;
RSAThread. -

16.5. Thread

681

, ThreadedRSAKey, 16.15.
, ,
, ,
.
2000 . RSA- (United States Pat
ent No. 4,405,829),
.
1 6 . 1 5 . ThreadedRSAKey

> j a v a ThreadedRSAKey 50 8
N
=> 22318033
p u b l i c => 99371593
p r i v a t e => 13439917
N
=> 80587 805972834 4259805164 31184 4 824160199414 998 4 603 9
p u b l i c => 8214 567 32107 9385034 667 0822324 9107 04 7 4 3113 917 4 81417
p r i v a t e => 54738576754079530157967908359197723401677283881913

,
, 17.
HTTP-,
. ,
h a n d l e C o n n e c t i o n , HTTP-
,
S o c k e t .

16.5. Thread
, ,
T h r e a d . w a i t , n o t i f y n o t i f y A l l ,
T h r e a d Ob j e c t .

public ThreadO
T h r e a d
, r u n ,
.
T h r e a d , r u n . new T h r e a d ()
new T h r e a d ( n u l l , n u l l , "Thread-N") , N
.
public Thread(Runnable target)
}< T h r e a d ,
s t a r t r u n ,

682

16.

. T h r e a d ( n u l l ,
t a r g e t , "Thread-N").
public T h r e a d ( T h r e a d G r o u p g r o u p , R u n n a b l e target)
, r u n
R u n n a b l e . t a r g e t .
T h r e a d G r o u p ( c h e c k A c c e s s
). T h r e a d G r o u p
.
. , T h r e a d G r o u p .
, , , ,
. T h r e a d ( g r o u p , t a r g e t ,
"Thread-N").
public Thread(String name)
,
" T h r e a d - N " . .
g e t Name.
T h r e a d ( n u l l , n u l l , n a m e ) . ,
r u n Thread,
, .
public T h r e a d ( T h r e a d G r o u p g r o u p , String n a m e )
.
r u n T h r e a d .
T h r e a d ( g r o u p , n u l l , n a m e ) .
public T h r e a d ( R u n n a b l e target, String name)
,
R u n n a b l e . r u n t a r g e t .
T h r e a d ( n u l l , t a r g e t , n a m e ) .
public T h r e a d ( T h r e a d G r o u p g r o u p , R u n n a b l e target. String name)

, R u n n a b l e . g r o u p
n u l l , c h e c k A c c e s s
S e c u r i t y E x c e p t i o n . g r o u p
n u l l , .
t a r g e t n u l l , r u n T h r e a d .

public final int MAX_PRIORITY


.
public final int MIN__PRIORITY
.

16.5. Thread

683

p u b l i c final int N O R M _ P R I O R I T Y
.
,
.
, Java MAX_PRIORITY 10,
NORM_PRIORITY- 5, MIN_PRIORITY 1. Java
. , Solaris
2 , Windows N T 7 ,
, Java -. Windows
NT Java
.
, ,
.

p u b l i c static int activeCount()


T h r e a d G r o u p (
).
p u b l i c v o i d checkAccessO
, .
c h e c k A c c e s s ,

SecurityManager.
public static native T h r e a d currentThread()
c u r r e n t T h r e a d . ,
s t a t i c
T h r e a d , , .
p u b l i c v o i d destroyO
,
. , . JDK 1.2
.
public static void dumpStack()
S y s t e m , e r r .
p u b l i c static int enumerate(Thread[ ] g r o u p T h r e a d s )
T h r e a d G r o u p ,
.
.
a c t i v e C o u n t .

684

16.

public ClassLoader getContextClassLoader() [Java 2]


g e t C o n t e x t C l a s s L o a d e r C l a s s L o a d e r ,
. C l a s s L o a d e r
s e t C o n t e x t C l a s s L o a d e r , C l a s s L o a d e r
C l a s s L o a d e r .
public final String g e t N a m e ( )
.
public final int getPriority()
g e t P r i o r i t y .

setPriority.
public final T h r e a d G r o u p getThreadGroupO
T h r e a d G r o u p ,
. .
, 1 T h r e a d , .
public void interrupt()
. -,
j o i n , s l e e p w a i t ,
I n t e r r u p t e d E x c e p t i o n . -,
, i s I n t e r r u p t e d .
.
i n t e r r u p t e d , i s l n t e r r u p t e d .
public static b o o l e a n interrupted()
,
(.. ), ,
i n t e r r u p t .
i s l n t e r r u p t e d , ,
.
public final native b o o l e a n isAlive()
t r u e ,
, . ,
r u n , f a l s e . i s A l i v e
, )' - ,
, . i s A l i v e
, , ,
.
public final b o o l e a n i s D a e m o n ( )
, .
, , Java-

16.5. Thread

685

. ,
,
s e t Daemon. ,
, .
public b o o l e a n i s l n t e r r u p t e d ( )
, ;
. , r u n ,
, i n t e r r u p t e d .
public final void join() throws I n t e r r u p t e d E x c e p t i o n
public final s y n c h r o n i z e d j o i n ( l o n g m i l l i s e c o n d s ) throws I n t e r r u p t e d E x c e p t i o n
public final s y n c h r o n i z e d j o i n ( l o n g m i l l i s e c o n d s , int n a n o s e c o n d s ) throws
InterruptedException

, j o i n (
i s A l i v e f a l s e ) .
j o i n , ,
, ;
, , .
j o i n , )'
.
w a i t n o t i f y .
public final native void notify()
public final native v o i d notifyAll()
w a i t , n o t i f y n o t i f y A l l O b j e c t .
n o t i f y "", , , n o t i f y A l l
, ,
. n o t i f y n o t i f y A l l
,
(.. ).
, ,
n o t i f y , )'.
w a i t .
public void run()
,
. r u n . ,
, r u n ;
s t a r t .
public v o i d setContextClassLoader(ClassLoader loader) [Java 2]
( C l a s s L o a d e r ) .
C l a s s L o a d e r , Java -

686

16.

, . S e c u r i t y M a n a g e r
C l a s s L o a d e r ,
S e c u r i t y E x c e p t i o n . C l a s s L o a d e r ,
.
public final void s e t D a e m o n ( b o o l e a n b e c o m e D a e m o n )
.
; s e t Daemon
. Java- ,
, .
public final void s e t N a m e ( S t r i n g t h r e a d N a m e )
.
public 1 v o i d setPriority(int threadPriority)
s e t P r i o r i t y ;

.
Thread.MIN_PRIORITY Thread.MAX_PRIORITY.
.
, MAX_PRIORITY , .
,
,
,
, "" .
public static native void s l e e p ( l o n g m i l l i s e c o n d s ) throws I n t e r r u p t e d E x c e p t i o n
public static native void s l e e p ( l o n g m i l l i s e c o n d s , int n a n o s e c o n d s )
throws I n t e r r u p t e d E x c e p t i o n
,
, . s l e e p ,
.


Thread, sleep .
public s y n c h r o n i z e d native v o i d start()
, r u n .
t a r g e t (. )
n u l l , s t a r t r u n T h r e a d .
R u n n a b l e , s t a r t r u n .
, A p p l e t s t a r t ,
i n i t p a i n t .
. ,
s t a r t .

16.5. Thread

687

public 1 void wait() throws InterruptedException


public final void wait(long milliseconds) throws InterruptedException
public final void wait(long milliseconds, int nanoseconds)
throws InterruptedException
.
n o t i f y n o t i f y A l l .
w a i t Thread, Object,
. :
p u b l i c synchronized void someMethodO {
doSomePreliminaries();
while (!someContinueCondition()) {
try {
/ / .
/ /
/ / nporpaiviMbi,
/ / ,
/ / - .
,
wait ;
} c a t c h ( I n t e r r u p t e d E x c e p t i o n ie) {}
}

continueOperations();
}

w a i t , .
,
( t h i s ) , w a i t
, :
public void someOtherMethod() {
doSomeUnsynchronizedStuff();
synchronized(someObject) {
doSomePreliminaries() ;
while (!someContinueCondition0) {
try {
someObject.wait0 ;
} catch(InterruptedException ie) {}
}
continueOperations();
}
doSomeMoreUnsynchronizedStuff();
}

public static native void yield()



"" ,
,
. y i e l d ,
. ,
" " .
,
. ,
Java 2 .

688

16.


Java
s t o p . Java
,
, ,
. ,
s t o p .
, , run
. :
c l a s s ThreadExample implements Runnable {
p r i v a t e boolean runningsp u b l i c ThreadExample()
Thread t h r e a d = new T h r e a d ( t h i s ) ;
thread.start() ;
}

p u b l i c void run(){
running = t r u e ;
while (running) {
}
}

public void setRunning(boolean running) {


this.running = running;
}
}

, f a l s e r u n n i n g , ,
, w h i l e
run . ,
run , ,
.
Thread
run. }^
, , run.
, 16.16.
s e t S t a t e , : STOP,
RUN WAIT. run ( s t a t e )
STOP (
run s e t S t a t e ) , w h i l e
. s e t S t a t e
"" ,
( t h r e a d , i n t e r r u p t ()) s e t S t a t e
RUN. .

16.5. Thread

16.16-StoppableThread.Java
/** ,
* .

public class StoppableThread extends Thread {


public static final
public static final
public static final
private int state =
/**
*
*
*

int STOP
int RUN
int WAIT
RUN;

= 0
= 1
= 2

,
,
.
checkState.

V
public synchronized void setState(int state) {
this.state = state;
if (state==RUN) {
notify 0 ;
}
}
/** (RUN, STOP, WAIT).
* InterruptedException
* .

V
private synchronized int checkState() {
while (state==WAIT) {
try {
wait ();
} catch (InterruptedException e) { }
}
return state;
/** , ,
* .

V
public void run() {
while (CheckState !=STOP) {

689

690

16.


Applet s t o p , Web ( Netscape)
. Web-
, s t o p
, .


stop .
s tart.

16.6.
ThreadGroup .
, ThreadGroup ,
.
ThreadGroup.

public ThreadGroup(String groupName)


ThreadGroup,
, , .
public ThreadGroup(ThradGroup parent, String groupName)
ThreadGroup,
.

public synchronized int activeCount()


a c t i v e C o u n t ,
.
public synchronized int activeGroupCount()
activeGroupCount ,
.
public final void checkAccess()
,
)1. checkAccess ,
SecurityManager, .

16.6.

691

public final s y n c h r o n i z e d void destroyO


, ,
.
, I l l e g a l T h r e a d S t a t e E x c e p t i o n .
public int e n u m e r a t e ( T h r e a d [ ] threads)
public int enumerate(Thread[ ] t h r e a d s , b o o l e a n recurse)
public int e n u m e r a t e ( T h r e a d G r o u p [ ] groups)
public int e n u m e r a t e ( T h r e a d G r o u p [ ] g r o u p s , b o o l e a n recurse)

. r e c u r s e t r u e , e n u m e r a t e
.
public final int getMaxPriorityO
g e t M a x P r i o r i t y ,
.
s e t M a x P r i o r i t y .
public final String g e t N a m e ( )
.
public final T h r e a d G r o u p getParent()
g e t P a r e n t .
, , n u l l .
public final v o i d interrupt()
i n t e r r u p t ,
. i n t e r r u p t .
public 1 b o o l e a n i s D a e m o n ( )
i s Daemon , .
, .
public final b o o l e a n isDestroyed()
i s D e s t r o y e d , . ,
,
.
T h r e a d T h r e a d G r o u p .
public s y n c h r o n i z e d v o i d list()
,
, S y s t e m , o u t . l i s t .

692

16.

public final b o o l e a n p a r e n t O f ( T h r e a d G r o u p d e s c e n d a n t )
p a r e n t O f , (
) -.
public final v o i d s e t D a e m o n ( b o o l e a n b e c o m e D a e m o n )
,
. s e t Daemon .
public final s y n c h r o n i z e d void setMaxPriority(int max)
,
s e t P r i o r i t y . ,
, . ,
.
public void u n c a u g h t E x c e p t i o n ( T h r e a d thread, Throwable error)
, ,
u n c a u g h t E x c e p t i o n .
.

16.7.


.
, .

paint.
,
.

.

,
. ,
.

paint.
, ,
.

update
paint.
,
.

.

.
.

16.7.

693

paint
, Java-
, r e p a i n t ;
p a i n t , . r e p a i n t u p d a t e ,
p a i n t , G r a p h i c s .
p a i n t ,
,
,
. p a i n t ,
, ,
.
, ,
, . .
, ,
r e p a i n t . p a i n t
( 16.17).
16.17. S h i p S i m u l a t i o n o a v a
import J a v a . a p p l e t . A p p l e t ;
import j a v a . a w t . * ;
p u b l i c c l a s s ShipSimulation extends Applet implements Runnable {
p u b l i c void run() {
Ship s;
for(int i=0; i<ships.length; i++) {
s = ships[i];
s.move(); // *
repaint()
}

p u b l i c void p a i n t ( G r a p h i c s g) {
Ship s;
f o r ( i n t i=0; i < s h i p s . l e n g t h ; i++) {
s = ships[i];
g . d r a w ( s ) ; / / .
}
}

,
.
, ,
. 16.18 ,
, p a i n t , , .
. 16.1.
S i m p l e C i r c l e c i r c l e s .
r e p a i n t S i m p l e C i r c l e .

694

16.

1 v:'^"^ ' ^'"W5j'^"'^^"asf


~3

Drawing Circles

1-

d
^^)^

Computet

. 16.1.
,
p a i n t , ,
.
, ,
,

1 6 . 1 8 . D r a w C i r c l e s . j a v a

import J a v a . a p p l e t . A p p l e t ;
import j a v a . a w t . * ;
import j a v a . a w t . e v e n t . * ;
import j a v a . u t i l . V e c t o r ;
/** ,
.*/
p u b l i c c l a s s DrawCircles extends Applet {
p r i v a t e Vector c i r c l e s ;
/** S i m p l e C i r c l e ,
* Vector,
* ,
* ( r e p a i n t u p d a t e ,
* p a i n t ) .

V
p r i v a t e c l a s s CircleDrawer extends MouseAdapter {
p u b l i c void mousePressed(MouseEvent event) {
circles.addElement(

16.7.

695

new SimpleCircle (event. getX () , event. getY () , 25) ) ,


repaint();
}
}
public void initO {
circles = new Vector();
addMouseListener(new CircleDrawer());
setBackground(Color.white);
/** SimpleCircle
* .

V
public void paint(Graphics g) {
SimpleCircle circle;
for(int i=0; i<circles.size(); i++) {
circle = (SimpleCircle)circles.elementAt(i);
circle.draw(g);
}

16.19 S i m p l e C i r c l e , D r a w C i r c l e s .
1 6 . 1 9 . S i m p l e C i r c l e . J a v a
import

java.awt.*;

/** ,
* , (draw)
public class SimpleCircle {
private int x, y, radius;
public SimpleCircle(int x, int y, int radius) {
setX(x);
setY(y);
setRadius(radius);
}
/** Graphics SimpleCircle
* .

V
public void draw(Graphics g) {
g.fillOval(x - radius, - radius,
radius * 2, radius * 2 ) ;
}
public int getXO { return (x); }
public void setX(int x) { this.x = x; }
public int getYO

{ return (y); }

696

16.

public void setY(int ) { this. = ; }


public int getRadiusO

{ return (radius) ;

public void setRadius(int radius) {


this.radius = radius;



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



,
, ,
. ,
C a n v a s ,
. ,
move . ,
, ,
,
. , , 13.


,
p a i n t ,
.
.
, ,
. C a n v a s
,
.

paint
p a i n t .
. ,
G r a p h i c s ,
XOR drawXxx G r a p h i c s . -

16.7.

697

, ,
, .
16.20 , .
.
. 16.2.
16.20.Rubberband.Java
import Java.applet.Applet;
import java.awt.*;
import Java.awt.event.*;
/k-k . */
public class Rubberband extends Applet {
private int startX, startY, lastX, lastY;
public void init() {
addMouseListener(new RectRecorder());
addMouseMotionListener(new RectDrawer());
setBackground(Color.white);
/ . x, , w, h
* .

V
private void drawRectangle(Graphics g, int startX, int startY,
int stopX, int stopY ) {
int X, y, w^ h;
X = Math.min(startX, stopX);
= Math.min(startY, stopY);
w = Math.abs(startX - stopX);
h = Math.abs(StartY - stopY);
g.drawRect(x, y, w, h ) ;
}
private class RectRecorder extends MouseAdapter {
/**
* .

V
public void mousePressed(MouseEvent event) {
StartX = event.getX0;
StartY = event.getY0;
lastX = StartX;
lastY = StartY;
}
/** ,
public void mouseReleased(MouseEvent event) {

698

16.

Graphics g = getGraphics();
g.setXORMode(Color.lightGray) ;
drawRectangle(g, startX, startY, lastX, lastY);
}
private class RectDrawer extends MouseMotionAdapter {
/** ,
'^ ,
* , .
public void mouseDragged(MouseEvent event) {
int X = event.getX();
int = event.getY0;
Graphics g = getGraphics();
g.setXORMode(Color.lightGray);
drawRectangle(g, startX, startY, lastX, lastY);
drawRectangle(g, startX, startY, x, y ) ;
lastX = x;
lastY = y;

te d i o ( HetP

13
Click and drag to show rubberbanding

iifacf

AR^Ri4*e^n<JlMww^ ;

..^^.. >2^J

. 16.2. Java

,


(
p a i n t )
, .
p a i n t , .
,
.

1 6 . 7 .

699

update
paint
,
.
; p a i n t ,
(, , )
.
. p a i n t ,
, , ,
r e p a i n t .
, u p d a t e ,
p a i n t .
public void update(Graphics g) {
paint(g);
}

p a i n t ,
, , ,
. ,
p a i n t ,
.

, paint,

,
.

16.21 , .
,
. . 16.3,
, .
.
16.21.Bounce.Java

import J a v a . a p p l e t . A p p l e t ;
import j a v a . a w t . * ;
import J a v a . a w t . e v e n t . * ;
import j a v a . u t i l . V e c t o r ;
/**
*
*
*
V

.
,
. update ,
.

public c l a s s Bounce extends Applet implements Runnable,


ActionListener {
p r i v a t e Vector c i r c l e s ;

700

16.

private int width, height;


private Button startButton, stopButton;
private Thread animationThread = null;
public void initO {
setBackground{Color.white) ;
width = getSize0 .width;
height = getSize().height;
circles = new Vector ();
StartButton = new Button("Start a circle");
StartButton.addActionListener(this);
add(startButton) ;
StopButton = new Button("Stop all circles");
StopButton.addActionListener(this);
add(stopButton) ;
}
/**
* "St^rt circle",
'^ ( ) .
* Vector.
* <>
* "Stop all circles"
* .

V
public void actionPerformed(ActionEvent event) {
if (event.getSource() == startButton) {
if (circles.size() == 0) {
// ,
// .
getOraphics().clearRect(, , getSize().width,
getSize().height);
animationThread = new Thread(this);
animationThread.start() ;
}
int radius = 25;
int X = radius + randomint(width - 2 * radius);
int = radius + randomint(height - 2 * radius);
int deltaX = 1 + randomint(10);
int deltaY = 1 + randomint(10);
circles.addElement(new MovingCircle(x, y, radius, deltaX,
deltaY));
} else if (event.getSource() == stopButton) {
if (animationThread != null) {
animationThread = null;
circles.removeAllElements();
}
repaint 0 ;
}
/ g paint,
* . paint
* .

V
public void run() {

16.7.

Thread myThread = Thread.currentThread();


// , animationThread null
while(animationThread==myThread) {
repaint();
pause(100);
}
/** update ,
* .
public void update(Graphics g) {
paint(g);
}
/** ,
* .
public void paint(Graphics g) {
MovingCircle circle;
for(int i=0; i<circles.size(); i++) {
circle = (MovingCircle)circles.elementAt(i);
g.setColor(getBackground());
circle.draw(g); // ,
circle.move(width, height);
g.setColor(getForeground());
circle.draw(g); // .
}
}
// to max
// (), + 1 .
private int randomint(int max) {
double X =
Math, floor ( (double) (max -- 1) * Math. random() ) ;
return((int)(Math.round(x)));
// "" .
private void.pause(int milliseconds) {
try {
Thread.sleep((long)milliseconds);
} catch(InterruptedException ie) {}

701

702

16.

Fife

ctt

)tttm

Favc#e

Jools

1|

Bouncing Circles

iA

J
^

tidfted

' ' [3''{(1

. 16.3. , paint,
,
,

Bounce MovingCircle,
; S i m p l e C i r c l e .
MovingCircle 16.22.
16.22. MovingCircle. java
/**
*
*
*
*

S i m p l e C i r c l e ;
, deltaX d e l t a Y .
,
, ""
.

public class MovingCircle extends SimpleCircle {


private int deltaX, deltaY;
public MovingCircle(int x, int y, int radius, int deltaX,
int deltaY) {
super(x, y, radius);
this.deltaX = deltaX;
this.deltaY = deltaY;
}

16.7.

703

public void move(int windowWidth, int windowHeight) {


setX(getX() + getDeltaX());
setY(getY() + getDeltaY());
bounce(windowWidth, windowHeight);
}
private void bounce(int windowWidth, int windowHeight) {
int X = g e t X O , = g e t Y O , radius = getRadius () ,
deltaX = getDeltaX0, deltaY = getDeltaY();
if ((X - radius < 0) && (deltaX < 0)) {
setDeltaX(-deltaX);
} else if ((X + radius > windowWidth) && (deltaX > 0)) {
setDeltaX(-deltaX);
}
if ((y -radius < 0) && (deltaY < 0)) {
setDeltaY(-deltaY);
} else if((y + radius > windowHeight) && (deltaY > 0)) {
setDeltaY(-deltaY);
}
}
public int getDeltaX0 {
return(deltaX);
}
public void setDeltaX(int deltaX) {
this.deltaX = deltaX;
}
public int getDeltaY0 {
return(deltaY);
public void setDeltaY(int deltaY)
this.deltaY = deltaY;
}
}



. ,
. , ""
, .


.
, .
, ,
.

704

16.

. (
), . ,
u p d a t e , .
; ,
, u p d a t e
, .
Swing-, AWT .
-,
.
1. update.
p a i n t . ,
p a i n t .
2. createlmage.
, ,
, [ . , c r e a t e l m a g e
i n i t ( , ),
.
c r e a t e l m a g e ,
(, s e t V i s i b l e ) .
c r e a t e l m a g e , , n u l l .
- ,
.
s e t V i s i b l e , a d d N o t i f .
!
createlmage ,
,
null.
3. )^ getGraphics.
, G r a p h i c s ,
G r a p h i c s ,
, .
4. .
, .
Swing ,

super.paintComponent.
5. .
d r a w l m a g e .
16.23 , .
DoubleBuf f , Bounce,
,
. . 16.4.

16.7.

16.23.DoubleBufferBounce.Java
import
import
import
import
/**
*
*
*

Java, applet .Appletsjava.awt.*;


Java.awt.event.*;
java.util.Vector;


;
.
update .

V
public class DoubleBufferBounce extends Applet implements
Runnable, ActionListener
private Vector circles;
private int width, height;
private Image offScreenlmage;
private Graphics offScreenGraphics;
private Button startButton, stopButton;
private Thread animationThread = null;
public void initO {
setBackground(Color.white);
width = getSize0.width;
height = getSize().height;
offScreenlmage = createlmage(width, height);
offScreenGraphics = offScreenlmage.getGraphics();
// .
offScreenGraphics.setColor(Color.black);
circles = new Vector();
StartButton = new Button("Start a circle");
StartButton.addActionListener(this);
add(StartButton);
StopButton = new Button("Stop all circles");
StopButton.addActionListener(this);
add(stopButton);
}
/**
*
*
*

*
*
*/


"Start circle",
( ).
Vector.
<>
"Stop all circles"
.

public void actionPerformed(ActionEvent event) {


if (event.getSource() == startButton) {
if (circles.size() == 0) {
animationThread = new Thread(this);
animationThread.start 0 ;
}
int radius = 25;
int X = radius + randomint(width - 2 * radius);

705

706

16.

int = radius + randomint(height - 2 * radius);


int deltaX = 1 + randomint(10);
int deltaY = 1 -f randomint (10) ;
circles.addElement(new MovingCircle(x, y, radius, deltaX,
deltaY));
repaint();
} else if (event.getSource() == stopButton) {
if (animationThread != null) {
animationThread = null;
circles.removeAllElements() ;
}
/**
* , deltaX/deltaY.
* .
*/
public void run () {
MovingCircle circle;
Thread myThread = Thread.currentThread();
// Ha , animationThread null,
while(animationThread==myThread) {
for(int j=0; j<circles.size(); j++) {
circle = (MovingCircle)circles.elementAt(j);
circle.move(width, height);
}
repaint();
pause(100);
}
}
/** update ,
* .
public void update(Graphics g) {
paint(g);
}
/** ,
* .
public void paint(Graphics g) {
offScreenGraphics.clearRect(0, 0, width, height);
MovingCircle circle;
for(int i=0; i<circles.size() ; i++) {
circle = (MovingCircle)circles.elementAt(i);
circle.draw(offScreenGraphics);
}
g.drawImage(offScreenlmage, 0, 0, this);
}
// max
// (), max + 1 .

16.7.

707

private int randomint(int ) {


double X = Math.floor((double)(max + 1 ) * Math.random());
return((int)(Math.round(x)));
}
// "" .
private void pause(int milliseconds) {
try {
Thread.sleep((long)milliseconds);
} catch(InterruptedException ie) {}
}

mm

P e <i Wm 0 c(imtnic^o(

ii(^

^' a .^ ^ iai-**

Bouncing Circles

!it

CHoodilditiss

'
'

4^

1
;n ^jhLk^^^

, , v<g^

. 16.4.
,
.



, .
,
.
, , ,
.

708

16.

.
AWT-
.
Swing ,
Swing.

16.8.
Java
. Web- GIF- (
GIF89A) . GIF-
, Adobe PhotoShop
Quark,
GIF-. Web-, GIF-
. Java
,
GIF89A.
.

Image.

Image.

,
, , ,
r e p a i n t s l e e p .

p a i n t (AWT) p a i n t C o m p o n e n t (Swing)
G r a p h i c s G r a p h i c s 2 D .

, ,
, ,
, , ""
. . 9.
16.24.
Duke ,
, 15 .
( t u m b l e D i r e c t i o n 1),
( t u m b l e D i r e c t i o n - 1 ) .
r e p a i n t , Duke
A p p l e t . r e p a i n t ,
. p a i n t
,
.
, Duke s e t S t a t e ,
HTML-
.
, , .
. 9.

16.8.

16.24. ImageAnimation. Java


import Java.applet.Applet;
import java.awt.*;
public class ImageAnimation extends Applet {
/**
*
*
*
*


15 . Duke
. stop
, setState Duke.
update .

private static final int NUMDUKES


private Duke[] dukes;
private int i;

= 2;

public void initO {


dukes = new Duke[NUMDUKES];
setBackground(Color.white);
}
/**
* .
public void start {
int tumbleDirection;
for (int i=0; KNUMDUKES ; i++) {
tumbleDirection = (i%2==0) ? 1 :-l;
dukes[i] = new Duke(tumbleDirection, this);
dukes[i].start();
}
}
/** update ,
* .
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
for (i=0 ; KNUMDUKES ; 1++) {
if (dukes[i] != null) {
g.drawlmage(Duke.images[dukes[i].getlndex()],
200*1, 0, this);
}
}
}

709

710

16.

/ stop setState
* Duke, ,
* run.

V
public void stop {
for (int i=0; i<NUMDUKES ; i++) {
if (dukes[i] != null) {
dukes[i].setState(Duke.STOP);
}
}
}

16.25.Duke.Java
import Java.applet.Applet;
import java.awt.*;
/**
*
*
*
*

Duke Thread.
Duke
, repaint.
Duke
.

public class Duke extends Thread {


public static final int STOP = 0;
public static final int RUN = 1;
public static final int WAIT = 2;
public static Image[] images;
private static final int NUMIMAGES = 15;
private static Object lock = new Object();
private int state = RUN;
private int tumbleDirection;
private int index = 0;
private Applet parent;
public Duke(int tumbleDirection, Applet parent) {
this.tumbleDirection = tumbleDirection;
this.parent = parent;
synchronized(lock) {
if (images==null) { // ,
images = new Image[ NUMIMAGES ];
for (int i=0; KNUMIMAGES; i++) {
images[i] = parent.getlmage( parent.getCodeBase(),
"images/T" + i + ".gif");
}
}
}
/** .

16.8.

public int getlndexO

{ return index; }

/** , ,
* .
* checkState.

V
public synchronized vo