Академический Документы
Профессиональный Документы
Культура Документы
WEB
PROGRAMMING
MARTY HALL
LARRY BROWN
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
"", 2001
Sun Microsystem, Inc., 2001
25
I. HTML
33
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
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
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
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
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.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
1100
24.1. HTML-
24.2.
24.3. JavaScript
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-. . .
.
.
, , , ,
.
IL Java
Java ,
, ,
Web-. .
Java. Java ?
Java, .
- Java. ,
, , . .
, CLASS PATH JAR-.
Java. , , , , , Math.
. . . .
. . Java Plug-In.
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
. GET POST. -.
. HTTP-.
IV. JavaScript
JavaScript , ,
Web-. .
.
JavaScript. , , , , ,
.
Web-. ,
JavaScript .
Web-. .
. .
HTML-. .
, .
cookie. . C o o k i e .
. .
)'.
. .
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/
.
, .
.
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
...
HTML-.
Web-.
HTML-.
J~1y\ZJSJZJ
36
. 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 - : ^ ^
-Ji' ^
CAKOf KOcii^^oiYiSfON
JNSI^f\/C^
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 . 2 . HTML 4 . 0 HTML
37
.
Web- ,
, ,
HTML-. ,
, HTML-
.
WWW-.
38
, .
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
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
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
Main Heading
pocument: Oortc
.,M .:^:..
1.4. -
43
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
H T M L .
HTML .
. (...)
,
.
, ,
. ,
. , HTML 4.0,
Netscape Internet Explorer, "".
, HTML-
Netscape 4.08-4.7 Internet Explorer 4.01-5.5.
!
Netscape DIR HTML,
VERSION
VERSION HTML .
. H T M L -
45
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
HEAD
TITLE HEAD
BASE, , BGSOUND LINK. , Web . HTML,
,
.
: < ...> ( )
: 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
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 .
49
SRC
SRC URL ,
. wav, . a u MIDI.
LOOP
LOOP , .
1. , - 1 , INFINITE,
, ,
.
SCRIPT ,
JavaScript. JavaScript 24.
: <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.
50
1 . W e b - HTML 4 . 0
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
BACKGROUND BGCOLOR
BACKGROUND URL . ,
, Web-.
, .
. , , ,
,
,
. BACKGROUND,
BGCOLOR, .
BGCOLOR "" , -
- .
(WHITE, #FFFFFF)
- (SILVER, #) . BACKGROUND
BGCOLOR ,
.
.
52
#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\
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
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),
"< " <>.
"<" "<", "&"
"&;".
60
2 . HTML 4.0
2 . 1 . HTML
<
<
>
&
>
&
"
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>
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>
. 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
'
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-,
.
: <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">
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
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
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
FavorRes
Tools:
J 3 i:2f
Help
1^1
^Search
Table Groups
1
Table Groups
Group 1
1 j Group 1
i
Group 1
Group 2
Group 2
Group 2
Group 2
Footer
^'Oone
. 2.10.
,
2.14
COLGROUP, Internet
Explorer, .
2 . 4 .
77
. COLGROUP
. COLGROUP
.
TABLE RULES="GROUPS",
, COLGROUP,
.
COLGROUP COL. COL
COLGROUP. ,
COLGROUP THEAD TBODY.
ALIGNHVALIGN
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
1 Year Cultivar
M
M
E
E-L
E
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).
: <CENTER>... </CENTER>
:
CENTER HTML 4.0
, <DIV ALIGN= "CENTER">,
.
80
2. HTML 4.0
: <NOSCRIPT>... </NOSCRIPT>
:
NOSCRIPT ,
JavaScript.
, JavaScript-.
24.
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
: <>... </>
:
.
: <U>... </U>
:
U, , HTML 4.0,
, .
: <SUB>... </SUB>
:
SUB , ,
, .
: <SUP> .. </SUP>
:
SUP .
: <BIG>... </BIG>
:
BIG , ,
,
.
, .
.
FONT.
: <SMALL>... </SMALL>
:
SMALL , ,
,
.
, .
.
FONT.
3 . 1 .
85
: <INS>... </INS>
: CITE, DATETIME
INS , DEL. INS
, . Internet Explorer 5.0
, Netscape
. CITE DATETIME , DEL.
: <Q>... </Q>
: CITE
Q
. CITE URI , .
Netscape, Internet Explorer .
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
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
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
: <DFN>... </DFN>
:
DFN . Internet Explorer
, , . Netscape
.
: <VAR>... </VAR>
:
VAR .
,
<VAR>, .
: <ACRONYM>... </ACRONYM>
: TITLE
ACRONYM TITLE
. :
<ACRONYM TITLE="Java D e v e l o p m e n t
Kit">JDK</ACRONYM>
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
Emphasized
Strongly Emphasized
Code
Semple Output
Keyboard Text
Dejinilion
Variable
Citation
Emphasized Code
1 JDK Acronym
1
.ij^Done
^
: i My CoflfipUer
'
. 3.2.
Internet Explorer 5.0,
Windows 2000
Professional
3.3.
Web-
.
,
3 . 3 .
91
,
.
,
.
, .
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
, .
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
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
"^^^^^!^.
. 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
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 .
, ,
.
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
t^
: Southwest
mm
Kansas Topography
Gick on a region of Kansas to get information on the teiiain
m that area
. 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.
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
3.6.
105
106
3. HTML 4.0
: <MARQUEE ...> ... </MARQUEE>
: WIDTH, HEIGHT, ALIGN, BEHAVIOR, BGCOLOR, DIRECTION, HSPACE, VSPACE,
LOOP, SCROLLAMOUNT, SCROLLDELAY
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 .
ROWS
ROWS (
FRAMESET) .
:
<FRAMESET ROWS="Rowl-Size,
...
RowN-Size">
</FRAMESET>
N .
(
), , }^ "%" (
),
"*". "*" " "; -
114
4 .
.
.
<FRAMESET
ROWS="50,10%,*f2*">
</FRAMESET>
.
50 . 10
. ,
, (
"*" 2).
. 4.1.
'
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^
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.
. 4.3.
FRAMEORDER
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 .
frames.
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>
<4(
View
go
jQommunicdJof
He^
Frame Cell
Frame Cell
Frame Cell
Frame Cell
Frame Cell
.:^-:^...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>
|ie^
^.~ ^
^ a
Frame Cell
Frame Cell
Frame Cell
This is a sample HTML document.to be used in
frame cells.
Frame Cell
Frame Cell
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
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>
132
4.
ite *
Yivf* fflvra*e*
loot
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
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.
jd
; ^ Done""
i i ^ My Computer
. 4.10. c s - 4 0 1 . h t m l :
, ,
,
Web-.
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.
138
5.
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 Advances in 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
PdJt View
Qo
Ffiwoiites
Help
m ^- :
3!.
. 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.
d'ft
yiew
iQo
Fisp*rt3rites
Jjelp
D a-
S-
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>
, ,
<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>
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
tjetp
Q a- ( ^
mm
"U
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.
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 }
tlelp
. QD a ( m- 3 M 1
C^Xhf Bear CUw
"
HORSEBACK: RIDIHC
111
JRVR PR05RRmmin5
Dom
^.
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.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.8.
^ ^iptxl
Edit
View
- *
Favorites
- '^
i3
loot
159
Help
'3^Sedfch
; i j Favorites
^History
-^- ^
"3
April 1,2001
VViiliam A. Bates
Macrosoft
Blumood.WA 12345
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
,
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;
,
. ,
, . 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>
fio
ofwnunicioi
. 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)
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.
z!
(6)
. 5.9. (a) , ,
; ()
,
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.
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="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>
.:.."
:u^:-:'-^~-:,.<M^'Z^:'^^i^
Si\
IQI*
-*.
;DOGUrfrtt D o n e
5.10.
.:^:......,
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
te4iHHitHiffil'ff1
fe cft ^lew
^^?^
fio
omfnunical ^
11
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.
5.12.
175
<DIV ID="layer2">
<Hl>This is Iayer2.</Hl>
</DIV>
</BODY>
</HTML>
Eaai
Changing Visibility
Dynamically
^!^:^^r
"" ^^*!*"'
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
,
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
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
[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
;
; ; '^z
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 . 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$^^:
??>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.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
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, .
,
.
, ,
( " ",
ActiveX).
Swing,
Java.
Java 2D .
6.3. Java
193
Collection Framework ,
, .
. wav, , a i f f, . a u , . m i d i . rmf.
RMI-IIOP ,
CORBA- .
Enterprise JavaBeans -
, .
,
JDBC.
JavaMail
STP, IMAP4.
JAXP XML-.
, , Java!
,
, .
)^ .
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/.
196
6. Java
L i n u x 86
http://Java.sun.com/products/jdk/1.2/download-linux.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-, , ,
, , ,
,
.
, , 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
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-
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.
^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
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,
. ,
. :
208
7. - .
( ) :
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 .
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
:
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 + ", " + + ") . ")
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);
}
216
7. - .
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. - ...
:
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 .
220
7. - .
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
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. - ...
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.
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
/ * , ( ) .
*
* .
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() ;
}
,
. ( )
(
, ). ,
, .
, .
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);
numSides) {
240
7. - ..
,
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.
.
( M e a s u r e U t i l )
; ,
, .
.
, ,
, . , ,
, ,
, , d e b u g ,
, . Java,
,
(Debuggable).
242
7. - ...
,
, ,
. Java . ,
,
, , .
, ,
. , ,
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 . . , ,
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 ;
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.
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.");}
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
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.
==,
!=
Ii
, . ,
== ,
>=
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
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 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
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) )
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 .
*/
8.5.
271
8.4. F a c t o r i a l
!
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 + '' + " ||
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
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:
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 .
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
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>
8.6. , Java
*
*
*
*
*
*
*
V
public static boolean exec(String command) {
return(exec(command, false, false));
}
/*"^ .
* , .
*
*
*
*
*
'^
*
*
*
*
*
*
*
*
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);
}
" +
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;
}
}
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
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
8.8.
287
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
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
/- .
*/
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
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;
/ , .
* ()
* .
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.23.TreeTest.Java
/** NodeOperator, . */
class PrintOperator implements NodeOperator {
public void operateOn(Node node) {
System.out.println(node.getNodeValue());
}
}
,
8 . 1 1 .
*
*
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 ,
.
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);
}
8.12.
305
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);
}
306
8. Java
throws
,
, . ,
.
:
p u b l i c SomeType s o m e M e t h o d ( . . . )
throws SomeException {
java.io.*;
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-
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);
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.
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">
("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.
329
330
9.
HHkrWWWAn^et
Netscm
S^
^^
:^ "^
, 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 , ().
331
STANDBY
STANDBY , .
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
333
"Internet Explorer for Windows and Solaris only" Internet Explorer Windows
Solaris.
,
.
*izJiii
Fee Edit
C\CWP2\Java-Applets+Graphics-Code
lCvvF2\java-Applets<-Graphics-Code\Backup
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>
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>
, 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.
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, 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 " )
}
9 . 1 2 .
343
'11||1-|11'
JavaManl
. 9.5. ,
;fflg''=^
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.
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
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)
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.
,
.
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.
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 ^
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;
.
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
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
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
364
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
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.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.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
372
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.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
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
* .
378
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.
();
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
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
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.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
}
}
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
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 ,
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
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);
}
. 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
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 .
...
.
.
.
.
.
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
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-
~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
d
Using External Listeners for Event Handling
Click ill the applet to di aw circles.
- 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) {}
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.*;
/ ,
* .
* .
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)
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
_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
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 . ,
H,tiHiflTlil'l'H'Hi'iika,
1^1-1|
J:
i^HyCompulef
. 11.4. JavaTextField
"C#"
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 . ,
^' /
"^
"^
{!31
SI
[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
<
Ytevv
^o
w!(Ttum:at.O(
1 :^ ^1 j^. ~s : ;3 13
Whiteboard Applet
1
Route
29
53|-\==.
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
^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 .
*/
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), ,
.
12.4. CardLayout
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.
,
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,
).
, .
12.4. CardLayout
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.
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.
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.
Demo");
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)
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 .
444
12.
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);
|11|||:||||:1.1|(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.*;
/*^
*
*
*
*
*
.
, .
, ,
.
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
iM 1
. R^ j
Left 1
mm 1
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
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.*;
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- .
^ ^ 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
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
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
13.2. Component
465
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
.
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.
}
}
private int round(double num) {
return((int)Math.round(num));
}
<
BetterCircleTest
gjj<ijj>r
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
. 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
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 ,
* .
|.^^.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.*;
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]);
}
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
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.
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.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
* .
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 {
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
1?||^|
LoQkiK
491
^ Awt
aJColorMenujava
] ColofPopupMenu
Mj Confirm. Java
jgjContirmTest.iava
Fjtejoome:
JDisplayFile.iava
FiwoTj**.
JAHFilesf"")
b]
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.*;
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.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 ,
.
(),
,
,
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
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.
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
, 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.*;
512
13. AWT
Vanilla
ichocolate
Colored Sprinklesg
Cashews
. 13.19. ,
Windows 98
List
28 , ,
L i s t .
13.18. List
513
514
13. AWT
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.
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
Label
.
,
.
.
Panel Frame.
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("");
}
^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
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
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
522
13. AWT
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
,
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.*;
13.20. TextArea
525
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
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.*;
13.21. Label
13.40.ReversibleLabel.Java
import java.awt.*;
import Java.awt.event.*;
/** Label,
* .
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.*;
0,
100));
532
13. AWT
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
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
.
,
.
.
/** , .
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'',','-'';
'^*''' ^'''''^
"^^'
^:[:!''!'''':'''-'-'
:<" ''/'"/.''-
. 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.
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
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);
}
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
^|
__j.
FgvoHte Kovie
Brazil
jMarK
:Curseotthe Demon
JBrian
iLara
Roger
Brent
jMark
Brazil
jjeir
lEwan
A Bug's Life
[Anny
Reser\ruirDcg
im
>0^
Table l>ew<?s
Selectkw wo<ie
J column sefecfeon
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'
^ '^
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
Albers
Favorite C(Hor
Favorite Movie
Favortte Number i
FgvorlteFood
sBrazil
Mark
Andrews
Brian
Beck
Lara
Bunni
Roger
Brinkley
Brent
Chnstian
Mark
Davidson
Brazil
Jeff
Dinkins
Ewan
Dinkins
A Bug's Life
Amy
Fowler
Reservoir Dogs
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
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.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
.
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
* ).
14.5. JButton
559
.rJPJXl
and :"./> TeKt
Bold and Italic Test
Fancy HTML
..0^^/*
. 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
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
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
JSB9rv^thdytTtekMart<$
gSiderwt&itlfcktilafks
JSIidJif ? k s
(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());
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();
}
}
*/
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
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
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.
578
14. Swing
^ M u l t i p l e Document Interfac
^^^^
'^^.|^!^!^1<1
()
()
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
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.
OK
I ! CanceJ
. 14.16. (
Java)
};
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
1^111||||
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
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
?
1#!&|11
ghSjJyfTiwtLab^^
Exampfe
#
WlfH'fflit'' '^'^-'1*'^^^^11
81Forwaml
\
?!
1>|@1|
" |>>5jexTub^s^
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;
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;
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
593
594
14. Swing
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);
}
}
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.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]);
}
598
14. Swing
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
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
608
15. Swing
java.awt.*;
javax.swing.*;
javax.swing.event.*;
javax.swing.border.*;
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
. 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>
15.2. JList
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
. 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
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
/** ,
"Java." */
public String getCountryO {
return(country);
/** ,
"Java." */
public void setCountry(String country) {
this.country = country;
}
/**
*
*
*
*/
,
"Java".
" < >".
15.2. JList
617
. 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, .
15.3. JTree
621
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
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
\^
Htfflwmw
J Root
JRoot
- J Child 1
Grandchild
Grandchild
# Grandchild
% Child 2
Grandchild
* . ? Child 1
^
I Child 2
+ . I Child 3
(a)
(6)
Grandchild
<5 Child 3
# Grandchild
Grandchild
Grandchild
11
12
1.3
2.1
il
23
::
il
31
32
3.3
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" ".".
<>
15.3.JTree
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
, 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 ) " },
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
638
15. Swing
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
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
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
tableModel.setValueAt(df.format(grandTotal),
ROW__LAST, COL_TOTAL) /
tableModel.fireTableDataChanged()/
} catch (NumberFormatException nfe) {
// .
JOptionPane,showMessageDialog(
JTableEvents.this,
"Illegal value entered!");
}
Using TdbleEvenU
$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;
Where-
128.244128 247.RAW
Comment.
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
.
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));
/
" '
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
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,
* .
670
16.
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();
, 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;
16.4.
.
,
R = ^ mod N.
R = R'^d mod N,
, a d .
679
680
16.
1 6 . 1 4 . ThreadedRSAKey. Java
import
/**
*
*
*
java.io.*;
,
.
computeKey.
, ,
,
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 .
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
.
, ,
.
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.
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
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();
}
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) {
}
}
, 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
/** ,
* .
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.
16.6.
691
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.
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
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.
{ return (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 ,
.
700
16.
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.
701
702
16.
Fife
ctt
)tttm
Favc#e
Jools
1|
Bouncing Circles
iA
J
^
tidfted
. 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 .
,
, ""
.
16.7.
703
. ,
. , ""
, .
.
, .
, ,
.
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
/**
*
*
*
;
.
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"
.
705
706
16.
16.7.
707
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.
15 . Duke
. stop
, setState Duke.
update .
= 2;
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
.
16.8.
{ return index; }
/** , ,
* .
* checkState.
V
public synchronized void setState(int state) {
this.state = state;
if (state==RUN) {
notify 0 ;
}
}
/**
*
*
*
V
private synchronized int checkState() {
while (state==WAIT) {
try {
wait 0 ;
} catch (InterruptedException e) {}
}
return state;
}
/**
*
*^
*
index ( ),
repaint . ,
.
V
public void run() {
while (CheckState !=STOP) {
index += tumbleDirection;
if (index < 0) {
index = NUMIMAGES - 1;
}
if (index >= NUMIMAGES) {
index = 0;
}
parent.repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break;
// while.
}
711
712
16.
.|'''14'1'11|'^|1
/ ^
1
4f}
Applet started.
. 16.5.
Duke
16.9.
,
,
- .
. ,
"" .
j a v a x . s w i n g . T i m e r ,
,
.
T i m e r .
A c t i o n E v e n t , .
s t a r t . :
Timer t i m e r = new T i m e r ( p e r i o d ,
timer.start() ;
listener);
T i m e r ,
( ), p e r i o d ,
(. 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 . T i m e r
,
, . T i m e r ,
s e t R e p e a t s ( f a l s e ) . T h r e a d ,
. T i m e r
r e s t a r t .
, T i m e r , .
,
T i m e r , , -
16.9.
713
. . ,
Timer,
. , ,
, s e t C o a l e s e ( f a l s e ) .
, setLogTimers ( t r u e ) ,
, ActionEvent,
.
. setLogTimers s t a t i c ,
, .
Timer
16.26 16.27.
,
Thread .
. TimedDuke
loaded; "".
MediaTracker ,
. a c t ionPe formed
TimedDuke,
r e p a i n t . s t a r t s t o p .
16.26, TimedAnimation. Java
import j a v a . a w t . * ;
import j avax.swing.*;
/** .
* Dukes
* .
V
p u b l i c c l a s s TimedAnimation extends JApplet {
p r i v a t e s t a t i c f i n a l i n t NUMDUKES = 2;
p r i v a t e TimedDuke[] dukes;
p r i v a t e i n t i , index;
p u b l i c void i n i t O {
dukes = new TimedDuke[NUMDUKES];
setBackground(Color.white);
dukesEO] = new TimedDuke( 1, 100, t h i s ) ;
dukes[1] = new TimedDuke(-1, 500, t h i s ) ;
//
Duke.
p u b l i c void s t a r t 0 {
for ( i n t i=0; KNUMDUKES ; i++) {
dukes[i].startTimer();
}
714
16.
Duke.
Java.applet.Applet;
java.awt.*;
Java.awt.event.*;
j avax.swing.*;
Duke
.
actionPerformed, ,
, repaint
.
16.9.
715
tracker.addlmage(images[i] , 0) ;
}
try {
tracker.waitForAll();
} catch (InterruptedException ie) {}
if (!tracker.isErrorAny0) {
loaded = true;
}
}
}
timer = new Timer(msec, this);
}
// .
public int getlndexO
{ return index; }
// . actionPerformed
//
/ / .
public void actionPerformed(ActionEvent event) {
index += tumbleDirection;
if (index < 0){
index = NUMIMAGES - 1;
}
if (index >= NUMIMAGES) {
index = 0;
}
parent.repaint();
}
// , ,
public void startTimerO {
timer.start();
}
// , ,
public void stopTimerO {
timer.stop();
}
T i m e r .
public Timer(int p e r i o d , A c t i o n L i s t e n e r listener)
, .
.
71
16.
Timer
public void addActionListener(ActionListener listener)
A c t i o n L i s t e n e r Timer.
ActionEvent, ,
a c t i o n P e r f ormed.
public boolean isRunningO
t r u e , ;
f a l s e .
public void removeActionListener(ActionListener listener)
A c t i o n L i s t e n e r
Timer.
public void restartO
r e s t a r t .
public void setCoalesce(boolean flag)
s e t C o a l e s c e ( t r u e ) ( f a l s e )
ActionEvent. ,
ActionEvent, ,
. ,
ActionEvent.
public void setDelay(int period)
. .
public void setInitialDelay(int delay)
s e t l n i t i a l D e l a y ( )
. ,
.
public static void setLogTimers(boolean flag)
,
. System, out
:
Timer r i n g i n g :
TimedDuke@3f345.
16.10.
717
16.10.
. ,
, .
; .
,
,
. ,
, .
. ,
.
(
), , , .
, .
,
.
...
.
S t r i n g T o k e n i z e r .
.
HTTP-.
Web- URL.
.
HTTP-.
.
RMI.
lt~y\3J^3J
:
. ,
. , ,
( ).
,
.
, , .
,
, ,
.
.
,
. ,
(socket).
. -
, ,
, Java. URL
,
-. ,
, , Java
RMI
(Remote Method Invocation ) JDBC (Java Database Connec
tivity Java- ). RMI -
720
17.
Java- . JDBC
SQL- . Java Data
base Connectivity 22.
17.1.
. .
1. Socket.
2. ,
Socket.
3. .
4. .
5. Socket .
. ,
, , lOException,
t r y / c a t c h .
Socket
Java- Socket ,
. ,
. ,
IP- . :
Socket c l i e n t = new Socket("hostname'\ portNumber);
1 7 . 1 .
721
t r u e ,
.
, .
, ,
p r i n t I n .
P r i n t W r i t e r .
P r i n t W r i t e r out =
new P r i n t W r i t e r ( c l i e n t . g e t O u t p u t S t r e a m ( ) ,
true);
O b j e c t O u t p u t S t r e a m Java .
O b j e c t O u t p u t S t r e a m , ,
, , : , ,
w r i t e O b j e c t . , ,
r e a d O b j e c t O b j e c t I n p u t S t r e a m .
, AWT- (
), , ,
, S e r i a l i z a b l e .
13, .
, Java , RMI.
,
. ,
. ,
, .
I n p u t S t r e a m R e a d e r .
InputStreamReader in =
new I n p u t S t r e a m R e a d e r ( c l i e n t . g e t l n p u t s t r e a m ( ) ) ;
,
, I n p u t S t r e a m
Buf f e r e d R e a d e r .
.
(
512 )
.
BufferedReader in =
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 m R e a d e r ( c l i e n t . g e t l n p u t S t r e a m O ) ) ;
,
.
722
17.
,
; , , .
. ,
(, ,
).
.
. Java
, O b j e c t l n p u t S t r e a m r e a d O b j e c t .
P r i n t S t r e a m p r i n t n p r i n t l n ,
, S t r i n g
. ( j e c t )
t o S t r i n g .
, S y s t e m , o u t ,
, P r i n t S t r e a m . O u t p u t S t r e a m
P r i n t S t r e a m w r i t e ,
.
P r i n t W r i t e r P r i n t S t r e a m ; p r i n t
p r i n t I n . ,
P r i n t W r i t e r Unicode.
Buf f e r e d R e a d e r : r e a d r e a d L i n e .
r e a d , r e a d L i n e
S t r i n g .
, . r e a d L i n e
EOF ( ,
), , ,
, , ,
. EOF r e a d L i n e
n u l l .
Socket
, c l o s e .
client.close();
, .
, 17.1, .
c o n n e c t , ,
h a n d l e C o n n e c t i o n , .
h a n d l e C o n n e c t i o n ,
( " G e n e r i c N e t w o r k C l i e n t " ) ,
17.1.
723
.
handle Connect ion,
. connect .
17.1.NetworkClient.Java
import java.net.*;
import java.io.*;
/**
*
*
*
*
*
,
.
, ,
connect .
PrintWriter
BufferedReader, SocketUtil.
V
public NetworkClient(String host, int port) {
this.host = host;
this.port = port;
}
/* connect , a
* handleConnection.
V
public void connect() {
try {
Socket client = new Socket(host, port);
handleConnection(client);
} catch(UnknownHostException uhe) {
System.out.println("Unknown host: " + host);
uhe.printStackTrace() ;
} catch(lOException ioe) {
System.out.println("lOException: " + ioe);
ioe.printStackTrace();
}
}
/**
* handleConnection.
*
* ("Generic Network Client"),
* , .
724
17.
SocketUtil ( 17.2)
Buf feredReader PrintWriter.
17.2.SocketUtil.Java
import java.net.*;
import java.io.*;
/** BufferedReader PrintWriter,
* Socket.
public class SocketUtil {
/** BufferedReader . */
public static BufferedReader getReader(Socket s)
throws lOException {
return(new BufferedReader(
new InputStreamReader(s.getlnputStreamO)));
}
/** PrintWriter .
* println PrintWriter
* , .
V
public static PrintWriter getWriter(Socket s)
throws lOException {
17.2. StringTokenizer
725
// true
// .
return(new PrintWriter(s.getOutputStream(), true));
}
}
, , NetworkClientTest, 17.3,
NetworkClient, .
17.3. NetworkClientTest.Java
/**
.
V
public class NetworkClientTest {
public static void main(String[] args) {
String host = "localhost";
int port = 8088;
if (args.length > 0) {
host = args[0];
}
if (args.length > 1) {
port = Integer.parseint(args[1]);
}
NetworkClient nwClient = new NetworkClient(host, port);
nwClient.connect();
}
FTP-
, 17.3,
FTP- Netscape,
21. ">"
DOS UNIX.
> Java N e t w o r k C l i e n t T e s t f t p . n e t s c a p e . c o m 21
G e n e r i c Network C l i e n t :
Made c o n n e c t i o n t o f t p . n e t s c a p e . c o m and g o t ' 2 2 0 f t p 2 6 FTP s e r v e r
(UNIX(r) System V R e l e a s e 4 . 0 ) r e a d y . * i n r e s p o n s e
17.2.
StringTokenizer
. ,
S t r i n g . Java-
S t r i n g T o k e n i z e r , .
726
17.
( j a v a . n e t ,
j a v a . u t i l ) , ,
-, S t r i n g T o k e n i z e r
.
StringTokenizer
, ,
, n e x t T o k e n .
, , ,
n e x t T o k e n .
( c o u n t T o k e n s ) ,
( h a s M o r e T o k e n s ) .
.
p u b l i c StringTokenizer(String input)
,
, ,
. .
p u b l i c StringTokenizer(String input, String delimiters)
,
. .
public StringTokenizer(String input, String d e l i m i t e r s , b o o l e a n
includeDelimiters)
,
. t r u e ,
.
1\/1
public String nextToken()
.
, n e x t T o k e n N o S u c h ElementException.
public String n e x t T o k e n ( S t r i n g delimiters)
,
. n e x t T o k e n ,
, NoSuchElementException.
17.2. StringTokenizer
727
public int c o u n t T o k e n s ( )
c o u n t T o k e n s , .
.
public b o o l e a n h a s M o r e T o k e n s ( )
h a s M o r e T o k e n s ,
; .
n e x t T o k e n ,
, n e x t T o k e n t r y / c a t c h ,
N o S u c h E l e m e n t E x c e p t i o n , ,
h a s M o r e T o k e n s ,
. , h a s M o r e T o k e n s
, n e x t T o k e n ,
.
StringTokenizer ,
17.4.
.
17.4.TokTest.Java
import java.util.StringTokenizer;
/** ,
* - .
V
public class TokTest {
public static void main(String[] args) {
if (args.length == 2) {
String input = args[0], delimiters = args[l];
StringTokenizer tok =
new StringTokenizer(input, delimiters);
while (tok.hasMoreTokens0) {
System.out.println(tok.nextToken());
}
} else {
System.out.println
("Usage: Java TokTest string delimeters");
TokTest.
> Java TokTest http://www. microsoft .com/''gates/ :/.
http
728
17.
microsoft
com
-gates
> Java TokTest "if (tok.hasMoreTokens()) {" " (){ . "
if
tok
hasMoreTokens
17.3. ,
. - t e l n e t .
,
, .
, ,
SMTP (Simple Mail Transfer Protocol
),
, .
_,
q u i t . SMTP-
. 17.5
, 1 . j hu . edu.
17.5.
> t e l n e t a p l . j h u . e d u 25
Trying 1 2 8 . 2 2 0 . 1 0 1 . 1 0 0 . . .
Connected t o a p l c e n M P . a p l . j h u . e d u .
Escape c h a r a c t e r i s ' ' ^ j ' .
220 a p l c e n M P . a p l . j h u . e d u ESMTP S e n d m a i l 8 . 9 . 3 / 8 . 9 . 1 ; S a t ,
12:05:42
500 (EST)
expn h a l l
250 Marty Hall <hall(?aplcenMP. apl. jhu. edu>
expn root
250-Tom Vellani <vellani@aplcenMP.apl.jhu.edu>
250 Gary Gafke <gary@aplcenMP.apl.jhu.edu>
quit
221 aplcenMP.apl.jhu.edu closing connection
Connection closed by foreign host.
10 Feb 2001
,
, ,
, , ,
q u i t . SMTP-
. , , r e a d L i n e -
17.3. , ...
729
, .
,
. readLine
read, ,
, , w r i t e
. , ,
17.6, 17.7 ,
. ,
.
17.6. AddressVerif i e r . java
import j a v a . n e t . * ;
import j a v a . i o . * ;
/** @.
* 25
* *'. .
V
public class AddressVerifier extends NetworkClient {
p r i v a t e String username;
public s t a t i c void main(String[] args) {
if (args.length != 1) {
usage();
}
730
17.
/** , . ^
public static void usage() {
System.out.println ("You must supply an email address
"of the form *username@hostname'.") ;
System.exit(-1);
}
17.4. -...
731
-.
> Java AddressVerifier tbl@w3.org
250 <timbl@hq.lcs.mit.edu>
> Java AddressVerifier tiinbl@hq.lcs.mit.edu
250 Tim Berners-Lee <timbl>
> Java AddressVerifier gosling@mail.javasoft.com
550 gosling... User unknown
17.4. -,
URL
HTTP .
, (
, H T T P ) ,
GET,
" / 1 . ", .
. ,
17.3, r e a d L i n e ,
r e a d L i n e
n u l l .
,
. , Java
URL U R L C o n n e c t i o n ,
HTTP-. ,
"" ;
HTTP ,
. telnet- HTTP, www. c o r e w e b p r o g r a m m i n g . com,
17.8. 80.
17.8. HTML- telnet-
Unix> t e l n e t www.corewebprograimning.com 80
Trying 2 1 6 . 2 4 8 . 1 9 7 . 1 1 2 . . .
Connected t o www.corewebprograinming.com.
Es:?.pe character is ' ^ ] ' .
732
17.
GET / /1.0
/1.1 200
Date: Sat, 10 Feb 2001 18:04:17 GMT
Server: Apache/1.3.3 (Unix) PHP/3.0.11 FrontPage/4.0.4.3
Connection: close
Content-Type: text/html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
</HTML>
C o n n e c t i o n c l o s e d by f o r e i g n
host.
GET. ,
HTTP-
. , , ,
.
, Web-, , ,
. ,
HEAD GET, . Java
HEAD, , ,
, .
,
17.9 ,
, URI ( URL, ).
. ,
GET, N e t w o r k C l i e n t ,
17.1., ,
.
1 7 . 9 . U r i R e t r i e v e r , J a v a
import
import
java.net.*;
java.io.*;
/ * * ,
* , .
V
p u b l i c c l a s s U r i R e t r i e v e r extends NetworkClient {
private String u r i ;
p u b l i c s t a t i c void m a i n ( S t r i n g [ ] args) {
UriRetriever uriClient
17.4. -...
733
V
//
//
//
//
readLine.
,
HTTP- ,
readLine null.
,
URL
, ,
, URI. 17.10 ,
URL S t r i n g T o k e n i z e r ,
URL U r i R e t r i e v e r .
1 7 . 1 0 . U r i R e t r i e v e r . J a v a
import
/**
*
*
*
java.util.*;
,
, .
UriRetriever,
.
V
public class UriRetriever {
public static void main(String[] args) {
checkUsage(args);
StringTokenizer tok = new StringTokenizer(args[0]);
734
17.
UriRetriever
:
Prompt> Java UriRetriever
http://www.microsoft.com/netscape-beats~ie.html
> HTTP/1.1 404 Object Not Found
> Server: Microsoft-IIS/5.0
> Date: Fri, 31 Mar 2000 18:22:11 GMT
> Content-Length: 3243
> Content-Type: text/html
>
> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
> <html dir=ltr>Explicit port number:
17.5, URL
735
:
Prompt> Java UrlRetriever
http://home.netscape.com:80/ie-beats-netscape.html
> HTTP/1.1 404 Not found
> Server: Netscape-Enterprise/3.6
> Date: Fri, 04 Feb 2000 21:52:29 GMT
> Content-type: text/html
> Connection: close
>
> <TITLE>Not Found</TITLE><Hl>Not Found</Hl> The r e q u e s t e d o b j e c t
d o e s n o t e x i s t on t h i s s e r v e r . The l i n k you f o l l o w e d i s e i t h e r o u t
d a t e d , i n a c c u r a t e , o r t h e s e r v e r h a s b e e n i n s t r u c t e d n o t t o l e t you
have i t .
, . " "
. , , ,
.
URL.
, HTTP-
. , 14
, J E d i t o r HTML .
1 7 . 5 . URL
URL , Web-.
, URL,
(, h t t p ) , (, j a v a . s u n . c o m ) ,
(, 80) (, / r e p o r t s / e a r n i n g s . h t m l ) .
URL .
URL
-,
HTTP- ,
, , Java
J a v a . n e t . URL.
9.5: URL t A p p l e t C o n t e x t () . showDocument. , URL
.
URL 17.1L
1 7 . 1 1 . U r l R e t r i e v e r 2 . J a v a
import
import
java.net.*;
java.io.*;
/** URL.
736
17.
UrlRetriever2.
Prompt> Java UrlRetriever2 http://www.whitehouse.gov/
> <HTML>
> <HEAD>
> <TITLE>Welcome To The White House</TITLE>
> </HEAD>
> ... HTML- ...
> </HTML>
, , HTTP-
, U r l R e t r i e v e r .
Java- URLConnection.
URLConnection openConnection
URL. ,
, HTTP- (,
getContentType getLastModif ied).
j a v a . n e t . URLConnection API.
URL
, ,
URL
URL. , URL
.
17.5. URL
737
738
17.
1 7 . 1 2 . U r l T e s t . J a v a
import
java.net.*;
/ URL, ,
* .
public class UrlTest {
public static void main(String[] args) {
if (args.length == 1) {
try {
URL url = new URL(args [0]);
System.out.println
URL: " + url.toExternalFormO + "\n" +
+ url.getFileO + "\n" +
File:
+ url.getHost0 + "\n" +
Host:
+ url.getPort0 + "\n" +
Port:
+ url.getProtocol0 + "\n"
Protocol:
+ url.getRef0);
Reference:
} catch(MalformedURLException mue) {
System.out.println("Bad URL.");
}
else
System.out.printlnC'Usage: UrlTest <URL>")
UrlTest.
> Java UrlTest http://www.irs.g0v/mission/#scjueeze-them-dry
URL: http://www.irs.gov/mission/#squeeze-them-dry
File:
/mission/
Host:
www.irs.gov
Port:
-1
Protocol: http
Reference: squeeze-them-dry
17.6. WebClient:
Web-
, URL
. W e b C l i e n t ,
HTTP-. ,
17.13, HTTP. Submit Request ;
.
J T e x t A r e a , .
,
.
17.6.WebCllent...
739
H t t p C l i e n t ,
17.14. Web-,
JTextArea. ,
H t t p C l i e n t
islnterrupted.
lOiacc L a b e l e d T e x t F i e l d , 17.15,
J T e x t F i e l d J L a b e l .
WebClient .
I n t e r r u p t i b l e , 17.16,
, i s l n t e r r u p t e d . I n t e r r u p t i b l e ,
H t t p C l i e n t WebClient ,
.
h t t p : / / w w w . c o r e w e b programming. com/ .
, w w w . c o r e s e r v l e t s .
com, . 17.1. GET;
. , HTTP HTTP- , 19.
17.13. WebCHent.java
740
17.
int fontSize = 1 4 ;
Font labelFont =
new Font("Serif", Font.BOLD, fontSize);
Font headingFont =
new Font("SansSerif", Font.BOLD, fontSize+4);
Font textFont =
new Font("Monospaced", Font.BOLD, fontSize-2);
JPanel inputPanel = new JPanelO;
inputPanel.setLayout(new BorderLayout());
JPanel labelPanel = new JPanelO;
labelPanel.setLayout(new GridLayout(4,1));
hostField = new LabeledTextField("Host:", labelFont,
30, textFont);
portField = new LabeledTextField("Port:", labelFont,
"80", 5, textFont);
//
// HTTP 1.0. HTTP 1.1,
//
// Host.
requestLineField =
new LabeledTextField("Request Line:", labelFont,
"GET / HTTP/1.0", 50, textFont);
labelPanel.add(hostField);
labelPanel.add(portField);
labelPanel.add(requestLineField);
JLabel requestHeadersLabel =
new JLabel("Request Headers:");
requestHeadersLabel,setFont(labelFont);
labelPanel.add(requestHeadersLabel);
inputPanel.add(labelPanel, BorderLayout.NORTH);
requestHeadersArea = new JTextArea(5, 80);
requestHeadersArea.setFont(textFont);
JScrollPane headerScrollArea =
new JScrollPane(requestHeadersArea);
inputPanel.add(headerScrollArea, BorderLayout.CENTER);
JPanel buttonPanel = new JPanelO;
submitButton = new JButton("Submit Request");
submitButton.addActionListener(this);
submitButton.setFont(labelFont);
buttonPanel.add(submitButton);
inputPanel.add(buttonPanel, BorderLayout.SOUTH);
add(inputPanel, BorderLayout.NORTH);
JPanel resultPanel = new JPanelO;
resultPanel.setLayout(new BorderLayout());
JLabel resultLabel =
new JLabel("Results", JLabel.CENTER);
resultLabel.setFont(headingFont);
resultPanel.add(resultLabel, BorderLayout.NORTH);
resultArea = new JTextArea();
resultArea.setFont(textFont);
JScrollPane resultScrollArea =
new JScrollPane(resultArea);
resultPanel.add(resultScrollArea, BorderLayout.CENTER);
JPanel interruptPanel = new JPanelO;
interruptButton = new JButton("Interrupt Download");
17.6.WebClJent...
interruptButton.addActionListener(this);
interruptButton.setFont(labelFont);
interruptPanel.add(interruptButton);
resultPanel.add(interruptPanel, BorderLayout.SOUTH);
add(resultPanel, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == submitButton) {
Thread downloader = new Thread(this);
downloader.start() ;
} else if (event.getSource() == interruptButton) {
islnterrupted = true/
}
}
public void run() {
islnterrupted = false;
if (hasLegalArgs())
new HttpClient(host, port, requestLine,
requestHeaders, resultArea, this);
}
public boolean islnterrupted() {
return(islnterrupted);
}
private boolean hasLegalArgs() {
host = hostField.getTextFieldO.getText0;
if (host.length 0 == 0) {
report("Missing hostname");
return(false);
}
String portString =
portField.getTextField0 .getText();
if (portString.length 0 == 0) {
report("Missing port number");
return(false);
}
try {
port = Integer.parseint(portString);
} catch(NumberFormatException nfe) {
report("Illegal port number: " + portString);
return(false);
}
requestLine =
requestLineField.getTextField().getText();
if (requestLine.length() == 0) {
report("Missing request line");
return(false);
}
getRequestHeaders();
return(true);
private void report(String s)
741
742
17.
resultArea.setText(s);
}
private void getRequestHeaders() {
for(int i=0; i<requestHeaders.length; i++) {
requestHeaders[i] = null;
}
int headerNum = 0;
String header =
requestHeadersArea.getText();
StringTokenizer tok =
new StringTokenizer(header, "\r\n");
while (tok.hasMoreTokens()) {
requestHeaders[headerNum++] = tok.nextToken();
}
}
17.14.HttpClient.Java
import java.net.*;
import java.io.*;
import javax.swing.*;
/ , WebClient. */
public class HttpClient extends NetworkClient {
private String requestLine;
private String[] requestHeaders;
private JTextArea outputArea;
private Interruptible app;
public HttpClient(String host, int port.
String requestLine, String[] requestHeaders,
JTextArea outputArea, Interruptible app) {
super(host, port);
this.requestLine = requestLine;
this.requestHeaders = requestHeaders;
this.outputArea = outputArea;
this.app = app;
if (checkHost(host)) {
connect() ;
}
}
protected void handleConnection(Socket uriSocket)
throws lOException {
try {
PrintWriter out = SocketUtil.getWriter(uriSocket);
BufferedReader in = SocketUtil.getReader(uriSocket);
outputArea.setText("") ;
out.println(requestLine);
for(int i=0; i<requestHeaders.length; i++) {
if (requestHeaders[i] == null) {
17.6.WebClient...
break;
} else {
out.println(requestHeaders[i] ) ;
}
}
out.println();
String line;
while ((line = in.readLine()) != null &&
!app.islnterrupted()) {
outputArea.append(line + " \ n " ) ;
}
if (app.islnterrupted() ) {
outputArea.append("
Download Interrupted
}
} catch(Exception e) {
outputArea.setText("Error: " + e ) ;
}
}
private boolean checkHost(String host) {
try {
InetAddress.getByName(host);
return(true);
} catch(UnknownHostException uhe) {
outputArea.setText("Bogus host: " + host);
return(false);
}
}
}
17.15.LabeledTextField.Java
import java.awt.*; // FlowLayout, Font,
import javax.swing.*;
/** Label. */
public class LabeledTextField extends JPanel {
private JLabel label;
private JTextField textField;
public LabeledTextField(String labelString,
Font labelFont,
int textFieldSize,
Font textFont) {
setLayout(new FlowLayout(FlowLayout.LEFT));
label = new JLabel(labelString, JLabel.RIGHT);
if (labelFont !- null) {
label.setFont(labelFont) ;
}
add(label);
textField = new JTextField(textFieldSize) ;
if (textFont != null) {
textField.setFont(textFont);
}
add(textField);
");
743
744
17.
Label LabeledTextField.
Label
:
<PRE>
LabeledTextField Itf = new LabeledTextField(...);
Itf.getLabel().someLabelMethod(...);
</PRE>
V
public JTextField getTextField() {
return(textField) ;
17.16.Interruptible.Java
/k-k
*
*
*
1 , ,
. HttpClient
WebClient ,
.
V
public interface Interruptible {
public boolean islnterrupted();
}
17.7.
745
11
ISESSCBI
Hetst: jmnr. c o r e s e r v l e t s .
Port: (
ReqoBsiliikeiijJGET / HTTP/I
Ee^pest Heaiders:
]f^^
, ', ,
Jtf^
Results
HTTF/l.e 200 OK
Date: S a t , 25 Hov 2000 0 0 : 3 5 : 1 4 GKI
S e r v e r : ] l p a c h e / l . 3 . 3 (Unix) F H P / 3 . 0 . 1 1 F r o n t P a g e / 4 . 0 . 4 . 3
iContent-Type: t e x t / h t m l
l e : 15
Via: HTTP/1.0 c l u s t e r . I n h . m d ( T r a t f i c - S e r v e r / 4 . 0 . 0
[dteSlW])
kiDOCTCTE HTML PUBLIC -//W3C//DTD HTML 4 . 0 T r a n s i t i o n a l / / E H " >
|<HTHL>
<HE]a
<TITLE>Core S e r v l e t s and JavaServer Pages (JSP)</TITLE>
^
Interrupt Dowttload
. 17.1. www.coreservlets.com
17.7.
-- ,
. .
1. S e r v e r S o c k e t .
2. S o c k e t S e r v e r S o c k e t .
3. .
4. .
5. .
6. S o c k e t .
. ,
, ,
l O E x c e p t i o n , t r y / c a t c h .
ServerSocket
. ,
, ;
.
746
17.
ServerSocket listenSocket =
new S e r v e r S o c k e t (portNuinber) ;
UNIX ,
1023, 1024-5000 ,
5000. ,
/ e t c / s e r v i c e s , ,
, .
, ,
l O E x c e p t i o n .
Socket ServerSocket
,
, .
a c c e p t S e r v e r S o c k e t ,
S o c k e t .
while(someCondition) {
Socket server = listenSocket.accept();
doSomethingWith(server);
}
,
, a c c e p t , .
,
.
S o c k e t , ,
-, 17.1.
, ,
, .
, .
-,
Buf f e r e d R e a d e r .
BufferedReader in =
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 m R e a d e r ( s e r v e r . g e t l n p u t s t r e a m ( ) ) ) ;
Java O b j e c t l n p u t S t r e a m
Java-. O b j e c t l n p u t S t r e a m ,
, , , :
r e a d O b j e c t
. 13.
,
, .
17.7.
747
Outputs t earn.
p r i n t H p r i n t l n , P r i n t W r i t e r . .
P r i n t W r i t e r out =
new P r i n t W r i t e r ( s e r v e r . g e t O u t p u t S t r e a m ) ;
Java Java,
Obj ectOutputStream.
BufferedReader, D a t a l n p u t S t r e a m P r i n t W r i t e r
, -.
Buf f e r e d R e a d e r r e a d r e a d L i n e .
readByte
r e a d F u l l y D a t a l n p u t S t r e a m . P r i n t W r i t e r
p r i n t
println.
Socket
, Socket,
server.close();
,
.
, 17.17, .
l i s t e n ,
handleConnection, .
h a n d l e C o n n e c t i o n ,
, ,
, h a n d l e C o n n e c t i o n
. h a n d l e C o n n e c t i o n ,
, , ,
, , ,
( "Generic Network Server")
( ).
17.17.NetworkServer.Java
import j a v a . n e t . * ;
import j a v a . i o . * ;
/** .
* handleConnection.
748
*
*
*
17.
listen .
PrintWriter BufferedReader,
NetworkServer SocketUtil.
.
handleConnection.
(System.exit)
,
. maxConnections
,
.
V
public void listen {
int i=0;
try {
ServerSocket listener = new ServerSocket. (port) ;
Socket server;
while((i++ < maxConnections) i| (maxConnections = = 0 ) ) {
server = listener.accept();
handleConnection(server);
}
} catch (lOException ioe) (
System.out.println("lOException: " + ioe) ;
ioe.printStackTrace();
}
}
/
*
'^
*
*
*
*
*
,
, .
<>
.</>
<>
, ,
, .
17.7.
749
System.out.println
("Generic Network Server: got connection from " +
server .getlnetAddress 0 .getHostName 0 + "\n" +
"with first line '" + in.readLine() + " ' " ) ;
out.println("Generic Network Server");
server.close();
}
/**
*
*
*
,
. ,
,
.
.
,
,
.
V
public void setMaxConnections(int maxConnections) {
this.maxConnections = maxConnections;
}
/** , no . */
public int getPortO {
return(port);
}
/k-k . <
* connect.</>
* .
V
protected void setPort(int port) {
this.port = port;
N e t w o r k S e r v e r T e s t N e t w o r k S e r v e r
. 17.18.
1 7 . 1 8 . N e t w o r k S e r v e r T e s t . J a v a
public c l a s s NetworkServerTest {
public s t a t i c void m a i n ( S t r i n g [ ] args)
i n t p o r t = 8088;
i f ( a r g s . l e n g t h > 0) {
port = Integer.parseint(args[0]);
}
750
17.
Web-
, , 17.18,
s y s t e m l . com 8080.
systeml> Java NetworkServerTest
Web- ( Netscape),
system2 . com, :
Generic Network Server:
got connection from system2.com
with first line 'GET /foo/ HTTP/1.0'
NetworkClient NetworkServer
N e t w o r k C l i e n t NetworkServer,
- FTP-,
Web-.
. ,
. s y s t e m l . c o m
6001, system2 . com.
.
to, systeml:
systeml> Java NetworkServerTest 6001
tj, system2:
system2> Java NetworkClientTest systeml.com 6001
tg, systeml:
Generic Network Server:
got connection from system2.com
with f i r s t l i n e 'Generic Network C l i e n t '
tj, system2:
Generic Network Client:
Made connection to systeml.com and got 'Generic Network Server' in
response
17.8. HTTP-
751
17.8. HTTP-
17.19 NetworkServer,
HTTP-. :
,
. ,
HTML- . , ,
HTML-, ,
19 24 , . ,
HTTP- ,
JSP.
.
17.19.EchoSarver.Java
import j a v a . n e t . ^ ;
import j a v a . i o . * ;
import J a v a . u t i l . S t r i n g T o k e n i z e r ;
/**
*
*
*
*
*
*
*
*
*
*
*
*
HTTP-, Web-,
, Web- (
). ,
, (
8088). , server.com.
Web-
h t t p : / / s e r v e r . c o m : 8 0 8 8 / w h a t e v e r .
Web-, , ,
.
CGI- ACTION
FORM h t t p : / / s e r v e r . c o m : 8 0 8 8 / w h a t e v e r .
GET POST.
V
p u b l i c c l a s s EchoServer extends NetworkServer {
p r o t e c t e d i n t maxRequestLines = 50;
p r o t e c t e d S t r i n g serverName = "EchoServer";
/**
* . 8088.
V
p u b l i c s t a t i c void m a i n ( S t r i n g [ ] args) {
i n t p o r t = 8088;
i f ( a r g s . l e n g t h > 0) {
try {
port = Integer.parseint(args[0] ) ;
} catch(NumberFormatException nfe) {}
}
new EchoServer(port,
0);
p u b l i c E c h o S e r v e r ( i n t p o r t , i n t maxConnections) {
s u p e r ( p o r t , maxConnections);
752
17.
listen();
}
/
*
*
*
*
*
handleConnection NetworkServer
.
,
. ,
PRE
HTML- .
V
public void handleConnection(Socket server)
throws IOException{
System.out.println
(serverName + ": got connection from " +
server.getlnetAddress().getHostName());
BufferedReader in = SocketUtil.getReader(server);
PrintWriter out = SocketUtil.getWriter(server);
String[] inputLines = new String[maxRequestLines];
int i;
for (i=0; i<maxRequestLines; i++) {
inputLines[i] = in.readLine();
if (inputLines[i] == null) // .
break;
if (inputLines[i] .length () == 0) { // ,
if (usingPost(inputLines)) {
readPostData(inputLines, i, in);
i = i + 2;
}
break;
}
}
printHeader(out);
for (int j=0; j<i; j++) {
out.println(inputLines[j]);
}
printTrailer(out);
server.close() ;
}
// HTTP- Web-.
// HTTP 1.0
/ / .
private void printHeader(PrintWriter out) {
out.println
("HTTP/1.0 200 OK\r\n" +
"Server: " + serverName + "\r\n" +
"Content-Type: text/html\r\n" +
"\r\n" +
"<HTML>\n" +
"<!DOCTYPE HTML PUBLIC " +
"\"-//W3C//DTD HTML 4.0 Transitional//EN\">\n" +
"<HEAD>\n" +
" <TITLE>" + serverName + " Results</TITLE>\n" +
"</HEAD>\n" +
"\n" +
17.8. HTTP-
"<BODY BGC0L0R=\"#FDF5E6\">\n" +
"<1 ALIGN=\"CENTER\">" + serverName +
" Results</Hl>\n" +
"Here is the request line and request headers\n" +
"sent by your browser:\n" +
"<PRE>");
}
// Web-.
private void printTrailer(PrintWriter out) {
out.println
("</PRE>\n" +
"</BODY>\n" +
"</HTML>\n");
}
// Web- GET,
/ /
// . HTML-
// POST; ,
// HTTP-.
private boolean usingPost(String[] inputs) {
return(inputs[0] .toUpperCase () .startsWith("POST"));
}
private void readPostData(String[] inputs, int i,
BufferedReader in)
throws lOException {
int contentLength = contentLength(inputs);
char[] postData = new char[contentLength];
in.read(postData, 0, contentLength);
inputs[++i] = new String(postData, 0, contentLength);
}
// Content-Length
// , .
private int contentLength(String[] inputs) {
String input;
for (int i=0; i<inputs.length; i++) {
if (inputs[i].length 0 == 0)
break;
input = inputs[i].toUpperCase0;
if (input.StartsWith("CONTENT-LENGTH"))
return(getLength(input));
}
return (0);
}
private int getLength(String length) {
StringTokenizer tok = new StringTokenizer(length);
tok.nextToken();
return(Integer.parseint(tok.nextToken()));
753
754
17.
. 17.2 E c h o S e r v e r ,
, Netscape 4.7,
Windows 98.
^^^Bookmi^
Jff',
fioto:jhrtp
EchoServer Results
Here is the request line and request headers sent by your browser:
GET /top/selling/java/book/
Connection: Keep-Alive
HTTP/1.0
iinage/pjpeg,
iniage/png, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
gfpyr
;DoajrJ(nt Oofs
.t^J 4
. 17.2. EchoServer ,
E c h o S e r v e r , ,
. ,
0.001 ,
0.01 0.01 . ,
0.02 , ,
50 .
, 1000 .
17.20 , E c h o S e r v e r
.
16.
h a n d l e C o n n e c t i o n ,
h a n d l e C o n n e c t i o n . ,
S o c k e t h a n d l e C o n n e c t i o n r u n .
, "". S o c k e t
C o n n e c t i o n , T h r e a d ,
.
1 7 . 2 0 . T h r e a d e d E c h o S a r v e r . J a v a
import
import
java.net.
java.io.^
/ * * E c h o S e r v e r .
*/
17.8. HTTP-
handleConnection,
.
<1></1> handleConnection,
, .
Socket.
, run .
Socket ,
.
V
class Connection extends Thread {
private Socket serverSocket;
public Connection(Runnable serverObject,
Socket serverSocket) {
super(serverObject);
755
756
17.
this.serverSocket = serverSocket;
public Socket getSocketO {
return serverSocket;
}
}
, Echo S e r v e ,
.
757
3.
. HTTP-
RMI-.
4. RMI-, .
RMI-
RMI
.
.
RMI .
1. .
, .
2. RMI-. ,
, ,
, . ,
,
. )^ " ", .
3. . , ,
, .
4. RMI-. 1 ,
, , URL.
,
, ,
.
1. .
.
2. .
(marshalling) . (
, , ,
.)
r m i c .
,
. ,
, .
,
, . , Java 2 -
758
17.
, . ,
Java 2, - v l . 2 r m i c .
3. RMI-peecTpa. ,
. RMI ,
, .
4. . , .
5. . .
RMI
RMI.
. , ,
.
1. .
J a v a . r m i . R e m o t e ;
J a v a . r m i . R e m o t e E x c e p t i o n .
17.21.
17.21.Rem.java
i m p o r t J a v a . r m i . ^;
/
*
*
*
RMI- .
RMI- ,
,
.
V
public interface Rem extends Remote {
public String getMessageO throws RemoteException;
}
2. RMI-.
,
N a m i n g . l o o k u p ,
. CORBA, RMI-
, . URL
rmi :///
rmi: //:/.
,
1099. :
R e m o t e E x c e p t i o n , N o t B o u n d E x c e p t i o n M a l f o r m e d U R L E x c e p t i o n .
t r y / c a t c h .
M a l f o r m e d U R L E x c e p t i o n j a v a . n e t . * .
, S e r i a l i z a b l e ,
j a v a . i o . *,
. RMI-
17.22.
759
3. .
UnicastRemoteObject
, .
RemoteException.
17.23.
17.23. Remlmpl. java
import Java.rmi.*;
import Java.rmi.server.UnicastRemoteObject;
/** Rem, RMI-.
* ,
* URL.
V
public class Remlmpl extends UnicastRemoteObject
implements Rem {
public Remlmpl() throws RemoteException {}
public String getMessage() throws RemoteException {
760
17.
RMI-.
URL. Naming, r e b i n d (
) N a m i n g . b i n d (
, A l r e a d y B o u n d E x c e p t i o n ) .
"" RMI CORBA.
"" , .
t r y / c a t c h , ,
R e m o t e E x c e p t i o n MalformedURLE x c e p t i o n . RMI- 17.24.
1 7 . 2 4 . Remlmpl. j a v a
import
import
java.rmi.*;
java.net.*;
/ * * Remlmpl ( Rem),
* URL Rem.
V
p u b l i c c l a s s RemServer {
public s t a t i c void main(String[] args) {
try {
Remlmpl l o c a l O b j e c t = new R e m l m p l ( ) ;
Naming.rebind("rmi:///Rem", l o c a l O b j e c t ) ;
} catch(RemoteException re) {
System.out.println("RemoteException: " + re);
} c a t c h ( M a l f o r m e d U R L E x c e p t i o n mfe) {
System.out.println("MalformedURLException: " + mfe);
,
. RMI-,
(RemServer) ( R e m C l i e n t ) .
, , RMI, ,
, S e c u r i t y M a n a g e r . RMI
.
,
RMI-,
.
1 7 . 9 . R M I : R e m o t e M e t h o d Invocation
761
1. .
Rem.
Prompt> j a v a c R e m C l i e n t . J a v a
Remlmpl.
Prompt> j a v a c RemServer.Java
2. .
R e m I m p l _ S t u b . c l a s s
RemImpl_Skeleton.class.
( J a v a 2)
Rem. c l a s s , R e m C l i e n t . c l a s s Remlmpl_
S t u b . c l a s s , a R e m . c l a s s , R e m l m p l . c l a s s , R e m S e r v e r . c l a s s
RemImpl_Skeleton.class.
Java 2 R e m I m p l _ S k e l e t o n . c l a s s .
Java 2 ,
RMI - v l . 2 . ,
RMI 1.2, Java 2.
r m i c , RMI
1.2, RMI 1.1, B J D K 1.1.
Java 2, ^^^^^
rmic -"^1.2.
^/
.
^^^^
3. RMI-peecTpa.
RMI- :
Prompt>
rmiregistry
UNIX "&",
. Windows
s t a r t r m i r e g i s t r y . ,
1099.
4. .
:
S e r v e > Java RemServer
RMI-, "&",
. Windows
s t a r t J a v a R e m S e r v e r .
762
17.
5. .
.
Proinpt> Java RemClient
Here i s a remote message.
,
17.25 , .
:
stop
fix)
f () Eva l u a t a b l e ( 17.26).
, i n t e g r a t e ,
:
stop
J f(x)dx
x=8tart +steps ize/2
y^evalObj .evaluate(x) -
stepSiize
x= start
x=stop
. 17.3. integrate
, .
stepSize,
17.25. I n t e g r a l . Java
/** .
* .
*/
public class Integral {
/** f() x = s t a r t x=stop,
* f e v a l u a t e
* Evaluatable.
public static double (double start, double stop,
double StepSize,
763
Evaluatable evalObj) {
double sum = 0.0, current = startswhile (current <= stop) {
sum += evalObj.evaluate(current);
current += stepSize;
}
return(sum);
}
/**
*
*
*
f(x)
start stop. f
evaluate Evaluatable
.
V
public static double integrate(double start, double stop,
int numSteps,
Evaluatable evalObj) {
double StepSize = (stop - start) / (double)numSteps;
start = start + stepSize / 2.0;
return(stepSize * sum(start, stop, stepSize, evalObj));
V
public interface Evaluatable {
public double evaluate(double value);
, ,
,
,
.
.
RMI .
,
,
.
764
17.
1. Remotelntegral.
17.27 , , .
1 7 . 2 7 . R e m o t e l n t e g r a l . J a v a
import
java.rmi.*;
/- . */
public interface Remotelntegral extends Remote {
public double sum(double start, double stop, double stepSize,
Evaluatable evalObj)
throws RemoteException;
public double integrate(double start, double stop,
int numSteps, Evaluatable evalObj)
throws RemoteException;
2. Remotelntegral.
17.28 RMI-. R e m o t e l n t e g r a l
,
. , E v a l u a t a b l e ( S i n , Cos, Q u a d r a t i c )
E v a l u a t a b l e S e r i a l i z a b l e ,
, . S i n , Cos Q u a d r a t i c
17.29-17.31. t o S t r i n g
RMI-.
1 7 , 2 8 . R e m o t e l n t e g r a l C l i e n t . J a v a
import
import
import
java.rmi.*;
java.net.*;
java.io.*;
/ * *
* .
* ,
* .
V
public class RemotelntegralClient {
public static void main(String[] args) {
try {
String host = (args.length > 0) ? args[0] : "localhost";
Remotelntegral remotelntegral =
(Remotelntegral)Naming.lookup("rmi://" + host +
"/Remotelntegral");
for(int steps=10; steps<-10000; steps*=10) {
System.out.printIn
17.29.Sin.Java
import Java.io.Serializable;
/** sin(x),
Evaluatable.
765
766
17.
V
class Cos implements Evaluatable, Serializable {
public double evaluate(double val) {
return(Math.cos(val));
}
public String toStringO {
return("Cosine");
}
}
V
class Quadratic implements Evaluatable, Serializable {
public double evaluate(double val) {
return(val * val);
}
public String toStringO {
return("Quadratic");
}
}
3. Remotelntegral.
17.32 Remotelntegral.
Integral.
17.32. Remotelntegrallmpl. Java
import j ava.rmi.*;
import Java.rmi.server.UnicastRemoteObject;
/** Remotelntegral.
*/
767
f(x),
.
f evaluate
Evaluatable.
4. Remotelntegral.
17.33 , Remotelnte
grallmpl U R L Remotelntegral.
17.33. RemotelntegralServer.Java
import java.rmi.*;
import java.net.*;
/**
*
*
*
*
*
Remotelntegrallmpl
'Remotelntegral',
. ,
.
V
public class RemotelntegralServer {
public static void main(String[] args) {
try {
Remotelntegrallmpl integral = new Remotelntegrallmpl();
Naming.rebind("rmi:///Remotelntegral", integral);
} catch(RemoteException re) {
System.out.println("RemoteException: " + re) ;
} catch(MalformedURLException mfe) {
System.out.println("MalformedURLException: " + mfe);
}
}
768
1 7 .
RMI-,
( R e m o t e l n t e g r a l S e r v e r ) ( R e m o t e l n t e g r a l C l i e n t ) .
, , , ,
S e c u r i t y M a n a g e r . RMI
( ) .
, RMI-,
.
1. .
:
Prompt> j a v a c
Prompt> j a v a c
RemotelntegralClient.Java
RemotelntegralServer.Java
2. .
:
Prompt> rmic - v l . 2
Remotelntegrallmpl
R e m o t e l n t e g r a l . c l a s s , R e m o t e
l n t e g r a l C l i e n t . c l a s s R e m o t e I n t e g r a l I m p l _ S t u b . c l a s s .
R e m o t e l n t e g r a l . c l a s s , R e m o t e l n t e g r a l l m p l . c l a s s Remote
l n t e g r a l S e r v e r . c l a s s . , JDK 1.1, ,
Remote I n t e g
r a l I m p l _ S k e l e t o n , - v l . 1.
3. RMI-peecTpa.
RMI- :
Prompt>
rmiregistry
4. .
:
Prompt> Java R e m o t e l n t e g r a l S e r v e r
5. .
:
Prompt> Java RemotelntegralClient
Approximated with 10 steps:
Integral from 0 to pi of sin(x)=2.0082484079079745
Integral from pi/2 to pi of cos (x)=-1.0010288241427086
Integral from 0 to 5 of x"2=41.5625
Approximated with 100 steps:
Integral from 0 to pi of sin(x)=2.0000822490709877
Integral from pi/2 to pi of cos(x)=-1.000010280911902
769
\sm{x)dx = 2
\ cos{x)dx = -1
/2
Jt/2
55
. R M I ,
, ,
.
1
, RMI-,
.
, RMI, .
, RMI- ,
. RMI-
; r m i r e g i s t r y
.
, ,
, .
, RMI
, .
R M I S e c u r i t y M a n a g e r ,
R e m o t e I n t e g r a l C l i e n t 2 ( 17.34).
System.setSecurityManager(new
RMISecurityManager());
770
1 7 .
rmireglstry
,
AccessExceptlon,
,
PMISecuri
tyManager.
17.34.RemoteIntegralClient2.Java
import java.rmi.*;
import java.net.*;
import java.io.*;
/**
*
*
*
*
Java 2
RemotelntegralClient. SecurityManager
.
V
public class RemoteIntegralClient2 {
public static void main(String[] args) {
try {
System.setSecurityManager(new RMISecurityManager());
String host =
(args.length > 0) ? args[0] : "localhost";
Remotelntegral remotelntegral =
(Remotelntegral)Naming.lookup("rmi://" + host +
"/Remotelntegral") ;
for(int steps=10; steps<=10000; steps*=10) {
System.out.printIn
("Approximated with " + steps + " steps:" +
"\n Integral from 0 to pi of sin(x)=" +
remotelntegral.integrate(0.0, Math.PI,
steps, new Sin()) +
"\n Integral from pi/2 to pi of cos(x)=" +
remotelntegral.integrate(Math.PI/2.0, Math.PI,
steps, new Cos()) +
"\n Integral from 0 to 5 of x''2=" +
remotelntegral.integrate(0.0, 5.0, steps,
new Quadratic()));
}
System.out.println
("'Correct' answer using Math library:" +
"\n Integral from 0 to pi of sin(x)=" +
(-Math.cos(Math.PI) - -Math.cos(0.0)) +
"\n Integral from pi/2 to pi of cos(x)=" +
(Math.sin(Math.PI) - Math.sin(Math.PI/2.0)) +
"\n Integral from 0 to 5 of x^2=" +
(Math.pow(5.0, 3.0) / 3 . 0 ) ) ;
} catch(RemoteException re) {
System.out.println("RemoteException: " + re);
771
catch(NotBoundException nbe) {
System.out.println("NotBoundException: " + nbe);
catch(MalformedURLException mfe) {
System.out.println("MalformedURLException: " + mfe)
}
, Java 2
. ,
. 17.35
,
r m i r e g i s t r y , rmihost, HTTP webhost.
r m i r e g i s t r y 1099.
r m i r e g i s t r y ,
. ,
. ,
, RMI-
1024-65535. , , r m i h o s t ,
. HTTP-,
.
17.35. 1 ( r m i c l i e n t .policy)
grant {
// rmihost - RMI-
// webhost - HTTP-
permission Java.net.SocketPermission
"r^iihost: 1024-65535", "connect";
permission java.net.SocketPermission
"webhost:8 0", "connect";
.
Java - D j a v a . s e c u r i t y . p o l i c y = r m i c l i e n t . p o l i c y
RemoteIntegralClient2
, , J a v a . p o l i c y ,
Java,
. JDK 1.3 J a v a . p o l i c y / r o o t / j d k l . 3 /
lib/security/.
HTTP-, .
, HTTP-
; j a v a . r m i . s e r v e r . c o d e b a s e .
Java
-Djava.rmi.server.codebase=http://webhost:port/directory/
RemotelntegralServer
772
17.
j a v a . r m i . s e r v e r . c o d e b a s e ,
, , HTTP-
h t t p : / / w e b h o s t : p o r t / d i r e c t o r y / . HTTP- ,
80, .
1. .
:
Prompt> j a v a c
Prompt> j a v a c
RemoteIntegralClient2.Java
RemotelntegralServer.Java
2. 1 .
:
Prompt> rmic - v l . 2
Remotelntegrallmpl
3. .
. 17.1 .
R e m o t e I n t e g r a l C l i e n t 2 , R e m o t e l n t e g r a l ,
S i n , Cos Q u a d r a t i c .
E v a l u a t a b l e , , E v a l u a t a b l e
-. ,
r m i p o l i c y . c l i e n t .
,
, R e m o t e l n t e g r a l S e r v e r ,
Remotelntegrallmpl,
R e m o t e l n t e g r a l ( ) E v a l u a t a b l e (
HTTP-). I n t e g r a l ,
I n t e g e r , sum I n t e g e r . e v a l u a t e
R e m o t e l n t e g r a l l m p l .
Remote I n t e g r a l Imp 1_S t u b . ,
S i n , Cos Q u a d r a t i c . e v a u l a t e ,
E v a l u a t a b l e ;
I n t e g r a l . -.
HTTP- Remote I n t e g r a l Imp I S t u b , -.
, HTTP- I n t e g r a l I m p l
R e m o t e l n t e g r a l E v a l u a t a b l e .
, r m i r e g i s t r y ,
.
1 7 . 9 . R M I : R e m o t e M e t h o d Invocation
773
1 7 . 1 .
HTTP-
RemoteIntegralClient2
RemoteIntegralServe
RemoteIntegral
RemoteIntegrallmpl
RemoteIntegral
Evaluatable
RemoteIntegralImp1_Stub
Evaluatable
Sin
RemoteIntegral
Cos
Integral
Quadratic
Evaluatable
RemoteIntegral
Impl_Stub
Sin
Cos
Quadratic
4. HTTP-.
Ha - Remote I n t e g r a l S t u b . c l a s s , R e m o t e I n t e g e r a l . c l a s s E v a l u a t a b l e . c l a s s ,
.
5. RMI-peecxpa.
RMI- :
Server>
/somedirectory/rmiregistry
r m i r e g i s t r y ,
, , ,
CLASS PATH.
!
RMI'peecTp
CLASSPATH, ,
,
. rmireglstry
CLASSPATH, , ,
.
6. .
:
Server> J a v a
-Djava.rmi.server.codebase=http://webhost/rmi/
RemoteIntegralServer
, -
w e b h o s t r m i . ,
, r m i r e g l s t r y , . -
774
1 7 .
,
RMI-.
RMI'peecTp ,
AccessException.
7. .
, ,
( rmihost ,
rmiregistry ):
Client> Java -DJava.security.policy=rmiclient.policy
RemGteIntegralClient2 rmihost
Approximated with 10 steps:
Integral from 0 to pi of sin(x)=2.0082484079079745
Integral from pi/2 to pi of cos(x)=-1.0010288241427086
Integral from 0 to 5 of x^2=41.5625
Approximated with 100 steps:
Integral from 0 to pi of sin(x)=2.0000822490709877
Integral from pi/2 to pi of cos(x)=-1.000010280911902
Integral from 0 to 5 of x"2=41.665624999999906
Approximated with 1000 steps:
Integral from 0 to pi of sin(x)=2.0000008224672983
Integral from pi/2 to pi of cos (x)=-1.000000102808351
Integral from 0 to 5 of x^2-41.666656249998724
Approximated with 10000 steps:
Integral from 0 to pi of sin(x)=2.00000000822436
Integral from pi/2 to pi of cos(x)=-1.0000000010278831
Integral from 0 to 5 of x"2=41.666666562504055
'Correct' answer using Math library:
Integral from 0 to pi of sin(x)=2.0
Integral from pi/2 to pi of cos(x)=-0.9999999999999999
Integral from 0 to 5 of x"2=41.666666666666664
RMI-annera
, RMI-,
,
, , RMI-
RMISecurityManager. ,
. , ,
, RMI-, ,
, HTTP-, ,
.
. HTTP-, ,
, . JAR-
ARCHIVE APPLET.
JAR- 7.10.
775
17.36 ,
RMI. RMI-
, , RMI U R L
getCodeBase () .getHost ().
Netscape 6 . 17.4.
17.36. RemotelntegralApplet. Java
import
import
import
import
import
import
/**
*
*
*
*
*
java.awt.*;
Java.awt.event.*;
java.rmi.*;
java.net.*;
java.io.*;
javax.swing.*;
RemotelntegralClient,
.
.
,
RMISecurityManager .
V
public class RemotelntegralApplet extends JApplet
implements ActionListener {
private Evaluatable[] shapes;
private Remotelntegral remotelntegral;
private JLabel result;
private JTextField startlnput, stoplnput, steplnput;
private JComboBox combo;
public void initO {
String host = getCodeBase().getHost();
try {
remotelntegral =
(Remotelntegral)Naming.lookup("rmi://" + host +
"/Remotelntegral");
} catch(RemoteException re) {
reportError("RemoteException: " + re);
} catch(NotBoundException nbe) {
reportError ("NotBoundException: " -i- nbe);
} catch(MalformedURLException mfe) {
reportError("MalformedURLException: " + mfe);
}
Container context = getContentPane();
// .
shapes = new Evaluatable[]{ new Sin(),
new Cos(),
new Quadratic!) };
combo = new JComboBox(shapes);
context.add(combo, BorderLayout.NORTH);
// ,
startlnput = new JTextField();
stoplnput = new JTextField0;
776
17.
:^ .:^
^ 1
J Ffle Edit Vievv
Search
Go i
Quadratic
i t ^ i,
0 0
i^b^i
5 0
iU'-u
1000
^.,.,>,..
Suhmtt
r r r : : i . '::|
. 17.4. ,
RMI,
Netscape 6
777
17.10.
, Java,
, ,
. :
, ,
.
, .
, .
S t r i n g T o k e n i z e r .
RMI.
,
. HTML-,
,
CGI-.
.
Java-, Web-
)' Web- HTTP-
, .
JavaSei-\'er Pages (JSP),
HTML- .
, HTTP-,
. , JDBC API,
SQL- . , , Java
API, XML-.
-Jzj^-j^
...
18. -
19. Java :
20. JavaServer Pages
21.
22. JDBC
23. -
HTML-
...
, .
FORM.
, .
.
.
.
,
.
.
.
.
.
Sly\ZJ^^
Java- Java-,
. Java
, "
)", Web-.
, , Java- JavaSen^er
Pages. , , ,
.
1 8 . 1 .
HTML-
HTML-
.
. HTML-, HTML .
URL , ,
. (
),
, , :
1=152=25.
. . &=
. ( HTML- GET),
URL . URL
. POST.
)' POST,
, )' .
18.1 HTML- ,
. . 18.1. HTML-
782
18. HTML-
, ,
. Web-. , , f i r s t N a m e ,
l a s t N a m e . -, ! ,
, Web-
, . , ,
, URL h t t p : / / l o c a l h o s t : 8 0 8 8 / S o m e P r o g r a m ,
, .
1 8 . 1 . GetForm.html
<IDOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
<TITLE>A Sample Form U s i n g GET</TITLE>
</HEAD>
Transitional//EN">
<BODY BGC0L0R="#FDF5E6">
<H2 ALIGN="CENTER">A Sample Form U s i n g GET</H2>
<FORM A C T I O N = " h t t p : / / l o c a l h o s t : 8 0 8 8 / S o m e P r o g r a m " >
<CENTER>
F i r s t name:
<INPUT TYPE="TEXT" NAME="firstName" VALUE="Joe"XBR>
L a s t name:
<INPUT TYPE="TEXT" NAME="lastName" VALUE="Hacker"XP>
<INPUT TYPE="SUBMIT"> < ? >
</CENTER>
</FORM>
</BODY>
</HTML>
, ,
, (
) E c h o S e r v e r , 17.8.
"-"
. , URL, E c h o S e r v e r
, Web-.
. 18.2, J o e ,
H a c k e r Submit Query, URL
h t t p : / / l o c a l h o s t : 8 0 8 8 / S o m e P r o g r a m ? f i r s t N a m e = J o e & l a s t N a m e = H a c k e r .
18.2 ,
GET POST; . 18.3.
. 18.4, J o e H a c k e r - f i r s t N a m e =
J o e & l a s t N a m e = H a c k e r ,
, 1-.
18.1.
HTML-
k 4' ^- ^ ^^ -^-
'
'^^''*1<$
783
1 |hp//localhosl/'GetFofm html
First name: p o e
SiAmtt Query
' ^ ==^
boctiment Done
^^^
^<^ -^
,^
.-^ , : J
. HTML-
, .
,
.
19.6.
, ) .
Fie ( *
Si
"3
4 ~i __^<
<>loc*on-|hHp
^. i l //
-J> ^
^
8088/'Somerruyci
,, | i " Bookmafks
EchoSei4'er Results
Here is the request line and request headers sent by your browser:
GET /SoineProgram)?f irstName-JoeflastNeune-Hacker
Relerer: http://localhost/GetFor.html
Connection: Keep-Alive
User-Xgent: H o z i H a / 4 . 7 [en] (Uin98; U)
HTTP/1,0
Host: localhost:8088
Accept: iniage/gif, image/x-xbitrtap, image/jpeg, iroage/pjpeg, iroage/png, */
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-B
',^;.-
^^ :: -2^
784
18. HTML-
18.2. PostForm.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>A Sample Form Using POST</TITLE>
</HEAD>
<BODY BGC0L0R="#FDF5E6">
<H2 ALIGN="CENTER">A Sample Form Using P0ST</H2>
<FORM ACTION="http://localhost:8088/SomeProgram"
METHOD="POST">
<CENTER>
First name:
<INPUT TYPE="TEXT" NAME="firstName" VALUE="Joe"><BR>
Last name:
<INPUT TYPE="TEXT" NAME="lastName" VALUE="Hacker"><P>
<INPUT TYPE="SUBMIT">
</CENTER>
</FORM>
</BODY>
</HTML>
UsmaPOST -Netscdoe
g o j;jc4Tmu'm-^^fof tieto
ll :P ^^ i
f
BiXik-i>afks
IS:
-I- '' J
LcscalJon:jhftp/'/locaihos:t,''PostFofmhtni
;; j j o e
Subtnit Query
* Done
. 18.3. PostForm.html
^;^
18.2. FORM
MfirVffiliffflMiEBaMHHHHHHHHHIIIillllllllliiilillllllillli
file
<* ^ie/v g o
ommurac^tor
I il [
785
__
jrj
EchoSei^ er Results
Here is the request line and request headers sent by your browser:
POST /SotneProgram HTTP/1.0
R e f e r e r : h t t p : / / l o c a l h o s t / P o s t F o r n > . html
Connection: Keep-Alive
User-JLgent: H o z i l l a / 4 . 7 [en] (Win98; U)
Host: localhost:8088
Accept: Itaagei/gii,
image/x-xbitmap, image/Jpeg, iroage/pjpeg, image/png, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,ut-8
Content-type: application/x-www-form-uriencoded
Content-length: 29
firstName-Joes lastName-Hacker
^^^
. 18.4. HTML-, PostForm.html,
Netscape 4.7
18.2. FORM
HTML- ,
. URL ).
,
HTML-
.
.
("="), - 1 "&".
, URL .
URL ( URL "?"),
HTTP-, .
,
METHOD FORM; GET POST.
FORM; !
URL .
1 , .
786
18. HTML-
18.2. FORM
787
""
j j
r^6o
'Links**
I Q Subnj5uefy^ J 1
1 ^ Local r^net
vj
. 18.5. GetForm.html
,
1 Expfotet
' file
<
Vbv
f^voftes
lods
^Go
Lmks *
EchoSei^er Results
Here is the request Hne and request headers sent by your browser:
* ^ l o c ^ rtifdnet
,
m u l t i p a r t / f o r m - d a t a ENCTYPE.
- .
POST.
. ,
( 18.7). , 18.3
, G e t F o r m . h t m l
( 18.1) ,
<FORM
ACTION="http://localhost:8088/SomeProgram">
788
18. HTML-
<FORM
ACTION="http://localhost:8088/SomeProgram"
ENCTyPE="multipart/form-data">
. 18.7 18.8.
1 8 . 3 . M u l t i p a r t F o r m . 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>Using E N C T Y P E = " m u l t i p a r t / f o r m ~ d a t a " < / T I T L E >
</HEAD>
<BODY BGC0L0R="#FDF5E6">
<H2 ALIGN="CENTER">Using
ENCTYPE="multipart/form-data"</H2>
fio
CowtwntcaJo
Netsc
Using ENCTYPE=^'miiltipiirt/form-data'^
First name: j Joe
Last name: JHacker
Submit Query
. 18.7. MultipartForm.html
18.2. FORM
789
n|X!
fl
Here is the request line and request headers sent by your browser:
POST /SomeProgram HTTP/1.0
Referer: h t t p : / / l o c a l h o s t / H u l t i p a r t . r o r . h t m l
Connection: Keep-Alive
User-Agent: H o z i l l a / 4 . 7 [en] (in98; U)
Host: localhost:8088
Accept: iroage/gif, image/x-xbitmap, image/jpeg, image/pjpeg, iroage/png, /
Accept-Encoding: gsip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-e
Content-type: multipart/form-data; boundary*
30247933410805
Content-Length: 253
30247933410805
Content-Disposition: form-data; name="firstName"
Joe
30247933410805
Content-Disposition: form-data; *"lastName"
Hacker
302 47933 410805
",>'
^::.::.:.::^
TARGET
TARGET , .
,
,
. , ,
.
ONSUBMIT ONRESET
JavaScnpt-,
. , ONSUBMIT,
f a l s e , .
JavaScript- ,
, .
ACCEPT ACCEPT-CHARSET
HTML 4.0.
MIME- (ACCEPT) (ACCEPT-CHARSET),
,
. MIME-, ACCEPT,
,
.
790
1 8 . H T M L -
18.3.
HTML , :
, .
(
18.4).
: <INPUT TYPE="TEXT" NAME="..." ...> (
)
: NAME (), VALUE, SIZE, MAXLENGTH, DISABLED, RE^ONLY,
ONCHANGE, ONSELECT, ONFOCUS, ONBLUR, ONKEYDOWN, ONKEYPRESS, ONKEYUP
,
. 18.1-18.3.
, ,
TEXTAREA. TYPE INPUT ,
TEXT, HTML-
. }^ ,
,
,
.
HTML-,
.
,
<Enter> , .
,
. , Netscape
<Enter>,
. .
Internet Explorer <Enter>
, ;
. Mosaic
, <Enter> )
Web-.
!
, <Enter>
.
.
%%
18.3.
791
,
. , HTML-, .
TABINDEX, , 18.11.
NAME
NAME .
= , ,
NAME, - .
VALUE
VALUE
. ,
.
,
: _8text f
ieldname^Sinpo4ue_daHHue.
SIZE
SIZE ,
, .
, ,
.
, ,
(, W). ,
,
Netscape. Internet Explorer ,
, INPUT
FONT CODE.
MAXLENGTH
MAXLENGTH
. ,
SIZE.
DISABLED, R E A D O N L Y
DISABLED ,
READONLY " ". ,
, ,
<>, .
, , ,
. , ,
" ", ,
,
. DISABLED READONLY
HTML 4.0, Netscape 4.x .
792
1 8 . H T M L -
O N C H A N G E , ONSELECT, O N F O C U S , O N B L U R , O N K E Y D O W N ,
ONKEYPRESS O N K E Y U P
,
JavaScript. , ,
,
,
, , .
: <INPUT TYPE="PASSWORD" NAME="..." ...> (
)
: NAME (), VALUE, SIZE, MAXLENGTH, DISABLED, READONLY,
ONCHANGE, ONSELECT, ONFOCUS, ONBLUR, ONKEYDOWN, ONKEYPRESS, ONKEYUP
,
, , ("*").
. 18.9.
, ,
.
. ^ GET URL
, POST.
,
POST.
. 18.9. ,
<INPUTTYPE="PASSWORD" ...>
:<TEXTAREANAME='..." ROWS=xxxCOLS=yyy>... </TEXTAREA>
: NAME (), ROWS (), COLS (), WRAP
(), DISABLED, READONLY, ONCHANGE, ONSELECT, ONFOCUS, ONBLUR,
ONKEYDOWN, ONKEYPI^SS, ONKEYUP
TEXTAREA , ,
. . 18.10.
18.3.
793
VALUE .
,
. , <TEXTAREA> </TEXTAREA>,
, : ,
HTML- . & l t ; ,
&; ,
. ENCTYPE (. 18.2),
. ,
"+", , ,
"%", XX ,
.
NAME
.
ROWS
ROWS ,
. ROWS,
.
COLS
COLS .
,
. COLS,
-. Netscape
(, WRAP
, ). Internet Explorer ,
, .
WRAP
WRAP, Netscape, ,
, ,
, COLS. OFF,
, . ,
, . HARD
"" ;
. , SOFT
,
, .
DISABLED, R E A D O N L Y
DISABLED )^ ,
READONLY . ,
, ,
<>, .
794
18. HTML-
, , ,
. , ,
" ", ,
, , ,
.
HTML 4.0, Netscape 4.x .
ONCHANGE, ONSELECT, ONFOCUS, ONBLUR, ONKEYDOWN,
ONKEYPRESS ONKEYUP
,
JavaScript. ,
, , .
ONCHANGE
. ,
ONSELECT, ,
. ONFOCUS ONBLUR
.
.
,
, 30 .
. 18.10.
<CENTER>
<>
Enter some HTML:<BR>
<TEXTAREA NAME="HTML" R0WS=5 COLS=30>
Delete this text and replace
with some HTML to validate.
</TEXTAREA>
<CENTER>
Enter some HTML:
Delete this text and replace
with some HTML to validate.
. 18.10.
18.4.
, , ..
, HTML-. ,
JavaScript, JavaScript-.
INPUT; TYPE
SUBMIT, RESET BUTTON. , HTML 4.0
BUTTON, Internet
Explorer. ,
, , ,
1 8 . 4 .
795
. BUTTON ,
Web-, ,
, .
, in
tranet, Internet Explorer.
!
Netscape BUTTON.
Submit
: <INPUT TYPE="SUBMIT" ...> (
)
: NAME, VALUE, DISABLED, ONCLICK, ONDBLCLICK, ONFOCUS, ONBLUR
S u b m i t
, URL ACTION
FORM.
, ,
S u b m i t .
, S u b m i t ,
-. . 18.11
S u b m i t , <INPUT TYPE="SUBMIT">
Windows 98.
Submit Query
. 18.11. Submit ,
NAME VALUE
,
. }^ S u b m i t
, NAME ;
-
. ,
. .
VALUE,
.
S u b m i t . . 18.12.
, , ,
Item=256MB+SIMM&Add=Add+Item+to+Cart.
<CENTER>
Item:
<INPUT TYPE="TEXT" NAME="Item" VALUE="256MB SIMM"><BR>
<INPUT TYPE="SUBMIT" NAME="Add"
VALUE="Add Item to Cart">
<INPUT TyPE="SUBMIT" NAME="Delete"
VALUE="Delete Item from Cart">
</CENTER>
796
18. HTML-
. 18.12. Submit ,
DISABLED
DISABLED . )^
, . JavaScript-,
Web-, .
DISABLED HTML 4.0,
Netscape 4.x .
ONCLICK, ONDBLCLICK, O N F O C U S O N B L U R
,
JavaScript. , ONCLICK
ONDBLCLICK, . , )1
ONFOCUS, , ,
ONBLUR, . ,
, f a l s e , .
HTML- , )'
o n C l i c k , o n D b l C l i c k , o n F o c u s o n B l u r .
Transitional//EN">
18.4.
797
<BUTTON TYPE="SUBMIT">Multi-line<BR>label</BUTTON>
<P>
<BUTTON TYPE="SUBMIT">
<B>Label</B> w i t h < I > f o n t < / I > c h a n g e s .
</BUTTON>
<P>
<BUTTON TYPE="SUBMIT">
<IMG S R C = " i m a g e s / J a v a - L o g o . g i f " WIDTH=110 HEIGHT=101
ALIGN="LEFT" ALT="Java Cup Logo">
LabeKBIO^with image
</BUTTON>
</CENTER>
</FORM>
</BODY>
</HTML>
BMK.rnlxfl
fcl^.llu^l^g;i^J|^^P^Jfw.'!';f^
' EHe m
B l
Smgte-line Label
MuttHme
label j
1
'&
i ^
ifJMyCoft
. 18.13. Submit,
BUTTON
<INPUT
Reset
: <INPUT TYPE="RESET" ...> (
)
: VALUE, NAME, DISABLED, ONCLICK, ONDBLCLICK, ONFOCUS, ONBLUR
R e s e t ,
VALUE . R e s e t
.
798
18. HTML-
VALUE
VALUE .
"Reset".
NAME
Reset , NAME,
, . , JavaScript-,
NAME JavaScript- .
DISABLED
.
. JavaScript-, Web-,
. DISABLED
HTML 4.0, Netscape 4.x .
ONCLICK, ONDBLCLICK, ONFOCUS ONBLUR
,
JavaScript. , ONCLICK
ONDBLCLICK, . ,
ONFOCUS, , , ,
ONBLUR, . HTML-
,
onClick, onDblClick, onFocus onBlur.
JavaScript
: <INPUT TYPE="BUTTON" ...> (
)
: NAME, VALUE, DISABLED, ONCLICK, ONDBLCLICK, ONFOCUS, ONBLUR
INPUT BUTTON ,
JavaScript. , Submit
Reset ONCLICK, ONDBLCLICK,
ONFOCUS ONBLUR. , ,
, . JavaScript-
18.5.
799
, ,
. ,
JavaScript- v a l i d a t e Form.
<INPUT TYPE="BUTTON" VALUE="Check Values"
onClick="validateForm{)">
18.5.
,
.
. ;
.
: <INPUT TYPE="CHECKBOX" NAME="..." ...>
( )
: NAME (), VALUE, CHECKED, DISABLED, READONLY, ONCLICK,
ONFOCUS, ONBLUR
, , INPUT
, , .
, . 18.14.
<>
<INPUT TYPE="CHECKBOX" NAME="noEmail" CHECKED>
Check here if you do <I>not</I> want to
get our email newsletter
F Check here if you do not want to get our newsletter
. 18.14. ,
INPUT
,
HTML-.
, ,
. , <>
.
800
1 8 . H T M L -
FOPM ,
.
,
-, .
NAME
,
. ,
JavaScript-,
NAME .
VALUE
' .
VALUE, on. ,
, .
n o E m a i l = o n ,
, .
CGI-, ,
, ;
.
CHECKED
CHECKED, Web-
. .
DISABLED, READONLY
)^^ DISABLED , READONLY
. DISABLED
READONLY HTML 4.0, Netscape 4.x
.
ONCLICK, O N F O C U S O N B L U R
JavaScript-,
, .
: <INPUT TYPE="RADIO" NAME="..." VALUE="..." ...>
( )
: NAME (), VALUE
READONLY, ONCLICK, ONFOCUS, ONBLUR
(),
CHECKED,
DISABLED,
,
.
1 8 . 5 .
801
( NAME).
, .
. ,
, ,
. .
INPUT ,
DL. . 18.15.
, S u b m i t
c r e d i t C a r d = j a v a .
<DL>
<DT>Credit
<DD><INPUT
Visa
<DD><INPUT
Master
<DD><INPUT
Card:
TYPE="RADIO" NAME="creditCard" VALUE="visa">
TYPE="RADIO"
Card
TYPE="RADIO"
VALUE="java"
Java Smart Card
<DD><INPUT TYPE="RADIO"
American Express
<DD><INPUT TYPE="RADIO"
Discover
</DL>
Credit Card:
r Visa
r Master Card
a Java Smart Card
r American Express
r Discover
NAME="creditCard" VALUE="mastercard">
NAME="creditCard"
CHECKED>
NAME="creditCard" VALUE="amex">
NAME="creditCard" VALUE="discover">
. 18.15. HTML-
NAME
,
. ) . , ,
, , .
<INPUT TYPE="RADIO" NAME="Foo" VALUE="Valuel">
<INPUT TYPE="RADIO" NAME="FOO" VALUE="Value2">
!
NAME ,
, .
VALUE
VALUE NAME
. VALUE .
802
18. HTML-
,
HTML-.
CHECKED
, CHECKED, Web-
.
.
DISABLED, R E A D O N L Y
DISABLED , READONLY
" ". DISABLED READONLY
HTML 4.0, Netscape 4.x .
ONCLICK, O N F O C U S O N B L U R
JavaScript-,
, .
18.6.
SELECT ,
. ,
. SELECT
,
, , .
OPTION,
<SELECT> </SELECT>. SELECT .
<SELECT NAME="Name" . . . >
<OPTION VALUE="Valuel">TeKCT 1-
<OPTION VALUE="Value2">TeKCT 2-
<OPTION VALUE="ValueN">TeKCT N-ro
</SELECT>
HTML 4.0 OPTGROUP (
LABEL), OPTION ,
Netscape, Internet Explorer .
18.6.
803
SIZE
SIZE . ,
. SIZE, MULTIPLE, SELECT
.
MULTIPLE
MULTIPLE ,
. ,
.
DISABLED
DISABLED .
DISABLED HTML 4.0, Netscape 4.x
.
ONCLICK, O N F O C U S , O N B L U R O N C H A N G E
,
JavaScript. JavaScript-,
,
, .
: <OPTION ...> ( )
: SELECTED, VALUE, DISABLED
SELECT
, .
SELECTED
<OPTION> SELECTED, ,
Web-.
VALUE
VALUE ,
SELECT. .
<OPTION>.
DISABLED
.
HTML 4.0, Netscape 4.x
.
SELECT,
. <SELECT>
) SIZE MULTIPLE,
. . 18.16 18.17
Web- ,
804
18. HTML-
. ,
l a n g u a g e = j a v a .
, ,
VALUE.
Favorite language:
<SELECT NAME="language">
<OPTION VALUE="c">C
<OPTION VALUE="c++">C++
<OPTION VALUE-"Java" SELECTEOJava
<OPTION VALUE="lisp">Lisp
<OPTION VALUE="perl">Perl
<OPTION VALUE="smalltalk">Smalltalk
</SELECT>
. 18.16. SELECT
^J
1
1
C++
99
Lisp
Perl
Smalltalk
. 18.17. SELECT
SELECT .
,
VALUE ( SELECT ).
, . 18.18,
l a n g u a g e = j a v a & l a n g u a g e = p e r l .
-
, g e t P a r a m e t e r V a l u e s
H t t p S e r v l e t R e q u e s t g e t P a r a m e t e r .
19.6.
L a n g u a g e s you know:<BR>
<SELECT NAME="language" MULTIPLE>
<OPTION VALUE="c">C
<OPTION VALUE="c++">C++
<OPTION VALUE="java" SELECTED>Java
<OPTION VALUE="lisp">Lisp
<OPTION VALUE="perl" SELECTED>Perl
<OPTION VALUE="smalltalk">Smalltalk
</SELECT>
Languages you know.
3
Lisp
Smalltalk J j
. 18.18. SELECT,
MULTIPLE
1 8 . 7 . ...
805
18.7. ,
,
<FOPM>
ENCTYPE= "mul tlpart/form-da
ta "-
NAME
NAME ,
.
VALUE
.
.
SIZE M A X L E N G T H
SIZE MAXLENGTH ,
. SIZE ,
MAXLENGTH .
ACCEPT
ACCEPT MIME-.
)^ )^ ,
.
806
18. HTML-
DISABLED, READONLY
)'
. DISABLED READONLY
HTML 4.0, Netscape 4.x .
ONCHANGE, ONSELECT, ONFOCUS ONBLUR
, JavaScript
, ,
, ,
, .
. . 18.20 ,
Browse.
<FORM ACTION="http://localhost:8088/SomeProgram"
ENCTYPE="multipart/form-data">
Enter data file below:<BR>
<INPUT TYPE="FILE" NAME="fileName">
</FORM>
Enter datafilebelow:
. 18.19.
Browse...
Lookr*:] _jWINDOVv/S
bmdlog.Ul
] Bubbles bmp
SiCALCEXE
^ cap_pi.ini
^ Carved Stone.bmp
^pcd32exe
Li
.'j^CDPLuYEREXE
5? C\^ne\ Screen Sav(
*VCHARMAPEXE
JC] Circles.bmp
^CLEANMGREXE
I File name:
jcdpiaver in,
I F3es 0} type
11
UP&n
. 18.20. ,
Browse
18.8.
HTML- MAP URL
. ,
, URL.
.
, URL , ,
. HTML-
.
, .
, . ,
18.8.
807
URL
. ,
URL ,
.
.
IMAGE
<INPUT TYPE="IMAGE" . . . >.
,
(URL
)' ACTION) .
. =_ .=_.
.
NAME
NAME ,
.
SRC
SRC URL .
ALIGN
ALIGN (, MIDDLE, BOTTOM, LEFT,
RIGHT; BOTTOM) , ALIGN
IMG.
DISABLED
.
DISABLED HTML 4.x, Netscape
4.x .
18.5 ,
. ACTION URL
EchoServer, 17.8. . 18.21
}^, . 18.22
.
808
18. HTML-
1 8 . 5 . ImageMap.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>The IMAGE Input Control</TITLE>
</HEAD>
<BODY>
<H1 ALIGN="CENTER">The IMAGE Input Control</Hl>
Which island is Java? Click and see if you are correct.
<FORM ACTION="http://localhost:8088/GeographyTester">
<INPUT TYPE="IMAGE" NAME="map" SRC="images/indonesia.gif">
</FORM>
Of course, image maps can be implemented <B>in</B>
Java as well. :-)
</BODY>
</HTML>
0t
1< ^mf
f;8vert
look
.^
b*tP
-ll
gj'Oone
^MyCoRwtet
18.8.
809
!^1fri-frailffMiT^I'IVIIIill>'ii'J4'.!''!l-MHHHHHHHHHHHHH^
EchoServ'er Results
Here IS the request line and request headers sent by your browser;
GET /GeographyTester?niap.x-305itiap.y-280 HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, appllcation/wswcrd, application/vnd.ms-excei,
Accept-Language: en-us
Accept-Encoding: gzip, d e f l a t e
User-Agent: H o z i l l a / 4 . 0 (compatible; HSIE 5.0; Windows 98; DigExt)
application/v
Host: localhost:80e8
Connection: Keep-Alive
^
g j Done
* ^ locd
ISMAP
ISMAP <IMG>. IMG
ISMAP CGI-npor .
,
URL.
.
18.6 , ISMAP
, h t t p : / /
l o c a l h o s t : 8 0 8 8 / C h i p T e s t e r . - H T T P ,
17.8. . 18.23 ,
, IMG ISMAP.
, ,
X 271 184 ,
URL h t t p : / / l o c a l h o s t : 8 0 8 8 / C h i p T e s t e r ? 2 7 1 , 184 (. 18.24).
1 8 . 6 . I s M a p . h t m l
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
<TITLE>The ISMAP A t t r i b u t e < / T I T L E >
Transitional//EN">
810
18. HTML-
</HEAD>
<BODY>
<1 ALIGN="CENTER">The ISMAP Attribute</Hl>
<H2>Select a pin:</H2>
<A H R E F = " h t t p : / / l o c a l h o s t : 8 0 8 8 / C h i p T e s t e r " >
<IMG S R C = " i m a g e s / c h i p . g i f " WIDTH=495 HEIGHT=200 ALT="Chip"
BOiyDER=0 ISMAPX/A>
</BODY>
</HTML>
Mi.!iHi'i!ii.fjiiM",MamMi
fie
,*
View go
4: ->' - A^W^^'t%'m'
The ISMAP Attribute
Select a pin:
^^'
^Wpc/^eoalwtt i^8/ChipTe$ef1
. 18.23.
IMG
ISMAP
^,iS^ m ^,^
Si:
image/pjpeg,
-^-*'--
- '
imat
JL!
-^ ^
. 18.24. ,
ISMAP,
URL
18.9.
811
URL .
,
URL .
, INPUT IMAGE.
, URL,
, URL
, IMG ISMAP.
18.9.
)[.
,
. .
-,
. ,
API, (. 19.12),
.
-,
, .
HTML-
. , , Internet-
, .
Web- ,
, .
-,
HTML-. , , ,
,
,
.
itemID=hall001.
<INPUT TYPE="HIDDEN" NA]y[E="itemID" VALUE="hall001">
, "" ,
.
, ,
HTML-. , HTML-,
.
812
1 8 . H T M L -
18.10.
, ,
HTML 4.0 FIELDSET
LEGEND. , Internet
Explorer. , FIELDSET
Netscape 6,
, intranet,
Internet Explorer.
!
Netscape 4.7
FIELDSET.
Explorer</H2>
1 8 . 1 1 .
813
1^ ||||
^
- j
~- - -
Field lA. h e l d A
iField IB: JField
iFieldlCIFieldC
'' 01 Two ;
Field 2A: Held A
Field 2B: jField
Field 2C [Field
J
J:^ !
. 18.25. FIELDSET
: <LEGEND>... </LEGEND>
: ALIGN
FIELDSET.
, .
ALIGN
ALIGN .
( ), BOTTOM, LEFT RIGHT. . 18.25
.
, ALIGN="RIGHT".
.
.
1 8 . 1 1 .
HTML 4.0 TAB INDEX,
, .
,
<>.
Internet Explorer, ,
Internet. ,
Web-. TAB INDEX
18.8, . 18.26.
!
Netscape 4.7 TABINDEX.
814
18. HTML-
18.8. Tabindex.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Controlling TAB Order</TITLE>
</HEAD>
<BODY BGC0L0R="#FDF5E6">
<H2 ALIGN="CENTER">Controlling TAB Order</H2>
<FORM ACTION="http://localhost:8088/SomeProgram">
Field 1 (first tab selection):
<INPUT TYPE="TEXT" NAME="fieldl" TABINDEX=1><BR>
Field 2 (third tab selection):
<INPUT TYPE="TEXT" NAME="field2" TABINDEX=3><BR>
Field 3 (second tab selection):
<INPUT TYPE="TEXT" NAME="fieldS" TABINDEX=2><BR>
</FORM>
</BODY>
</HTML>
\^Hf6ntij^^
"U
18.12.
HTML- FORM,
INPUT, . ACTION
<FORM> URL ,
. INPUT .
HTML-, HTML-,
. -
. URL ( GET),
( POST).
.
, , .
.
JAVA
:
...
.
, JSP.
.
.
.
,
HTTP 1.1.
,
CGI-.
, .
cookie .
.
J~y\ZJ^3J
818
19. Java :
; .
,
, Web-.
HTML- .
Web- ,
.
, ,
, .
Web- .
, Web- .
,
.
Web-
,
.
, ,
,
.
Web-
, HTTP-.
FTP ,
.
, HTTP-.
1 9 . 1 .
CGI-
CGI-
,
, ,
, .
CGI-
. , , , ,
,
, )^' .
Java "
" . CGI- N
) N . )^ -
1 9 . 1 . ...
819
N , .
CGI- .
, ,
, .
,
.
,
, HTML-,
cookie, ,
. , Java,
Perl? , Java-
, , C++
?
, ,
CGI-. , ,
Web-. CGI-
API . Web-
URL
, .
, .
,
.
Java APL
, , , iPlanet Enterprise Sei^ver,
Apache, Microsoft Internet In
formation Server (IIS), IBM WebSphere, StarNine WebStar .
Web- (
). Java 2 Platform, Enter
prise Edition (J2EE; . h t t p : / / j a v a . s u n . c o m / j 2 e e / ) ,
.
, CGI, ,
. , CGI, -
820
19. Java :
,
(, ..)
, ,
CGI- ,
.
CGI- ,
, ,
( , ). , C++
100- . , 900
. ,
, .
,
.
.
. ,
, .
, ,
Java.
Web-,
Web-. Web-
, . , CGI- .
19.2.
,
, .
, , .
API, ,
Web- .
.
.
)' .
JSP
, Java Servlet 2.1 2.2 nJavaServer Pages 1.0 1.1.
Web- ,
, . -
19.2.
821
, ,
h t t p : / / j a v a . s u n . c o m / p r o d u c t s / s e r v l e t / i n d u s t r y . h t m l .
Web- , ,
,
.
,
. ,
, .
Apache Tomcat
Tomcat Java Sei-vlet 2.2
,
Apache.
,
Java 2. Apache Tomcat
h t t p : / / J a k a r t a . a p a c h e . o r g / t o m c a t / .
Allaire JRun
J R u n Java Sei-vlet 2.2 JSP 1.1,
Netscape Enterprise FastTrack, IIS, Micro
soft Personal Web Server, Apache, O'Reilly WebSite StarNine WebStar.
, .
Allaire J R u n h t t p : / / w w w .
a l l a i r e . com/products/j run/.
ServletExec
ServletExec Java SeiMet 2.2 JSP 1.1
Web-,
Solaris, Windows, MacOS, HP-UX Linux.
,
. h t t p : / / w w w .
servletexec.com/.
LiteWebServer
LiteWebSei~ver (LWS)
Web-, Gefion Software Tomcat.
Java Sei~vlet 2.2 JSP 1.1. Gefion Software
WAICooIRunner, Servlet
2.2 JSP 1.1 Netscape FastTrack Enterprise.
h t t p : //www. g e f i o n s o f t w a r e . com/.
Caucho Resin
Resin JSP,
Java SeiMet 2.2 JSP 1.1.
. Caucho Resin
.
h t t p : //www. c a u c h o . c o m / p r o d u c t s / r e s i n / .
822
19. Java :
,
JSP
, Java, n a J D K 1.1 1.3 API. ,
, ,
j a v a x . s e r v l e t . o)^v^ea API .
http://java.sun.com/products/jsp/download.htinl
2.1/1.0 API 2 . 2 / 1 . 1 API.
, .
http://java.sun.eom/products/servlet/2.2/javadoc/
Java Servlet 2.2 JSP 1.1.
http://www.java.sun.com/j2ee/j2sdkee/techdocs/api/
, 1!._;-::";1 /J. i Java 2
Platform, Enterprise Edition (J2EE), Servlet 2.2 JSP 1.1.
,
Java , JSP.
. ,
l i b ,
; s e r v l e t . j a r , JSP
j s p . j a r , j s p e n g i n e . j a r j a s p e r , j a r . j a v a c
, CLASS PATH.
CLASS PATH ,
.
CLASSPATH, (".").
cJAR- 7.10.
,
Web-, , ,
. ,
CLASSPATH .
19.2.
823
,
, ,
HTML- ..
.
DOS
Tomcat JSWDK Windows 95
98, DOS,
. DOS, MS-DOS
Properties ().
Memory () Initial Environment (
) Auto 2816. .
CLASS PATH,
j a v a c
S e r v l e t N a m e . J a v a (
S e r v l e t N a m e ).
, . , ,
, .
.
Tomcat JSWDK. , i n s t a l l d i r
, .
Tomcar 3
instalLdir/webapps/ROOT/WEB-INF/classes
. ,
Servlet 2.2 JSP 1.1, ,
: . . . / W E B - I N F / c l a s s e s . , Allaire JRun
i n s t a l l _ d i r / s e r v e r s / d e f a u l t / d e f a u l t - a p p / W E B - I N F / c l a s s e s .
install_dir/lib
JAR-OB .
instalLdir/webapps/ROOT
HTML-, JSP.
Sei-vlet 2.2 JSP 1.1. ,
Allaire J R u n i n s t a l l d i / s e r v e r s /
default/default-app/.
JSWDK 1.0.1
install_dir/webpages/WEB-INF/servlets
.
824
19. Java :
install_dir/lib
JAR- ,
install_dir/webpages
HTML-, JSP.
,
h t t p : ////.
.
, URL
\\,,^\ ///s^TV^Q'L/_.
, URL
s e r v l e t ( " s " ), ,
s e r v l e t s , c l a s s e s l i b .
URL.
URL , .
, .
URL htt'p: ///servlet/_._.
Web- Web-
JSP ( , HTML- ..). URL,
, : htt'p:
///mb_K_Web/servlet/_._.
, Web URL ,
, Web-.
19.3.
19.1 ,
GET. , HTTP, , GET
HTTP-.
, URL
Web-. , GET
, <0]1> GET METHOD.
POST, ,
<FORM> METHOD="POST".
HTML- 18.
1 9 . 1 . S e r v l e t T e m p l a t e . J a v a
import
import
import
java.io.*;
javax.servlet.^;
javax.servlet.http.*;
19.3.
throws ServletException,
825
lOException {
/ / r e q u e s t
/ / , H T T P - , ,
/ / HTML-.
/ / r e s p o n s e "
/ / HTTP- .
P r i n t W r i t e r out = r e s p o n s e . g e t W r i t e r ( ) ;
/ / o u t .
, , H t t p S e r v l e t .
d o G e t d o P o s t . GET
d o G e t , POST d o P o s t .
,
, d o G e t d o P o s t ,
, , d o P o s t d o G e t .
, ^
H t t p S e r v l e t R e q u e s t H t t p S e r v l e t R e s p o n s e .
H t t p S e r v l e t R e q u e s t ,
, , ,
, .. H t t p S e r v l e t
R e s p o n s e .
(200, 404 .) ( C o n t e n t - T y p e , S e t - C o o k i e , ..)
, H t t p S e r v l e t R e s p o n s e P r i n t W r i t e r ,
. p r i n t l n .
, , HTTP-, HTTP- cookie
.
d o G e t d o P o s t ,
. , ,
j a v a . i o ( P r i n t W r i t e r .), j a v a x . s e r v l e t
( H t t p S e r v l e t .) j a v a x . s e r v l e t . h t t p ( H t t p S e r v l e t R e q u e s t
HttpServletResponse).
,
19.2 , .
. 19.1. ,
HTML-,
19.3. , HTML-,
,
.
-, ,
CLASS PATH HaJAR-,
826
19. Java :
j a v a x . s e r v l e t (. 19.2). -,
j a v a c HelloWorld. Java (
). -, HelloWorld. c l a s s
, (
i n s t a l l _ d i r / . . ./WEB-INF/classes).
Java , -D j a v a c . ,
h t t p : / / / s e r v l e t /
URL, .
, . 19.1,
, .
19.2.HelloWorld.Java
import j a v a . i o . * ;
import j a v a x . s e r v l e t . * ;
import j a v a x . s e r v l e t . h t t p . * ;
p u b l i c c l a s s HelloWorld extends H t t p S e r v l e t {
p u b l i c void doGet(HttpServletRequest r e q u e s t ,
HttpServletResponse response)
throws S e r v l e t E x c e p t i o n , lOException {
P r i n t W r i t e r out = r e s p o n s e . g e t W r i t e r ( ) ;
o u t . p r i n t l n C ' H e l l o World");
}
Fie ytew go
ljlxafoft-|httpMocalhost/se>vlet/HelloWofld^^^'^^
. 19.1. ,
19.2
Hello World
Ooain
\^
J..? : i | . ^
,,\
(HelloWorld.j ava)
HTML-KOM
HTML-.
.
1. ,
HTML
2. HTML- , p r i n t In.
HTTP-
Content-.
s e t H e a d e r H t t p S e r v l e t R e s p o n s e , Content-Type
, H t t p S e r v l e t R e s p o n s e
s e t C o n t e n t T y p e . HTML 1- t e x t / h t m l ,
:
response.setContentType("text/html");
19.3.
827
HTML, . ,
,
GIF ( i m a g e / g i f ) Excel ( a p p l i c a t i o n / v n d . m s - e x c e l ) .
HTTP- 19.10. ,
,
, P r i n t W r i t e r . , HTTP-
, ,
, .
; ,
. -.
, ,
Web- ,
. 2.1
P r i n t W r i t e r ,
, . 2.2
,
. getBuf f e r S i z e
H t t p S e r v l e t R e s p o n s e , ,
setBuf f e r S i z e . 2.2
, ,
.
, ,
isCoiranitted.
Content-Type
.
%
HTML- , p r i n t In,
HTML-, I .
19.3 , cwp.
. 19.2. ,
, ,
CLASS PATH ,
( cwp).
package cwp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWWW extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, lOException {
828
19. Java :
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" +
"<BODY>\n" +
"<Hl>Hello WWW</Hl>\n" +
"</BODY></HTML>");
UJJ ^^ ^^ J
AS^es*[#] http/'/locaihost/servlet.^cwpHelloWWW
i*'^*^
Hello WWW
d
Done
|^tocdi*ne(
y:^:
. 19.2. ,
19.3 (HelloWWW. j ava)
HTML-
I, HTML- :
<!DOCTYPE ...>
<HTML>
<HEAD><TITLE>...</TITLE>...</HEAD>
<BODY ...>...</BODY>
</HTML>
HTML-
, DOCTYPE.
HTML 3.2 4.0,
.
. DOCTYPE HTML- ,
.
,
. ,
-.
HTML- h t t p : / /
v a l i d a t o r . w 3 . o r g / h t t p : / / w w w . h t m l h e l p . c o m / t o o l s / v a l i d a t o r / .
URL Web-.
HTML-, , Web-.
}< URL, GET,
.
1 9 . 3 .
829
]/'
HTML', .
HTML- p r i n t I n
. ,
DOCTYPE.
HTML- .
,
. -, ,
HTML- , JSP,
. -,
HTML- HTML-
(, CLASS ID , JavaScript-,
..). ,
, HTML-, , ,
HTML-.
DOCTYPE HEAD,
)
. , DOCTYPE HEAD,
19.4, 19.5
HelloWWW, .
.
1 9 , 4 . S e i r v l e t U t i l i t i e s . J a v a
p a c k a g e cwp;
/*^ HTML-.
* static.
V
public class ServletUtilities {
public static final String DOCTYPE =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">";
public static String headWithTitle(String title) {
return(DOCTYPE + "\n" +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n");
}
// ServletUtilities .
830
19. Java :
1 9 . 5 . SimplerHelloWWW. Java
p a c k a g e cwp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** , HTML-.
* HelloWWW ServletUtilities
* DOCTYPE, HEAD TITLE.
19.4.
,
.
, d o G e t d o P o s t .
, .
i n i t .
.
, s e r v i c e .
. .
S i n g l e T h r e a d M o d e l ,
. s e r v i c e d o G e t ,
d o P o s t , doXxx,
. -
, d e s t r o y .
init
i n i t .
. ,
.
19.4.
831
,
URL, . ,
, .
, ,
19.2.
i n i t :
p u b l i c void i n i t O throws S e r v l e t E x c e p t i o n {
/ / . . .
}
i n i t
, . ,
, ,
.. ,
g e t S e r v l e t C o n f i g S e r v l e t C o n f i g ,
g e t l n i t P a r a m e t e r . ,
, .
p u b l i c void i n i t O throws S e r v l e t E x c e p t i o n {
ServletConfig config = g e t S e r v l e t C o n f i g ( ) ;
S t r i n g paraml = c o n f i g . g e t l n i t P a r a m e t e r ( " S o m e P a r a m e t e r " ) ;
}
, g e t l n i t P a r a m e t e r ( ),
( ) S t r i n g .
19.5.
, . ,
, Tomcat , 2.2
, w e b . x m l .
JSWDK s e r v l e t s . p r o p e r t i e s , Java Web Server
.
service
, , ,
, s e r v i c e . s e r v i c e
HTTP- (GET, POST, PUT, DELETE, ..)
(, doGet, d o P o s t , doPut, d o D e l e t e ) .
POST GET, , ,
doGet do P o s t s e r v i c e .
. doGet
d o P o s t ( ). .
p u b l i c void doGet(HttpServletRequest r e q u e s t ,
HttpServletResponse response)
throws S e r v l e t E x c e p t i o n , lOException {
/ / . . .
832
19. Java :
GET POST, service.
doPost doGet doGet
doPost.
SingteThreadModel
,
.
. , d o G e t d o P o s t
.
,
, S i n g l e T h r e a d M o d e l .
public class YourServlet extends HttpServlet
implements SingleThreadModel {
}
19.5.
833
,
.
.
.
.
( s t a t i c ) , , .
,
, .
,
SingleThreadModel.
destroy
. ,
,
. , d e s t r o y .
, ,
cookie
. ,
d e s t r o y . , ,
, .
(, cookie) .
19.5.
19.6 ,
m e s s a g e r e p e a t s . . 19.3
, S h i b b o l e t h m e s s a g e ,
r e p e a t s 5. ShowMsg. 19.7
XML- , Tomcat
3, 19.8 JSWDK. ,
2.2, ,
Tomcat, ,
.
. .
,
,
^.
834
1 9 . Java :
, ,
, ,
.
1 9 . 6 . S h o w M e s s a g e . J a v a
p a c k a g e cwp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** .
*
* .
V
public class ShowMessage extends HttpServlet {
private String message;
private String defaultMessage = "No message.";
private int repeats = 1;
public void initO throws ServletException {
ServletConfig config = getServletConfigO;
message = config.getlnitParameter("message");
if (message == null) {
message = defaultMessage;
}
try {
String repeatString = config.getlnitParameter("repeats");
repeats ~ Integer.parseint(repeatString);
} catch(NumberFormatException nfe) {
// NumberFormatException
// , repeatString
// null, ,
// .
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, lOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "The ShowMessage Servlet";
out.printIn(ServletUtilities.headWithTitie(title) +
"<BODY BGC0L0R=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</Hl>");
for(int i=0; i<repeats; i++) {
out.println("<B>" + message + "</B><BR>");
}
19.5.
out.println("</BODY></HTML>");
T h e ShowpMessage S e i v l e l - N e t s c a p e
fie
dit
y*ew
go
^-
Hefe>
.,,1
. 79.3. ShowMessage,
showMsg
1 9 . 7 . w e b . x m l ( T o m c a t 3 )
835
836
19. Java :
ShowMsg.initparams=message=Shibboleth,repeats=5
#
j sp.code=com.sun.j sp.runtime.JspServlet
# , JSP
j sp.initparams=keepgenerated=true
19.6. :
, ,
Web-,
, , .
.
- ,
Internet-,
, URL, :
h t t p : / / h o s t / p a t h ? u s e r = M a r t y + H a l l & o r i g i n = b w i & d e s t = l a x . ,
( u s e r = M a r t y + H a l l & o r i g i n = b w i & d e s t = l a x ) ,
, .
Web- ,
. URL (
GET) ( POST).
HTML-
18.
CGI-
Web, ,
. ,
, GET ( CGI,
QUERY_STRING) POST (CGI-
).
, -
. .
,
"+", %, XX
, .
. , g e t P a r a m e t e r H t t p S e r v l e t R e q u e s t . g e t P a r a m e t e r
( ). g e t P a r a m e t e r
19.6. :
837
, GET POST.
. S t r i n g , ,
.
, , .
,
n u l l . ,
- .
g e t P a r a m e t e r g e t P a r a m e t e r V a l u e s ,
. , g e t
P a r a m e t e r V a l u e s n u l l ,
, , .
,
request.getParameter("Paraml")
request.getParameter("paraml")
!
,
getParameter
Values,
.
getParameter
)1
,
. g e t P a r a m e t e r N a m e s ,
, E n u m e r a t i o n . E n u m e r a t i o n
S t r i n g g e t P a r a m e t e r g e t P a r a m e t e r
V a l u e s . , API H t t p S e r v l e t R e q u e s t ,
E n u m e r a t i o n .
19.9 T h r e e P a r a m s ,
p a r a m l , p a r a m 2 .
.
19.10 HTML-,
. . URL,
ACTION, ( / s e r v l e t / c w p . T h r e e Pa ams), , Web-
, . ,
Java Servlet 2.2, HTML- ( JSP)
, ,
WEB-INF. , Tomcat i n s t a l l d i r /
webapps/ROOT, J R u n i n s t a l l _ d i r / s e r v e r s / d e f a u l t / c i e f a u l t - a p p .
(,
JSWDK i n s t a l l _ d i r / w e b p a g e s ) . ,
T h r e e P a r a m s , 1 , ,
. , -
838
19. Java :
,
.
. 19.4 19.5 HTML-
.
19.9. T h r e e P a r a m s . j a v a
package cwp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ThreeParams extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, lOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Three Request Parameters";
out.printIn(ServletUtilities.headWithTitie(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</Hl>\n"
"<UL>\n" +
" <LI><B>paraml</B>: "
+ request.getParameter("paraml") + "\n" +
" <LI><B>param2</B>: "
+ request.getParameter("param2") + "\n" +
<LI><B>param3</B>: "
+ request.getParameter("") + "\n" +
"</UL>\n" +
"</BODY></HTML>");
}
}
19.10. ThreeParamsForm.html
<!DOCTYPE HTML PUBLIC "-//W5C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Collecting Three Parameters</TITLE>
</HEAD>
<BODY BGC0L0R="#FDF5E6">
<H1 ALIGN="CENTER">Collecting Three Parameters</Hl>
<FORM ACTION="/servlet/cwp.ThreeParams">
First Parameter: <INPUT TYPE="TEXT" NAME="paraml"><BR>
Second Parameter: <INPUT TYPE="TEXT" NAME="param2"><BR>
Third Parameter: <INPUT TYPE="TEXT" NAME="param3"><BR>
<CENTER><INPUT TYPE="SUBMIT"></CENTER>
</FORM>
</BODY>
</HTML>
19.6. :
[t^iffiifflffiimiFmffinmnff,migffii^ii^^ii
;
Ftle
drt
View
Tools
839
1
" 3 r^Go I
J
. 19.4. HTML-,
ThreeParamsForm.html
\\;\1
Frfe
dtt
View
Fvontes
loots H d p
""1^
paimnl: ~hall
paiaml: -brown
paiamS: -mcnamee
jj
^Oone
~ Local
. / 9 . 5 .
CGI-, , ,
, POST .
. g e t R e a d e r
g e t l n p u t S t r e a m H t t p S e r v l e t R e q u e s t ,
.
, . g e t P a r a m e t e r
, .
,
POST. ,
POST-, g e t P a r a m e t e r .
,
p a r a m l , p a r a m 2
HTML-, .
,
, ,
"<". Web-, -
840
19. Java :
. ,
Web-,
HTML-. 19.11
f i l t e r , .
1 9 . 1 1 . S e r v l e t U t i l i t i e s . J a v a
p a c k a g e cwp;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletUtilities {
// ServletUtilities .
/** "<"
* "<", ">" ">" (
* )
* """, "&" "&;".
* , ,
* Web-.
public static String filter(String input) {
StringBuffer filtered = new StringBuffer(input.length());
char c;
for(int i=0; i<input.length(); i++) {
= input.charAt(i);
if (c == '<') {
filtered.append("<") ;
} else if (c == >') {
filtered.append(">");
} else if (c == " " ) {
filtered.append(""")/
} else if (c == '&') {
filtered.append("&");
} else {
filtered.append(c);
}
}
return(filtered.toString()) ;
19.7. :
HTTP-
,
HTTP (HypcrText Transfer Protocol
).
, , ,
19.7- : HTTP-
841
. ,
. ,
, , H T T P
1.1. .
, )^ ,
Web- , .
, ,
HTTP-. ,
, URL
. ,
(GET POST).
HTTP-, ,
h t t p : / / w w w . s o m e b o o k s t o r e . c o m /
s e r v l e t / S e a r c h . A c c e p t , A c c e p t - E n c o d i n g ,
C o n n e c t i o n , C o o k i e , H o s t , Ref e r e r U s e r - A g e n t . Bee
, ,
. ,
.
GET / s e r v l e t / S e a r c h ? k e y w o r d s = s e r v l e t s + j s p HTTP/1.1
A c c e p t : i m a g e / g i f , i m a g e / j p g , */"*"
Accept-Encoding: gzip
Connection: Keep-Alive
Cookie: userID=id456578
Host: www.somebookstore.com
Referer:
http://www.somebookstore.com/findbooks.html
U s e r - A g e n t : M o z i l l a / 4 . 7 [en] (Win98; U)
:
g e t H e a d e r H t t p S e r v l e t R e q u e s t ;
. , g e t H e a d e r
S t r i n g , ,
n u l l . . ,
r e q u e s t . g e t H e a d e r ( " C o n n e c t i o n " ) r e q u e s t . g e t H e a d e r ( " c o n n e c
t i o n " ) .
g e t H e a d e r
, H t t p S e r v l e t R e q u e s t
, .
getCookies
g e t C o o k i e s C o o k i e .
C o o k i e .
19.1.
getAuthType getRemoteUser
g e t A u t h T y p e g e t R e m o t e U s e r
Authorization.
842
19. Java :
getContentLength
g e t C o n t e n t L e n g t h C o n t e n t - L e n g t h
( i n t ) .
getContentType
g e t C o n t e n t T y p e C o n t e n t - T y p e (
S t r i n g ) .
getDateHeader getlntHeader
g e t D a t e H e a d e r g e t l n t H e a d e r
D a t e i n t .
getHeaderNames
g e t H e a d e r N a m e s E n u m e r a t i o n ,
, .
, 19.12.
getHeaders
.
. A c c e p t - L a n g u a g e .
Java 51'11 2.2,
g e t H e a d e r s , E n u m e r a t i o n ,
.
,
. H t t p S e r v l e t R e q u e s t .
, , .
getMethod
g e t M e t h o d ( GET POST,
HEAD, PUT DELETE).
getRequestURI
g e t R e q u e s t U R I URL,
. , URL h t t p : / /
r a n d o m h o s t . c o m / s e r v l e t / s e a r c h . B o o k S e a r c h g e t R e q u e s t U R I
/ s e r v l e t / s e a r c h . B o o k S e a r c h .
getProtocol
g e t P r o t o c o l ,
HTTP-.
H T T P / 1 . 0 H T T P / 1 . 1 .
, HTTP 1.1, g e t P r o t o c o l
, 1.1 .
19.7. : HTTP-
843
,
19.12 , ,
.
(, URI ).
, Netscape Internet Explorer,
. 19.6 19.7.
1 9 . 1 2 . S h o w R e q u e s t H e a d e r s . J a v a
p a c k a g e cwp;
import
import
import
import
java.io.*;
javax.servlet.*;
javax.servlet.http.*;
java.util.*;
/ , .
public class ShowRequestHeaders extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, lOException {
response.setContentType{"text/html");
PrintWriter out = response.getWriter();
String title = "Servlet Example: Showing Request Headers";
out.printIn(ServletUtilities.headWithTitle(title) +
"<BODY BGC0L0R=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</Hl>\n" +
"<B>Request Method: </B>" +
request. getMethodO + "<BR>\n" +
"<B>Request URI: </B>" +
request.getRequestURI0 + "<BR>\n" +
"<B>Request Protocol: </B>" +
request.getProtocolO + "<BR><BR>\n" +
"<TABLE B0RDER=1 ALIGN=\"CENTER\">\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Header Name<TH>Header Value");
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
out.println("<TR><TD>" + headerName);
out.println("
<TD>" + request.getHeader(headerName));
}
out.println("</TABLE>\n</BODY></HTML>");
}
/** GET, POST. */
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, lOException {
844
19. Java :
doGet(request,
wsam
ie
response);
ss
d View &
Cofrtfiiuntcatoi
>:d
-.j^ '
-:J
^^
!^i} J^.
f;.
Connection
Keep-Alive
User-Agent
Accept-Charset
iso-8859-l,*,utf-8
iHost
localhost
jAccept-Encoding ;gzip
:Accept
Q#
-"J^
>: Done
j<r',:.,i:s.:-;e^:
t^tflnfiifmi^mffiif^i!Hiw^inmiinimif'
' Ffe
View
F^vofites
3,
:|||1||'
Accept:iLanguage
:en-us
iConnection
-Keep-AHvc
;User-Agent
iHost
ilocalhost
^Accept;Encoding
jgap, deflate
jAccept
30one
LOCi
19.7. : HTTP-
845
,
HTTP 1.1
.
, .
H T T P 1.1, RFC
2616. RFC Internet .
h t t p : //www. r f c - e d i t o r . o r g / .
Accept
MIME- ,
HTTP-, . ,
,
A c c e p t ,
. , PNG
GIF, ,
PNG, . ,
PNG-, r e q u e s t . g e t H e a d e r ( " A c c e p t " ) ,
, - i m a g e / p n g ,
, xxx.png.
. g i f . MIME- . 19.1.
Accept-Charset
(, ISO-8859-1),
.
Accept-Encoding
, .
)' A c c e p t - E n c o d i n g ,
, .
C o n t e n t - E n c o d i n g .
.
MIME- (
C o n t e n t - ) ,
.
,
Web-. g z i p c o m p r e s s .
,
, ,
, .
,
10 .
846
19. Java :
Accept-Language
, ,
, ,
. ,
en, e n - U S , d a .. RFC 1766.
Authorization
Web-,
.
Connection
,
HTTP-.
(, HTML-
). ,
. H T T P 1.1
, , HTTP-
, C o n n e c t i o n
c l o s e . H T T P 1.0 K e e p - A l i v e ,
.
HTTP- ,
,
. HTTP-.
,
. ,
, . ,
, ,
C o n t e n t - L e n g t h .
Content-Length
POST.
. r e q u e s t . g e t l n t H e a d e r ( " C o n t e n t L e n g t h " ) , r e q u e s t . g e t C o n t e n t L e n g t h ( ) .
,
.
Cookie
C o o k i e cookie,
. 19.11.
cookie H T T P 1.1. Cookie
Netscape, Netscape,
Internet Explorer.
19.7. : HTTP-
847
Host
HTTP-
. Host ,
URL.
, ,
Host .
, HTTP 1.0 .
If-Modified-Since
,
, .
, 302 (Not
Modified). If-Modif i e d - S i n c e
, ,
.
- .
,
g e t L a s t M o d i f i e d .
If-Unmodified-Since
, If-Modif i e d - S i n c e .
, ,
. IfModif i e d - S i n c e GET (
, , , ),
If-Unmodif i e d - S i n c e PUT (
,
, ).
Referer
URL Web-, ,
. , ,
,
R e f e r e r , URL .
,
, .
R e f e r e r . R e f e r e r
, ,
. , R e f e r e r (
R e f e r r e r , ); HTTP
.
User-Agent
, ,
,
. ,
848
1 9 . Java :
, ,
.
, HTTP-. ,
, g z i p ,
A c c e p t - E n c o d i n g .
, Internet Explorer U s e r - A g e n t
" M o z i l l a " , . ,
JavaScript-.
]/\/'
)'. ^1 Web, C o n t e n t - E n c o d i n g ,
Web-pecypc.
)^ , ,
, ,
.
.
Netscape UNIX,
Netscape 4.7 Windows,
Internet Explorer Windows.
, A c c e p t - E n c o d i n g . 19.13
. 19.8 , , ,
g z i p , Web-, )',
, HTML-. Netscape 4.7
Internet Explorer 5.0 , 28,8 / , ,
5 ,
Web- 50 .
, Java
g z i p , J a v a .
u t i l . z i p . A c c e p t - E n c o d i n g ,
g z i p . ,
G Z I P O u t p u t S t r e a m , C o n t e n t E n c o d i n g . G Z I P O u t p u t S t r e a m ,
c l o s e . g z i p ,
P r i n t W r i t e r .
URL
? e n c o d i n g = n o n e , .
19.7. : HTTP-
1 9 . 1 3 . E n c o d e d P a g e . J a v a
p a c k a g e cwp;
import
import
import
import
java.io.*;
javax.servlet.*;
javax.servlet.http.*;
java.util.zip.*;
/** ,
* gzip.
V
public class EncodedPage extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, lOException {
response.setContentType("text/html");
String encodings = request.getHeader("Accept-Encoding");
String encodeFlag = request.getParameter("encoding");
PrintWriter out;
String title;
if ((encodings != null) &&
(encodings.indexOf("gzip") != -1) &&
!"none".equals(encodeFlag)) {
title = "Page Encoded with GZip";
Outputstream outl = response.getOutputStreamO;
out = new PrintWriter(new GZIPOutputStream(outl), false);
response . setHeader ("Content-Encoding" , "gzip") ;"
} else {
title = "Unencoded Page";
out = response.getWriter0;
out.printIn(ServletUtilitles.headWithTitie(title) +
"<BODY BGC0L0R=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</Hl>\n"
String line = "Blah, blah, blah, blah, blah. " +
"Yadda, yadda, yadda, yadda.";
for(int 1=0; i<10000; i++) {
out.println(line);
}
out.println("</BODY></HTML>");
out.close 0 ;
849
850
19. Java :
- ^ y^ J : . i ^ j i i ^ . i ^ r f ' a a
j ^
19.8. CGI-
CGI-, , ,
CGI-.
, . CGI , ,
(, IP- );
, (,
URL ).
, ,
, CGI-,
, CGI-.
CGI-, , :
,
CGI-. , , ,
, URI ( URL,
), g e t S e r v l e t C o n t e x t () . g e t R e a l P a t h ,
IP- r e q u e s t .
getRemoteHost request.getRemoteAddress.
AUTH_TYPE
A u t h o r i z a t i o n ,
( b a s i c d i g e s t ) .
r e q u e s t . g e t A u t h T y p e ( ) .
CONTENT_LENGTH
POST. CONTENTLENGTH ,
, .. CONTENTLENGTH
, C o n t e n t - L e n g t h .
, CONTENTLENGTH,
S t r i n g . v a l u e O f ( r e q u e s t . g e t C o n t e n t L e n g t h )
r e q u e s t . g e t H e a d e r ( " C o n t e n t - L e n g t h " ) .
r e q u e s t . g e t C o n t e n t L e n g t h ( ) , i n t .
19.8. CGI-
851
CONTENT.TYPE
CONTENT_TYPE 1- ,
. -
. 19.1. , CONTENT_TYPE, ,
r e q u e s t . g e t C o n t e n t T y p e ( ) .
DOCUMENT_ROOT
DOCUMENT_ROOT , URL
h t t p : / / h o s t / , h o s t .
g e t S e r v l e t C o n t e x t () . g e t R e a l Path ( " / " ) .
r e q u e s t . g e t R e a l P a t h ( " / " ) ,
. URI ( URL,
)
g e t S e r v l e t C o n t e x t ( ) . g e t R e a l P a t h .
HTTP^XXX.YYY
HTTP-. ,
Cookie _001, User-Agent
HTTP__USER__AGENT, HTTP_REFERER
R e f e r e r ..
r e q u e s t . g e t H e a d e r ,
19.7.
PATHJNFO
PATHINFO , URL
. , h t t p : / / h o s t /
s e r v l e t / c w p . S o m e S e r v l e t / f oo/bar?baz=quux PATH_INFO
/ f / b a r . ,
CGI-, , ,
PATH_INFO, ,
r e q u e s t . g e t P a t h I n f .
PATH^TRANSLATED
PAT RAN SLATED ,
. ,
g e t S e r v l e t
Context () . g e t R e a l P a t h .
CGI-, .
r e q u e s t . G e t PathTranslated.
852
19. Java :
QUERY_STRING
GET ,
URL.
,
r e q u e s t . g e t P a r a m e t e r (. 19.7).
- ,
r e q u e s t . g e t Q u e r y S t r i n g .
REMOTE__ADDR
IP- , .
(, "198.137.241.30").
r e q u e s t . g e t Remote Addr ( ) .
REMOTE_HOST
REMOTE_HOST (,
m y c l i e n t . g o v ) . ,
IP-. r e q u e s t .
getRemoteHost().
REMOTE^USER
A u t h o r i z a t i o n , ,
REMOTEUSER ,
.
r e q u e s t . g e t R e m o t e U s e r ( ) .
REQUEST^METHOD
HTTP- ( GET POST,
HEAD, PUT, DELETE, OPTIONS TRACE).
d o G e t , do P o s t ..
HEAD,
s e r v i c e . , REQUESTMETHOD,
r e q u e s t . g e t M e t h o d ( ) .
SCRIPT__NAME
. , r e q u e s t . g e t S e r v l e t P a t h .
SERVER_NAME
SERVER_NAME ,
. r e q u e s t . g e t S e r v e r N a m e .
SERVER_PORT
,
. ,
19.9. :
853
s t r i n g . v a l u e O f ( r e q u e s t . g e t S e r v e r P o r t ( ) ) ,
S t r i n g .
r e q u e s t . g e t S e r v e r P o r t ( ) ,
.
SERVER_PROTOCOL
SERVER_PROTOCOL ,
(, H T T P / 1 . 0 H T T P / 1 . 1 ) .
r e q u e s t . g e t P r o t o c o l .
SERVER_SOFTWARE
Web-.
g e t S e r v l e t C o n t e x t ( ) . g e t S e r v e r I n f .
19.9. :
Web- Web-
, , .
( ) :
/1.1 200
Content-Type: text/plain
Hello World
H T T P (
/ 1 . 1 ) , ( 200) ,
( ).
. C o n t e n t - , MIME . , ,
( ,
)^. HEAD,
, ,
.
,
. , ,
, , , ,
, Adobe Acrobat HTML-,
, , ..
.
.
, HTTP-
HTTP, .
, -
854
1 9 . Java :
, , ,
. s e t S t a t u s H t t p S e r v l e t R e s p o n s e .
HTTP- . ,
,
, , s e t S t a t u s
P r i n t W r i t e r . 19.3,
( Servlet 2.1
).
P r i n t W r i t e r , ,
.
,
.
s e t S t a t u s (
). H t t p S e r v l e t
R e s p o n s e .
, HTTP-.
, SC,
. , 404 "Not
Found", , H t t p S e r v l e t R e s p o n s e ,
SCNOTFOUND. Servlet 2.1
. 302 H T T P 1.0
(Moved Temporarily), 307 (Temporary Redirect) 416
(Requested Range Not Satisfiable) . 2,2
416, 307 302 .
,
H t t p S e r v l e t R e s p o n s e , .
s e t S t a t u s ,
l O E x c e p t i o n .
HTML-. ,
,
404 "File Not Found",
.
19.9. :
855
HTTP 7.1
,
H T T P 1.1.
. ,
.
H T T P 1.1 RFC 2616.
RFC h t t p : / / w w w . r f c - e d i t o r . o r g / .
,
H T T P 1.0, , , ,
H T T P 1.1, ,
. , r e q u e s t . g e t R e q u e s t P r o t o c o l .
.
100-199
, 1, , ,
, .
200 - 299
, 2, ,
.
300-399
, , ,
. L o c a t i o n ,
.
400-499
, 4, , .
500 - 599
.
,
H t t p S e r v l e t R e s p o n s e .
. , r e s p o n s e . s e t S t a t u s (204)
r e s p o n s e . s e t S t a t u s ( r e s p o n s e . SC_NO_CONTENT).
. ,
,
. , / 1 . 1 200
/ 1 . 1 200 Document F o l l o w s .
100 (Continue)
E x p e c t , 1 0 0 - c o n t i n u e ,
,
. 100
(SCCONTINUE), . 417
( E x p e c t a t i o n F a i l e d ) , '.
100 HTTP 1.1.
856
19. Java :
200 ( )
200 (SCOK) , .
, .
. s e t S t a t u s ,
200.
201 (Created)
201 (SC_CREATED) ,
. URL L o c a t i o n .
202 (Accepted)
202 (SCACCEPTED) , ,
. .
204 ( N o Content)
204 (SC_NO_CONTENT) ,
, .
, Web-
Reload - ,
.
205 (Reset Content)
205 (SC RESETCONTENT) ,
,
. ,
. H T T P 1.1.
301 (Moved Permanently)
301 (SC_MOVED_PERMANENTLY) ,
. URL
L o c a t i o n . URL.
302 (Found)
301 , URL,
L o c a t i o n , .
301 302 .
, HTTP 1.0 Moved Tempo
r a r i l y , H T T P 1.1 Found. , ,
H t t p S e r v l e t R e s p o n s e ,
SC_FOUND,
SC_MOVED_TEMPORARILY.
, 302,
ED
TEMPORARILY,
SC_FOUND,
SC^MOV-
19.9. :
857
302 , ,
L o c a t i o n . ,
sendRedirect.
response. sendRedirect(url)
, r e s p o n s e . s e t S t a t u s ( r e s p o n s e . SC_MOVED_TEMPORARILY) r e s p o n s e .
s e t H e a d e r ( " L o c a t i o n " , u r l ) . -, , -,
]1 , ,
s e n d R e d i r e c t , . ,
, 2.2 ( J2EE) s e n d R e d i r e c t
URL .
,
GET. 307.
303 (See Other)
303 (SC_SEE_OTHER) 301 302,
. POST,
, L o c a t i o n ,
GET. H T T P 1.1.
304 (Not Modified)
,
, I f - M o d i f i e d - S i n c e . ,
,
If-Modif ied-Since.
304
(SCNOTMODIFIED) ,
.
,
200. ,
304, g e t L a s t M o d i f i e d
s e r v i c e .
307 (Temporary Redirect)
307 302 . 307
HTTP 1.1 , 302,
,
POST. POST
303. :
303 GET,
POST, 307 GET, POST.
H t t p S e r v l e t R e s p o n s e ,
, s e t S t a t u s 307.
400 (Bad R e q u e s t )
400 (SC_BAD_REQUEST) ,
.
858
19. Java :
401 ( U n a u t h o r i z e d )
401 (SC_UNAUTHORIZED) ,
, ,
A u t h o r i z a t i o n .
WWW-Authenticate.
403 ( F o r b i d d e n )
403 (SC_FORBIDDEN) , ,
, .
,
.
404 ( N o t F o u n d )
404 (SCNOTFOUND) , , URL
, .
, H t t p S e r v l e t R e s p o n s e
s e n d E r r o r .
. s e n d E r r o r
s e t S t a t u s , s e n d E r r o r
. Internet Explorer 5
,
HTTP. ,
Tools (), Internet Options (
), Advanced ()
Show friendly HTTP error m e s s a g e s (
HTTP). ,
Internet Explorer 5, ,
, . Internet
Explorer 4 .
!
internet Explorer ,
.
405 ( M e t h o d N o t Allowed)
405 (SC_METHOD_NOT_ALLOWED) , (GET,
POST, HEAD, PUT, DELETE ..) .
H T T P 1.1.
410 ( G o n e )
410 (SCGONE) ,
. 410
404 , , , 404
, .
H T T P 1.1.
19.9. :
859
411 (Length R e q u i r e d )
411 (SC_LENGTH_REQUIRED) ,
( POST ),
C o n t e n t - L e n g t h , ,
. H T T P 1.1.
413 (Request Entity T o o Large)
41S (SC_REQUEST_ENTITy_TOO__LARGE) ,
, .
, ,
R e t r y - A f t e r . H T T P 1.1.
414 (Request U R I T o o L o n g )
414 ( S C R E Q U E S T U R I T O O L O N G ) , URI
. URI URL,
. , URL h t t p : / / w w w . y 2 k - d i s a s t e r . c o m : 8 0 8 0 /
w e / l o o k / s i l l y / n o w / / w e / l o o k / s i l l y / n o w /
URI. H T T P 1.1.
415 ( U n s u p p o r t e d M e d i a Type)
415 (SC_UNSUPPORTED_MEDIA_TYPE) ,
, , ,
. H T T P 1.1.
417 (Expectation Failed)
E x p e c t , 1 0 0 c o n t i n u e , , ,
.
417, ,
, 100 (SC CONTINUE),
, .
H T T P 1.1.
500 (Internal Server Error)
500 (SC_INTERNAL_SERVER_ERROR)
" ". ,
CGI-
.
501 ( N o t I m p l e m e n t e d )
501 (SC_NOT_IMPLEMENTED) , ,
, .
PUT, .
860
19. Java :
19.14 ,
: 302 404. 302
s e n d R e d i r e c t H t t p S e r v l e t R e s p o n s e , 404
s e n d E r r o r .
, HTML (. 19.9 19.16).
,
. ,
, URL, ,
( S e a r c h S p e c 19.15),
URL (. 19.10).
, Web-,
(. 404).
1 9 . 1 4 . S e a r c h E n g i n e s . J a v a
cwp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
/**
*
*
*
*
*
*
*/
,
.
. ,
302 ( sendRedirect).
4 04
( sendError).
19.9. :
861
862
19. Java :
1 9 . 1 5 . S e a r c h S p e c . J a v a
p a c k a g e cwp;
Z'^* ,
* .
public class SearchSpec {
private String name, baseURL, numResultsSuffix;
private static SearchSpec[] commonSpecs =
{ new SearchSpec("google",
"http:ZZwww.google.comZsearch?q=",
"&num="),
new SearchSpec("infoseek",
"http:ZZinfoseek.go.comZTitles?qt=",
"&nh="),
new SearchSpec("lycos",
"http:ZZlycospro.lycos.comZcgi-binZ" +
"pursuit?query=",
"&maxhits="),
new SearchSpec("hotbot",
"http:ZZwww.hotbot.comZ?MT=",
"&DC=")
};
public SearchSpec(String name.
String baseURL,
String numResultsSuffix) {
this.name = name;
this.baseURL = baseURL;
this.numResultsSuffix = numResultsSuffix;
}
public String makeURL(String searchString,
String numResults) {
return(baseURL + searchString +
numResultsSuffix + numResults);
}
public String getName() {
return(name);
}
public static SearchSpec[] getCommonSpecs() {
return(commonSpecs) ;
}
}
19.9. :
863
j;^A!ijj!i;ii|jf|MJi|.H.iiu/^i.!iifira!ff^^
'.r-T^jTa^a -^'^-j'
AiJdiess \fi] h(tp //localhost/cwp/Seafd-ngines html
^J
^ ^^^
J
^
Done
1 ^ local rtidfiet
Gougle
j j
Google Serch
fv>So
Search Tips
:?'.' / ; I' 10 1'/. : 2,580* vservlets JSP book .-^'' i L-^-0.68 ^.7.'.- ^
"^-i'"'';'"^ Computers > Programming > Languages > Java > Runtime Environments > Sen/lets
Core S e r v l e t s and JavaServer Pages (JSP): Book Table of
...contents of Core Servlets and JavaServer Pages (JSP) in HTML...
...CHAPTER 11 The JSP page Directive. Structuring Generated Servlets...
vvWiAf.coreseivlels.corn/rabie-Oi-Coritentb himi - 20k- Cs.kMfJ - 1::!^
Core S e r v l e t s and JavaServer Pages
...and integrating servlets and JSP) The book includes...
GosciVptiOi:- Home page for new seivlet/JSP book from Sun Microsystems Press and Prentice Hall.
Covers servlets
iigj
intefnet
. 19.10. , . 19.9
zl
864
19. Java :
19.16,SearchEngines.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Searching the Web</TITLE>
</HEAD>
<BODY BGC0L0R="#FDF5E6">
<H1 ALIGN="CENTER">Searching the Web</Hl>
<FORM ACTION="/servlet/cwp.SearchEngines">
<CENTER>
Search String:
<INPUT TYPE="TEXT" NAME="searchString"><BR>
Results to Show Per Page:
<INPUT TYPE="TEXT" NAME="numResults"
VALUE=10 SIZE=3><BR>
<INPUT TYPE="RADIO" NAME="searchEngine"
VALUE="google">
Google I
<INPUT TYPE="RADIO" NAME="searchEngine"
VALUE="infoseek">
Infoseek |
<INPUT TYPE="RADIO" NAME="searchEngine"
VALUE="lycos">
Lycos I
<INPUT TYPE="RADIO" NAME="searchEngine"
VALUE="hotbot">
HotBot
<BR>
<INPUT TYPE="SUBMIT" VALUE="Search">
</CENTER>
</FORM>
</BODY>
</HTML>
19.10. :
, Web-
, ,
. ,
, .
.
, , (300-307),
L o c a t i o n , 401 ( U n a u t h o r i z e d )
w w w - A u t h e n t i c a t e . ,
"" . cookie,
, -
19.10. :
865
Web- , ,
, ,
.
s e t H e a d e r H t t p S e r v l e t R e s p o n s e . :
, . ,
.
s e t H e a d e r , H t t p S e r v l e t R e s p o n s e ,
.
H T T P
, ,
. , ,
A c c e p t S e t - C o o k i e ,
MIME- c o o k i e . s e t H e a d e r , s e t D a t e H e a d e r
s e t l n t H e a d e r , SeiTlet 2.1,
,
, . Sei'vlet 2.2,
s e t H e a d e r , s e t D a t e H e a d e r s e t l n t H e a d e r
, ,
, a d d H e a d e r , a d d D a t e H e a d e r
a d d l n t H e a d e r . , ,
c o n t a i n s H e a d e r .
, , H t t p S e r v l e t R e s p o n s e
. .
setContentType
C o n t e n t - T y p e
.
setContentLength
C o n t e n t - L e n g t h
, (keep-alive) HTTP-.
866
19. Java :
addCookie
addCookie S e t - C o o k i e ,
cookie. s e t Cookie ,
cookie .
cookie 19.11.
sendRedirect
, s e n d R e d i r e c t ,
302, L o c a t i o n .
19.14.
,
HTTP 1.1. ,
.
RFC 2616, HTTP 1.1.
RFC h t t p : / / w w w . r f c - e d i t o r . o r g / .
,
.
, HTTP 1.1,
. Internet, ,
HTTP 1.0. HTTP 1.1
,
intranet. HTTP 1.1,
r e q u e s t . g e t R e q u e s t P r o t o c o l , HTTP
-.
Allow
, .
405 (Method Not Allowed).
s e r v i c e Allow
OPTION.
Cache-Control
C a c h e - C o n t r o l - ,
, , .
.
p u b l i c . ,
(, ).
p r i v a t e .
() .
- c a c h e . .
n o - c a c h e = " h e a d e r l , h e a d e r 2 , . . . ,headerN",
19.10. :
867
, ,
. ,
, ,
.
, , , . ,
, Pragma,
.
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
n o - S t o r e .
.
.
m u s t - r e v a l i d a t e .
( proxy-).
p r o x y - r e v a l i d a t e . ,
m u s t - r e v a l i d a t e , ,
.
max-age=xxx. .
E x p i r e s ,
, HTTP 1.1.
max-age E x p i r e s ,
max-age.
s-max-age=xxx
.
C a c h e - C o n t r o l HTTP 1.1.
Connection
C o n n e c t i o n c l o s e ,
. ,
HTTP 1.1, .
, HTTP 1.0 C o n n e c t i o n :
k e e p - a l i v e , HTTP 1.1 C o n n e c t i o n : c l o s e .
C o n t e n t - L e n g t h .
/
Content-Encoding
,
.
. g z i p ,
.
19.7.
868
19. Java :
Content-Language
C o n t e n t - L a n g u a g e .
, e n , e n - u s , da
.. RFC 1766.
Content-Length
,
. ,
HTTP-. ,
, C o n n e c t i o n .
,
B y t e A r r a y O u t p u t S t r e a m , ,
C o n t e n t - L e n g t h ,
r e s p o n s e . s e t C o n t e n t L e n g t h ,
b y t e A r r a y S t r e a m . w r i t e T o ( r e s p o n s e . g e t O u t p u t S t r e a m ( ) ).
Content-Type
C o n t e n t - T y p e MIME- ,
. ,
H t t p S e r v l e t R e s p o n s e s e t C o n t e n t T y p e . MIME- /,
/-.
MIME- t e x t / p l a i n ,
t e x t / h t m l .
MIME- . 19.1.
MIME- RFC 1521 RFC 1522 (
h t t p : / / w w w . r f c - e d i t o r . o r g / ) .
MIME- ,
. MIME-
h t t p : / / w w w . i s i . e d u / i n - n o t e s / i a n a / a s s i g n m e n t s / m e d i a ^ t y p e s / m e d i a - t y p e s .
h t t p : / / w w w . l t s w . s e / k n b a s e / i n t e r n e t / mime.htp.
1 9 . 1 . MIME-
application/msword
Microsoft Word
application/octet-stream
application/pdf
Acrobat ( . p d f )
application/postscript
PostScript
application/vnd. lotus-notes
Lotus Notes
application/vnd.ms-excel
Excel
19.10. :
869
. 19.1
application/vnd.ms-powerpoint
PowerPoint
application/x-gzip
Gzip
application/x-java-archive
JAR-
application/-jva
se rial i zed-object
Java-
application/x-java-vm
Java ( . c l a s s )
application/zip
Zip-
audio/basic
. . s n d
audio/x-aiff
AIFF
audio/x-wav
Microsoft Windows
audio/midi
MIDI
text/ess
HTML
text/html
HTML-
text/plain
image/gif
GIF
image/jpeg
JPEG
image/png
PNG
image/tiff
TIFF
image/x-xbitmap
X Windows
( )
video/mpeg
MPEG
video/quicktime
QuickTime
Expires
,
, , .
,
. ,
, , , ,
10 .
long currentTime = System.currentTimeMillis ( ) ;
l o n g t e n M i n u t e s = 1 0 * 6 0 * 1 0 0 0 ; / /
response.setDateHeader("Expires",
currentTime + tenMinutes);
m a x - a g e C a c h e - C o n t r o l .
870
19. Java :
Last-Modified
L a s t - M o d i f i e d .
I f - M o d i f i e d - S i n c e ,
. ,
, Last-Modif i e d ,
If-Modif i e d - S i n c e .
304 (Not Modified)
, .
, s e t D a t e H e a d e r .
.
getLastModif i e d s e r v i c e
.
Location
,
3, .
.
s e n d R e d i r e c t
H t t p S e r v l e t R e s p o n s e , , 302.
.
Pragma
Pragma, cache, , HTTP 1.0,
. HTTP 1.1
Cache-Control: no-cache.
Refresh
( ),
Web-. ,
30 ,
30 :
response.setlntHeader("Refresh", 30)
, R e f r e s h .
,
. Refresh,
204 (No Content), .
R e f r e s h .
Web. , ,
URL . ,
, h t t p : / / h o s t / p a t h ,
s e t Header :
response.setHeader("Refresh",
"5; URL=http://host/path/")
19.10. :
871
, .
,
HEAD HTML-.
< HTTP-EQUIV="Refresh"
C0NTENT="5; URL=http://host/path/">
Web-.
.
Refresh HTTP 1.1,
Netscape, Internet Explorer.
Retry-After
503 ( S e r v i c e
U n a v a i l a b l e ) , .
Set-Cookie
S e t - C o o k i e cookie, Web-.
cookie S e t - C o o k i e .
r e s p o n s e . s e t H e a d e r ( " S e t - C o o k i e " , . . . ),
addCookie H t t p S e r v l e t R e s p o n s e .
cookie 19.11. S e t - C o o k i e
HTTP 1.1. cookie Netscape,
Netscape, Internet Explorer.
www-Authenticate
401
(Unauthorized). ,
A u t h o r i z a t i o n .
, Web-
, .
\/'
, ,
. (, 150),
,
,
.
Web-.
, Refresh,
.
872
19. Java :
,
. -, ,
,
. -, ,
; CGI-
.
,
s e r v i c e ( d o G e t d o P o s t ) . ,
,
. Web N
. -
, . ,
.
S e r v l e t C o n t e x t ,
g e t S e r v l e t C o n t e x t . S e r v l e t C o n t e x t
s e t A t t r i b u t e g e t A t t r i b u t e , ,
.
S e r v l e t C o n t e x t , S e r v l e t
C o n t e x t , ,
(, , Web-).
19.17. ,
: n u m P r i m e s n u m D i g i t s .
, HTML-.
19,18 HTML- , , . 19.11
.
g e t I n t P a r a m e t e r ,
I n t e g e r . p a r s e i n t (. 19.21).
f i n d P r i m e L i s t
, ,
, .
P r i m e L i s t , , .
,
R e f r e s h . ,
. , ,
. Web-,
, . 19.12,
. 19.13.
19.19 ( P r i m e L i s t . J a v a ) 19.20 ( P r i m e s . J a v a )
, . P r i m e L i s t
, . P r i m e
, ,
, . ,
, B i g l n t e g e r .
19.10. :
1 9 . 1 7 . P r i m e N u m b e r s . J a v a
package cwp;
import
import
import
import
/*"^
*
*
*
*
*
*
*
*
*
*
java.io.*;
javax.servlet.*;
javax. servlet.http. "^;
java.util.*;
, , n
, m .
,
,
. ,
Refresh,
,
.
,
,
.
873
874
19. Java :
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Some " + numDigits + "-Digit Prime Numbers";
out.printIn(ServletUtilities.headWithTitie(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H2 ALIGN=CENTER>" + title + "</H2>\n" +
"<H3>Primes found with " + numDigits +
" or more digits: " + numCurrentPrimes +
".</H3>");
if (isLastResult)
out.println("<B>Done searching.</B>");
else
out.println("<B>Still looking for " + numPrimesRemaining +
" more<BLINK>...</BLINK></B>");
out.println("<0L>") ;
for(int i=0; i<numCurrentPrimes; i++) {
out.println(" <LI>" + currentPrimes.elementAt(i));
}
out.println("</0L>");
out.println("</BODY></HTML>");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, lOException {
doGet(request, response);
}
// ,
//
// . ,
// , .
// ,
/ / .
// .
private PrimeList findPrimeList(Vector primeListVector,
int numPrimes,
int numDigits) {
synchronized(primeListVector) {
for(int i=0; i<primeListVector.size(); i++) {
PrimeList primes =
(PrimeList)primeListVector.elementAt(i);
if ((numPrimes == primes.numPrimes()) &&
(numDigits == primes.numDigits()))
return(primes);
}
return(null);
}
}
19.10. :
-^^ ^ 3 . ^^- Si s ui 3 Jl
Finding Large Prime Numbers
f-f"^
Document. Dor
'^ ^
. ^^.J
. 19.11, PrimeNumbers.html,
PrimeNumbers
875
876
19. Java :
i-inixf
^
^- - 3 '^ ^ ^ ^s ^ 3
Some 125-Digit Prime Numbers
Primes fomid with 125 or mote digits: S.
Still lookiiig for 7 more
1.
2.
3.
4.
5.
6.
7.
8
25955811439632246588281060898749698746124929689978474726713518542454
25955811439632246588281060898749698746124929689978474726713518542454
25955811439632246588281060898749698746124929689978474726713518542454
25955811439632246588281060898749698746124929689978474726713518542454
25955811439632246588281060898749698746124929689978474726713518542454
25955811439632246588281060898749698746124929689978474726713518542454
25955811439632246588281060898749698746124929689978474726713518542454
25955811439632246588281060898749698746124929689978474726713518542454
1
:;==>-:
,GI
. 19.12.
PrimeNumbers.
,
.
1?
^^ J 3 <^ ^ ^ ^:% ^'
2595581 14396322465882810608987496987461249296899784747267135185424
2595581 14396322465882810608987496987461249296899784747267135185424
2595581 14396322465882810608987496987461249296899784747267135185424
2595581 14396322465882810608987496987461249296899784747267135185424
2595581 14396322465882810608987496987461249296899784747267135185424
2595581 14396322465882810608987496987461249296899784747267135185424
2595581 14396322465882810608987496987461249296899784747267135185424
259558 14396322465882810608987496987461249296899784747267135185424
2595581 14396322465882810608987496987461249296899784747267135185424
osQ*;*;??!
Li
f^'^ii^'.
14'?0^0^'^)0174<5717400000747^7')>;71?^1';4':>]
Document Done
':^.2-._::^.^.:....,.^^
' /
. 19.13.
PrimeNumbers.
,
.
Web-
19.10. :
1 9 . 1 9 . P r i m e L i s t . J a v a
p a c k a g e cwp;
import Java . util.'^^ ;
import Java.math.Biglnteger;
/** Vector, .
* .
V
public class PrimeList implements Runnable {
private Vector primesFound;
private int numPrimes, numDigits;
Z*'^
*
*
*
*
*
numPrimes ,
numDigits .
,
, ,
.
877
878
19. Java :
19.20.Primes.Java
package cwp;
import Java.math.Biglnteger;
/** ,
* Biglnteger
* Biglnteger.
public class Primes {
// Biglnteger.ZERO JDK 1.2.
private static final Biglnteger ZERO = new Biglnteger("0"),
private static final Biglnteger ONE = new Biglnteger("1");
private static final Biglnteger TWO = new Biglnteger("2");
private static final int ERR_VAL = 100;
public static Biglnteger nextPrime(Biglnteger start) {
if (isEven(start))
start = start.add(ONE);
else
start = start.add(TWO);
if (start.isProbablePrime(ERR_VAL))
return(start);
else
return(nextPrime(start));
}
private static boolean isEven(Biglnteger n) {
return(n.mod(TWO).equals(ZERO));
}
private static StringBuffer[] digits =
19.10. :
{ new
new
new
new
new
StringBuffer("")/
StringBuffer("2") ,
StringBuffer("4"),
StringBuffer("6") /
StringBuffer("8")/
new StringBuffer("1")/
new StringBuffer("3"),
new StringBuffer("5").
new StringBuffer("7")^
new StringBuffer("9") }/
,
.
,
50
.
V
public static void main(String[] args) {
int numDigits;
if (args.length > 0)
numDigits = Integer.parseint(args[0]);
else
numDigits = 150;
Biglnteger start = random(numDigits);
for(int i=0; i<50; i++) {
start = nextPrime(start);
System.out.println("Prime " + i + " = " + start);
}
}
19-21. S e r v l e t 0 t i l i t i e s . Java
package cwp;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletUtilities {
/
*
*
*
*
,
,
.
1' ,
.
879
880
19. Java :
V
public static int getlntParameter(HttpServletRequest request.
String paramName,
int defaultValue) {
String paramString = request.getParameter(paramName);
int paramValue;
try {
paramValue = Integer.parseint(paramString);
} catch(NumberFormatException nfe) { // null
//
paramValue = defaultValue;
}
return(paramValue);
}
1 9 . 1 1 . Cookie
cookie , Web
. ,
, }^ ,
,
.
, cookie.
cookie , .
cookie
cookie,
, .
1,
" ". ,
. Web HTTP- ,
, , !
. , ,
, , .
HTTP- .)^ , }'
,
, , , , Web . ,
. cookie. cookie
1 9 . 1 1 . Cookie
881
, API
cookie.
19.12.
,
: ) ,
. , ,
cookie.
cookie, .
,
. , ,
, ,
. -
, ,
.
, "",
) .
^ , ,
. '
, , ,
cookie. Web-
,
cookie. )^1
, ,
.
Web-, ,
.
, ,
. , , ,
"Java Servlets", , ,
, ,
, ,
. .
"Java Hotels", . cookie
, .
, .
882
19. Java :
cookie
cookie , Web-. , cookie
.
cookie ,
. 300 cookie,
20 , cookie 4 ,
cookie
, .
cookie
, . , ,
,
,
, .
, , Internet
,
.
, ,
cookie.
, . (Netscape cookie,
, ,
.) cookie
. , ,
, cookie.
Web- .
, cookie
. ,
cookie ,
. ,
, ,
, . .
cookie , ,
. ,
, cookie, )^
. , ,
,
cookie ,
cookie.
, .
?
cookie ? ,
. , cookie,
, cookie
, cookie .
19.11. Cookie
883
API,
cookie
cookie ,
cookie, (new C o o k i e (name, v a l u e ) ) ,
c o o k i e . setXxx (
c o o k i e . getX)cx) c o o k i e
, r e s p o n s e . a d d C o o k i e ( c o o k i e ) .
cookie, ,
r e q u e s t . g e t C o o k i e s , C o o k i e .
cookie,
( cookie ,
, n u l l ) .
, cookie (getName),
, , g e t V a l u e .
.
cookie
cookie Cookie,
: cookie. ,
:
[
( ) = , / ?
@ :
cookie
cookie S e t - C o o k i e ,
a d d C o o k i e H t t p S e r v l e t R e s p o n s e .
, s e t C o o k i e , a d d C o o k i e ,
S e t - C o o k i e .
Cookie u s e r C o o k i e = new C o o k i e ( " u s e r " ,
userCookie.setMaxAge(60*60*24*365); / /
response.addCookie(userCookie);
"uidl234");
1
cookie,
cookie, ,
g e t C o o k i e s H t t p S e r v l e t R e q u e s t .
C o o k i e ; C o o k i e
HTTP-. C o o k i e
.
getName C o o k i e . ,
g e t V a l u e .
, cookie
.
884
19. Java :
cookie
cookie ,
cookie, s e t X x x (
). s e t X x x getXxx,
. , cookie
cookie, ;
cookie, , .
public String g e t C o m m e n t O
public void s e t C o m m e n t ( S t r i n g c o m m e n t )
s e t C o m m e n t , a getComment
, cookie. Cookie (.
g e t V e r s i o n s e t V e r s i o n ) ,
.
public String getDomain()
public void setDomain(String domainPattern)
s e t D o m a i n , a g e t D o m a i n ,
cookie. s e t D o m a i n
, , cookie
, .
cookie , ,
' s e t D o m a i n ,
, (. com, . e d u , . gov .),
, (. . , . e d u . e s .).
, cookie, b a l i . v a c a t i o n s . c o m ,
m e x i c o . v a c a t i o n s . com.
, c o o k i e . s e t Domain ( " . v a c a t i o n s . c o m " ) .
public int getMaxAge()
public void setMaxAge(int lifetime)
setMaxAge , a getMaxAge
cookie, .. ( ), cookie
. ,
, , cookie
(.. , )
. 19.25
C o o k i e L o n g L i v e d C o o k i e ,
, . ,
cookie .
1 9 . 1 1 . Cookie
885
886
19. Java :
,
(.. cookie
).
public int getVersionO
p u b l i c void setVersion(int v e r s i o n )
s e t V e r s i o n , a g e t V e r s i o n ,
cookie. ,
Netscape ( h t t p : //www. n e t s c a p e . com/
n e w s r e f / s t d / c o o k i e _ s p e c . h t m l ) . 1, ,
, ^ RFC 2109 (
RFC h t t p : //www. r f c - e d i t o r . o r g / ) .
cookie
19.22 . 19.14 S e t C o o k i e s ,
cookie.
, .. .
, ,
.
19.23 , ,
cookie, . . 19.15 S e t C o o k i e s . . 19.16 )^, S e t C o o k i e s .
19.22.SetCookies.Java
p a c k a g e cwp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/
*
*
*
*
cookie.
(
, ).
(
).
V
public class SetCookies extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, lOException {
for(int i=0; i<3; i++) {
/ / maxAge -1, ..
// cookie
// .
Cookie cookie = new Cookie("Session-Cookie-" + i,
"Cookie-Value-S" + i ) ;
response.addCookie(cookie);
1 9 . 1 1 . Cookie
1^1'|1
te
^mi
FavoKes
loefe
Setting Cookies
~3
There are six cookies associated with this page. To see them, visit
the showCooicieg setvlst.
Three of the cookies are associated only with the current session,
v^ue three are persistent. Quit the browser, restart, and return to the
ShowCooJcies servlet to verify that the three long-lived ones persist
across sessions.
l^Done
Loca intranet
, 19.14.
SetCookies
1 9 . 2 3 . S h o w C o o k i e s . J a v a
package cwp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** cookie,
887
888
19. Java :
F3e
x^J
.*
' ^
View
Fs\'Of4e*
Joote
fef:fgHW*ff 5
File
Heto
Linki ** ;
E*
'
View
Help
J J ^ _ ^ -._i' ^ _^ '
FdvofAes
loots
Links **
Ji
Active Cookies
Active Cooldes
Cooki? Katm
Session-Cookie-0
Cookie Vn]u
Cookie-Value-SO
Persistent-Coobe-O Cookie-Value-PO
Persistent-Cookie-0 Coobe-Value-PO
Session-Coobe-1
Persistent-Cookie-2 Cookie-Value-P2
Coobe-Value-Sl
Persistent-Cookie-1 Coobe-Value-Pl
Session-Cookie-2
Cooloe-Value-S2
Persistent-Co -2 Cookie-Value-P2
J
;^Done
Pvic. 19.15.
ShowCookies
SetCookies.
^Oone
|sjLoe^*afiet
'
. 19.16.
ShowCookies
SetCookies.
SetCookies
19.11. Cookie
889
cookie
,
cookie.
cookie
19.24 S e r v l e t U t i l i t i e s . J a v a ,
cookie .
g e t C o o k i e V a l u e C o o k i e ,
, .
, .
.
Cookie[] cookies = r e q u e s t . g e t C o o k i e s ( ) ;
String color =
ServletUtilities.getCookieValue(cookies,
S t r i n g font =
ServletUtilities.getCookieValue(cookies,
"color",
"font",
"black");
"Arial");
g e t C o o k i e ,
C o o k i e . ,
C o o k i e , .
1 9 , 2 4 . S e r v l e t U t i l i t i e s . Java
p a c k a g e cwp;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletUtilities {
// .
/** Cookie
^ . ,
* .
public static String getCookieValue(Cookie[] cookies,
String cookieName,
String defaultValue) {
if (cookies ?= null) {
for(int i=0; Kcookies. length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
return(cookie.getValue());
}
}
return(defaultValue);
}
/** Cookie
890
*
*
19. Java :
. ,
null.
cookie
19.25 ,
Cookie, .
19.25. LongLivedCookie. Java
package cwp;
import javax.servlet.http.*;
/** cookie, .
* cookie
* .
V
public class LongLivedCookie extends Cookie {
public static final int SECONDS_PER_YEAR = 60*60*24*365;
public LongLivedCookie(String name. String value) {
super(name, value);
setMaxAge(SECONDS_PER_yEAR) ;
}
}
19.12.
,
.
19.12.
891
H T T P .
, Web-,
,
. , ,
,
.
. ,
,
, , ""
"" .
cookie,
URL . ,
, (
, )
.
cookie
cookie .
, :
String sessionID = makeUniqueString();
H a s h t a b l e s e s s i o n l n f o = new H a s h t a b l e O ;
Hashtable globalTable = f i n d T a b l e S t o r i n g S e s s i o n s ( ) ;
globalTable.put(sessionID, sessionlnfo);
Cookie s e s s i o n C o o k i e = new C o o k i e ( " J S E S S I O N I D " , s e s s i o n I D ) ;
sessionCookie.setPathC'/") ;
response.addCookie(sessionCookie);
g l o b a l T a b l e ,
, cookie,
, .
, , ,
API, .
cookie ,
.
cookie.
-.
URL
URL, ,
, .
, ,
. , URL h t t p : / / h o s t / p a t h / f i l e . h t m l ; j s e s s i o n i d = 1 2 3 4 -
892
19. Java :
(j s e s s i o n i d = 1 2 3 4 ) .
, ,
, cookie. ,
cookie,
. , , ,
, URL, )^ (
URL, L o c a t i o n ),
.
, , , .
HTML- .
<INPUT TYPE="HIDDEN" NAME="session" VALUE=",..">
GET POST .
. ,
.
" API H t t p S e s s i o n .
cookie URL.
cookie, cookie ,
URL.
, API.
).
API
,
, , ,
.
URL, URL,
.
HttpSession,
H t t p S e s s i o n g e t S e s s i o n
H t t p S e r v l e t R e q u e s t .
cookie, , , URL,
H t t p S e s s i o n . "" ; ,
, g e t S e s s i o n .
n u l l , ,
19.12.
893
. ,
g e t S e s s i o n t r u e .
:
HttpSession s e s s i o n = r e q u e s t . g e t S e s s i o n ( t r u e ) ;
,
g e t S e s s i o n ,
isNew.
,
H t t p S e s s i o n
cookie URL.
. 2.1 API
, , s e s s i o n . g e t V a l u e ( " a t t r i b u t e " ).
g e t V a l u e Object,
. n u l l ,
. , HttpSession^
g e t V a l u e .
2.2 API g e t V a l u e .
g e t At t r i b u t e ,
s e t A t t r i b u t e ( 2.1 g e t V a l u e putValue).
H t t p S e s s i o n .
, ShoppingCart
.
ShoppingCart c a r t =
(ShoppingCart)session.getAttribute("shoppingCart") ;
if ( c a r t == n u l l ) { / / ""
c a r t = new ShoppingCart();
session.setAttribute("shoppingCart", cart);
}
doSomethingWith(cart) ;
. ,
getValueNames, . 2.1
. 2.2
g e t A t t r i b u t e N a m e s , Enumeration.
getHeaderNames getParameterFames
H t t p S e r v l e t R e q u e s t .
, , ,
, H t t p S e s s i o n .
.
894
19. Java :
19.12.
895
, ,
Date s e t T i m e l n M i l l i s GregorianCalendar.
public long getLastAccessedTimeO
, 1
1970 . (GMT)
.
public int getMaxInactiveInterval()
public void setMaxInactiveInterval(int seconds)
,
.
.
, .
, -, ,
, .
public void invalidate()
.
, , ,
g e t V a l u e ( 2.1) g e t At t r i b u t e ( 2.2).
, p u t Value
s e t A t t r i b u t e .
. g e t A t t r i b u t e s e t A t t r i b u t e
g e t / s e t JavaBeans API.
, , ,
, H t t p S e s s i o n B i n d i n g L i s t e n e r .
p u t Value s e t A t t r i b u t e valueBound.
, p u t V a l u e s e t A t t r i b u t e
. , ,
removeValue ( 2.1) remove At t r i b u t e (
2.2). , H t t p S e s s i o n
B i n d i n g L i s t e n e r , valueUnbound.
,
(. r e f e r r i n g P a g e ).
, (.
p r e v i o u s Items ). ,
ShoppingCart addltem,
"", C a t a l o g g e t l t e m ,
, , .
HttpSession s e s s i o n = r e q u e s t . g e t S e s s i o n ( t r u e ) ;
session.setAttribute("referringPage",
rec[uest.getHeader ("Referer")) ;
896
19. Java :
ShoppingCart cart =
(ShoppingCart)session.getAttribute("previousltems");
if (cart == null) { // ""
cart = new ShoppingCart();
session.setAttribute("previousltems", cart);
}
String itemID = request.getParameter("itemID");
if (itemID != null) {
cart.addItem(Catalog.getItem(itemID));
}
,
s e t M a x I n a c t i v e I n t e r v a l , .
. ,
H t t p S e s s i o n B i n d i n g L i s t e n e r , v a l u e U n b o u n d .
,
, i n v a l i d a t e .
URL,
URL
URL, , ,
. JSP
URL, cookie ,
URL, . URL
. -, URL, Web-,
. URL encodeURL
H t t p S e r v l e t R e s p o n s e . ,
URL, .
, URL .
S t r i n g originalURL = someRelativeOrAbsoluteURL;
S t r i n g encodedURL = r e s p o n s e . e n c o d e U R L ( o r i g i n a l U R L ) ;
o u t . p r i n t l n ( " < A HREF=\"" + encodedURL 4- " \ " > . . . </A>") ;
-, URL, ,
s e n d R e d i r e c t (.. L o c a t i o n ).
, ,
encodeURL . H t t p S e r v l e t
R e s p o n s e e n c o d e R e d i r e c t U R L ,
.
S t r i n g o r i g i n a l U R L = someURL; / / 2 . 2
/ / URL
S t r i n g encodedURL = r e s p o n s e . e n c o d e R e d i r e c t U R L ( o r i g i n a l U R L ) ;
response.sendRedirect(encodedURL);
,
, ,
URL, .
1 9 . 1 2 .
897
: URL,
, response. encodeURL response,
encodeRedlrectURL, ,
.
19.26 ,
.
r e q u e s t . g e t S e s s i o n ( t r u e ) , ,
. ( I n t e g e r ) a c c e s s C o u n t .
, .
p u t V a l u e . , HTML-,
. . 19.17 19.18
, .
19.26. ShowSession. Java
p a c k a g e cwp;
import
import
import
import
import
java.io.*;
javax.servlet.*;
javax.servlet.http.*;
java.net.*;
java.util.*;
/** . */
public class ShowSession extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, lOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Session Tracking Example";
HttpSession session = request.getSession(true);
String heading;
Integer accessCount =
(Integer)session.getAttribute("accessCount");
if (accessCount == null) {
accessCount = new Integer(0);
heading = "Welcome, Newcomer";
} else {
heading = "Welcome Back";
accessCount = new Integer(accessCount.intValue() + 1)
}
// putValue setAttribute.
898
19. Java :
session.setAttribute("accessCount", accessCount);
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGC0L0R=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + heading + "</Hl>\n" +
"<H2>Information on Your Session:</H2>\n" +
"<TABLE B0RDER=1 ALIGN=\"CENTER\">\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
" <TH>Info Type<TH>Value\n" +
"<TR>\n" +
" <TD>ID\n" +
" <TD>" + session. getldO + "\n" +
"<TR>\n" +
" <TD>Creation Time\n" +
ft
<TD>"
SSi
Welcome, Newcomer
Information on Your Session:
i
Vrttae
ID
Tol010mC6608409833952431At
Creation Time
.jif j#ij'
. 19.17.
ShowSession
s-f m
19.12.
899
1-*!1,1.]111.
Ftie
Edit
ytew
Q,o jQomrmKBcetor
fil
^ >" 3 ^^ i^a c# rf Q
Welcome Back
Information on Your Session:
Tol010mC6608409833952431At
Creation Time
Oocument Dcxws
^. 4^ ^
\^
. 19.18.
ShowSession.
19.13.
, ,
CGI-
, . ,
: HTML-.
p r i n t In Web- ,
, , .
, , , , ,
.
JSP, .
JAVASERVER PAGES
...
JSP.
, .
,
JSP.
JSP.
JavaBeans.
.
JSP.
"--".
j-:y\3j^^
2 0 . 1 . JSP
JSP HTML- ,
. HTML-
(
) .
"<%" "%>". JSP,
h t t p : / / h o s t / O r d e r C o n f i r m a t i o n . j s p ? t i t l e = C o r e - i Web-t-Programming 1, " T h a n k s f o r o r
d e r i n g C o r e Web P r o g r a m m i n g " .
Thanks f o r o r d e r i n g <!><%= r e q u e s t . g e t P a r a m e t e r ( " t i t l e " )
%></!>
no HTML-
. , ,
JSP, ,
ASP, PHP ColdFusion. 20.2 JSP
, . -,
JSP , JSP,
. -, JSP
.
JavaServer Pages, Web, ,
. Web-, JSP.
, ,
. j s p , JSP (
). ,
,
CLASS PATH. -
902
2 0 . JavaServer P a g e s
, ,
JSP Java.
,
19.2.
JSP- HTML, , .
HTML- , . ,
JSP .
, JSP, ,
JSP .
, JSP-
.
JSP, .
JSP,
, .
HTML- . Internet Explorer 5
,
"". JSP
Internet Explorer 5.0.
Tools (), Internet Options ( ),
Advanced () Show friendly HTTP
error m e s s a g e s ( HTTP).
JSP, , Internet
.
^^
Explorer 5.0 -
^^^^^
HTML-, ,
JSP-: , .
Java-,
, ,
, .
,
.
1.0 L1 JavaSei-ver Pages.
0.92, 1.0 ,
JSP ,
0.92. , 1.1, .
2.2 . JSP 1.1,
, Servlet
2.2, , JSP 1.0. JSP 1.0
JSP 1.1.
2 0 . 2 . JSP
903
20.2. JSP
Java
. .
JSP
,
, HTML-. ,
JSP Java. ,
API ,
.
, .
JSP JSP
.
JSP
JSP ,
. JSP
, HTML- ,
p r i n t In,
HTML- . , HTML-
JSP
. Web-, ,
HTML- , Web-
.
.
,
JSP ? . JSP
.
L JSP- .
JSP, .
904
JSP SSI
SSI
Web-. SSI, JSP
. SSI
, JSP
,
.
JSP JavaScript
JavaScript ( Java)
HTML- . JavaScript
, JSP
( ). JavaScript
, JSP ,
.
20.3. JSP
,
JSP, . .
L , "<%= %>".
.
2. , "<% %>".
_ j s p S e r v i c e , s e r v i c e .
3. , "<% ! %>".
.
.
JSP-
HTML-, . HTML-,
. -
2 0 . 3 . JSP
905
,
Web-. JSP,
, Allaire HomeSite.
. , "<%",
"<\%". -, ,
JSP ,
:
<%-- JSP --%>
HTML,
<!-- HTML -->
HTML-.
JSP- ,
.
<^o=
Java %>
,
.
, , . ,
1 JSP:
C u r r e n t t i m e : <%= new J a v a . u t i l . D a t e () %>
j s p S e r v i c e ( s e r v i c e )
:
out.print("Current time: " ) ;
out.println(new Java.util.Date ());
; , ,
. (
.)
request H t t p S e r v l e t R e q u e s t .
response H t t p S e r v l e t R e s p o n s e .
session H t t p S e s s i o n , (
s e s s i o n p a g e . 20.4).
out P r i n t W r i t e r , .
.
Your h o s t n a m e : <%= r e q u e s t . g e t R e m o t e H o s t ( )
%>
906
2 0 . JavaServer Pages
XML
,
JSP-.
:
<jsp:expression>
Java</jspiexpression>
JSP 1.1
. , JSP 1.2,
, ASP (<%= . . . %>). HTML-, XML-
; j s p : e x p r e s s i o n
.
JSP-
CLASS PATH .
URL. ,
JSP , HTML-,
. JSP URL,
Web-, .
JSP URL,
( h o s t ).
, T o m c a t
install_dir\webapps\ROOT
install_dir\webapps\ROOT\anyDir
URL Tomcat
http://host/filename.jsp
http://host/anyDir/filename.jsp
, J R u n
install_di\servers\default\default-app
install_dir\servers\default\default-app\anyDir
URL JRun
http://host/filename.jsp
http://host/anyDir/filename.jsp
2 0 . 3 . JSP
907
JSP ,
Java-, JSP,
(, . . . / W E B - I N F / c l a s s e s ) .
JSP
10.1 JSP-, . 20.1
. Tomcat JSP i n s t a l l _ d i r \
webapps\ROOT\cwp\Expressions . j sp;
URL h t t p : / / h o s t / c w p / E x p r e s s i o n s . j sp. ,
LINK.
. -, HTML-
p r i n t I n . JSP
,
. -,
URL, URL Web -. JSP- , HTML, URL
. , , LINK,
, JSP-. . e s s
h t t p : / /www. c o r e w e b p r o g r a m m i n g . com/.
2 0 , 1 . E x p r e s s i o n s . j sp
<!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>JSP E x p r e s s i o n s < / T I T L E >
<META NAME="keywords"
CONTENT="JSP,expressions,JavaServer,Pages,servlets">
<META N A M E = " d e s c r i p t i o n "
CONTENT="A q u i c k e x a m p l e of JSP e x p r e s s i o n s . " >
<LINK REL=STYLESHEET
HREF="JSP-Styles . e s s "
TYPE="text/css">
</HEAD>
<BODY>
<H2>JSP E x p r e s s i o n s < / H 2 >
<UL>
< L I > C u r r e n t t i m e : <%= new j a v a . u t i l . D a t e ( ) %>
<LI>Your h o s t n a m e : <%= r e c j u e s t . g e t R e m o t e H o s t ( ) %>
<LI>Your s e s s i o n ID: <%= s e s s i o n . g e t l d O %>
<LI>The <CODE>testParam</CODE> form p a r a m e t e r :
<%= r e q u e s t . g e t P a r a m e t e r ( " t e s t P a r a m " ) %>
</UL>
</BODY>
</HTML>
908
2 0 . JavaServer Pages
te i *
Convaunicato
; ^^ ^ 3 J>!t i ^ ^:f rf Q^ ^
JSP Expressions
Current time: Mon Aug 07 15:06:27 EDT 2000
Your hostname: 127.0.0,1
Your session : Tol010mC22565256379010112At
. 20.1.
'^ - i i
-..
Expressions.jsp
, ,
.
Java- _ j s p S e r v i c e ( s e r v i c e ) .
:
<% Java-
%>
, ,
( r e q u e s t , r e s p o n s e , s e s s i o n , o u t ..). , ,
,
o u t .
<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
,
}^ :
A t t a c h e d GET d a t a :
<%= r e q u e s t . g e t Q u e r y S t r i n g ( )
%>
)^
, .
,
, ,
, .. ,
, , ,
HTML-:
<% r e s p o n s e . s e t C o n t e n t T y p e ( " t e x t / p l a i n " ) ;
%>
,
JSP, (
). , JSP
( J s p W r i t e r ) , .
; 20.4.
20.3.
JSP
909
BGColor.jsp
|.y.'P|jlffl|Wi|i.i.l|Jl.l|.!I^I^IIJ.!JIJi].!).l|Ji|l
Fiis
file
Edft
View
F^rrtaftes
Xods
di'
\V4-v
Fiivortes
Joois
Help
He^
Color Testing
1]
"13
Color Testing
J:
l^jOone
"3
f si Local TiistvA
. 20.2. ,
BGColor. j sp
J
g ] DGr
-h.lvAriV'Xr^
. 20.3. BGColor.
j s p
bgColor RGB-
910
2 0 . JavaServer Pages
JSP-
HTML JSP .
, HTML-
_ j s p S e r v i c e , JSP. ,
, , HTML-
( p r i n t l n ) JSP
. JSP-:
<% i f
Have
<% }
Have
<% }
{ %>
:
if
,
. -, '*%>",
**%\>". -, <% Java-
%> XML-. :
<jsp:scriptlet>Java-o</jsp:scriptlet>
, ,
JSP 1.2, j s p : s c r i p t l e t -
JSP (
j s p S e r v i c e , s e r v i c e ) .
:
<%! Java-
%>
,
JSP- . ,
, . , ,
,
( s e r v i c e , d o G e t , i n i t ..). , -
2 0 . 3 . JSP
911
JSP. ,
s e r v i c e , d o G e t do P o s t , s e r v i c e
_ j s p S e r v i c e , ,
.
j s p l n i t j s p D e s t r o y .
i n i t d e s t r o y .
JSP
jsplnit
jspDestroy.
JSP-,
( ).
,
, s e r v i c e
. ,
S i n g l e T h r e a d M o d e l . S i n g l e T h r e a d M o d e l 19.4
20.4 i s T h r e a d S a f e
p a g e .
, , a c c e s s C o u n t
s t a t i c .
<%! p r i v a t e i n t a c c e s s C o u n t = 0; %>
Accesses t o page s i n c e s e r v e r r e b o o t :
<%= +-i-accessCount %>
JSP 20.3,
. 20.4.
1 0 . 3 . A c c e s s C o u n t s . j s p
<!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>JSP D e c l a r a t i o n s < / T I T L E >
<META NAME="keywords"
CONTENT^"JSP,declarations,JavaServer,Pages,servlets">
<META N A M E = " d e s c r i p t i o n "
CONTENT="A q u i c k e x a m p l e of JSP d e c l a r a t i o n s . " >
<LINK REL=STYLESHEET
HREF="JSP-Styles.ess"
TYPE="text/css">
</HEAD>
<BODY>
<H1>JSP Declarations</Hl>
<%? private int accessCount = 0 ; %>
<H2>Accesses to page since server reboot:
<%= ++accessCount %></H2>
</BODY>
</HTML>
912
2 0 . JavaServer Pages
^SZBB
ffc * t ^lew go
jQomiTiuracator
^: -/ 3 ^^ ^ rf L^
^^^Bocfemafk*
iS
JSP Declarations
Accesses to page since server
reboot: 10
; ^ b ^ '
. >;* '^^ . \^
. 20.4.
AccessCounts. j sp
,
"%>", "% \ > " . XML- <% ! Java- %>
:
<j s p : d e c l a r a t i o n > J a v a - < / j s p : d e c l a r a t i o n >
JSP- ,
,
. ,
, _ j s p S e r v i c e ,
. r e q u e s t ,
r e s p o n s e , o u t , s e s s i o n , a p p l i c a t i o n , config,pageContext page.
request
H t t p S e r v l e t R e q u e s t ,
. (, GET
POST) .
response
r e s p o n s e H t t p S e r v l e t R e s p o n s e ,
, . (.
o u t ) , JSP,
. ,
.
out
P r i n t W r i t e r ,
. JSP
r e s p o n s e , P r i n t W r i t e r
J s p W r i t e r .
b u f f e r p a g e . o u t -
20.4. page
913
, JSP-
o u t .
session
H t t p S e s s i o n , .
,
, ,
s e s s i o n p a g e .
s e s s i o n
JSP .
application
a p p l i c a t i o n S e r v l e t C o n t e x t ,
g e t S e r v l e t C o n t e x t . JSP
S e r v l e t C o n t e x t , ,
. S e r v l e t C o n t e x t
s e t At t r i b u t e g e t A t t r i b u t e ,
, .
S e r v l e t C o n t e x t ,
S e r v l e t C o n t e x t ,
( Web-).
config
S e r v l e t C o n f i g .
pageContext
JSP P a g e C o n t e x t ,
. p a g e C o n t e x t P a g e C o n t e x t ,
.
page
t h i s
. , , JSP
Java.
20.4. page
, JSP. .
,
, .
, ; *
\ ' , " \ ".
914
import
i m p o r t p a g e ,
, JSP-.
, j a v a . l a n g . *, j a v a x . s e r v l e t . *,
j a v a x . s e r v l e t . j s p . *, j a v a x . s e r v l e t . h t t p . * , , ,
. JSP,
, ,
, , . i m p o r t
:
<%@ p a g e i m p o r t = " p a c k a g e . c l a s s " %>
<%@ p a g e i m p o r t = " p a c k a g e . c l a s s l , . . . , p a c k a g e . c l a s s N "
%>
, ,
, , , J a v a . u t i l ,
.
<%@ p a g e i m p o r t = " J a v a . u t i l . * " %>
i m p o r t p a g e ,
.
p a g e
i m p o r t , , ,
, .
,
, . ,
Java Web Server 2.0 s e r v l e t s,
, JSP,
20.4. page
915
c l a s s e s . JSWDK Tomcat .
.
20.4 JSP-, ,
, JSP: j a v a . u t i l . D a t e c w p . S e r v l e t U t i l i t i e s (. 19.21).
, :
<%@ p a g e i m p o r t = " J a v a . u t i l . * , c w p . * " %>
Ha . 20.5 20.6 JSP.
20.4. ImportAttribute. j s p
<!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>The i m p o r t A t t r i b u t e < / T I T L E >
<LINK REL=STYLESHEET
HREF="JSP-Styles.CSS"
TYPE="text/css">
</HEAD>
<BODY>
<H2>The i m p o r t A t t r i b u t e < / H 2 >
<% JSP p a g e d i r e c t i v e %>
<%( p a g e import" j a v a . u t i l . * , c w p . *" %>
<% %>
<%!
p r i v a t e S t r i n g randomlDO {
i n t num = ( i n t ) ( M a t h . r a n d o m { ) * 1 0 0 0 0 0 0 0 . 0 ) ;
r e t u r n ( " i d " + num);
}
916
2 0 . JavaServer Pages
Re
Jools
^^
\ fe
<St ^
Fjvonle
Juofe
Help
"3
d
^
^locaii*art
;30one
. 20.5.
I m p o r t A t t r i b u t e . j sp
. 20.6.
I m p o r t A t t r i b u t e . j sp
contentType
c o n t e n t T y p e C o n t e n t Type, 1- , .
MIME- 19.10.
MIME- . 19.1.
c o n t e n t T y p e :
<%@ page contentType="MIME-Type" %>
<%@ page contentType="MIME-Type; charset=Character-Set" %>
,
<%@ page contentType="application/vnd.ms-excel" %>
, :
<%
response.setContentType("application/vnd.ms-excel")
%>
, 1- t e x t / p l a i n ,
JSP t e x t / h t m l ( ISO-8859-1).
20.5 JSP-, ,
. . 20.7
Internet Explorer.
, Microsoft Office.
2 0 , 5 . E x c e l . j s p
Email AddressFirst
Last
h a l l @ c o r e w e b p r o g r a r n m i n g . com
Marty
Hall
brown@corewebprogramming.com
Larry
Brown
gates@sun.com
Bill
Gates
Larry
Ellison ellison@microsoft.com
<%@ p a g e c o n t e n t T y p e = " a p p l i c a t i o n / v n d . m s - e x c e l " %>
<% T h e r e a r e t a b s , n o t s p a c e s , b e t w e e n c o l u m n s . %>
20.4. page
1 Be
d ^ |nsft
917
^1^||||
^ 3 4 aija:i3-J)-J mg.
Adde|#J http /Vlocaihosl/'cwp/Excei (Sfj
I
P7C6
1 ,^ _J_
1 1 'First "
l_2_ Marty
"''Larry
1 4 J Bill
j 5 Larry
Last
Hall
Brown
Gates
Ellison
1 4 W \ E K c e l /
3 _
4
6__
Email Address
halh^corewebprogramming.com
brown@corewebprogrannmmg com
gates@sun com
elliscn^micrcsoft com
\*\
:\
"""I
|
^^ |
>\r\
isThreadSafe
i s T h r e a d S a f e , ,
JSP, S i n g l e T h r e a d M o d e l .
:
<%0 p a g e i s T h r e a d S a f e = " t r u e " %> <%-- %>
<%@ p a g e i s T h r e a d S a f e = " f a l s e " %>
.
, ,
.
, -
. }^ (, ,
) ,
, (,
) . ,
, idNum
,
.
<%! private int idNum = 0; %>
<%
String userlD = "userlD" + idNum;
out.println ("Your ID is " 4- userlD + " . " ) ;
idNum = idNum + 1;
%>
,
synchronized.
synchronized(someObject) {
, ,
,
. s y n c h r o n i z e d
:
<%! private int idNum = 0; %>
<%
918
synchroni zed(thi s) {
String userlD = "userlD" + idNum;
out.println("Your ID is " + userlD + " . " ) ;
idNum = idNum + 1;
}
%>
S i n g l e T h r e a d M o d e l , ,
. ,
, ,
.
<%@ p a g e i s T h r e a d S a f e = " f a l s e " %>, ,
,
, JSP, S i n g l e T h r e a d
Model. t r u e , ..
.
session
s e s s i o n , . :
<%@ p a g e s e s s i o n = " t r u e " %> <% --%>
<%@ p a g e s e s s i o n = " f a l s e " %>
t r u e , s e s s i o n
( H t t p S e s s i o n ) ,
. ,
s e s s i o n . f a l s e ,
. s e s s i o n
, JSP .
. ,
, .
,
, .
buff
b u f f e r , ,
o u t (
J s p W r i t e r , P r i n t W r i t e r ) .
:
<%@ p a g e b u f f e r = " p a 3 M e p k b " %>
<%@ p a g e b u f f e r = " n o n e " %>
, , ,
. , <%@ p a g e b u f f e r = " 3 2 k b "
20.4. page
919
%> ,
, , ,
32 , , .
, 8 .
, . ,
,
, HTML-.
autoflush
a u t o f l u s h ,
,
.
:
<%(? p a g e a u t o f l u s h = " t r u e " %> <% %>
<%@ p a g e a u t o f l u s h = " f a l s e " %>
aTpH6yTbuf f e r = " n o n e " , f a l s e .
extends
e x t e n d s , JSP,
:
<%@ p a g e e x t e n d s = " p a c k a g e . c l a s s " %>
,
, .
info
i n f o , g e t S e r v l e t I n f o . .
<%@ p a g e i n f o = " "
%>
errorPage
e r r o r P a g e JSP (
T h r o w a b l e ) ,
. :
<%@ p a g e errorPage="_(7/?" %>
JSP, ,
e x c e p t i o n .
920
2 0 . JavaServer Pages
isErrorPage
,
JSP- .
i s E r r o r P a g e :
<%@ page isErrorPage="true" %>
<%@ page isErrorPage="false" %> <%-- % >
language
, l a n g u a g e
, :
<%@ p a g e l a n g u a g e = " c o b o l " %>
,
Java .
1\/'
XML-.
:
< j s p : d i r e c t i v e . _ =""
/>
, XML-
<%@ p a g e i m p o r t = " j a v a . u t i l . * " %>
:
<jsp:directive.page
import="Java.util.*"
/>
20.5.
JSP-
JSP
.
L include. JSP-
, .
, JSP-
,
C o n t e n t - T y p e . .
2. jsp:include. JSP-
,
, JSP. j s p : i n c l u d e
JSP ,
20.5. -
921
.
i n c l u d e , JSP ,
,
. j s p : i n c l u d e
.
3. jspiplugin.
Java, , Java-,
Web-,
, i n t r a n e t .
j s p i p l u g i n JSP , Java PlugIn. .
include:
i n c l u d e JSP.
( ).
:
<%@ i n c l u d e file="_"
%>
, JSP
, ,
j s p : i n c l u d e . .
-, JSP-,
. , , s n i p p e t , j s p
:
<%! int accessCount = 0 ; %>
:
<%@ i n c l u d e f i l e = " s n i p p e t . j s p "
<%= a c c e s s C o u n t + + %>
-, JSP-
.
( ), ,
. JSP 1.1
j s p p r e c o m p i l e ,
JSP . JSP 1.0 .
JSP-.
, ( UNIX t o u c h ) .
JSP-.
. ,
:
922
2 0 . JavaServer P a g e s
JSP- ,
.
, 20.6 JSP-,
,
, . 20.7 ,
, 20.6 .
20.6. C o n t a c t S e c t i o n . j s p
<%@ p a g e i m p o r t = " J a v a . u t i l . D a t e " %>
<% ,
J S P , . --%>
<%!
p r i v a t e i n t accessCount = 0;
p r i v a t e Date accessDate = new D a t e ( ) ;
p r i v a t e S t r i n g accessHost = "<I>No p r e v i o u s a c c e s s < / I > " ;
%>
<P>
<HR>
T h i s p a g e © 2001
<A HREF="http//www.my-company.com/">my-company.com</A>.
T h i s p a g e h a s b e e n a c c e s s e d <%= + + a c c e s s C o u n t %>
t i m e s s i n c e s e r v e r r e b o o t . I t was l a s t a c c e s s e d from
<%= a c c e s s H o s t %> a t <%= a c c e s s D a t e %>.
<% a c c e s s H o s t = r e q u e s t . g e t R e m o t e H o s t ( ) ; %>
<% a c c e s s D a t e = new D a t e O ; %>
2 0 . 7 . S o m e R a n d o m P a g e . j s p
<!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>Some Random Page</TITLE>
<META NAME="author" CONTENT="J. Random H a c k e r " >
<META NAME="keywords"
CONTENT="foo,bar,baz,quux">
<META N A M E = " d e s c r i p t i o n "
CONTENT="Some random Web p a g e . " >
<LINK REL=STYLESHEET
HREF="JSP-Styles.ess"
TYPE="text/css">
</HEAD>
<BODY>
20.5. JSP-
923
^o(if.!gt^||J:iJJ!paL^!l^li[ppp^
fa Edrt Ytew fit? iJommunJcflttof 1
^'^eoofanoHcs
t0cgtfton:|http//Jocalhost/cwp/SQmeRandomPagejsp
Tjf^'V^af^Retated
'Document Done
. 20.8. SomeRandomPage . j sp
XML- include
XML-
<%@ i n c l u d e f i l e = " . . . " %>
:
<jsp:directive.include
file="..."
/>
i n c l u d e JSP ,
. . j s p : i n c l u d e
JSP-,
. j s p : i n c l u d e )'
JSP-,
924
2 0 . JavaServer P a g e s
,
.
, j s p : i n c l u d e .
flush="true"
/>
,
20.8. I t e m l . h t m l , I t e m 2 . h t m l I t e m 3 . h t m l
.
. 20.9.
2 0 . 8 . WhatsNew . j s p
<!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>What's New a t JspNews.com</TITLE>
<LINK REL=STYLESHEET
HREF="JSP-Styles.ess"
TYPE="text/css">
</HEAD>
<BODY>
<TABLE B0RDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">
W h a t ' s New a t JspNews.com</TABLE>
<P>
Here is a summary of our three most recent news stories:
<0L>
<LI><jsp:include page="news/lteml.html" flush="true" />
<LI><jsp:include page="news/ltem2.html" flush="true" />
<LI><jsp:include page="news/Item3.html" flush="true" />
</0L>
</BODY>
</HTML>
20.5. JSP-AOicyMeHTOB
925
20.10. Item2.html
<B>Scott McNealy acts serious.</B> In an unexpected twist,
wisecracking Sun head Scott McNealy was sober and subdued at
yesterday's meeting.
<A HREF="http://www.sun.com/Imposter.html">More details...</A>
"3
"3
J
%Oci^
;|^toca< intrant
. 20.9.
, Java Plug-In
JSP
, HTML-
APPLET. i n t r a n e t ,
Netscape 6, JDK 1.1 JDK
1.02, Netscape 4.x, Internet Explorer 5.x
926
Swing Swing- .
Internet Explorer 3 Netscape 3.x 4.01 4.05 (
J D K 1.02).
Java 2D.
c o l l e c t i o n s .
,
Java 2 ,
.
, Sun
Netscape Internet Explorer, Java 2
. Java Plug-In h t t p : / / j a v a .
s u n . c o m / p r o d u c t s / p l u g i n / , , JDK 1.2.2
. Java Plug-In
, , WWW
. ,
intranet.
- .
, APPLET Java Plug-In,
, ,
Java.
Internet Explorer
OBJECT, Netscape EMBED. ,
,
, OBJECT EMBED
( EMBED COMMENT OBJECT)
.
.
j s p : p l u g i n ,
Java Plug-In. -,
Web-
OBJECT, EMBED.
jsprplugin
j s p : p l u g i n
: t y p e , c o d e , w i d t h h e i g h t . t y p e
a p p l e t , ,
<APPLET>, :
,
. ,
<APPLET CODE="MyApplet.class"
WIDTH=475 HEIGHT=350>
</APPLET>
20.5. JSP-
927
:
<jsp:plugin type="applet"
code="MyApplet.class"
width="475" height="350">
</jsp:plugin>
j s p i p l u g i n .
( ) , APPLET.
j s p : p l u g i n .
type
a p p l e t . Java Plug-In
Web- JavaBeans.
b e a n .
code
, CODE
<APPLET>, .. , A p p l e t
JApplet.
width
WIDTH
<APPLET> ( ) , .
height
h e i g h t , HEIGHT
<APPLET>, ( ) , .
codebase
, CODEBASE
<APPLET>, .. .
, c o d e .
APPLET, , ,
. JSP ,
JSP-, ,
.
align
ALIGN
<APPLET> <IMG> .
l e f t , r i g h t , t o p , b o t t o m m i d d l e .
hspace
, HSPACE
<APPLET>, ..
.
vspace
, VSPACE
<APPLET>, ..
.
928
2 0 . JavaServer Pages
archive
a r c h i v e ARCHIVE
<APPLET> JAR-,
.
name
, NAME
<APPLET>, .. .
, , , JavaScript.
title
t i t l e ,
.
TITLE <APPLET> ( HTML, HTML 4.0).
j reversion
Java Runtime
(JRE). L L
Environment
iepluginurl
i e p l u g i n u r l URL Java Plug-In Internet Explorer.
, ,
.
Sun, ^ intranet
Plug-In .
nspluginurl
n s p l u g i n u r l URL Java Plug-In Netscape.
Sun, intranet
Plug-In .
jsp:param jsp:params
j s p : p a r a m j s p r p l u g i n ,
PARAM APPLET, ..
g e t P a r a m e t e r . j s p : p a r a m
. -, j s p : p a r a m XML,
,
, ">",
" / > " . -, j s p : p a r a m
j s p : p a r a m s .
,
<APPLET C O D E = " M y A p p l e t . c l a s s "
WIDTH=475 HEIGHT=350>
<PARAM NAME="PARAM1" VALUE="VALUE1">
<PARAM NAME="PARAiyi2" VALUE="VALUE2">
</APPLET>
20.5. -
929
:
<jsp;plugin
type="applet"
code="MyApplet.class"
width="475" height="350">
<jsp:params>
< j s p : p a r a m name="PARAMl" value="VALUEl" />
< j s p : p a r a m name="PARAM2" value="VALUE2" />
</jsp:params>
</jsp:plugin>
jsp: fallback
,
OBJECT EMBED. j s p : f a l l b a c k
, APPLET.
,
<APPLET C O D E = " M y A p p l e t . c l a s s "
WIDTH=475 HEIGHT=350>
<B>Error: t h i s example r e q u i r e s
</APPLET>
Java.</B>
:
<jsp:plugin type="applet"
code="MyApplet.class"
width="475" height="350">
<jsp:fallback>
<B>Error: this example requires Java.</B>
</jsp:fallback>
</jsp:plugin>
jsp:plugin
20.12 JSP, j s p : p l u g i n
P l u g i n A p p l e t . 20.13-20.15 ,
20.10 .
2 0 . 1 2 . P l u g i n A p p l e t . j s p
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
<TITLE>Using j s p : p l u g i n < / T I T L E >
<LINK REL=STYLESHEET
HREF="JSP-Styles.ess"
TYPE="text/css">
</HEAD>
<BODY>
<TABLE B0RDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">
Using jsp:plugin</TABLE>
<P>
Transitional//EN">
930
<CENTER>
<jsp:plugin type="applet"
code="PluginApplet.class"
width="370" height="420">
</j sp:plugin>
</CENTER>
</BODY>
</HTML>
20.14.TextPanel.Java
import java.awt.*;
import Java.awt.event.*;
import javax.swing.*;
/** JPanel, ,
* , JComboBox.
public class TextPanel extends JPanel
implements ActionListener {
private JComboBox fontBox;
private DrawingPanel drawingPanel;
public TextPanel0 {
GraphicsEnvironment env =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = env.getAvailableFontFamilyNames();
fontBox = new JComboBox(fontNames);
setLayout(new BorderLayout() ) ;
JPanel fontPanel = new JPanel();
fontPanel.add(new JLabel("Font:"));
fontPanel.add(fontBox);
JButton drawButton = new JButton("Draw");
drawButton.addActionListener(this);
fontPanel.add(drawButton) ;
20.5. JSP-
add(fontPanel, BorderLayout.SOUTH);
drawingPanel = new DrawingPanel();
fontBox.setSelectedltem("Serif");
drawingPanel.setFontName("Serif");
add(drawingPanel, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
drawingPanel.setFontName((String)fontBox.getSelectedItem()
drawingPanel.repaint();
}
20.15.DrawingPanel.java
import java.awt.*;
import Java.awt.geom.*;
import javax.swing.*;
/** , .
* setFontName.
V
class DrawingPanel extends JPanel {
private Ellipse2D.Double circle =
new Ellipse2D.Double(10, 10, 350, 350);
private GradientPaint gradient =
new GradientPaint(0, 0, Color.red, 180, 180, Color.yellow,
true); // true
private Color[] colors = { Color.white. Color.black };
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(gradient);
g2d.fill(circle);
g2d.translate(185, 185);
for (int 1=0; i<16; i-f+) {
g2d.rotate(Math.PI/8.0);
g2d.setPaint(colors[i%2]);
g2d.drawstring("jsprplugin", 0, 0 ) ;
}
}
public void setFontName(String fontName) {
setFont(new Font(fontName, Font.BOLD, 35));
931
932
,dit
View
Fvof*es
Joofs
hJelp
"3
"13
Using jsp:plug
-*
or
J
^
Applet sfaftP'd
J k localirrfimeS
. 2 0 . 1 0 .
P l u g i n A p p l e t . j sp
Internet Explorer. Ha
Java 2 Plug-In
933
. -,
(, ,
, s e t S p e e d
). -,
. (,
) ;
g e t S p e e d l n M P H g e t S p e e d l n K P H . ) -,
,
(,
s e t P o s i t i o n ) .
3.
getXxxu setXxx. , ^
, )^ g e t N u m P a s s e n g e r s (
i n t ) s e t N u m P a s s e n g e r s
( v o i d , ).
, N u m P a s s e n g e r s
( , ;
).
qetXxx, s e t X r x , ,
, .
, .
i s X x x , , l e a s e d
i s L e a s e d ( b o o l e a n ,
), s e t L e a s e d (
v o i d , b o o l e a n ) .
JSP
, JSP
g e t / s e t i s / s e t .
JavaBeans
j s p : u s e B e a n b e a n
o)^eeJSP. JavaBeans ,
Java-, JSP.
b e a n .
<jsp:useBean
/>
: ,
c l a s s , , i d .
, JSP
<jsp:useBean
id="bookl" class="cwp.Book"
/>
934
_ j s p S e r v i c e :
/>
R u n n a b l e t h r e a d l = new M y C l a s s O ;
j s p : u s e B e a n XML-, )^ HTML: ,
">", "/>"
JSP-, j s p : x x x .
, .
,
. ,
( \ ' ) ' ,
( \ " ) .
'", "%>" "%\>", '*<%" "<\%".
beans
b e a n ,
j s p : g e t P r o p e r t y . j s p : g e t P r o p e r t y ,
i d j s p : u s e B e a n ,
p r o p e r t y , .
, JSP-,
; ,
i d . , , Book
S t r i n g t i t l e b o o k l ,
j s p : u s e B e a n . JSP- t i t l e
:
935
/>
,
Web-,
Java.
, , , ,
, , .
, b e a n s , "
f " "
g e t Foe, , ,
s e t F o o ; ,
g e t F o o " .
beans
j s p : s e t P r o p e r t y .
-.
)': name ( i d
j s p : u s e B e a n ) , p r o p e r t y ( , )
v a l u e ( ).
j s p : s e t P r o p e r t y ,
. ,
, ,
,
, .
j s p : s e t P r o p e r t y ,
. ,
t i t l e b o o k l , ,
:
<jsp:setProperty name="bookl"
property="title"
v a l u e = " C o r e Web Programming" / >
<% b o o k l . s e t T i t l e ( " C o r e Web P r o g r a m m i n g " ) ; %>
j s p : s e t P r o p e r t y ,
,
,
,
getXxx s e t X x x .
StrmgBean
20.16 S t r i n g B e a n ,
cwp.
, ,
, b e a n .
S t r i n g B e a n g e t M e s s a g e , S t r i n g
936
setMessage, S t r i n g .
JavaBeans, S t r i n g message.
20.17 JSP-, StringBean.
S t r i n g B e a n j s p : useBean :
<jsp:useBean i d = " s t r i n g B e a n " class="cwp.StringBean" />
message )'
:
< j s p : g e t P r o p e r t y name="stringBean" property="message" />
<%= StringBean.getMessage() %>
message :
<j sp:setProperty name="stringBean"
property="message"
value="some message" />
<% StringBean.setMessage("some message"); %>
. 20.11.
2 0 . 1 6 . S t r i n g B e a n . J a v a
package cwp;
/** bean,
* String message.
V
public class StringBean {
private String message = "No message specified";
public String getMessage() {
return(message);
}
public void setMessage(String message) {
this.message = message;
20.17.StringBean.j sp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Using JavaBeans with JSP</TITLE>
<LINK REL=STYLESHEET
HREF="JSP-Styles.css"
TYPE="text/css">
</HEAD>
<BODY>
937
View
i^o
:"l :
,f
wuc4rr'3fi<s
^'
<
^^ -h f :i;
Localton jh'tp/.'localbost/
1.
. 20.11.
StringBean.j sp
beans
beans j s p : s e t P r o p e r t y .
: (
i d j sp:useBean), p r o p e r t y
( , ) v a l u e ( ).
, S a l e E n t r y , 20.18,
itemID ( S t r i n g ) , numiterns ( i n t ) , discountCode ( double),
a , , itemCost t o t a l C o s t
( double). 20.19 JSP-,
S a l e E n t r y )' :
<jsp:useBean i d = " e n t r y " c l a s s = " c w p . S a l e E n t r y " />
. 20.12.
938
bean
itemlD.
<jsp:setProperty
name="entry"
property="itemID"
value='<%= r e q u e s t . g e t P a r a m e t e r ( " i t e m I D " )
%>' />
, v a l u e JSP-.
,
v a l u e name j s p : s e t P r o p e r t y
. ,
( \ ' \ " ) .
2 0 . 1 8 . S a l e E n t r y . J a v a
package cwp;
/** bean,
* jsp:setProperty .
/ /
// .
public double getltemCost() {
double cost;
if (itemlD.equals("al234")) {
cost = 12.99*getDiscountCode0;
} else {
cost = -9999;
}
return(roundToPennies(cost)) ;
}
private double roundToPennies(double cost) {
return(Math.floor(cost*100)/100.0) ;
}
public double getTotalCost() {
return(getltemCost() * getNumltems());
20.19.SaleEntryl.j sp
<1D0CTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Using jsp:setProperty</TITLE>
<LINK REL=STYLESHEET
HREF="JSP-Styles.ess"
TYPE="text/css">
</HEAD>
<BODY>
<TABLE B0RDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">
Using jsp:setProperty</TABLE>
<jsp:useBean id="entry" class="cv.SaleEntry" />
<j sp:setProperty
name=" entry "
property="i temID"
value='<%= request.getParameter("itemID") %>' />
<%
int numltemsOrdered = 1 ;
try {
numltemsOrdered =
Integer. parseint (request. getParameter ("niimltems ") ) ;
} catch(NumberFormatException nfe) {}
%>
<j sp:setProperty
name="entry"
property="numiterns"
value="<%= niomltemsOrdered %>" / >
939
940
2 0 . JavaServer Pages
<%
double discountCode = 1.0;
try {
String discountString =
request.getParameter("discountCode");
// Double.parseDouble JDK 1.1
discountCode =
Double.valueOf(discountString) doubleValue()
} catch(NumberFormatException nfe) {}
%>
<j sp:setProperty
name="entry"
property="discountCode"
value="<%= discountCode %>" />
<BR>
<TABLE ALIGN="CENTER" B0RDER=1>
<TR CLASS="COLORED">
<TH>Item ID<TH>Unit Price<TH>Number Ordered<TH>Total Price
<TR ALIGN="RIGHT">
<TD><jsp:getProperty name="entry" property="itemID" />
<TD>$<jsp:getProperty name="entry" property="itemCost" />
<TD><jsp:getProperty name="entry" property="numltems" />
<TD>$<jsp:getProperty name="entry" property="totalCost" />
</TABLE>
</BODY>
</HTML>
|.,
fee
E<irt
View
t^iiiiimifflB
Fgvof^i*^
loo4
4?>lp
"3
Usfna ISD:seroDerty
) UmtT'iite *?! Onleie-sl Total 1<?
al234
J 11.95
2'? S32:. 6f.
J
^ D o f
' ^ l o c a l inaie
. 20.12.
SaleEntryl.jsp
itemID ,
S t r i n g . numltems
d i s c o u n t C o d e , ,
g e t P a r a m e t e r S t r i n g .
, numltems.
int numltemsOrdered = 1;
try {
numltemsOrdered =
Integer.parseInt(request.getParameter("numltems"));
941
} catch(NumberFormatException nfe) {}
%>
<jsp:setProperty
name="entry"
property="numItems"
value="<%= numltemsOrdered %>" />
, JSP .
,
, . v a l u e
p a r a m , .
;
.
, (
n u l l ) . , ,
n u m l t e r n s , :
<j sp:setProperty
name="entry"
property="numItems"
param="numlterns" />
20.20 JSP-,
.
2 0 . 2 0 . S a l e E n t r y 2 . j s p
<jsp:useBean id="entry" class="cwp.SaleEntry"
<jsp:setProperty
name="entry"
property="itemID"
param="itemID" />
<jsp:setProperty
name="entry"
property="numItems"
param="numlterns" />
<j sp:setProperty
name="entry"
property="discountCode"
param="discountCode" />
/>
b e a n ,
,
( b y t e , i n t , d o u b l e ..) ( ( B y t e , I n t e
g e r , D o u b l e ..). , JSWDK 1.0.1 Java Web Sei'ver 2.0
JSP-,
d o u b l e .
Tomcat .
942
2 0 . JavaServer Pages
.
, JSP ,
,
. "*" p r o p e r t y .
, j s p : s e t P r o p e r t y 20.20
, . oJSP 20.21.
<jsp:setProperty name="entry" property="*" />
,
. -, ,
, ;
n u l l . -, JSWDK Java Web Server
d o u b l e . -,
.
Web-
. , , ,
.
2 0 . 2 1 . SaleEntiryS . j s p
< j s p : u s e B e a n i d = " e n t r y " c l a s s = " c w p , S a l e E n t r y " />
< j s p : s e t P r o p e r t y name="entry" p r o p e r t y = " * " / >
bean
, ,
j s p : u s e B e a n , _ j s p S e r v i c e .
_ j s p S e r v i c e s e r v i c e , JSP. , s c o p e j s p i u s e B e a n ,
-.
s c o p e .
page
. , ,
, b e a n
P a g e C o n t e x t , )^ .
P a g e C o n t e x t , ,
g e t A t t r i b u t e p a g e C o n t e x t .
application
, ,
, b e a n S e r v l e t C o n t e x t .
a p p l i c a t i o n
943
g e t S e r v l e t C o n t e x t . S e r v l e t C o n t e x t
Web- (, Web-
, , ). ,
S e r v l e t C o n t e x t , g e t A t t r i b u t e . .
-, ,
JSP .
;
.
-, b e a n ,
JSP-.
, , S e r v l e t C o n t e x t ,
JSP-.
20.8.
session
, ,
, b e a n H t t p S e s s i o n ,
)' .
getAttribute.
request
r e q u e s t , ,
, b e a n S e r v l e t R e q u e s t , g e t A t t r i b u t e .
(Model 2). 20.8.
bean
bean
.
-, j s p : u s e B e a n bean
, i d s c o p e .
, , i d .
b e a n ,
. ,
C l a s s C a s t E x c e p t i o n .
-,
. . . >/</jsp: us>
j s p : u s e B e a n , ,
,
944
, bean.
bean .
, bean,
. ,
, ,
.
, . ,
20.22 bean,
. ,
, .
:
<jsp:useBean
id="counter"
lass="cwp.AccessCountBean"
scope="application">
< j s p : s e t P r o p e r t y narne="counter"
property="firstPage"
v a l u e = " C u r r e n t Page Name" />
</jsp:useBean>
C o l l e c t i v e l y , t h e pages u s i n g t h e c o u n t e r have been a c c e s s e d
< j s p : g e t P r o p e r t y n a m e = " c o u n t e r " p r o p e r t y = " a c c e s s C o u n t " />
times.
20.23 JSP-, .
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 . com/. Fia . 20.13.
2 0 . 2 2 . AccessCountBean . Java
p a c k a g e cwp;
/** bean,
* scope jspruseBean .
*/
public class AccessCountBean {
private String firstPage;
private int accessCount = 1;
public String getFirstPage() {
return(firstPage);
public void setFirstPage(String firstPage)
this.firstPage = firstPage;
public int getAccessCount() {
return(accessCount++);
945
20.23.SharedCountsl.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Shared Access Counts: Page 1</TITLE>
<LINK REL=STYLESHEET
HREF-"JSP-Styles.ess"
TYPE="text/css">
</HEAD>
<BODY>
<TABLE B0RDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">
Shared Access Counts: Page 1</TABLE>
<P>
<jsp:useBean id="counter"
class="cwp.AccessCountBean"
scope="application">
<jsp:setProperty name="counter"
property="firstPage"
value="SharedCountsl.jsp" />
</jsp:useBean>
Of SharedCountsl.jsp (this page),
<A HREF="SharedCounts2.j sp">SharedCounts2.j sp</A>, and
<A HREF="SharedCounts3.jsp">SharedCounts3.jsp</A>,
<jsp:getProperty name="counter" property="firstPage" />
was the first page accessed.
<P>
Collectively, the three pages have been accessed
<jsp:getProperty name="counter" property="accessCount" />
times.
</BODY>
</HTML>
]^H>"i
voc'jKnsm -Jone
. 20.13.
SharedCounts3 . j sp.
SharedCounts2 . j sp.
SharedCountsl.jsp,
SharedCounts2.j sp
SharedCountsS.j sp,
,
12
946
20.7. JSP-
JSP 1.1 JSP, . ,
, ,
, .
JSP-.
.
,
bean,
. bean
. -, bean,
, JSP. -,
, , bean. -,
, bean. -, bean,
, JSP-
.
. , , B J S P 1.1,
bean KaKjSP 1.0, n J S P 1.1.
,
JSP-
: ,
, ,
XML- , JSP-,
. ,
.
Java-,
,
. j a v a x . s e r v l e t .
j s p . t a g e x t . T a g . ,
T a g S u p p o r t B o d y T a g S u p p o r t . 20.24
, JSP- "Custom t a g
e x a m p l e (cwp. t a g s . E x a m p l e T a g ) ".
, :
. , E x a m p l e T a g
cv/p. t a g s . Tomcat 3
i n s t a l l _ _ d i r / w e b a p p s / R O O T / W E B - I N F / c l a s s e s / c w p / t a g s / E x a m p l e T a g . c l a s s .
20.7. JSP-
947
JSP-,
("Custom tag example...").
;
.
taglib JSP-.
V
public class ExampleTag extends TagSupport {
public int doStartTag0 {
try {
JspWriter out = pageContext.getOut();
out.print("Custom tag example " +
"(cwp.tags.ExampleTag)");
} catch(lOException ioe) {
System.out.println("Error in ExampleTag: " + ioe);
}
return(SKIP_BODY);
}
}
,
XML- .
( XML). 20.25.
,
, . ,
, ,
.
http://www.corewebprogramming.com/, ,
Tomcat 3 ( i n s t a l l _ d i r / w e b a p p s / e x a m p l e s / W E B INF/jsp).
.
, t a g (
, ) .
cwp. t a g s ,
cwp. t a g s . ExampleTag. , t a g URL
, . ,
bean . Tomcat 3
install_dir/webapps/ROOT/WEB-
948
I N F / c l a s s e s , E x a m p l e T a g i n s t a l l _ d i r /
w e b a p p s / R O O T / W E B - I N F / c l a s s e s / c w p / t a g s .
, Tomcat 3.1
.
2 0 . 2 5 . c w p ~ t a g l i b . t l d
<?xml version="1.0" encoding="ISO-8859-l" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://Java.sun.com/j2ee/dtds/web-jsptaglibrary_l_l.dtd">
<taglib>
<tlibversion>l.0</tlibversion>
<j spversion>l.1</jspversion>
<shortname>cwp</shortname>
<info>
A tag library from Core Web Programming Java 2 Edition,
http://www.corewebprogramming.com/.
</info>
<tag>
<name>example</name>
<tagclass>cwp.tags.ExampleTag</tagclass>
<info>Simplest example: inserts one line of output</info>
</tag>
</taglib>
JSP-
, JSP-,
. 20.26.
t a g l i b ,
:
<%@ t a g l i b u r i = " . . . " p r e f i x = " . . . " %>
u r i ,
URL (
20.25).
p r e f i x , , ,
,
. ,
t a g l , p r e f i x t e s t ,
t e s t : t a g l .
:
<test:tagl>JSP-KOfl</test:tagl>
20.7. JSP-
949
<test:tagl />
, 20.25, c w p - t a g l i b . t l d
, JSP-,
20.26. t a g l i b , JSP-,
.
<%0 t a g l i b u r i = " c w p - t a g l i b . t l d "
p r e f i x cwp, JSP-
e x a m p l e cwp: e x a m p l e .
. 20.14.
2 0 . 2 6 . SimpleExample. j s p
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0 T r a n s i t i o n a l / / E N " >
<HTML>
<HEAD>
<%@ t a g l i b u r i = " c w p - t a g l i b . t l d " p r e f i x = " c w p " %>
<TITLE><cwp:example /></TITLE>
<LINK REL=STYLESHEET
HREF="JSP-Styles.ess"
TYPE="text/css">
</HEAD>
<BODY>
<Hl><cwp:example /></Hl>
<cwp:example />
</BODY>
</HTML>
. lie
^SM
i,iriH!imiiff,mifffi-io|>^i
loois ^
"3
~1
J
] Done
'
f^ Locsi ^*
. 20.14.
SimpleExample.j sp
, .
<prefix:tagname />.
950
:
, ,
TagSupport. TagSupport
j avax. s e r v l e t . j s p . t a g e x t , Tag
, .
, j a v a x . s e r v l e t .
j sp j ava . i o . i m p o r t :
import j a v a x . s e r v l e t . j s p . * ;
import j a v a x . s e r v l e t . j s p . t a g e x t . * ;
import j a v a . i o . * ;
,
http://www.corewebprograinming.com/,
" " .
)
d o S t a r t T a g . ,
.
J s p W r i t e r ( P r i n t W r i t e r , JSP out).
getOut PageContext,
pageContext. getOut PageContext
, .
g e t R e q u e s t , g e t R e s p o n s e , g e t S e r v l e t C o n t e x t g e t S e s s i o n .
p r i n t J s p W r i t e r
lOException, t r y / c a t c h .
, ,
d o S t a r t T a g J s p E x c e p t i o n ,
.
, d o S t a r t T a g
SKIPBODY. , ,
, .
SKIP_BODY ,
<pref i x : tagname />
.
20.27 ,
, 50 .
Primes, .
20.27.SimplePrimeTag.Java
package c w p . t a g s ;
import
import
import
import
import
javax.servlet.jsp.*;
javax.servlet.jsp.tagext.
java.io.*;
java.math.*;
cwp.*;
2 0 . 7 . JSP-
951
:
XML, DOCTYPE t a g l i b .
h t t p : //www. corewebprogramming. com/.
t a g ,
t a g l i b . <tag> < / t a g >
.
name ,
, t a g l i b .
s i m p l e Prime, ..
:
<name>simplePrime</name>
tagclass .
:
<tagclass>cwp.tags.SimplePrimeTag</tagclass>
info .
:
< i n f o > O u t p u t s random 5 0 - d i g i t
prime.</info>
bodycontent ,
, , ,
empty. ,
, b o d y c o n t e n t JSP.
,
, t a g d e p e n d e n t .
SimplePrimeTag b o d y c o n t e n t
empty.
952
2 0 . JavaServer P a g e s
<bodycontent>empty</bodycontent>
, Tomcat 3.1 bodycontent,
. Tomcat 3.2, JRun
b o d y c o n t e n t .
!!
Tomcat 3.1,
bodycontent.
20.28 .
20.28. c w p ~ t a g l i b . t l d ()
<tag>
<name>simplePrime</naine>
<tagclass>cwp.tags.SimplePrimeTag</tagclass>
<info>Outputs a random 50-digit prime.</info>
</tag>
: JSP-
JSP-, ,
t a g l i b , u r i ,
, p r e f i x ,
. JSP-,
20.29, t a g l i b :
<%@ t a g l i b u r i = " c w p - t a g l i b . t l d " prefix="cwp" %>
, 20.28,
cwp. simple Prime,
:
<cwp:simplePrime />
. 20.15.
20.29. SimplePrimeExample. j sp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Some 50-Digit Primes</TITLE>
<LINK REL=STYLESHEET
HREF="JSP-Styles.css"
TYPE="text/css">
</HEAD>
<BODY>
<Hl>Some 50-Digit Primes</Hl>
<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>
<UL>
20.7.
<LI><cwp
<LI><cwp
<LI><cwp
<LI><cwp
</UL>
</BODY>
</HTML>
:simplePrime
:simplePrime
:simplePrime
: simplePrime
JSP-
953
/>
/>
/>
/>
t-r4Mi,rH'Mi-i|IJil,l4M.I-l[if'!l
File cM View o
ommufcat IHet
SI
-^
. 20.15.
;^4^""
SimplePrimeExample.j sp
<prefix:name a t t r i b u t e l = " v a l u e l " a t t r i b u t e 2 = " v a l u e 2 " . . .
/>
. .
:
.
a t t r i b u t e 1 s e t A t t r i b u t e l ,
TagSupport ( ,
Tag). S t r i n g .
, a t t r i b u t e 1
:
p u b l i c void s e t A t t r i b u t e l ( S t r i n g v a l u e l ) {
doSomethingWith(valuel);
, a t t r i b u t e N a m e ( "")
s e t A t t r i b u t e N a m e ( "").
d o S t a r t T a g .
, message.
private String message = "Default Message";
public void setMessage(String message) {
this.message = message;
954
2 0 . JavaServer Pages
,
g e t A t t r i b u t e N a m e . s e t A t t r i b u t e N a m e
.
20.30 SimplePrimeTag,
l e n g t h . ,
s e t L e n g t h , S t r i n g
( i n t ) 1.
d o S t a r t T a g .
20.30. PrimeTag. Java
package c w p . t a g s ;
import javax.servlet.jsp.*;
import javax.servletj sp.tagext.*;
import java.io.*;
/**
*
*
*
*
*
, N
( N = 50).
SimplePrimeTag,
length,
.
doStartTag
1 .
t a g .
a t t r i b u t e . < a t t r i b u t e > < / a t t r i b u t e >
.
1. name , (
).
<name>length</name>
2. required , ,
(true) (false). ,
length , r e q u i r e d :
<required>false</required>
2 0 . 7 . JSP-
955
, s e t A t t r i b u t e N a m e
, }^
.
3. rtexprvalue , ,
JSP- <%= e x p r e s s i o n %> ( t r u e )
( f a l s e ) .
f a l s e , ,
, .
20.31 t a g
. a t t r i b u t e , l e n g t h , t a g
name ( p r i m e ) , t a g c l a s s
( cwp . t a g s . P r i m e T a g ) i n f o ( ).
2 0 . 3 1 . c w p - t a g l i b . t l d ()
<tag>
<name>prime</name>
<tagclass>cwp.tags.PrimeTag</tagclass>
<info>Outputs a random N-digit prime.</info>
<attribute>
<name>length</name>
<required>false</required>
</attribute>
</tag>
: JSP-
20.32 JSP-, t a g l i b .
cwp.
' p r i m e l e n g t h ,
:
<cwp:prime l e n g t h = " x x x "
/>
XML,
.
l e n g t h , p r i m e :
<cwp:prime
/>
, , .
, 20.32,
. 20.16.
956
20.32.PrimeExample.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Some N-Digit Primes</TITLE>
<LINK REL=STYLESHEET
HREF="JSP-Styles.ess"
TYPE="text/css">
</HEAD>
<BODY>
<Hl>Some N-Digit Primes</Hl>
<%@ taglib uri="cwp~taglib.tld" prefix="cwp" %>
<UL>
<LI>20-digit: <cwp:prime length="20" />
<LI>40-digit: <cwp:prime length="40" />
<LI>80-digit: <cwp:prime length=:"80" />
<LI>Default (50-digit): <cwp:prime />
</UL>
</BODY>
</HTML>
|[..f'l7M'i^IWIfJII.:!J!lfJI.U.!|l!.'IJI.Uiii|.![.]pi
Pe
Edit
.^'--
View
Favorites
'Jj2-:ii
Toofs
^11^
Hel?
-_
~3.
ij
J
iS] Done
-^ 1 inhseieJ
. 20.16. PrimeExample . j sp
,
. :
<prefix:tagname
/>
, ,
. :
< p r e f i x : t a g n a m e > e o ' < / p r e f i x : tagname>
2 0 . 7 . JSP-
957
:
d o S t a r t T a g ,
, SKIP_BODY. ,
,
d o S t a r t T a g EVAL_BODY_INCLUDE.
, JSP-,
, . JSP- ,
.
, , ,
,
, .
doEndTag.
.
d o E n d T a g EVAL_PAGE. ,
, , SKIP_PAGE.
20.33 ,
.
HTML- 1 - 6 .
, ,
, (LEFT, CENTER, RIGHT).
HTML- 1 - 6
. ,
SPAN, . d o S t a r t T a g
<TABLE> <SPAN>
EVAL_BODY_INCLUDE, ,
. d o E n d T a g </SPAN>
</TABLE> EVAL_PAGE, ,
. (, b g C o l o r
f o n t S i z e ) s e t A t t r i b u t e N a m e .
2 0 . 3 3 . HeadingTag. j a v a
package
cwp.tags;
import javax.servlet.jsp.*;
import j avax.servlet.j sp.tagext.*;
import java.io.*;
/**
*
*
^
*
*
HTML-,
, .
.
,
.
.
958
private
private
private
private
private
String
String
String
String
String
align="CENTER";
fontSize="36";
fontList="Arial, Helvetica, sans-serif";
border="0";
width=null;
2 0 . 7 . JSP-
959
, ,
tag b o d y c o n t e n t , JSP.
<bodycontent>JSP</bodycontent>
, , Tomcat 3.1 b o d y c o n t e n t
, ,
. , t a g c l a s s , i n f o a t t r i b u t e
, .
20.34.
20.34. c w p - t a g l i b . t l d ()
<tag>
<name>heading</name>
<tagclass>cwp.tags.HeadingTag</tagclass>
<info>Outputs a 1-cell table used as a heading.</info>
<attribute>
<name>bgColor</name>
<required>true</required>
<!-- bgColor - -->
</attribute>
<attribute>
<name>color</name>
<required>false</required>
</attribute>
<attribute>
<name>align</name>
<required>false</required>
</attribute>
<attribute>
<name>fontSize</name>
<required>false</required>
</attribute>
<attribute>
<name>fontList</name>
<required>false</required>
</attribute>
960
<attribute>
<name>border</name>
<required>false</required>
<./attribute>
<attribute>
<name>width</name>
<required>false</required>
</attribute>
</tag>
: JSP-
20.35 ,
h e a d i n g . b g C o l o r ,
.
. 20.17.
2 0 . 3 5 . HeadingExample. j s p
<!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>Some T a g - G e n e r a t e d Headings</TITLE>
</HEAD>
<BODY>
<%@ t a g l i b u r i = " c w p - t a g l i b . t l d " p r e f i x = " c w p " %>
< c w p : h e a d i n g bgColor="#COCOCO">
Default Heading
</cwp:heading>
<P>
<cwp:heading bgColor="BLACK" color="WHITE">
White on Black Heading
</cwp:heading>
<P>
<cwp:heading bgColor="#EF8429" fontSize="60" border="5">
Large Bordered Heading
</cwp:heading>
<P>
<cwp:heading bgColor="CYAN" width="100%">
Heading with Full-Width Background
</cwp:heading>
<P>
<cwp:heading bgColor="CyAN" fontSize="60"
fontList="Brush Script MT, Times, serif">
Heading with Non-Standard Font
</cwp:heading>
</BODY>
</HTML>
20.7. JSP-
961
AH
<^f "Sookmoks
"3
Default Heading
White on Blacic Heading
^ =='
Ooctmf<; Done
jii
,
.
, .
JSP ,
,
.
, ,
, d o S t a r t T a g
EVAL_BODY_INCLUDE SKIP_BODY. , s e r v i c e , _ j s p S e r v i c e , d o G e t d o P o s t , d o S t a r t T a g
H t t p S e r v l e t R e q u e s t H t t p S e r v l e t R e s p o n s e , ,
. , ,
g e t R e q u e s t , p a g e C o n t e x t ,
T a g S u p p o r t , H t t p S e r v l e t
R e q u e s t . , g e t R e q u e s t S e r v l e t R e q u e s t , , , H t t p S e r v l e t
R e q u e s t , .
g e t P a r a m e t e r , .
962
20.36 ,
, debug.
, JSP
.
20.36.DebugTag.Java
package cwp.tags;
import
import
import
import
javax.servlet.jsp.*;
javax.servlet.j sp.tagext.*;
java.io.*;
javax.servlet.*;
/** , ,
* debug.
public class DebugTag extends TagSupport {
public int doStartTagO {
ServletRequest request = pageContext.getRequest();
String debugFlag = request.getParameter("debug");
if ((debugFlag != null) &&
(!debugFlag.equalsIgnoreCase("false") ) ) {
return (EVAL_BODY_INCLUDE) ;
} else {
return(SKIP BODY);
}
}
}
:
,
b o d y c o n t e n t JSP ( ).
t a g , .
20.37 DebugTag.
2 0 . 3 7 . c w p - t a g l i b . t l d ()
<tag>
<name>debug</naine>
<tagclass>cwp.tags.DebugTag</tagclass>
<info>Includes body only if debug param is set.</info>
</tag>
20.7. JSP-
963
: JSP-
20.38 ,
< c w p : d e b u g > < / c w p : d e b u g > . . 20.18
20.19 ,
d e b u g .
2 0 . 3 8 . D e b u g E x a m p l e . j s p
<!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>Using t h e Debug Tag</TITLE>
<LINK REL=STYLESHEET
HREF="JSP-Styles.ess"
TYPE="text/ess">
</HEAD>
<BODY>
<Hl>Using t h e Debug Tag</Hl>
<%@ t a g l i b u r i = " c w p - t a g l i b . t l d " p r e f i x = " c w p " %>
Top of regular page. Blah, blah, blah. Yadda, yadda, yadda.
<P>
<cwp:debug>
<B>Debug:</B>
<UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Requesting hostname: <%= request.getRemoteHost() %>
<LI>Session ID: <%= session.getid() %>
</UL>
</cwp:debug>
<P>
Bottom of regular page. Blah, blah, blah. Yadda, yadda, yadda.
</BODY>
</HTML>
^< Using the Debug Tog - Netscape
ile dit View ^ o Communicator
ti^lp
^'Booknriarks
Lgcattoft:|http.//localhQst/cwp/TeigExamples/DebugExamplejsp
Using t h e Debug T a g
Top of regular page. Blah, blah, blah. Yadda, yadda, yadda.
Bottom of regular page. Blah, blah, blah. Yadda, yadda, yadda.
y;.^^:
. 20.18.
Document' Done
&,. ..:^..
cwp: debug
964
f u s i n g theOebuq Tag-Netscape
iie dit ^iew Qo Communicator
Oelp
^ ^ J j^. i^ ~.:J^ rf 2l j l
SI
Using t h e Debug T a g
Top of regular page. Blah, blah, blah. Yadda, yadda, yadda.
Debug:
Cun-ent time: Mon Apr 16 11:03:21 EDT 2001
Requesting hostname: localhost
Session : Tol010mC6608409833952431At
Bottom of regular page. Blah, blah, blah. Yadda, yadda, yadda.
'^'r^
Document: Done
. 20.19. debug
cwp: debug
c w p : p r i m e , c w p : h e a d i n g
, cwp: d e b u g
.
, ;
, .
, .
)^
T a g S u p p o r t . Tag
, , p a g e C o n t e x t
P a g e C o n t e x t . T a g S u p p o r t
, .
T a g S u p p o r t B o d y T a g S u p p o r t .
B o d y T a g S u p p o r t T a g S u p p o r t ,
d o S t a r t T a g d o E n d T a g , . ,
B o d y T a g S u p p o r t .
1. doAfterBody ,
.
SKIP_BODY, ,
.
2. getBodyContent , B o d y C o n t e n t ,
.
20.7. JSP-
965
BodyContent .
1. getEnclosingWriter J s p W r i t e r ,
d o S t a r t T a g doEndTag.
2. getReader , Reader,
.
3. getString S t r i n g ,
.
S e r v l e t U t i l i t i e s (. 19.11) f i l
t e r ,
<, >, " & "<", ">", ""/" "&".
, , ,
, HTML-. 20.39
, ,
JSP-.
20.39. FilterTag. Java
package c w p . t a g s ;
import
import
import
import
/**
*
*
*
javax.servlet.jsp.*;
j avax.servlet.j sp.tagext.*;
java.io.*;
cwp.*;
966
:
, ,
b o d y c o n t e n t , , ,
, JSP. Tomcat 3.1
b o d y c o n t e n t ,
. ,
. 20.40 .
2 0 . 4 0 . c w p - t a g l i b . t l d ()
<tag>
<name>filter</name>
<tagclass>cwp.tags.FilterTag</tagclass>
<info>Replaces HTML-specific characters in body.</info>
</tag>
: JSP-
20.41 , ,
HTML- .
HTML, ,
"<" ">"
" & l t ; " " & g t ; " . ,
. ,
20.7. JSP-
<TR CLASS="COLORED"><TH>Example<TH>Result
<TR>
<TD><PRE><cwp:filter>
<EM>Some emphasized text.</EM><BR>
<STRONG>Some strongly emphasized text.</STRONG><BR>
<CODE>Some code.</CODE><BR>
<SAMP>Some sample text.</SAMP><BR>
<KBD>Some keyboard text.</KBD><BR>
<DFN>A term being defined.</DFN><BR>
<VAR>A variable.</VAR><BR>
<CITE>A citation or reference.</CITE>
</cwp:filter></PRE>
<TD>
<EM>Some emphasized text.</EM><BR>
<STRONG>Some strongly emphasized text.</STRONG><BR>
<CODE>Some code.</CODE><BR>
<SAMP>Some sample text.</SAMP><BR>
<KBD>Some keyboard text.</KBD><BR>
<DFN>A term being defined.</DFN><BR>
<VAR>A variable.</VAR><BR>
<C1TE>A citation or reference.</CITE>
</TABLE>
</BODY>
</HTML>
hl!lli'.llffHHiTffWnH|i|l41i'Hf#Hl
4^:.^..^...^..
^^^
^it>owtt**l>or>
-^ ^p m, >j> ' i i
. 20.20. cwp: f i l t e r
HTML-
967
968
, ,
,
.
JSP- , ,
.
:
,
, ,
BodyTagSupport. , , d o S t a r t T a g ,
doEndTag , , doAf terBody.
, doAf terBody.
EVAL_BODY_TAG, ,
doAf terBody. ,
doAf terBody SKIP_BODY.
20.42 , r e p s
.
JSP- ( ,
),
.
20.42. RepeatTag. java
package c w p . t a g s ;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
/** ,
* .
V
public class RepeatTag extends BodyTagSupport {
private int reps;
public void setReps(String repeats) {
try {
reps = Integer.parseint(repeats);
} catch(NumberFormatException nfe) {
reps = 1;
}
}
public int doAfterBody() {
if (reps >= 1) {
BodyContent body = getBodyContent();
try {
2 0 . 7 . JSP-
969
:
20.43 ,
cwp: r e p e a t . ,
, r t e x p r v a l u e , t r u e .
2 0 . 4 3 . c w p - t a g l i b . t l d ()
<tag>
<name>repeat</name>
<tagclass>cwp.tags.RepeatTag</tagclass>
<info>Repeats body the specified number of times.</info>
<attribute>
<name>reps</name>
<required>true</required>
<!-- rtexprvalue ,
JSP-. -->
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
: JSP-
20.44 JSP-,
. r e p e a t s ,
.
. 20.21.
2 0 . 4 4 . R e p e a t E x a m p l e . j s p
<]DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
<TITLE>Some 4 0 - D i g i t Primes</TITLE>
<LINK REL=STYLESHEET
Transitional//EN">
970
2 0 . JavaServer Pages
HREF="JSP-Styles.ess"
TYPE="text/css">
</HEAD>
<BODY>
<Hl>Some 40-Digit Primes</Hl>
Each entry in the following list is the first prime number
higher than a randomly selected 40-digit number.
<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>
<0L>
<!-- Repeats N times. A null reps value means repeat once. >
<cwp:repeat reps='<%= request.getParameter("repeats") %>'>
<LI><cwp:prime length="40" />
</cwp:repeat>
</0L>
</BODY>
</HTML>
miiffimniiii
"3
1.
2.
3.
4.
5.
6.
7
779042788484692290696496905990659223259
5654911225096957336845971755232574136573
4440250773563950124888671855331783776667
4557511042237325396986257256572883741037
584476361241995395252711786232246484577
2878822708441674101514196529821727599631
9665985263198820747432458513545913598401
^Ooiiei""
iltic4ir*tne
. 20.21.
RepeatExample. j sp.
r e p e a t s ,
, 20
20.44 cwp: p r i m e cwp: r e p e a t ,
. ,
JSP-, ,
, .
,
. , HTML TD
TR, , , TABLE.
TABLE TR, TR, ,
TD . , ,
, . ,
t a g l i b , t a g , a t t r i b u t e r e q u i r e d ,
.
20.7. JSP-
971
,
, ,
.
:
T a g S u p p o r t B o d y T a g S u p p o r t .
, (
B o d y T a g S u p p o r t ) , ( ) ,
, (
TagSupport).
. ,
f i n d A n c e s t o r W i t h C l a s s .
(.. t h i s ) C l a s s .
, J s p T a g E x c e p t i o n . -,
, .
.
, ,
:
<cwp:if>
<cwp:condition><%= someExpression %></cwp:condition>
<cwp:then>JSP to include if condition is true</cwp:then>
<cwp:else>JSP to include if condition is false</cwp:else>
</cwp:if>
, c w p : i f
I f Tag. , ,
t r u e f a l s e ( s e t C o n d i t i o n g e t C o n d i t i o n ) ,
, ( s e t H a s C o n d i t i o n
g e t H a s C o n d i t i o n ) . , cwp: i f ,
cwp: c o n d i t i o n . I f Tag
20.45.
cwp: c o n d i t i o n .
I f C o n d i t i o n T a g d o S t a r t T a g ,
, I f Tag. ,
EVAL_BODY_TAG,
. d o A f t e r B o d y
( g e t B o d y C o n t e n t ) , S t r i n g ( g e t S t r i n g )
t r u e . )'
<%= e x p r e s s i o n %> t r u e ,
t h e n . t r u e ,
f a l s e .
, ,
s e t C o n d i t i o n I f T a g . I f C o n d i t i o n T a g
20.46.
972
cwp: then.
doStartTag , If Tag,
(, ,
I f Condi t i o n T a g I f Tag). doAfterBody ,
If Tag, , ,
. 20.47.
, , cwp:else.
then,
, doAfterBody ,
If Tag f a l s e . 20.48.
2 0 . 4 5 . I f T a g . j a v a
package c w p . t a g s ;
import j a v a x . s e r v l e t . j s p . * ;
import j a v a x . s e r v l e t . j s p . t a g e x t . * ;
import j a v a . i o . * ;
import j a v a x . s e r v l e t . * ;
/** , i f / t h e n / e l s e .
p u b l i c c l a s s IfTag extends TagSupport {
p r i v a t e boolean conditionsp r i v a t e boolean hasCondition = falserp u b l i c void s e t C o n d i t i o n ( b o o l e a n c o n d i t i o n ) {
this.condition = condition;
hasCondition = t r u e ;
p u b l i c boolean g e t C o n d i t i o n ( ) {
return(condition);
p u b l i c void setHasCondition(boolean flag) {
this.hasCondition = flag;
}
f-k-k ? */
p u b l i c boolean hasCondition() {
return(hasCondition);
public int doStartTag0 {
return(EVAL_BODY_INCLUDE);
}
}
20.7. JSP-
javax.servlet.jsp.*;
javax.servlet.j sp.tagext.*;
java.io.*;
javax.servlet.*;
/** , . */
public class IfConditionTag extends BodyTagSupport {
public int doStartTagO throws JspTagException {
IfTag parent =
(IfTag)findAncestorWithClass(this, IfTag.class);
if (parent == null) {
throw new JspTagException("condition not inside if")/
}
return (EVAL__BODY_TAG) ;
}
public int doAfterBody() {
IfTag parent =
(IfTag)findAncestorWithClass(this, IfTag.class);
String bodyString = getBodyContent().getString();
if (bodyString.trim 0 .equals("true")) {
parent.setCondition(true);
} else {
parent.setCondition(false);
}
return (SKIP__BODY) ;
}
}
javax.servlet.jsp.*;
j avax.servlet.j sp.tagext.*;
java.io.*;
javax.servlet.*;
/** then . */
public class IfThenTag extends BodyTagSupport {
public int doStartTagO throws JspTagException {
IfTag parent =
(IfTag)findAncestorWithClass(this, IfTag.class);
if (parent == null) {
throw new JspTagException("then not inside if");
} else if (!parent.hasCondition0) {
String warning =
"condition tag must come before then tag";
973
974
2 0 . 4 8 . I f E l s e T a g . j a v a
package c w p . t a g s ;
import
import
import
import
javax.servlet.jsp.*;
javax.servlet.j sp.tagext.*;
java.io.*;
javax.servlet.*;
/** else . */
public class IfElseTag extends BodyTagSupport {
public int doStartTag0 throws JspTagException {
IfTag parent =
(IfTag)findAncestorWithClass(this, IfTag.class);
if (parent == null) {
throw new JspTagException("else not inside if");
} else if (!parent.hasCondition0 ) {
String warning =
"condition tag must come before else tag";
throw new JspTagException(warning);
}
return(EVAL_BODY_TAG);
}
public int doAfterBody() {
IfTag parent =
(IfTag)findAncestorWithClass(this, IfTag.class);
if (?parent.getCondition0) {
try {
BodyContent body = getBodyContent();
JspWriter out = body.getEnclosingWriter0;
20.7. JSP-
975
out.print(body.getString());
} catch(lOException ioe) {
System.out.println("Error in IfElseTag: " + ioe);
}
}
return(SKIP_BODY);
}
}
:
,
( 20.49). ,
, .
JSP , T a g E x t r a l n f o .
g e t V a r i a b l e I n f ,
.
T a g E x t r a l n f o , .
t e i c l a s s , , t a g c l a s s .
T a g E x t r a l n f o .
20.49. c w p - t a g l i b . t l d ()
<tag>
<name>if</name>
<tagclass>cwp.tags.IfTag</tagclass>
<info>if/condition/then/else tag.</info>
</tag>
<tag>
<name>condition</name>
<tagclass>cwp.tags.IfConditionTag</tagclass>
<info>condition part of if/condition/then/else tag.</info>
</tag>
<tag>
<name>then</name>
<tagclass>cwp.tags.IfThenTag</tagclass>
<info>then part of if/condition/then/else tag.</info>
</tag>
<tag>
<name>else</name>
<tagclass>cwp.tags.IfElseTag</tagclass>
<info>else part of if/condition/then/else tag.</info>
</tag>
976
: JSP-
20.50 , cwp: i f
.
t r u e .
HTTP-.
. )^1 . 20.22.
2 0 . 5 0 . I f E x a m p l e . j s p
<!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>If Tag Example</TITLE>
<LINK REL=STYLESHEET
HREF="JSP-Styles.ess"
TYPE="text/css">
</HEAD>
<BODY>
<Hl>If Tag E x a m p l e < / H l >
<%(? t a g l i b u r i = " c w p - t a g l i b . t l d " p r e f i x = " c w p " %>
<cwp:if>
<Gwp:condition>true</cwp:condition>
<cwp:then>Condition i s true</cwp:then>
<cwp:else>Condition is false</cwp:else>
</cwp:if>
<P>
<cwp:if>
<cwp:condition><%= r e q u e s t . i s S e c u r e ( ) %></cwp:condition>
< c w p : t h e n > R e q u e s t i s u s i n g SSL ( h t t p s ) < / c w p : t h e n >
<cwp:else>Request i s not using SSL</cwp:else>
</cwp:if>
<P>
Some c o i n t o s s e s : < B R >
<cwp:repeat reps="10">
<cwp:if>
<cwp:condition><%= Math.random() < 0.5 %></cwp:condition>
<cwp:then><B>Heads</B><BR></cwp:then>
<cwp:else><B>Tails</B><BR></cwp:else>
</cwp:if>
</cwp:repeat>
</BODY>
</HTML>
2 0 . 8 . JSP
"SSBI
So CommuMcatof
-^.1^" Bookrwwks
977
b^
J-
J^ Location |ht;p//locaihc:. , ^
_,_ _ ^
If Tag Example
j Condition is true
j Request is not using SSL
1 Some coin tosses:
Heads
Tails
Heads
Tails
Tails
Heads
Tails
Heads
Heads
Heads
ijtf^'-^-
''TT^^iSScuBwH Done
. 20.22.
...
^.,:
.-^r.::i:4
IfExample.jsp
20.8. JSP
,
. ,
^- HTTP-, ,
cookie, ,
, ,
, GIF-,
. HTML- ,
. , .
JSP,
. JSP Web-
HTML-, ,
JSP-. JSP-,
Java-,
, JSP.
.
bean
JSP-.
)' : " JSP
, ?" JSP
, .
)'
. ? JavaBeans
-- , ,
.
JavaSei-ver Pages.
,
978
2 0 . JavaServer P a g e s
bean, a JSP.
" --" (model
view controller architecture), model 2. , ,
h t t p : / / J a k a r t a , apache . o r g / s t r u t s / .
RequestDispatcher. RequestDispatcher
g e t R e q u e s t D i s p a t c h e r S e r v l e t C o n t e x t , URL
. , RequestDispatcher,
h t t p : / / y o u r h o s t / p r e s e n t a t i o n s / p r e s e n t a t i o n l . j s p ,
:
String url = "/presentations/presentationl.jsp";
RequestDispatcher dispatcher =
getServletContext () .getRequestDispatcher(url);
R e q u e s t D i s p a t c h e r , forward
URL i n c l u d e
.
H t t p S e r v l e t R e q u e s t H t t p S e r v l e t R e s p o n s e .
S e r v l e t E x c e p t i o n lOException. ,
20.51 ,
JSP-.
o p e r a t i o n .
gotoPage, URL, H t t p S e r v l e t
Request H t t p S e r v l e t R e s p o n s e . g e t R e q u e s t
D i s p a t c h e r R e q u e s t D i s p a t c h e r forward
.
2 0 . 5 1 .
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, lOException {
String operation = request.getParameter("operation")
if (operation == null) {
operation = "unknown";
}
if (operation.equals("operationl")) {
gotoPage("/operations/presentationl.jsp",
request, response);
} else if (operation.equals("operation2")) {
gotoPage("/operations/presentation2.jsp",
request, response);
} else {
gotoPage("/operations/unknownRequestHandler.j sp",
request, response);
}
20.8. JSP
979
JSP .
HTML-. ,
Web-,
HTML-. GET HTML-
;
. HTML- g e t
R e q u e s t D i s p a t c h e r .
, HTML-
POST. , HTML- ,
. j s p . s o m e f i l e . h t m l ,
somef i l e . j s p , GET, POST.
, JSP-, H t t p
S e r v l e t R e q u e s t , H t t p S e s s i o n S e r v l e t C o n t e x t .
s c o p e j s p : u s e B e a n : r e q u e s t , s e s s i o n a p p l i
cation.
L .
:
S o m e C l a s s v a l u e = new
SomeClass{...);
request.setAttribute("key",
value);
JSP-,
:
<jsp:useBean id="k:ey" class="SomeClass"
scope="request" />
2.
. :
SomeClass value = new SomeClass(...);
HttpSession session = request.getSession(true);
session.setAttribute("key", value);
980
JSP-, ,
.
<jsp:useBean id="key" class="SomeClass"
scope="session" />
3. ,
.
:
SomeClass value = new SomeClass (...);
getServletContext().setAttribute("key", value);
JSP-oye)^ ,
.
<jsp:useBean id="key" class="SomeClass"
scope="application" />
URL
)^
, forward s e n d R e d i r e c t
H t t p S e r v l e t R e s p o n s e . -, s e n d R e d i r e c t
, forward R e q u e s t D i s p a t c h e r . -, s e n d R e d i r e c t
, forward. -,
s e n d R e d i r e c t ,
URL, forward URL .
, URL
, ,
,
. , ,
:
<LINK REL=STYLESHEET
HREF="my-styles.ess"
TYPE="text/css">
JSP, , , s t y l e s .CSS ,
URL , .
.
, )^ .
<LINK REL=STYLESHEET
HREF="/path/my-styles.css"
TYPE="text/css">
To <IMG SRC=. . . > < HREF=. . . >.
2 0 . 8 . JSP
981
RequestDispatcher
Servlet 2.2, ,
g e t R e q u e s t D i s p a t c h e r S e r v l e t C o n t e x t ,
R e q u e s t D i s p a t c h e r .
-,
JSP, ,
. g e t N a m e d D i s p a t c h e r S e r v l e t C o n t e x t .
-,
, ,
. ):' JSP
h t t p : / / h o s t / s e r v l e t / . . ., .
, ;
g e t R e q u e s t D i s p a t c h e r H t t p S e r v l e t R e q u e s t
S e r v l e t C o n t e x t . ,
h t t p : / / h o s t / t r a v e l / T o p L e v e l ,
getServletContext().getRequestDispatcher("/travel/cruises.jsp")
:
request.getRequestDispatcher("cruises.j sp");
,
Web- (. 20.23
20.52). ,
.
, , .
. ,
Flights, ,
(. 20.24).
. Edit Account
. Rent
Cars Find Hotels Web-.
, ,
( 20.52),
) , 20.53.
( 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 , ),
H t t p S e s s i o n , c w p . T r a v e l C u s t o m e r
c u s t o m e r , JSP-,
. ( 20.54 . 20.24)
)^ :
982
2 0 . JavaServer Pages
<jsp:useBean id="customer"
class="cwp.TravelCustomer"
scope="session" />
a j s p i g e t P r o p e r t y
.
T r a v e l C u s t o m e r (
20.55, www. c o r e w e b p r o g r a m m i n g . com). , , ,
HTML-. ,
, bean.
JSP JSP
Java-,
HTML-. ,
JSP, ,
.
1^|111>|1!'1:|||.|'1114.1|11^1|^|1|11^^^^^^
^;^
"
i |# \1 Ntp://loelMtArevei/ouick-t8erchh(ml
Pagyword: F^*^
O n y h r JBaltimore
D e s t i l i a t i o u ; |LOS Angeles
ggokBghl 1
flnciHoiei |
Ecl<tAccoat
. 20.23. ( 20.52)
20.8. JSP
20.52. /travel/quick-search.html ()
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Online Travel Quick Search</TITLE>
<LINK REL=STYLESHEET
HREF="travel-styles.ess"
TYPE="text/css">
</HEAD>
<BODY>
<BR>
<Hl>Online Travel Quick Search</Hl>
<FORM ACTION="/servlet/cwp.Travel" METHOD="POST">
<CENTER>
Email address: <INPUT TYPE="TEXT" NAME="emailAddress"><BR>
Password: <INPUT TYPE="PASSWORD" NAME="password" SIZE=10><BR>
<TABLE CELLSPACING=1>
<TR>
<TH> <IMG SRC="airplane.gif" WIDTH=100 HEIGHT=29
ALIGN="TOP" ALT="Book Flight">
<TR>
<TH><SMALL>
<INPUT TYPE="SUBMIT" NAME="flights" VALUE="Book Flight">
</SMALL>
</TABLE>
</CENTER>
</FORM>
</BODY>
</HTML>
983
984
(*
yw
Favodtej
Jocfe
"""
~""^
"
'
'
'
B e s t Available Flights
Fiiiduiafliglit.s'for Joe Hacka
'^^<:^-'^-;
; '
Oufgomg: Lea\ es> Baltimore at 9 00 AM on 1/1/2001, aniMiig in Los Angelefc; at 3 15 PM (1 stop - Java, Indonesia).
Retiuii: Lea\es Los Angeles at 900 AM on 1/8/2001, arming in Baltimore at 15 PM (1 stop -- Sim Microsystems),
. SfnletEa^ireirsijri^tadaa (1^505.95)
Outgoing: Leaves Baltimore at 9,30 AM on 1 1/2001, aiTi\ing in Los Angeles at 415 PM (1 stop -- Ne>^' Atlanta)
Retmii: Leaves Los Angeles at 9 30 AM on 1/8/2001, anivuig in Baltimore at 415 PM (1 stop -- New Atlanta)
^^^^ '^-^V^;ki.~7''^
>?
?||<:415^<$<?75.0) ~ ^'' ^ ^ ^^ ^^^ ^-^^^^^-V'\;:\^ ^'^
Outgoing: La\es Balhmore at 10.02;3'7 . ^ I on 1/1/2001, aiTi\ing ui Los Angeles at 2 22 19 PM (1 stop -- JHIT)
Return: Leaves Los Angeles at 10:0237 AM on l/8/'2001, aiTi\iiig Balhmore at 2 22 19 PM (1 stop -- )
Aiiiiue
Fre|uent Flyer Number
Ja\Ti Airways
321-9299-J
United
442-2212-U
Soiitliwest
1A345
Crf dir Cai'd: JavaSmartCard (XXXX-XXXX-XXXX-3120)
HoWfor24Hrs
Book It! 1
J
i ^ Don*
1 ^ \joceA irtranei
. 20.24. , ( 20.53),
B o o k F l i g h t s . j sp ( 20.54)
20.8. JSP
2 0 . 5 3 . T r a v e l . j a v a
package cwp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** .
* bean,
* .
public class Travel extends HttpServlet {
private TravelCustomer[] travelData;
public void initO {
travelData = TravelData.getTravelData();
}
/** ,
POST. */
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, lOException {
String emailAddress = request.getParameter("emailAddress");
String password = request.getParameter("password");
TravelCustomer customer =
TravelCustomer.findCustomer(emailAddress, travelData);
if ((customer == null) I I (password == null) I I
([password.equals(customer.getPassword()))) {
gotoPage("/travel/accounts.jsp", request, response);
}
// , ,
// , ,
customer.setStartDate(request.getParameter("startDate"));
customer.setEndDate(request.getParameter("endDate"));
customer.setOrigin(request.getParameter("origin"));
customer.setDestination(request.getParameter
("destination"));
HttpSession session = request.getSession(true);
session.setAttribute("customer", customer);
if (request.getParameter("flights") != null) {
gotoPage("/travel/BookFlights.jsp",
request, response);
} else if (request.getParameter("cars") != null) {
gotoPage("/travel/RentCars.j sp",
request, response);
} else if (request.getParameter("hotels") != null) {
gotoPage("/travel/FindHotels.jsp",
request, response);
} else if (request.getParameter("cars") != null) {
gotoPage("/travel/EditAccounts.jsp".
985
986
2 0 . JavaServer Pages
request, response);
} else {
gotoPage("/travel/IllegalRequest.j sp",
request, response);
}
}
private void gotoPage(String address,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, lOException {
RequestDispatCher dispatcher =
getServletContext().getRequestDispatcher(address)
dispatcher.forward(request, response);
}
20.54. BookFlights.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Best Available Flights</TITLE>
<LINK REL=STYLESHEET
HREF="/travel/travel-styles.ess"
TYPE="text/css">
</HEAD>
<BODY>
<Hl>Best Available Flights</Hl>
<CENTER>
<jsp:useBean id="customer"
class="cwp.TravelCustomer"
scope="session" />
Finding flights for
<jsp:getProperty name="customer" property="fullName" />
<P>
<jsp:getProperty name="customer" property^"flights" />
<P><BR><HR><BR>
<FORM ACTION="/servlet/BookFlight">
<jsp:getProperty 1="customer"
property="frequentFlyerTable" />
<P>
<B>Credit Card:</B>
<jsp:getProperty name="customer" property="creditCard" />
<P>
<INPUT TYPE="SUBMIT" NAME="holdButton" VALUE="Hold for 24 Hrs">
<P>
<INPUT TYPE="SUBMIT" NAME="bookItButton" VALUE="Book It!">
</FORM>
</CENTER>
</BODY>
</HTML>
2 0 . 8 . JSP
987
988
2 0 . JavaServer Pages
JSP-
:
JSP-. ,
, bean
;
, JSP. JSP,
HTML-.
, , ,
.
. ,
JSP. , , JSP ,
, , ,
, .
20.8. JSP
989
JSP ,
R e q u e s t D i s p a t c h e r . JSP- R e q u e s t D i s p a t c h e r
j s p : f o r w a r d . :
<jsp:forward
p a g e JSP-,
. , )^
h t t p : / / h o s t / e x a m p l e s / p a g e l . j s p ,
h t t p : / / h o s t / e x a m p l e s / p a g e 2 . j s p .
<% S t r i n g d e s t i n a t i o n ;
i f (Math.random0 > 0.5) {
destination = "/examples/pagel.jsp";
} else {
destination = "/examples/page2.jsp";
}
%>
20.9.
, , JSP,
. JSP ) HTML .
, Web-,
Java-, .
.
JSP. , ,
,
JSP. , , JSP,
JSP.
JSP ,
, JSP.
bean .
,
Java. , ,
JSP .
,
, ,
.
...
GET
.
GET
(-).
POST
(-).
HTTP-.
Tly\^sJZJ
TML-, 18,
CGI. HTML- .
. ,
.
, , , .
, ,
; , , ,
.
,
, HTML- .
, HTML , .
HTML- .
METHOD FORM.
. , 21.1,
GET, ,
. 21.2.
, 21.3, GET
, .
21.4. , 21.5,
, POST,
. 21.6. , 21.7
,
HTTP- .
, ,
(. 9)
.
992
2 1 . .
2 1 . 1 .
GET
showDocument ,
, URL.
CGI-, URL ("?").
, URL
)' showDocument.
, baseURL , URL
, some D a t a ,
.
try {
URL programURL = new URL(baseURL + "?" + someData);
getAppletContext().showDocument(programURL);
} catch(MalformedURLException mue) { ... }
, , ..
"+", , ,
, "%" ,
. ,
s o m e D a t a ,
. JDK 1.1
URLEncoder, e n c o d e ,
.
, GET,
, "=",
, "&", =. ,
URLEncoder. e n c o d e ( s o m e D a t a ) ,
. s o m e D a t a
:
String someData =
namel + "=" + URLEncoder.encode(vail) + "&" +
name2 + "=" + URLEncoder.encode(val2) + "&" +
nameN + "=" + URLEncoder.encode(valN);
try {
URL programURL = new URL(baseURL + "?" + someData);
getAppletContext().showDocument(programURL);
} catch(MalformedURLException mue) { ... }
.
2 1 . 2 .
993
21.2.
2L1 ,
. ,
, , URL
GET, . Google,
Infoseek, Lycos. showDocument,
.
HTML-,
URL. 12.2 SearchSpec,
URL,
. SearchSpec
. . 2L1 2L2.
2L3 HTML- , 2L4
HTML-o)^e, .
,
(. 2L1), h t t p : / / w w w . corewebprogramming.com/.
2 1 . 1 . S e a r c h / ^ p l e t . Java
import
import
import
import
/**
*
*
*
*
*
*
*
*
Java.applet.Applet;
java.awt.*;
Java.awt.event.*;
java.net.*;
TextField,
URL,
, GET.
URL Google, -
Infoseek, - Lycos.
, URL,
. ,
HTML-
.
V
public class SearchApplet extends Applet
implements ActionListener {
private TextField queryField;
private Button submitButton;
public void initO {
setBackground(Color.white);
setFont(new Font("Serif", Font.BOLD, 18));
add(new Label("Search String:"));
queryField = new TextField(40);
queryField.addActionListener(this);
add(queryField);
submitButton = new Button("Send to Search Engines");
994
2 1 . ...
submitButton.addActionListener(this);
add(submitButton);
}
/** <></>
* <Enter> ,
* .
21.2.SearchSpec.Java
/** ,
* .
public class SearchSpec {
private String name, baseURL, numResultsSuffix;
private static SearchSpec[] commonSpecs =
{ new SearchSpec("google",
"http://www.google.com/search?q=",
"&num="),
new SearchSpec("infoseek",
"http://infoseek.go.com/Titles?qt=",
"&nh="),
new SearchSpec("lycos",
"http://lycospro.lycos.com/cgi-bin/" +
"pursuit?query=",
"&maxhits="),
new SearchSpec("hotbot",
"http://www.hotbot.com/?MT=",
"&DC=")
};
21.2.
995
i-y{jriiaHmiiiiiHiiiiffliH.;HHiifflHiHaa
Search Stiiiig:
Stiil to Scardi Enffaiei [
. 21.1. SearchApplet
996
2 1 . .
lie
d*
Yew
F^vortes
Tooh
Search Striii;:
JServlets Jeve
JAII Language
Google Se
??'1 Tp^
GQc
Search > Seivleis JavaSefvet Pages Book
(*' H:Vv search <^ Search within
results
^ *i:
iL
ResuttS
for
Fmt
| GOquai-diar'" is
.f.K HFBEJ
Wee SITES
HJ-IJ.I.IJJ,JIIUJ
1 matchf Hid
jufTirr^jflt? I gort fry
I d k i ^ fWJits
'^,
1 Object News
Cuiient
NETWORK
COMPUTING
TAKES FIVE
GO Shopping
'- ig'>E._SjvejjgLiQ.5P,%,fin-.6?s,tsgilirig-B'20
1000's of brands
Search GO Shopp
Serylets.pprri
I Useful L'PLs:
[f^J
:...M.
. 21.2. ,
2 1 . 3 . P a r a l l e l S e a r c h e s . h t m l
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0 F r a m e s e t / / E N " >
<HTML>
<HEAD>
<TITLE>Parallel Search Engine Results</TITLE>
</HEAD>
<FRAMESET ROWS="120,*">
<FRAME SRC="SearchAppletFrame.html" SCROLLING="NO">
<FRAMESET COLS="*, *f''">
<FRAME SRC="GoogleResultsFrame.html" NAME="resultsO">
<FRAME SRC="InfoseekResultsFranie.html" NAME="resultsl">
<FRAME SRC="LycosResultsFrame.htral" NAME="results2">
</FRAMESET>
</FRAMESET>
21.4.SearchAppletFrame.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Search Applet Frame</TITLE>
21.3. GET...
997
</HEAD>
<BODY BGCOLOR="WHITE">
<CENTER>
<APPLET CODE="SearchApplet.class" WIDTH=600 HEIGHT=100>
<B>This example requires a Java-enabled browser.</B>
</APPLET>
</CENTER>
</BODY>
</HTML>
21.3. GET
(-)
,
.
,
, CGI HTML-. , , , ,
HTML-
. ,
. -, HTTP- ,
. -,
, ,
..
.
, URL,
U R L C o n n e c t i o n . .
B u f f e r e d l n p u t S t r e a m ,
ASCII-, .
O b j e c t I n p u t S t ream,
. , ,
, Java.
ASCII-
, ,
URL U R L C o n n e c t i o n , Buf f e r e d l n p u t
S t r e a m . , . ,
. ,
HTML-oveo.
998
2 1 . .
lOException,
t r y / c a t c h .
1. URL, ,
. URL ,
URL,
, ,
URL :
URL c u r r e n t P a g e = getCodeBase ( ) ;
String protocol = currentPage.getProtocol();
String host = currentPage.getHost()/
int port = currentPage.getPort();
String urlSuffix = "/servlet/SomeServlet";
URL dataURL = new URL(protocol, h o s t , p o r t , u r l S u f f i x ) ;
2. URLConnection. openConnection URL
URLConnection,
.
URLConnection c o n n e c t i o n = d a t a U R L . o p e n C o n n e c t i o n ( ) /
3. . , ,
URLConnection, .
connection.setUseCaches(false);
4. HTTP-.
HTTP- (. 19.7),
s e t R e q u e s t P r o p e r t y .
connection.setRequestProperty("header", "value");
5. .
; Buf f eredReader.
Web-.
BufferedReader in =
new BufferedReader(new InputStreamReader(
connection.getInputStream{)));
6. . HTTP,
. ,
r e a d L i n e n u l l .
S t r i n g linerw h i l e ( ( l i n e = i n . r e a d L i n e ( ) ) != n u l l ) {
doSomethingWith(line);
}
7. .
in.close();
2 1 . 3 . GET...
999
, , ,
Web.
. ASCII-
, Java.
readObject;
. , -,
.
, ,
. ASCII-
5 6 . ,
, t r y / c a t c h .
1. URL, ,
. , ,
URL .
URL c u r r e n t P a g e = g e t C o d e B a s e ( ) /
String protocol = currentPage.getProtocol();
String host = currentPage.getHost();
int port = currentPage.getPort0/
String urlSuffix = "/servlet/SomeServlet";
URL dataURL = new URL(protocol, h o s t , p o r t , u r l S u f f i x ) ;
2. URLConnection. openConnection URL
URLConnection, .
URLConnection c o n n e c t i o n = d a t a U R L . o p e n C o n n e c t i o n ( ) ;
3. . , ,
URLConnection, .
connection.setUseCaches(false);
4. HTTP-.
HTTP- (. 19.7),
s e t R e q u e s t P r o p e r t y .
connection.setRequestProperty("header", "value");
5. ObjectlnputStream.
URLConnection.
Web-.
ObjectlnputStream in =
new ObjectInputStream(connection.getInputStream());
1000
2 1 . .
6. readObject. r e a d O b j e c t
Ob j e c t ,
, .
SomeClass v a l u e =
(SomeClass)in.readObject();
doSomethingWith(value);
7. .
in.close ();
)^
. , r e q u e s t r e s p o n s e
H t t p S e r v l e t R e q u e s t H t t p S e r v l e t R e s p o n s e ,
d o G e t d o P o s t .
1. , ,
.
1- a p p l i c a t i o n / x - j a v a - s e r i a l i z e d - o b j e c t . MIME-
, O b j e c t O u t p u t S t r e a m , , ,
, MIME- .
MIME- . 19.10.
String contentType =
"application/x-java-serialized-object";
response.setContentType(contentType);
2. ObjectOutputStream.
ObjectOutputStream out =
new
ObjectOutputStreain(response.getOutputStream());
3. writeObject.
w r i t e O b j e c t . , ,
S e r i a l i z a b l e . ,
S e r i a l i z a b l e .
.
S o m e C l a s s v a l u e = new
SomeClass(...);
out.writeObject(value) ;
4. .
out.flush()/
-.
21.4. ...
1001
21.4. ,
-
,
. . (" , 64%
AltaVista ,
Java?") HTML-,
) ,
.
, ,
"",
Web-. 21.5 ,
( 21.6)
, .
)^
(. 21.3). 21.7 , .
, , 50
. . 19.
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 . com/ , ,
, HTML-
H T T P . ,
, , .
2 1 . 5 . S h o w Q u e r i e s . j a v a
i m p o r t J a v a , a p p l e t .Appletsimport j a v a . a w t . ^ ;
import J a v a . a w t . e v e n t . * ;
im.port j a v a . n e t . * ;
/**
*
*
*
*"
Q u e r y C o l l e c t i o n
. Q u e r y C o l l e c t i o n
,
.
*/
public class ShowQueries extends Applet
implements ActionListener, Runnable {
private TextArea queryArea;
private Button startButton, stopButton, clearButton;
private QueryCollection currentQueries;
private QueryCollection nextQueries;
private boolean isRunning = false;
private String address =
"/servlet/cwp.QueryGenerator";
private URL currentPage;
1002
2 1 . .
Start
. Stop
. Clear TextArea
.
21.4. ...
/**
*
*
*
*
*
currentQueries
.
nextQueries currentQueries
nextQueries, .
21.6.QueryCollection.Java
import java.net.*;
import java.io.*;
/** ,
* isDone false, getQueries - null.
* ,
1003
1004
*
*
*
*
*
*
2 1 . .
ObjectlnputStream.
,
getQueries, isDone
true.
ShowQueries.
2 1 . 4 . .
new ObjtInputstream(connection.getInputStream())/
try {
// readObject Object,
// .
String[] queryStrings = (String[])in.readObject();
return(queryStrings);
} catch(ClassNotFoundException cnfe) {
return(null);
}
Edrt
Vievv
Fvoftles
lock
Hetp
~3
"3
jJ
;0j Recewed data hom sefver.
f g locae'irttane*
. 21.3. showQueries
2 1 . 7 . Q u e r y G e n e r a t o r . J a v a
package cwp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.
1005
1006
2 1 . .
/** ,
* , Java,
* ObjectOutputStream.
V
public class QueryGenerator extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, lOException {
boolean useNumbering = true;
String useNumberingFlag =
request.getParameter{"useNumbering");
if ((useNumberingFlag == null) I|
useNumberingFlag.equals("false")) {
useNumbering = false;
}
String contentType =
"application/x-java-serialized-object";
response.setContentType(contentType);
ObjectOutputStream out =
new ObjectOutputStream(response.getOutputStream());
String[] queries ~ getQueries(useNumbering);
// , ,
//
// "implements Serializable".
out.writeObject(queries);
out.flush 0 ;
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, lOException {
doGet(request, response);
}
private String[] getQueries(boolean useNumbering) {
String[] queries = new String[50];
for(int i=0; i<queries.length; i++) {
queries[i] = randomQuery();
if (useNumbering) {
queries [i] = "" -f (i + 1) + ": " + queries [i];
}
}
return(queries);
}
// ""
private String randomQuery() {
String[] locations = { "Where ", "How " };
String[] actions =
{ "can I look for ", "can I find ", "can I get " };
String[] sources =
{ "information ", "resources ", "data ", "references " };
String[] prepositions = { "on ", "about ", "concerning " };
String[] subjects =
21.5. POST...
1007
21.5. POST
(-)
GET
( URL A p p l e t C o n t e x t () . showDocument)
( URL,
U R L C o n n e c t i o n , ).
21.1 21,3. POST
. POST ,
, ,
,
. ,
,
HTML-,
Web-. , POST,
, . , ,
, - ,
. , GET,
, , URL
.
1008
2 1 . ...
POST
, .
, . t r y /
c a t c h .
1. URL, ,
. , ,
URL .
URL c u r r e n t P a g e = g e t C o d e B a s e ( ) ;
String protocol = currentPage.getProtocol();
String host = currentPage,getHost();
int port = currentPage.getPort();
S t r i n g u r l S u f f i x --= " / s e r v l e t / S o m e S e r v l e t " ;
URL dataURL =
new URL(protocol, h o s t , p o r t , u r l S u f f i x ) ;
2. URLConnection.
,
.
URLConnection c o n n e c t i o n = d a t a U R L . o p e n C o n n e c t i o n ( ) ;
3. .
connection.setUseCaches(false);
4. ( ).
connection.setDoOutput(true);
5. ByteArrayOutputStream,
, . B y t e A r r a y O u t p u t
Stream ,
.
ByteArrayOutputStream byteStream =
new ByteArrayOutputStream(512);
6. ByteArrayOutputStream.
, , P r i n t W r i t e r .
, P r i n t W r i t e r
Obj e c t O u t p u t S t r e a m .
P r i n t W r i t e r out = new P r i n t W r i t e r ( b y t e S t r e a m ,
true);
7. . )
p r i n t , w r i t e O b j e c t .
S t r i n g v a i l = URLEncoder.encode(someVail);
S t r i n g v a l 2 = URLEncoder.encode(someVal2)/
S t r i n g d a t a = "paraml=" + v a i l +
"¶m2=" -f- v a l 2 ; / / '&' .
21.6. , POST
1009
out.print(data);
/ / p r i n t , a p r i n t l n .
o u t . f l u s h O ; / / f l u s h ,
/ / p r i n t l n .
8. Content-Length. POST
.
connection.setRequestProperty
{"Content-Length", S t r i n g . v a l u e O f ( b y t e S t r e a m . s i z e ( ) ) ) /
9. Content-Type. Netscape
m u l t i p a r t / f o r m - d a t a ,
a p p l i c a t i o n / x - w w w - f orm-urlencoded, Internet
Explorer .
connection.setRequestProperty
("Content-Type",
"application/x-www-form-urlencoded");
10. .
byteStream.writeTo(connection.getOutputStream());
11. . ASCII
Buf feredReader, Java-
ObjectInputStream.
BufferedReader in =
new BufferedReader(new InputStreamReader
(connection.getInputStream()));
12. . ,
.
.
String line;
while((line = in.readLine()) != null) {
doSomethingWith(line);
}
, POST
,
. ,
www. corewebprogramming. com .
,
11.
21.6. ,
POST
21.8 , ,
. URLConnecticn B y t e -
1010
2 1 . ...
ArrayOutputStream POST ,
. , L a b e l e d T e x t F i e l d ,
, h t t p : / /www. corewebprograraming. com/.
Ha . 21.4 ShowParameters.
Web-,
, (. 19.6).
21.8. SendPost.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 . n e t . * ;
import j a v a . i o . * ;
/ * * , firstName, lastName
* emailAddress,
* POST.
*/
public class SendPost extends Applet
implements ActionListener {
private LabeledTextField fIrstNameField, lastNameField,
emailAddressField, hostField,
portField, uriField;
private Button sendButton;
private TextArea resultsArea;
URL currentPage;
public void initO {
setBackground(Color.white);
setLayout(new BorderLayout());
Panel inputPanel = new Panel();
inputPanel.setLayout(new GridLayout(9, 1));
inputPanel.setFont(new Font("Serif", Font.BOLD, 14));
fIrstNameField =
new LabeledTextField("First Name:", 15);
inputPanel.add(fIrstNameField);
lastNameField =
new LabeledTextField("Last Name:", 15);
inputPanel.add(lastNameField);
emailAddressField =
new LabeledTextField("Email Address:", 30);
inputPanel.add(emailAddressField);
Canvas separatorl = new Canvas();
inputPanel.add(separatorl);
hostField =
new LabeledTextField("Host:", 15);
// , ,
// ,
// , .
hostField.getTextField().setEditable(false);
21.6. , POST
currentPage = getCodeBase();
// , ,
// getHost .
String host = currentPage.getHost();
String resultsMessage = "Results will be shown here...";
if (host.length 0 == 0) {
resultsMessage = "Error: you must load this applet\n" +
"from a real Web server via HTTP,\n" +
"not from the local disk usingXn" +
"a file:' URL. It is fine,\n" +
"however, if the Web server is\n" +
"running on your local system.";
setEnabled(false);
}
hostField.getTextField().setText(host);
inputPanel.add(hostField);
portField =
new LabeledTextField("Port (-1 means default):", 4 ) ;
String portString = String.valueOf(currentPage.getPort());
portField.getTextField().setText(portString);
inputPanel.add(portField);
uriField =
new LabeledTextField("URI:", 40);
String defaultURI = "/servlet/cwp.ShowParameters";
uriField.getTextField0 .setText(defaultURI);
inputPanel.add(uriField);
Canvas separator2 = new Canvas();
inputPanel.add(separator2);
sendButton = new Button("Submit Data");
sendButton.addActionListener(this);
Panel buttonPanel = new Panel();
buttonPanel.add(sendButton);
inputPanel.add(buttonPanel);
add(inputPanel, BorderLayout.NORTH);
resultsArea = new TextAreaO;
resultsArea.setFont(new Font("Monospaced", Font.PLAIN, 14))
resultsArea.setText(resultsMessage);
add(resultsArea, BorderLayout.CENTER);
public void actionPerformed(ActionEvent event) {
try {
String protocol = currentPage.getProtocol();
String host = hostField.getTextField().getText();
String portString = portField.getTextField().getText();
int port;
try {
port = Integer.parseint(portString);
} catch(NumberFormatException nfe) {
port = -1; // no , .. 80
}
String uri = uriField.getTextField().getText();
URL dataURL = new URL(protocol, host, port, uri);
URLConnection connection = dataURL.openConnection();
// URL .
1011
1012
21. ...
connection.setUseCaches(false);
// .
connection.setDoOutput(true);
ByteArrayOutputStream byteStream =
new ByteArrayOutputStream(512); //
// .
// ,
PrintWriter out = new PrintWriter(byteStream, true);
String postData =
"firstName=" + encodedValue(firstNameField) +
"&lastName=" + encodedValue(lastNameField) +
"&emailAddress=" + encodedValue(emailAddressField);
// POST
out.print(postData);
out.flush ; // flush ,
// println print
// POST
// Content-Length
String lengthString =
String.valueOf(byteStream.size());
connection. setRecgfuestProperty
("Content-Length", lengthString);
// Netscape
// Content-Type, multipart/form-data.
// ,
// ,
// , application/x-www-form-urlencoded.
// Internet Explorer
/ / .
// ObjectOutputStream, .
connection.setRequestProperty
("Content-Type", "application/x-www-form-urlencoded");
// POST
byteStream.writeTo(connection.getOutputStream());
BufferedReader in =
new BufferedReader(new InputstreamReader
(connection.getlnputStream0));
String line;
String linefeed = "\n";
resultsArea.setText("");
while((line = in,readLine()) ?= null) {
resultsArea.append(line);
resultsArea.append(linefeed);
}
catch(lOException ioe) {
21.6. , POST
// Java Console
System.out.println("lOException: " + ioe);
}
//
//
//
//
LabeledTextField Panel,
Label TextField.
TextField,
.
t-#fT-mii'HifinmffiHna[infff
"^ ^ -./ 31 ^- '^ -^ ^ i i ^H
^i^" Boolynfk$
11
Host
bcnlhost
~1
,J
jj^-sa^as'
>' C3 --
, 21.4. SendPost
ShowParameters POST
1013
1014
2 1 . ...
21.7.
HTTP-
,
, , ,
( H T T P 80).
, JDBC RMI
, .
, Java-
. ,
.
21.8.
HTML-
, .
, ,
. HTML-.
, ,
, Java-.
JDBC
...
,
.
,
JDBC.
J1y\ZJ^ZJ
JDBC
. JDBC API
SQL, Java. , ,
, JDBC )^ ,
, ,
SQL- .
SQL-, .
SQL,
, ,
.
1 JDBC ,
, Java Database Connectivity.
, JDBC.
, SQL.
JDBC 1 h t t p : / / j a v a . s u n . c o m / p r o d u c t s / j d b c / ;
API J a v a . s q l JDBC
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 / j d b c / .
, ,
mySQL. mySQL ,
Windows, , ,
Windows .
mySQL h t t p : //www . m y s q l . com/.
2 2 . 1 . JDBC
.
L
JDBC-.
2. URL .
1018
22. JDBC
3. .
4. ( Statement).
5. .
6. .
7. .
.
,
. ;
, s t a t i c ,
JDBC.
, .
. -, ,
, , ? -, , , ,
, .
: C l a s s . forName.
, (..
), .
C l a s s N o t F o u n d E x c e p t i o n ,
t r y / c a t c h . ,
, .
try {
Class.forName{"connect.microsoft.MicrosoftDriver");
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("com.Sybase.jdbc.SybDriver");
} catch(ClassNotFoundException cnfe) {
System.err.println("Error loading driver: " + cnfe);
}
JDBC ,
. JDBC- (
) , Java,
, . ,
,
. JDBC-
; .
h t t p : / /
i n d u s t r y . j a v a . s u n . c o m / p r o d u c t s / j d b c / d r i v e r s .
(
),
JDBC.
C l a s s . forName ,
CLASS PATH.
JDBC- JAR-, , -
2 2 . 1 . JDBC
1019
JDBC-, . URL,
, j d b c : . ,
URL , , .
. URL
.
String host = "dbhost.yourcompany.com";
S t r i n g dbName = "someName";
int p o r t = 1234;
String oracleURL = "jdbc:oracle:thin:@" + host +
":" + port + ":" + dbName;
String sybaseURL = "jdbc:Sybase:Tds:" + host +
":" 4- port + ":" + "?SERVICENAME=" + dbName;
, JDBC ,
. JDBC
, ,
, . , ,
)%
, HTTP-. ,
proxy-, .
, ,
, URL,
g e t C o n n e c t i o n DriverManager. g e t C o n n e c t i o n
S Q L E x c e p t i o n ,
t r y / c a t c h . , ,
' ,
try/catch.
String username = " j a y _ d e b e s e e " ;
String password = " s e c r e t " ;
Connection c o n n e c t i o n =
DriverManager.getConnection(oracleURL,
username,
password);
Ha
g e t M e t a D a t a C o n n e c t i o n .
D a t a b a s e M e t a D a t a ,
( g e t D a t a b a s e P r o d u c t N a m e , g e t D a t a b a s e P r o d u c t V e r s i o n ) ( g e t D r i v e r Name,
g e t D r i v e r V e r s i o n ) . .
1020
22. JDBC
DatabaseMetaData dbMetaData = c o n n e c t i o n . g e t M e t a D a t a ( ) ;
S t r i n g productName =
dbMetaData.getDatabaseProductName();
S y s t e m . o u t . p r i n t l n ( " D a t a b a s e : " + productName);
S t r i n g productVersion =
dbMetaData.getDatabaseProductVersion();
System.out.println("Version: " + productVersion);
, Connection p r e p a r e S t a t e m e n t
( P r e p a r e d S t a t e m e n t ,
22.6), p r e p a r e C a l l ( C a l l a b l e S t a t e m e n t ) , r o l l b a c k (
, ), commit
( ), c l o s e ( ), i s C l o s e d (,
-).
Statement
S t a t e m e n t Connection
, :
Statement statement = c o n n e c t i o n . c r e a t e S t a t e m e n t ( ) ;
S t a t e m e n t , SQL-
executeQuery. executeQuery
( R e s u l t S e t ) .
.
S t r i n g query = "SELECT c o l l , c o l 2 , col3 FROM sometable";
ResultSet r e s u l t S e t = s t a t e m e n t . e x e c u t e Q u e r y ( q u e r y ) ;
, executeQuery
e x e c u t e Update, ,
UPDATE, INSERT DELETE. executeQuery executeUpdate
Statement e x e c u t e ( )
QueryTimeout ( ).
, ,
.
22.6.
, ()
n e x t R e s u l t S e t . R e s u l t S e t
qetXxx.
, ();
. ,
, g e t l n t ^ S t r i n g
g e t S t r i n g .. ,
g e t S t r i n g . , -
2 2 . 1 . JDBC
1021
, , SQL, ,
, , 1.
!!
ResultSet
1, .
,
ResultSet.
while(resultSet.next ) {
System.out.println(results.getString(1) + " " +
results.getString(2) + " " +
results.getString(3));
}
g e t X x x n n e x t R e s u l t S e t
, f i n d C o l u m n (
), g e t M e t a D a t a ( R e s u l t S e t
R e s u l t S e t M e t a D a t a ) was N u l l ( g e t X x x SQL NULL?). w a s N u l l
n u l l .
g e t M e t a D a t a .
R e s u l t S e t , ,
. , ,
. R e s u l t S e t M e t a D a t a ;
, R e s u l t S e t .
R e s u l t S e t M e t a D a t a g e t C o l u m n C o u n t (
), getColumnName ( ;
1), g e t C o l u m n T y p e ( ,
, J a v a , s q l . T y p e s ) , i s R e a d O n l y
(, ), i s S e a r c h a b l e (
WHERE), i s N u l l a b l e (
n u l l ) ,
, . R e s u l t S e t M e t a D a t a
;
n e x t ResultSet ,
f a l s e .
,
:
connection.close();
,
, ,
.
1022
2 2 . JDBC
22.2. JDBC
22.3 F r u i t T e s t ,
, ,
f r u i t s . 22.1 22.2, , ,
.
URL ,
D r i v e r U t i l i t i e s , 22.4.
,
.
, ;
.
JDBC (. 22.5).
,
, .
, , . F r u i t T e s t
cwp, cwp.
CLASS PATH ,
cwp. (JAR-, JDBC-,
CLASS PATH.) cwp
j a v a c F r u i t T e s t . J a v a . , F r u i t T e s t ,
, .. j a v a cwp. F r u i t T e s t
....
2 2 . 1 . F r u i t T e s t (
Oracle Solaris)
Prompt> J a v a c w p . F r u i t T e s t d b h o s t l . a p l . j h u . e d u
h a l l xxxx o r a c l e
Database: Oracle
Version: Oracle7 Server Release 7 . 2 . 3 . 0 . 0 - Production
PL/SQL R e l e a s e 2 . 2 . 3 . 0 . 0 - P r o d u c t i o n
Release
Comparing A p p l e s and O r a n g e s
QUARTER
1
2
3
4
APPLES
32248
35009
39393
42001
APPLESALES
$3547.28
$3850.99
$4333.23
$4620.11
ORANGES
18459
18722
18999
19333
ORANGESALES
$3138.03
$3182.74
$3229.83
$3286.61
TOPSELLER
Maria
Bob
Joe
Maria
2 2 . 2 . F r u i t T e s t (
Sybase NT)
Prompt> J a v a c w p . F r u i t T e s t d b h o s t 2 . a p l . j h u . e d u
h a l l xxxx Sybase
D a t a b a s e : A d a p t i v e S e r v e r Anywhere
Version: 6.0.2.2188
605741
2 2 . 2 . JDBC
apples
32248
35009
39393
42001
applesales
$3547.28
$3850.99
$4333.23
$4620.11
oranges
18459
18722
18999
19333
orangesales
$3138.03
$3182.74
$3229.83
$3286.61
topseller
Maria
Bob
Joe
Maria
22.3.FruitTest.Java
package cwp;
import java.sql.*;
/** JDBC.
* Oracle Sybase
* fruits.
V
public class FruitTest {
/
*
*
*
*
*
*
,
, ,
.
URL. ,
URL, ,
showFruitTable.
V
public static void main(String[] args) {
if (args.length < 5) {
printUsage();
return;
}
String vendorName = args[4];
int vendor = DriverUtilities.getVendor(vendorName)/
if (vendor == DriverUtilities.UNKNOWN) {
printUsage();
return;
}
String driver = DriverUtilities.getDriver(vendor);
String host = args[0];
String dbName = args[l];
String url = DriverUtilities.makeURL(host, dbName, vendor);
String username = args[2];
String password = args[3];
showFruitTable(driver, url, username, password);
/** . */
public static void showFruitTaUDle(String driver.
1023
1024
22. JDBC
string url,
String username,
String password) {
try {
// ,
// .
Class.forName(driver);
// .
Connection connection =
DriverManager.getConnection(url, username, password);
// .
DatabaseMetaData dbMetedData = connection.getMetaData();
String productName =
dbMetaData.getDatabaseProductName();
System.out.println("Database: " + productName);
String productVersion =
dbMetciData. getDatabaseProductVersion () ;
System.out.println("Version: " + productVersion + " \ n " ) ;
System.out.println("Comparing Apples and Oranges\n" +
"============:=:=========:======:" ) ;
Statement statement = connection.createstatement();
String query = "SELECT * FROM fruits";
// .
ResultSet resultSet = statement.executeQuery(query);
// .
ResultSetMetaData resultsMetaData =
resultSet .getMetedData ;
int coliunnCount = resultsMetaData.getColumnCount0;
// 1, .
for(int i=l; i<columnCount+l; i++) {
System, ou t. print (result sMetaData.getColtlnName (i) +
}
System.out.println();
// ,
while(resultSet.next ) {
//
System.out.print("
" + resultSet.getint(1));
//
System.out.print("
" + resultSet.getint(2));
//
System.out.print("
$" + resultSet.getFloat(3));
//
System.out.print("
" + resultSet.getint(4));
//
System.out.print("
$" + resultSet.getFloat(5));
//
System.out.println("
" + resultSet.getString(6));
}
} catch(ClassNotFoundException cnfe) {
System.err.println("Error loading driver: " + cnfe);
} catch(SQLException sqle) {
System.err.println("Error connecting: " + sqle);
2 2 . 2 . JDBC
)
}
22.4. DriverUtilities.Java
package cwp;
/**
*
*
*
JDBC- Oracle Sybase.
<1> </1>
, .
V
public class DriverUtilities {
public static final int ORACLE = 1;
public static final int SYBASE = 2;
public static final int UNKNOWN = -1;
/** URL ,
* Oracle Sybase.
public static String makeURL(String host. String dbName,
int vendor) {
if (vendor == ORACLE) {
return ("jdbc: oracle: thin: (3" + host + ":1521:" -i- dbName);
} else if (vendor == SYBASE) {
return("jdbc:Sybase:Tds:" + host + ":1521" +
"?SERVICENAME=" + dbName);
} else {
return(null);
}
}
/** . */
public static String getDriver(int vendor) {
if (vendor == ORACLE) {
return("oracle.jdbc.driver.OracleDriver");
} else if (vendor == SYBASE) {
return("com.Sybase.jdbc.SybDriver");
} else {
return(null) ;
}
/** . */
1025
1026
22. JDBC
22.5. FruitCreation.java
package cwp;
import java.sql.*;
/** fruits
* Oracle Sybase.
public class FruitCreation {
public static void main(String[] args) {
if (args.length < 5) {
printUsage();
return;
}
String vendorName = args[4];
int vendor = DriverUtilities.getVendor(vendorName);
if (vendor == DriverUtilities.UNKNOWN) {
printUsage ();
return;
}
String driver = DriverUtilities.getDriver(vendor);
String host = args[0];
String dbName = args[l];
String url =
DriverUtilities.makeURL(host, dbName, vendor);
String username = args[2];
String password = args[3];
String format =
"(quarter int, " +
"apples int, applesales float, " +
"oranges int, orangesales float, " +
"topseller varchar(16))";
String[] rows =
{ "(1, 32248, 3547.28, 18459, 3138 03, 'Maria')",
"(2, 35009, 3850.99, 18722, 3182 74, 'Bob')",
"(3, 39393, 4333.23, 18999, 3229 83, 'Joe')",
"(4, 42001, 4620.11, 19333, 3286 61, 'Maria')" };
Connection connection =
DatabaseUtilities.createTable(driver. url,
username, password.
22.3. JDBC
1027
22.3.
JDBC
. , JSP ,
, HTML-,
Excel Web- .
,
R e s u l t S e t ,
.
, ,
, ,
. , D a t a b a s e U t i l i t i e s ,
.
1.
getQueryResults
, ,
,
D B R e s u l t s (. 22.7). ,
D B R e s u i t s , C o n n e c t i o n .
g e t Q u e r y R e s u l t s :
, .
2. createTable
, , , ,
,
, ( ),
CREATE TABLE
INSERT INTO ().
)' , c r e a t e T a b l e :
, .
3. printTable
.
p r i n t T a b l e , -
1028
22. JDBC
.
SELECT * FROM
tableName g e t Q u e r y R e s u l t s .
4. printTableData
,
DBResults . p r i n t T a b l e D a t a
p r i n t T a b l e ,
.
D a t a b a s e U t i l i t i e s 22.6, DBResults
22.7. DBResults
(getRow) HTML- (toHTMLTable).
HTML-
, .
, ,
HTML-.
DBResults results =
DatabaseUtilities.getQueryResults(driver, url,
username, password,
query, true);
out.println(results.toHTMLTable("CYAN"));
, ,
DatabaseUtilities DBResults ,
www. corewebprogramming. com, .
22.6. DatabaseUtilities. Java
package cwp;
import java.sql.*;
public class DatabaseUtilities {
/**
*
*
*
*
*
,
DBRresults.
( close ,
),
DBResults.getConnection.
V
public static DBResults getQueryResults(String driver,
String url.
String username.
String password.
String query,
boolean close) {
try {
Class.forName(driver);
Connection connection =
2 2 . 3 . JDBC
/** , ,
*
* .
public static DBResults getQueryResults(Connection connection.
String query,
boolean close) {
try {
DatabaseMetaData dbMetaData = connection.getMetaData();
String productName =
dbMetaData.getDatabaseProductName();
String productVersion =
dbMetaData.getDatabaseProductVersion();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query) ;
ResultSetMetaData resultsMetaData =
resultSet.getMetaData();
int columnCount = resultsMetaData.getColumnCount();
String[] columnNames = new String[columnCount];
// 1, .
for(int i=l; i<columnCount+l; i++) {
columnNames[i-1] =
resultsMetaData.getColumnName(i).trim();
}
DBResults dbResults =
new DBResults(connection, productName, productVersion,
columnCount, columnNames);
while(resultSet.next 0 ) {
String[] row = new String[columnCount];
// 1.
for(int i=l; i<columnCount+l; i++) {
String entry = resultSet.getString(i);
if (entry != null) {
entry = entry.trim();
}
row[i-l] = entry;
}
dbResults.addRow(row);
}
if (close) {
connection.close() ;
}
return(dbResults);
} catch(SQLException sqle) {
1029
1030
22. JDBC
/**
* .
V
public static Connection createTable(String driver.
String url.
String username,
String password,
String tableName,
String tableFormat,
String[] tableRows,
boolean close) {
try {
Class.forName(driver);
Connection connection =
DriverManager.getConnection(url, username, password);
return(createTable(connection, username, password,
tableName, tableFormat,
tableRows, close));
} catch(ClassNotFoundException cnfe) {
System.err.println("Error loading driver: " + cnfe);
return(null);
} catch(SQLException sqle) {
System.err.println("Error connecting: " + sqle);
return(null);
}
/ , ,
* .
V
public static Connection createTable(Connection connection.
String username.
String password.
String tableName,
String tableFormat,
String[] tableRows,
boolean close) {
try {
Statement statement = connection.createStatement();
// , .
// ,
// try,
/ / catch,
try {
statement.execute("DROP TABLE " + tableName);
} catch(SQLException sqle) {}
String createCommand =
"CREATE TABLE " + tableName + " " + tableFormat;
2 2 . 3 . JDBC
.
entryWidth .
,
.
1031
1032
2 2 . JDBC
results.getProductName());
System.out.println("Version: " +
results.getProductVersion());
System.out.println() ;
}
System.out.println(tableName + " : " ) ;
String underline =
padString("", tableName.length()+1, " = " ) ;
System.out.println(underline);
int columnCount = results.getColumnCount();
String separator =
makeSeparator(entryWidth, columnCount);
System.out.println(separator);
String row = makeRow(results.getColumnNames0, entryWidth);
System.out.println(row);
System.out.println(separator);
int rowCount = results.getRowCount0;
for(int i=0; i<rowCount; i++) {
row = makeRow(results.getRow(i), entryWidth);
System.out.println(row);
}
System.out.println(separator);
}
// "|
xxx |
-f"
22.3. JDBC
,
JDBC-. ResultSet
:
<UL>
<LI>B ResultSet
.
.
<> DBResults .
<> DatabaseMetaData (
) ResultSetMetaData
( ).
< > DBResults toHTMLTable,
,
HTML-.
</UL>
V
public class DBResults {
private Connection connectionsprivate String productName;
private String productVersion;
private int columnCount;
private String[] columnNames;
private Vector queryResults;
String[] rowData;
public DBResults(Connection connection,
String productName,
String productVersion,
int columnCount,
String[] columnNames) {
this.connection = connection;
this.productName = productName;
this.productVersion = productVersion;
this.columnCount = columnCount;
this.columnNames = columnNames;
rowData = new String[columnCount];
queryResults = new Vector();
1033
1034
22. JDBC
22.4. DatabaseUtilities
1035
}
}
buffer.append("\n</TABLE>");
return(buffer.toString());
}
}
22.4. DatabaseUtilities
, D a t a b a s e U t i l i t i e s , 22.3,
. 22.8 ,
, ,
employees. 22.9 22.10
Oracle Sybase. 22.11 ,
, HTML-.
22.12 HTML-. 22.13 JDBC, employees.
22.8. EmployeeTest.Java
package cwp;
import j a v a . s q l . * ;
/** Oracle Sybase
* employees.
V
p u b l i c c l a s s EmployeeTest {
p u b l i c s t a t i c void m a i n ( S t r i n g [ ] args) {
i f ( a r g s . l e n g t h < 5) {
printUsage ( ) ;
return;
}
S t r i n g vendorName = a r g s [ 4 ] ;
i n t vendor = D r i v e r U t i l i t i e s . g e t V e n d o r ( v e n d o r N a m e ) ;
i f (vendor == DriverUtilities.UNKNOWN) {
printUsage ( ) ;
return;
}
1036
22. JDBC
22.9. EmployeeTest (
Oracle Solaris)
Prompt> Java cwp.EmployeeTest dbhostl.apl.jhu.edu
hall xxxx oracle
Database: Oracle
Version Oracle? Server Release 7.2.3.0.0 - Production Release
PL/SQL Release 2 2.3.0.0 - Production
employees:
I
ID
1
2
3
4
5
6
7
8 I
FIRSTNAME
Wye
Britt
Max
Polly
Frank
Justin
Sir
Jay
Jay
LASTNAME
Tukay
Tell
Manager
Morphic
Function
Timecompiler
Viet
Espy
LANGUAGE |
COBOL
C++
none
Smalltalk
Common Lisp
Java
Java
Java
1
1
1
|
|
1
1
1
SALARY I
42500
62000
15500
51500
51500
98000
114750
128500
22.10. EmployeeTest (
Sybase NT)
Prompt> Java cwp.EmployeeTest dbhost2.apl.jhu.edu 605741
hall xxxx Sybase
Database: Adaptive Server Anywhere
Version: 6.0.2.2188
employees:
1
id 1
firstname |
1
i
1
1
1
1
1
1
+
1
2
3
4
5
6
7
8
Wye
Britt
Max
Polly
Frank
Justin
Sir
Jay
1
1
1
i
1
1
1
1
+_.
lastname |
I
Tukay
1
Tell
1
Manager
1
Morphic
1
Function
1Timecompiler
1
Viet
1
Espy
+
language |
salary 1
|
COBOL |
42500.0 I
1
C++ 1
62000.0 1
|
none |
15500.0 1
1
Smalltalk |
51500.0 1
| Common Lisp 1
51500.0 1
|
Java |
98000.0 1
1
Java i
114750.0 1
1
Java |
128500.0 1
+
+__.
+
22.4. DatabaseUtilities
22.12. EmployeeTest2 (
Sybase NT)
Prompt> Java cv.EmployeeTst2 dbhost2 605741
hall xxxx Sybase
<TABLE B0RDER=1>
<TR BGCOLOR="CYAN">
<TH>id<TH>firstname<TH>lastname<TH>language<TH>salary
<TR>
1037
1038
22. JDBC
<TD>l<TD>Wye<TD>Tukay<TD>COBOL<TD>42500.
<TR>
<TD>2<TD>Britt<TD>Tell<TD>C++<TD>62000.0
<TR>
<TD>3<TD>Max<TD>Manager<TD>none<TD>15500.0
<TR>
<TD>4<TD>Polly<TD>Morphic<TD>Sinalltalk<TD>51500.0
<TR>
<TD>5<TD>Frank<TD>Function<TD>Common Lisp<TD>51500.0
<TR>
<TD>6<TD>Justin<TD>Timecompiler<TD>Java<TD>98000.0
<TR>
<TD>7<TD>Sir<TD>Vlet<TD>Java<TD>114750.0
<TR>
<TD>8<TD>Jay<TD>Espy<TD>Java<TD>128500.0
</TABLE>
22.13.EmployeeCreation.Java
package cwp;
import java.sql.*;
/** employees
* DatabaseUtilities.
public class EmployeeCreation {
public static Connection createEmployees(String driver.
String url,
String username,
String password,
boolean close) {
String format =
"(id int, firstname varchar(32), lastname varchar(32),
"language varchar(16), salary float)";
String[] employees =
{"(1, 'Wye', 'Tukay', 'COBOL', 42500)",
"(2, 'Britt', 'Tell',
'C++',
62000)",
"(3, 'Max', 'Manager', 'none', 15500)",
"(4, 'Polly', 'Morphic', 'Smalltalk', 51500)",
"(5, 'Frank', 'Function', 'Common Lisp', 51500)",
"(6, 'Justin', 'Timecompiler', 'Java', 98000)",
"(7, 'Sir', 'Viet', 'Java', 114750)",
"(8, 'Jay', 'Espy', 'Java', 128500)" } ;
return(DatabaseUtilities.createTsuDle(driver, url,
username, password,
"employees",
format, employees,
close));
22.5.
1039
if (args.length < 5) {
printUsage();
return;
}
String vendorName = args[4];
int vendor = DriverUtilities.getVendor(vendorName);
if (vendor == DriverUtilities.UNKNOWN) {
printUsage();
return;
}
String driver = DriverUtilities.getDriver(vendor);
String host = args[0];
String dbName = args[l];
String url =
DriverUtilities.makeURL(host, dbName, vendor);
String username = args[2];
String password = args[3];
createEmployees(driver, url, username, password, true);
private static void printUsage() {
System.out.println("Usage: EmployeeCreation host dbName
"username password oracle|Sybase.");
}
22.5.
.
, ,
.
, .
,
22.6. .
R e s u l t S e t M e t a D a t a ,
R e s u l t S e t , .
R e s u l t S e t 22.1. D a t a b a s e U t i l i t i e s ,
22.6, D B R e s u i t s ;
s h o w Q u e r y D a t a .
( Q u e r y V i e w e r ) , . 22.1-22.5. ,
, .
1040
2 2 . JDBC
{^
: ^ Of*cl Sybase
U^narw. 1
Pa)5$wof; |
Ousry: 1
SfKi^Resciltg 1
. 22.1.
OuiyOa!a
;-
Ui^f <^ Orid
DBName:(PTE
#: jhaii
PaewoJ: j * * * * * * *
IrisiivowRie^
1 b en 1 rrm-.frniVi ffiiTi rttir. muTifi
- <;iuaiyfllesu{t9
iD
RftSTHAME
Wye
LASTHAtiE
LANGUAGE
Tukay
S.ARy
COBOL
42500
62000
1 2
Britt
Tell
C++
Max
Manager
none
15500
Polly
Morphic
Smalltalk
51500
II
11
i1
Frank
Function
Common Lisp
51500
Justin
Time compiler
Java
98000
;J
Sir
Viet
Java
114750
Jay
Espy
Java
128500
. 22.2. ,
employees Oracle
"<lueyOaUi
: Host jdbhostl apljhuedu
. D0Name;|PTE
Usemame: jtiaii
Ouety Results
ID
6
jj BKowResiSs^t
LASTMAItE
FIR STKAME
Justin
LAMOUAGE
Time compiler
Java
SAU
98000
Sir
Viet
Java
114750
Jay
Espy
Java
128500
. 22.3. , QueryViewer
employees Oracle
22.5.
OueryData
1041
"-- ;-
OBNeme: |05741
Usemstrm: ^lai'l
Fesswofd:
apples
32248
ajpplesalet
oraitges
3547 28
:18459
j of9ii$es3te 1
313803
tojpseHer
Maria
i
[
35009
3850 99
;i8722
3182 74
Bob
39393
4333 23
18999
3229 83
Joe
' 1
42001
4620 11
19333
3286 61
Maria
']
. 22.4, , QueryViewer
fruits Sybase
II I I I l l l l l l l l l l l I
|||||||"";["f^f|
<JuryDta
00 Name J605741
Usemarm jhall
i7ti:r-7fnriTftTtri-iirriifniMmiHitii
fMrng
18459
19333
11
.22.5. ,
fruits Sybase
QueryViewer
, . 22.1-22.5,
. D a t a b a s e U t i l i t i e s ,
, , ,
, , .
QueryViewer 22.14,
, Show Results.
,
, , .
QueryViewer .
DBResults results =
DatabaseUtilities.getQueryResults(driver, url,
username, password,
query, true);
1042
2 2 . JDBC
( 22.15).
Swing, ,
J T a b l e .
DBResultsTableModel model = new DBResultsTableModel(results);
JTable table = new JTable(model);
, , JTable JFrame
, JFrame.
22.14. QueryViewer. Java
package cwp;
import
import
import
import
/
*
*
*
java.awt.*;
Java.awt.event.*;
javax.swing.*;
javax.swing.table.*;
.
Oracle
Sybase database,
JTable.
V
public class QueryViewer extends JFrame
implements ActionListener{
public static void main(String[] args) {
new QueryViewer0 ;
}
private JTextField hostField, dbNameField,
queryField, usernameField;
private JRadioButton oracleButton, sybaseButton;
private JPasswordField passwordField;
private JButton showResultsButton;
private Container contentPane;
private JPanel tablePanel;
public QueryViewer () {
super("Database Query Viewer");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
contentPane = getContentPane();
contentPane.add(makeControlPanel(), BorderLayout.NORTH);
packO ;
setVisible(true);
}
/**
*
*
*
*
*
Show Results
<Enter> ,
,
,
JTable ,
.
22.5.
1043
1044
2 2 . JDBC
(BorderFactory.createTitledBorder("Query Results"));
return(panel);
// , ,
// .
private JPanel makeControlPanel() {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(makeHostPanel());
panel.add(makeUsernamePanel());
panel.add(makeQueryPanel());
panel.add(makeButtonPanel());
panel.setBorder
(BorderFactory.createTitledBorder("Query Data"));
return(panel);
}
// , DB Name
// , .
// .
private JPanel makeHostPanel() {
JPanel panel = new JPanel();
panel.add(new JLabel("Host:"));
hostField = new JTextField(15);
panel.add(hostField);
panel.add(new JLabel("
DB Name:"));
dbNameField = new JTextField(15);
panel.add(dbNameField);
panel.add(new JLabel("
Driver:"));
ButtonGroup vendorGroup = new ButtonGroup();
oracleButton = new JRadioButton("Oracle", true);
vendorGroup.add(oracleButton) ;
panel.add(oracleButton);
sybaseButton = new JRadioButton("Sybase");
vendorGroup.add(sybaseButton);
panel.add(sybaseButton);
return(panel) ;
}
// ,
// .
// .
private JPanel makeUsernamePanel() {
JPanel panel = new JPanel();
usernameField = new JTextField(10);
passwordField = new JPasswordField(10);
panel.add(new JLabel("Username: " ) ) ;
panel.add(usernameField);
panel.add(new JLabel("
Password:"));
panel.add(passwordField) ;
return(panel) ;
}
22.5.
// , .
// .
private JPanel makeQueryPanel() {
JPanel panel = new JPanel();
queryField = new JTextField(40);
queryField.addActionListener(this) ;
panel.add(new JLabel("Query:"));
panel.add(queryField);
return(panel);
// , Show Results.
// .
private JPanel makeButtonPanel() {
JPanel panel = new JPanel();
showResultsButton = new JButton("Show Results");
showResultsButton.addActionListener(this);
panel.add(showResultsButton);
return(panel);
}
// .
private JLabel makeErrorLabel() {
JLabel label = new JLabel("No Results", JLabel.CENTER)
label.setFont(new Font("Serif", Font.BOLD, 36));
return(label);
}
1045
1046
22. JDBC
22.6.
SQL-,
SQL-
( ) .
, ,
.
.
, setXxx (, s e t I n t ,
s e t S t r i n g ) . , .
executeQuery ( R e s u l t S e t ) e x e c u t e /
e x e c u t e U p d a t e ( ) ,
. ,
,
employees, :
Connection connection =
D r i v e r M a n a g e r . g e t C o n n e c t i o n ( u r l , u s e r , password);
String template =
"UPDATE employees SET s a l a r y = ? WHERE i d = ?";
PreparedStatement statement =
connection.preparestatement(template);
f l o a t [] newSalaries = getNewSalaries ( ) ;
i n t [ ] employeelDs = g e t l D s O ;
f o r ( i n t i=0; i<employeeIDs.length; i++) {
statement.setFloat(l, newSalaries[i]);
statement.setint(2, employeelDs[i]);
statement.execute();
}
, ,
, . , 22.16
, 40 ,
, 40
. ,
Internet 28,8 Oracle,
. , 40 , -
22.6.
1047
,
17,5 , 40 35 .
Oracle
,
70 (0,22
0,31 ).
Sybase
, .
,
D r i v e r U t i l i t i e s . J a v a 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 / ,
P r e p a r e d S t a t e m e n t s .
2 2 . 1 6 . P r e p a r e d S t a t e m e n t s . j a v a
p a c k a g e cwp;
import
/**
*
*
*
*
java.sql.*;
,
,
.
.
1048
22. JDBC
if (connection != null) {
doPreparedStatements(connection, print);
doRawQueries(connection, print);
}
}
private static void doPreparedStatements(Connection conn,
boolean print) {
try {
String queryFormat =
"SELECT lastname FROM employees WHERE salary > ?";
PreparedStatement statement =
conn.preparestatement(queryFormat);
long startTime = System.currentTimeMillis();
for(int i=0; i<40; i++) {
statement. setFloatd, i*5000) ;
ResultSet results = statement.executeQuery();
if (print) {
showResults(results);
}
}
long stopTime = System.currentTimeMillis();
double elapsedTime = (stopTime - startTime)/1000.0;
System.out.println("Executing prepared statement " +
"40 times took " +
elapsedTime + " seconds.");
} catch(SQLException sqle) {
System.out.println("Error executing statement: " + sqle);
}
}
public static void doRawQueries(Connection conn,
boolean print) {
try {
String queryFormat =
"SELECT lastname FROM employees WHERE salary > ";
Statement statement = conn.createStatement();
long StartTime = System.currentTimeMillis();
for(int i=0; i<40; i++) {
ResultSet results =
statement.executeQuery(queryFormat + (i*5000));
if (print) {
showResults(results);
}
}
long StopTime = System.currentTimeMillis();
double elapsedTime = (stopTime - startTime)/1000.0;
System.out.println("Executing raw query " +
"40 times took " +
elapsedTime + " seconds.");
} catch(SQLException sqle) {
System.out.println("Error executing query: " - sqle);
}
}
private static void showResults(ResultSet results)
22.6.
1049
throws SQLException {
while(results.next ) {
System.out.print(results.getString(1) + " " ) ;
}
System.out.println();
}
private static Connection getConnection(String driver,
String url,
String username,
String password) {
try {
Class.forName(driver);
Connection connection =
DriverManager.getConnection(url, username, password);
return(connection);
} catch(ClassNotFoundException cnfe) {
System.err.println("Error loading driver: " + cnfe);
return(null);
} catch(SQLException sqle) {
System.err.println("Error connecting: " + sqle);
return(null);
}
}
private static void printUsageO {
System.out.println("Usage: PreparedStatements host " +
"dbName username password " +
"oracle I Sybase [print].");
}
22.7.
JDBC ,
Java, .
, ,
.
JDBC
, , SQL . ,
SQL-, .
SQL- ; ,
, .
JDBC .
, ,
. JDBC-
, , JSP.
; JSP
, ,
, , .
XML-
...
XML- Document
Object Model (DOM) Level 2.
DOM
XML- JTree.
, XML-,
Simple ! for XML Parsing (SAX) 2.0.
XML- SAX.
SAX.
L- XSLT.
XSLT
JSP.
Java API for XML Processing (JAXP).
Sly\ZJ^^
ML "" ,
.
,
, 2- ,
. XML
SOAP (Simple Object Access Protocol
).
XML- ,
, . DTD
(Document Definition )
, ,
. XML ,
, XML-, .
XML , Java .
Java =
XML =
XML-;
Java. ,
Java XML- DOM (Document Object Model
), SAX (Simple API for XML API XML) XSLT
(Extensible Style sheet Language for Transformations
).
X M L L
http://www.w3.org/TR/REC-xml
Web- S u n , XML Java
http://Java.sun.com/xml/
1052
23. XML-
WWW C o n s o r t i u m XML
http://www.w3.org/XML/
A p a c h e X M L Project
http://xml.apache.org/
, XML
http://xml.coverpages.org/
O'Reilly X M L R e s o u r c e C e n t e r
http://www.xml.com/
2 3 . 1 . XML-
DOM Level 2
DOM (Document Object Model) XML-
, Java-.
DOM
. ,
,
. 23.3
, XML-.
DOM Java 2 Standard Edition, API
JSP. , DOM,
. .
1. DOM- .
Java-, DOM Level 2 API.
h t t p : / / w w w . x m l . c o m / p u b / r g / J a v a _ P a r s e r s .
Apache Xerces-J.
DOM API Javadoc.
2. Java API XML (JAXP). API
"" DOM ,
, .
API h t t p : / / J a v a . s u n . c o m / x m l / .
3. DOM
CLASS PATH. Apache Xerces, CLASS PATH
x e r c e s _ i n s t a l l _ d i r \ x e r c e s . j a r . ,
Windows CLASS PATH :
set CLASSPATH=xerces_install_dir\xerces.jar;%CLASSPATH%
1053
DOM JSP,
JAR- l i b , JAR ( j -xvf) c l a s s e s
CLASS PATH;
.
4. CLASSPATH JAXP.
i a x p i n s t a l l d i r / j a x p . j a r . , Unix/Linux
s h e l l :
s e t e n v CLASSPATH j a x p _ i n s t a l l _ d i r / j a x p . j a r : $ C L A S S P A T H
JSP , .
5. DOM Level 2 JAXP API.
DOM http://www.w3.org/TR/D0ML e v e l - 2 - C o r e / , API Javadoc .
Apache Xerces
JAXP SAX (. 23.3).
6. JAXP.
h t t p : / / J a v a . s u n . c o m / x m l / j a x p - l _ l ~ s p e c . p d f .
DOM,
: XML- DOM
. ,
.
1. ,
. :
p a r s e r s . D o c u m e n t B u i l d e r F a c t o r y , j r e _ d i r / l i b / j a x p .
p r o p e r t i e s , J2EE Sei"vices API , -INF/
s e r v i c e s / j a v a x . x m l . p a r s e r s . DocumentBuilderFactory. ,
,
. DocumentBuilderFactory.
,
-D. ,
Apache Xerces.
public static void main(String[] args) {
String jaxpPropertyName =
"j avax.xml.parsers.DocumentBuilderFactory" ;
if {System.getProperty{jaxpPropertyName) == null) {
String apacheXercesPropertyValue =
"org.apache.xerces.jaxp.DocumentBuilderFactorylmpl";
System.setProperty(jaxpPropertyName,
apacheXercesPropertyValue);
}
1054
23. XML-
2. JAXP- .
XML.
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newlnstance();
DocumentBuilder b u i l d e r
builderFactory.newDocumentBuilder();
,
s e t N a m e s p a c e A w a r e s e t V a l i d a t i n g D o c u m e n t B u i l d e r F a c t o r y .
3. Document,
XML-. p a r s e
. , URI
( ) o r g . x m l . s a x . I n p u t S o u r c e .
Document ,
.
document.getDocumentElement().normalize();
5. .
E l e m e n t , Node,
XML-.
2 3 . 2 . DOM...
1055
23.2. DOM:
L-
JTree
23.1 XMLTree,
XML- J T r e e .
, ,
. .
1. XML-,
. , , . 1-5
, .
2. J T r e e . XML-
( n o d e .
g e t A t t r i b u t e s ) , ,
(getNodeName), ,
. ( g e t L e n g t h ,
n o d e . g e t A t t r i b u t e s , 0),
.
3. g e t C h i l d N o d e s ,
, J T r e e
.
4. , ,
.
23.2 , J T r e e
J F r a m e . , XML-
.
Java -Djavax.xml.parsers.DocumentBuilderFactory=xxx XMLFrame
-D , Apache Xerces. XML-
, ,
J F i l e C h o o s e r . E x t e n s i o n F i l e F i l t e r ,
23.3, , J F i l e C h o o s e r , ^
xml t I d ( JSP).
. 23.1 , p e r e n n i a l s . xml
( 23.4; DTD- 23.5). . 23.2 23.3
.
XML- DTD-, Xerces-J
DTD, .
p e r e n n i a l s . d t d , d t d s ,
XMLTree, DOCTYPE
p e r e n n i a l s . xml :
<!DOCTYPE perennials SYSTEM "dtds/perennials.dtd">
1056
23. XML-
Lookin.
iCWP-Code
^
jii ^ ^ 1 Jil
\ cwp-taglib.tid
|i*) orders.xml
iifi] teslxml
fi^mme:
jperenmalsx-mi
Fileo oftyp?
y'Mi .
Opt-n
zi
^^^^
'^^ 1
. 23. / . XML J F i l e C h o o s e r ,
E x t e n s i o n F i l e F i l t e r
^E;\CWP2\XML-Code\CWP-Code\p
S perennials
* ._] ciaylily(status=in-stock)
+
5 daylily (status=in-stock)
+ ..J daylily (status=sold-out)
+
I daylily (status=in-stock)
> i daylily (status=limited)
. 23.2. JTree-
p e r e n n i a l s .xml (
23.4)
^E:\CWP2\XML-Code\CWP-Code\perennials.xmliililO
^ perennials
>4 daylily (status=in-stock)
* cultlvar
*' , J award
- _J award
# name (note=snnall-flowered)
year
+
I award
bloom (code=M)
* cost(currency^US, dlscount=3)
+
; d ay 11 ly (statu s=i n- sto k)
- ^ daylily (status=sold-ou^
* cultivar
% award
* name
year
bloom (code=E)
* cost(currency=US)
. 23.3. JTree-
perennials .xml,
23.1.XMLTree.java
import
import
import
import
import
import
/**
*
*
*
java.awt.*;
javax.swing.*;
javax.swing.tree.*;
java.io.*;
org.w3c.dom.*;
javax.xml.parsers.^;
JTree,
XML-,
. DOM.
V
public class XMLTree extends JTree {
public XMLTree(String filename) throws lOException {
this(filename, new FileInputStream(new File(filename)))
23.2. DOM...
}
public XMLTree(String filename, InputStream in) {
super(makeRootNode(in));
}
// static,
/ /
// (super). .
private static DefaultMutableTreeNode
makeRootNode(InputStream in) {
try {
// JAXP DocumentBuilderFactory
// DOM.
//
// javax.xml.parsers.DocumentBuilderFactory
// ( Java-,
// -D)
// jre_dir/lib/jaxp.properties.
DocumentBuilderFactory builderFactory =
DocvimentBuilderFactory. newlnstance () ;
DocumentBuilder builder =
builderFactory.newDocumentBuilder();
// DOM-. parse
//
// Document. ,
// ( ) JTree.
Document document = builder.parse(in);
document.getDocumentElement().normalize();
Element rootElement = document.getDocumentElementO;
DefaultMutableTreeNode rootTreeNode =
buildTree(rootElement);
return(rootTreeNode) ;
} catch(Exception e) {
String errorMessage =
"Error making root node: " + e;
System.err.println(errorMessage);
e.printStackTrace();
return(new DefaultMutableTreeNode(errorMessage));
}
}
private static DefaultMutableTreeNode
buildTree(Element rootElement) {
// JTree,
// JTree
// . addChildren
// .
DefaultMutableTreeNode rootTreeNode =
new DefaultMutableTreeNode(treeNodeLabel(rootElement)) ;
addChildren(rootTreeNode, rootElement);
return(rootTreeNode);
}
private static void addChildren
(DefaultMutableTreeNode parentTreeNode,
1057
1058
23. -
Node parentXMLElement) {
// ,
// .
/ / : ,
// XML-, ,
// JTree.
// ,
// Jtree, in the
// "tree". , "childElement" -
// XML-, "childTreeNode" - JTree-.
// ,
// , XML JTree.
NodeList childElements =
parentXMLElement.getChildNodes();
for(int i=0; i<childElements.getLength(); i++) {
Node childElement = childElements.item(i);
if (!(childElement instanceof Text ||
childElement instanceof Comment)) {
DefaultMutableTreeNode childTreeNode =
new DefaultMutableTreeNode
(treeNodeLabel(childElement));
parentTreeNode.add(childTreeNode);
addChildren(childTreeNode, childElement);
}
}
}
// XML- , JTree
// XML-.
/ /
// XML-.
23.2. DOM...
~
JTree. ,
.
:
Java -Djavax.xml.parsers.DocumentBuilderFactory=xxx XMLFrame
, Apache Xerces.
XML ;
, JFileChooser
.
//
//
//
if
}
String filename;
if (args.length > 0) {
filename = args[0];
} else {
String[] extensions = { "xml", "tld" };
WindowUtilities.setNativeLookAndFeel();
filename = ExtensionFileFilter.getFileName(".",
"XML Files",
extensions);
if (filename == null) {
filename = "test.xml";
}
}
new XMLFrame(filename);
public XMLFrame(String filename) {
try {
WindowUtilities.setNativeLookAndFeel();
JTree tree = new XMLTree(filename);
JFrame frame = new JFrame(filename);
frame.addWindowListener(new ExitListener()
Container content = frame.getContentPane() .
1059
1060
2 3 . XML-
content.add(new JScrollPane(tree));
frame.() ;
frame.setVisible(true);
} catch(lOException ioe) {
System.out.println("Error creating tree: " + ioe)
}
Java.io.File;
java.util.*;
javax.swing.*;
javax.swing.filechooser.FileFilter;
FileFilter ,
. getFileName
JFileChooser.
<>
Sun SwingSet.
23.2. DOM...
return(getFileName(initialDirectory, description,
extensions, mode));
}
public static String getFileName(String initialDirectory,
String description.
String[] extensions) {
return(getFileName(initialDirectory, description,
extensions, LOAD));
}
/
*
*
*
*
*
JFileChooser,
. SAVE
Save;
Open.
String, . ,
Cancel, null.
V
public static String getFileName(String initialDirectory,
String description,
String[] extensions,
int mode) {
ExtensionFileFilter filter = new ExtensionFileFilter();
filter.setDescription(description);
for(int i=0; i<extensions.length; i++) {
String extension = extensions[i];
filter.addExtension(extension, true);
}
JFileChooser chooser =
new JFileChooser(initialDirectory);
chooser.setFileFilter(filter);
int selectVal = (mode==SAVE) ? chooser.showSaveDialog(null)
: chooser.showOpenDialog(null);
if (selectVal == JFileChooser.APPROVE_OPTION) {
String path = chooser.getSelectedFile().getAbsolutePath();
return(path);
} else {
JOptionPane.showMessageDialog(null, "No file selected.");
return(null);
}
}
public void addExtension(String extension,
boolean caselnsensitive) {
if (caselnsensitive) {
extension = extension.toLowerCase();
}
if (!extensionsTable.containsKey(extension)) {
extensionsTable.put(extension,
new Boolean(caselnsensitive));
if (extension.equals("*") ||
extension.equals("*.*") I I
extension.equals(".*")) {
allowAll = true;
}
}
1061
1062
23. XML-
23.4. perennials.xml
<?xml version="1.0" ?>
<!DOCTYPE perennials SYSTEM
"http://archive.corewebprogramming.com/dtds/perennials.dtd">
<perennials>
<daylily status="in-stock">
<cultivar>Luxury Lace</cultivar>
<award>
<name>Stout Medal</name>
<year>1965</year>
</award>
<award>
<name note="small-flowered">Annie T. Giles</name>
23.2. DOM...
<year>1965</year>
</award>
<award>
<name>Lenington All-American</name>
<year>1970</year>
</award>
<bloom code="M">Midseason</bloom>
<cost discount="3" currency="US">ll.75</cost>
</daylily>
<daylily status="in-stock">
<cultivar>Green Flutter</cultivar>
<award>
<name>Stout Medal</naine>
<year>197 6</year>
</award>
<award>
<name note="small-flowered">Annie T. Giles</name>
<year>1970</year>
</award>
<bloom code="M">Midseason</blooiTi>
<cost discount="3+" currency="US">7.50</cost>
</daylily>
<daylily status="sold-out">
<cultivar>My Belle</cultivar>
<award>
<name>Stout Medal</name>
<year>1984</year>
</award>
<bloom code="E">Early</bloom>
<cost currency="US">12.00</cost>
</daylily>
<daylily status="in-stock">
<cultivar>Stella De Oro</cultivar>
<award>
<name>Stout Medal</name>
<year>1985</year>
</award>
<award>
<name note="miniature">Donn Fishcer Memorial Cup</name>
<year>197 9</year>
</award>
<bloom code="E-L">Early to Late</bloom>
<cost discount="10+" currency="US">5.00</cost>
</daylily>
<daylily status="limited">
<cultivar>Brocaded Gown</cultivar>
<award>
<name>Stout Medal</name>
<year>198 9</year>
</award>
<bloom code="E">Early</bloom>
<cost currency="US" discount="3+">14.50</cost>
</daylily>
</perennials>
1063
1064
23. XML-
23.5. p e r e n n i a l s . d t d
<?1 v e r s i o n = " 1 . 0 " encocling="ISO-8859-l" ?>
<!ELEMENT perennials (daylily)*>
<!ELEMENT daylily (cultivar, award*, bloom, cost)+>
<!ATTLIST daylily
status (in-stock I limited | sold-out) #REQUIRED>
<!ELEMENT cultivar (#PCDATA)>
<!ELEMENT award (name, year)>
<!ELEMENT name (#PCDATA)>
<!ATTLIST name
note CDATA #IMPLIED>
<!ELEMENT year (#PCDATA)>
<!ELEMENT bloom (#PCDATA)>
<!ATTLIST bloom
code (E I EM I M I ML I L I E-L) #REQUIRED>
<!ELEMENT cost (#PCDATA)>
<!ATTLIST cost
discount CDATA #IMPLIED>
<!ATTLIST cost
currency (US i UK | CAN) "US">
23.3. XML-
SAX 2.0
DOM XML- ,
DOM ;
. DOM
, ,
. , ,
XML-, .
DOM ,
. SAX,
, .
, SAX,
. , ,
<language r a t i n g = " g o o d " >
</language>, (
, Java,
). ,
1065
. ?
XML SAX
(. 20.7).
SAX Java 2 Standard Edition, API
JSP. , SAX,
, ..
.
1. SAX- .
Java-, SAX 2 API.
h t t p : / / w w w . x m l . c o m / p u b / r g / J a v a _ P a r s e r s .
Apache Xerces-J.
SAX API Javadoc.
2. Java SAX XML (JAXP). API
"" SAX,
, . API
h t t p : / / J a v a , s u n . c o m / x m l / .
3. SAX
CLASSPATH. Apache Xerces, CLASS PATH
x e r c e s i n s t a l l d i r X x e r c e s . j a r . ,
Windows CLASSPATH
set
CLASSPATH=xerces_install_dir\xerces.jar;%CLASSPATH%
SAX JSP,
JAR- l i b , JAR-
( j a r - x v f ) c l a s s e s
CLASSPATH;
.
4. CLASSPATH JAXP.
j a x p i n s t a l l d i r / j a x p . j a r . , U N I X / L i n u x
shell :
s e t e n v CLASSPATH
jaxp_install_dir/jaxp.jar:$CLASSPATH
JSP , .
5. SAX 2 JAXP API.
API h t t p : / / w w w . m e g g i n s o n , c o m / S A X / J a v a /
j a v a d o c / , API Apache Xerces .
SAX h t t p : / / w w w .
megginson.com/SAX/.
1066
2 3 . XML-
SAX,
:
. ,
.
1. , .
:
j a v a x . x m l . p a r s e r s . SAX-ParserFactory, j r e _ d i r / l i b / j a x p .
p r o p e r t i e s , J2EE Services API , -INF/
s e r v i c e s / j a v a x . x m l . p a r s e r s . SAX-ParserFactory. ,
, .
,
-D.
, Apache Xerces.
public static void main(String[] args) {
String jaxpPropertyName =
"javax.xml.parsers.SAXParserFactory";
if (System.getProperty(jaxpPropertyName) == null) {
String apacheXercesPropertyValue =
"org.apache.xerces.j axp.SAXParserFactorylmpl";
System.setProperty(jaxpPropertyName^
apacheXercesPropertyValue);
}
}
2. .
, .
SAXParserFactory f a c t o r y = S A X P a r s e r F a c t o r y . n e w l n s t a n c e ( ) ;
SAXParser p a r s e r = f a c t o r y . n e w S A X P a r s e r ( ) ;
,
setNamespaceAware s e t V a l i d a t i n g SAXParserFactory.
3. .
D e f a u l t Handler;
.
startDocument, endDocument
,
. .
startElement, endElement
1067
. s t a r t E l e m e n t
: URI ( S t r i n g ;
, ),
( S t r i n g ; ),
( S t r i n g ,
p r e f i x r m a i n N a m e , , , mainName)
A t t r i b u t e s , ,
. e n d E l e m e n t ,
.
characters, ignoreableWhitespace
.
: ,
. , S t r i n g ,
.
4.
. p a r s e ,
, URI, , o r g . x m l .
s a x . I n p u t - S o u r c e , a .
parser.parse(filename, handler);
23.4. SAX:
XML-
23.7 ,
XML-: ,
.
, .
.
, .
startElement
,
. , , .
.
i n d e n t a t i o n .
i n d e n t a t i o n 2 (
0).
endElement
i n d e n t a t i o n 2,
, .
characters
c h a r a c t e r s ; ,
i n d e n t a t i o n , .
1068
23. XML-
23.8 ,
SAX- XML-, ,
(. 23.7). . 23.4
, 23.6
orders . xml (. 23.9).
!
Lookr: ,
JjCWP-Code
"3 ^ ^ j ^ i g p l
.:?^Yt^r?i^
Ilia) cwp-tagllb-Md
| i | perennials.xml
1 *il test.xml
fmmme:
[orders xmi
fl^of^C
|XML Files
Open
'^i
l^iw^ 1 1
9.95
End tag: price
Start tag: yacht
Start tag: manufacturer
Luxury...
End tag: manufacturer
Start tag: model
M-1
End tag: model
Start tag: standardFeatures (oars=plastic, lifeVests=none)
false
End tag: standardFeatures
End tag: yacht
End tag: order
... ( )
End tag: orders
23.7. PrintHandleroava
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.util.StringTokenizer;
/**
*
*
*
,
,
.
.
, ,
.
,
.
1069
1070
23. XML-
System.out.print(", " ) ;
}
System.out.print(attributes.getQName(i) + "=" +
attributes.getValue(i));
}
System.out.print(")");
}
System.out.println();
indentation = indentation + 2;
/** , ,
* .
*/
public void endElement(String namespaceUri,
String localName,
String qualifiedName)
throws SAXException {
indentation = indentation - 2;
indent(indentation);
System.out.println("End tag: " + qualifiedName);
/** . */
public void characters(char[] chars,
int startlndex,
int endlndex) {
String data = new String(chars, startlndex, endlndex);
/ / StringTokenizer
// .
StringTokenizer tok = new StringTokenizer(data);
if (tok.hasMoreTokens0) {
indent(indentation);
System.out.print(tok.nextToken());
if (tok.hasMoreTokens0) {
System.out.println("...");
} else {
System.out.println0;
}
}
}
private void indent(int indentation) {
for(int i=0; i<indentation; i++) {
System.out.print (" " ) ;
}
}
}
23.8.SAXPrinter.Java
import j a v a x . x m l . p a r s e r s . * ;
import o r g . x m l . s a x . * ;
import org.xml.sax.helpers.*;
/** , SAX
* -,
* .
public class SAXPrinter {
public static void main(String[] args) {
String jaxpPropertyName =
"javax.xml.parsers.SAXParserFactory";
//
// 01 -D. ,
// Apache,
if (System.getProperty(jaxpPropertyName) == null) {
String apacheXercesPropertyValue =
"org.apache.xerces.jaxp.SAXParserFactoryImpl";
System.setProperty(j axpPropertyName,
apacheXercesPropertyValue);
}
String filename;
if (args.length > 0) {
filename = args[0];
} else {
String!] extensions = { "xml", "tld" };
WindowUtilities.setNativeLookAndFeel();
filename = ExtensionFileFilter.getFileName(".",
"XML Files",
extensions);
if (filename == null) {
filename = "test.xml";
}
}
printOutline(filename);
System.exit(0);
}
public static void printOutline(String filename) {
DefaultHandler handler = new PrintHandler();
SAXParserFactory factory = SAXParserFactory.newlnstance<)
try {
SAXParser parser = factory.newSAXParser();
parser.parse(filename, handler);
} catch(Exception e) {
String errorMessage =
"Error parsing " + filename + ": " + e;
System.err.println(errorMessage);
e.printStackTrace ();
}
}
1071
1072
2 3 . XML-
23.5. SAX:
1073
<isbn>0130897 930</isbn>
<title>Core Web Programming Second Edition</title>
<authors>
<author>Marty Hall</author>
<author>Larry Brown</author>
</authors>
</book>
</order>
</orders>
23.5. SAX:
SAX DOM ,
SAX ; ,
, .
XML-, :
<orders>
<count>23</count>
<book>
<isbn>0130897 930</isbn>
</book>
</orders>
, ISBN
. ,
. SAX, DOM,
, ,
. ,
, i s b n count.
count ,
, i s b n ISBN .
,
.
startElement
, count
i s b n . , ,
c h a r a c t e r s ,
.
endElement
endElement , count
i s b n . , ,
s t a r t E l e m e n t .
1074
23. XML-
characters
c o u n t , ,
i n t i s b n .
i s b n ,
ISBN.
c o u n t
, .
endDocument
. 250
, .
C o u n t B o o k s ( 23.11) XML- ,
.
C o u n t H a n d l e r . . 23.5 , . 23.6
o r d e r s . xml (. 23.9).
Is^iifW.!
Look In:
jljCWP-Code
"3 j _gj d^ s p
_] cwp-taglib.tid
\ perennialsj<ml
3 test.xml
^Message
FBe name:
|ordersj<mP
FHesoftyp6t
|xML Files
. 23.5.
-T]
orders.xml
. 23.6.
orders.xml
CountBooks
org.xml.sax.^;
org.xml.sax.helpers.*;
java.util.StringTokenizer;
javax.swing.*;
,
. ,
:
<>
<count>23</count>
<book>
<isbn>01308 97 930</isbn>
</book>
</>
, ,
23.5. SAX:
V
public class CountHandler extends DefaultHandler {
private boolean collectCount = false;
private boolean collectlSBN = falserprivate int currentCount = 0;
private int totalCount = 0;
/**
* count isbn ,
* characters .
V
public void startElement(String namespaceUri,
String localName,
String qualifiedName,
Attributes attributes)
throws SAXException {
if (qualifiedName.equals("count")) {
collectCount = true;
currentCount = 0;
} else if (qualifiedName.equals("isbn")) {
collectlSBN = true;
}
}
/**
* count isbn .
* characters .
V
public void endElement(String namespaceUri,
String localName,
String qualifiedName)
throws SAXException {
if (qualifiedName.equals("count")) {
collectCount = false;
} else if (qualifiedName.equals("isbn")) {
collectlSBN = false;
}
/**
*
*
*
*
*
count book
( isbn),
,
count. ,
isbn ISBN , ,
count, .
1075
1076
23. XML-
23.11.CountBooks.Java
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
/** .
* , :
<>
...
*
*
*
<count>23</count>
<book>
<isbn>0130897 930</isbn>
*
*
*
</book>
</>
.
1077
1078
23. XML-
XSLT , XML-
. ,
XML, ,
(HTTP WAP),
HTML WML.
XSLT .
,
, .
XSLT, XSL XPath WWW Consortium.
:
XSLT L 0
http://www.w3.org/TR/xslt.html
XSL LO
http://www.w3.org/TR/xsl/
XPath LO
http://www.w3.org/TR/xpath.html
, XSLT, XSL XPath ,
URL h t t p : / / w w w . w 3 . o r g / S t y l e / X S L / . , GoXML
XSLT-, h t t p : //www. x s l t . com/.
XSLT Java 2 Standard Edition, API
JSP. , XSLT,
, ..
.
L XSLT- .
Java-, XSLT LO.
XSLT h t t p : / / w w w . w 3 . o r g / S t y l e / X S L /
h t t p : / / w w w . x s l t . c o m / x s l t _ t o o l s _ e n g i n e s . h t m .
Apache Xalan-J ( h t t p : / / x m l . a p a c h e . o r g /
xalan-j /).
2. CLASSPATH DOM SAX.
XSLT DOM SAX. Apache Xalan-J
CLASSPATH x e r c e s . j a r . Apache
Xalan-J 23.1 23.3. , x e r c e s . j a r
Apache Xalan-J.
3. CLASSPATH XSLT.
Xalan x a l a n _ i n s t a l l _ d i r \ x a l a n . j a r .
, Windows
set
CLASSPATH=xalan_install_dir\xalan.jar;
%CLASSPATH%
1079
UNIX/Linux shell :
1080
23. -
, XSL- S t r e a m S o u r c e .
S t r e a m S o u r c e XSL4j)apuia
F i l e , R e a d e r I n p u t S t ream, , ,
URI.
4. .
t r a n s f o r m ,
S t r e a m S o u r c e
R e s u l t , .
S o u r c e xml = new S t r e a m S o u r c e ( x m l S t r e a m ) ;
R e s u l t r e s u l t = new S t r e a m R e s u l t ( o u t p u t S t r e a m ) ;
tranformer.transform(xml,
result);
XSL, XML-
S t r e a m S o u r c e , F i l e , R e a d e r ,
I n p u t s t r e a m , URI. S t r e a m R e s u l t
F i l e , W r i t e r , O u t p u t S t r e a m URI.
23.12 , XSLT-
. XML- XSL- R e a d e r F i l e ,
W r i t e r F i l e .
R e a d e r W r i t e r
, .
S t r i n g R e a d e r C h a r A r r a y R e a d e r ,
S t r i n g W r i t e r C h a r A r r a y W r i t e r . ,
XML-,
XSLT- ,
HTML-.
XML-, .
2 3 . 1 2 . X s l T r a n s f o r m e r . j a v a
p a c k a g e cwp;
import
import
import
import
/**
*
*
*
javax.xml.transform.*;
javax.xml.transform.stream.*;
java.io.*;
java.util.*;
XSLT- XML-.
.
XSLT, DOM SAX ,
.
V
public class XslTransformer {
private TransformerFactory factory;
public XslTransformer() {
factory = TransformerFactory.newlnstance0;
}
/**
*
*
*
*
*
*
*
*
XML- XSL-,
<code>Reader</code>.
<code>Writer</code>.
XML-
String (<code>StringReader</code>) ,
, .
String (<code>StringWriter</code>)
<code>JSPWriter</code>.
V
public void process(Reader xmlFile, Reader xslFile,
Writer output)
throws TransformerException {
process(new StreamSource(xmlFile),
new StreamSource(xslFile),
new StrecunResuit (output) ) ;
}
/**
*
*
*
*
*
*/
XML- XSL-,
<code>File</code>,
<code>Writer</code>.
String
(<code>StringWriter</code)>
<code>JSPWriter</code>.
<code>aa</code> XML
<code>aa</code> XSL.
<code>OutputStream</code>.
<code>FileOutputStream</code>
<code>ByteArrayOutputStream</code>.
V
public void process(File xmlFile, File xslFile,
OutputStream out)
throws TransformerException {
process(new StreamSource(xmlFile),
new StreamSource(xslFile),
new StreamResult(out));
}
/**
*
*
*
1081
1082
23. XML-
23.7. XSLT:
23.13 ,
Swing. () XML, XSL- ,
XSLT. XML-, XSL-,
. Document
, J E d i t o r P a n e (.
23.14). XML- XSL- ,
XSLT- HTML-. XML XSL- XSLT- XML. , XSL-,
HTML- XSLT-.
2 3 . 1 3 . X s l t E x a m p I e . Java
import
import
import
import
import
import
import
/k-k
*
*
*
*
*
*
javax.xml.transform.*;
java.awt.*;
Java.awt.event.*;
javax.swing.*;
javax.swing.event.*;
java.io.*;
cwp.XslTransformer;
, XML- XSL-
XSLT HTML-.
:
XML- ,
XSL- ( )
HTML.
XML- XSL- XSLT
23.7. XSLT:
*
*
*
.
XML- XSL-,
.
V
public class XsltExample extends JFrame
implements ChangeListener {
private static final int XML = 0;
private static final int XSL = 1;
private static final int XSLT = 2;
private static final String DEFAULT_TITLE = "XSLT Example";
private static final String[] tabTitles =
{ "XML", "XSL", "XSLT" };
private static final String[] extensions =
{ "xml", "xsl", "html" };
private Action openAction, saveAction, exitAction;
private JTabbedPane tabbedPane;
private DocumentPane[] documents;
private XslTransformer transformer;
public XsltExample() {
super(DEFAULT_TITLE) ;
transformer = new XslTransformer();
WindowUtilities.setNativeLookAndFeel();
Container content = getContentPane{);
content.setBackground(SystemColor.control);
// .
JMenuBar menubar = new JMenuBar();
openAction = new OpenAction()
saveAction = new SaveAction{)
exitAction = new ExitAction()
JMenu fileMenu = new JMenu("File");
fileMenu.add(openAction);
fileMenu.add(saveAction);
fileMenu.add(exitAction);
menubar.add(fileMenu) ;
setJMenuBar(menubar) ;
// .
tabbedPane = new JTabbedPane();
documents = new DocumentPane[3];
for(int i=0; i<3; i++) {
documents[i] = new DocumentPane();
JPanel panel = new JPanelO;
JScrollPane scrollPane = new JScrollPane(documents[i]);
panel.add(scrollPane) ;
tabbedPane.add(tabTitles[i], scrollPane);
}
documents[XSLT].setContentType(DocumentPane.HTML);
// JEditorPane : setText
// HTML-,
// , CONTENT-TYPE.
// , setPage
// EditorKit. Xalan
/ / CONTENT-TYPE. ,
1083
1084
23. XML-
// ,
// CONTENT-TYPE.
documents[XSLT].loadFile("XSLT-Instructions.html");
documents[XSLT].setEditable(false);
tabbedPane.addChangeListener(this);
content.add(tabbedPane, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize (450, 350);
setVisible(true);
}
/** , .
* XML XSL ,
* XSLT .
public void stateChanged(ChangeEvent event) {
int index = tabbedPane.getSelectedlndex();
switch (index) {
case XSLT: if (documents[XML].isLoadedO &&
documents[XSL].isLoaded()) {
doTransform();
}
case XML:
case XSL: updateMenuAndTitle(index);
break;
default:
}
/**
*
*
*
XML- XSL-
(String), StringReader
XSLT-.
, .
V
private void doTransform() {
StringWriter strWriter = new StringWriter();
try {
Reader xmlInput =
new StringReader (docaents [XML] .getTextO) ;
Reader xslInput =
new StringReader(documents[XSL].getText());
transformer = new XslTransformer();
transformer.process(xmlInput, xsllnput, strWriter);
} catch(TransformerException te) {
JOptionPane.showMessageDialog(this,
"Error: " + te.getMessage0);
}
documents[XSLT].setText(strWriter.toString());
/** .
23.7. XSLT:
* ,
* . (Save, Load)
* .
*/
private void updateMenuAndTitle(int index) {
if ((index > -1) && (index < documents.length)) {
saveAction.setEnabled(documents[index].isLoaded()) ;
openAction.setEnabled(documents[index].isEditable());
String title = DEFAULT_TITLE;
String filename = documents[index].getFilename();
if (filename.length 0 > 0) {
title += " - [" + filename + " ] " ;
setTitle(title);
}
}
/
* ,
* .
*/
private void updateDocument(int mode) {
int index = tabbedPane.getSelectedlndex();
String description = tabTitles[index] + " Files";
String filename = ExtensionFileFilter.getFileName(".",
description,
extensions[index],
mode);
if (filename != null) {
if (mode==ExtensionFileFilter.SAVE) {
documents[index].saveFile(filename) ;
} else {
documents[index].loadFile(filename);
}
updateMenuAndTitle(index);
}
}
public static void main(String[] args) {
new XsltExample();
}
// Open,
// .
class OpenAction extends AbstractAction {
public OpenAction0 {
super("Open . . . " ) ;
}
public void actionPerformed(ActionEvent event) {
updateDocument(ExtensionFileFilter.LOAD);
}
}
// Save,
1085
1086
23. XML-
// , ,
class SaveAction extends AbstractAction {
public SaveAction0 {
super("Save");
setEnabled(false);
}
public void actionPerformed(ActionEvent event) {
updateDocument(ExtensionFileFilter.SAVE);
}
}
// Exit ,
class ExitAction extends AbstractAction {
public ExitAction0 {
super("Exit");
}
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
}
2 3 . 1 4 . DocijmentPane. Java
import
import
import
import
import
java.awt.*;
Java.awt.event.*;
javax.swing.*;
java.io.*;
java.net.*;
/** JEditorPane,
* .
* "text/plain" ( ) "text/html".
V
public class DocumentPane extends JEditorPane {
public static final String TEXT = "text/plain";
public static final String HTML = "text/html";
private boolean loaded = false;
private String filename
fi I I ,
/ , ,
* .
V
public void setPage(URL url) {
loaded = false;
try {
super.setPage(url);
File file = new File(getPage().toString());
setFilename(file.getName());
loaded = true;
} catch (lOException ioe) {
23.7. XSLT:
System.err.println("Unable to set page: " + url);
/** .
public void setText(String text) {
super.setText(text);
setFilename("");
loaded = true;
}
/** , .
*
*
*
*
, setPage JEditorPane
URL URL ,
, <></>
.
V
public void loadFile(String filename) {
try {
File file = new File(filename);
setPage(file.toURL());
} catch (lOException mue) {
System.err.println("Unable to load file: " + filename);
}
}
public void saveFile(String filename) {
try {
File file = new File(filename);
FileWriter writer = new FileWriter(file);
writer.write(getText ());
writer.close ();
setFilename(file.getName0);
} catch (lOException ioe) {
System.err.println("Unable to save file: " + filename);
}
}
/** . */
public String getFilename() {
return(filename);
}
/** , . */
public void setFilename(String filename) {
this.filename = filename;
}
/** true,
* <code>setPage</code>
1087
1088
2 3 . -
<code>setText</code>.
xsl:
output.
2 3 . 1 5 . p e r e n n i a l s . x s l
<?xml v e r s i o n = " 1 . 0 " ? >
<xsl:stylesheet version="l.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"
doctype-public ="-//W3C//DTD HTML 4.0 Transitional//EN"/>
<xsl:template match="/">
<HTML>
<HEAD>
<TITLE>Daylilies</TITLE>
</HEAD>
23.7. XSLT:
1089
<BODY>
<TABLE CELLPADDING^"3">
<CAPTION>Stout Medal Award</CAPTION>
<TR>
<TH>Year</TH>
<TH>Cultivar</TH>
<TH>Bloom Season</TH>
<TH>Cost</TH>
</TR>
< ! daylily,
award, name
Stout Medal. -->
<xsl:apply-templates
select="/perennials/daylily[award/nanie='Stout
Medal*]"/>
<TR>
<TD C0LSPAN="4" ALIGN="CENTER">
E-early M-midseason L-late</TD>
</TR>
</TABLE>
</BODY>
</HTML>
</xsl:template>
<xsl:template match="daylily">
<TR>
<TD><xsl:value-of select="award/year"/></TD>
<TD><xsl:value-of select="cultivar"/></TD>
< ! bloom. -->
<TD ALIGN="CENTER"><xsl:value-of
select="bloom/@code"/></TD>
<TD ALIGN="RIGHT"><xsl:value-of
select="cost"/></TD>
</TR>
</xsl:template>
</xsl:stylesheet>
p x . T Exampte -||>1^
..dSliSi
:)<ML|XSL|KSLT|
XML ^^SLJXSLTI
<'1'="1.0'*?>
<ID0CTYPE perenruals SYSTEM
"http (kiciavt corewri}progrananiiig.com/'dtds/peienniaJs.dtd''>
: <pereimials>
I <daylily status* "m-stock.">
<cultivr*Luxury L;</cultivar>
<?xinlveison="l,0'7>
<xsl stylesheet version-"! .0"
anhs xsl-"http://www.wr3.oisfl999SL/Tmisfonn">
<xsl:output mBthod="html"
doctype-pubhc "-//W3C//DTD HTML 4.0 Transitional//EN">
<xsl:tempkte match-T>
<HTML>
<HEAD>
<TITLE^Daylilies<n-ITLE>
<^EAD>
<>
<TABLE CELLPADDING-"3">
<CAPTION>Stout Medal Awird<CAPTION>
<nane>Stout Medal</Mnie>
<ye4i>1965<^er>
<fv/nrd>
<:awani>
< note="sxnall-ikwered">Aiuue T. Giles<ftiame>
<3reai1965</y4r>
<feward>
^
. 23.7. XML,
XML-,
p e r e n n i a l s .xml ( 23.4)
JPi xj
jf
. 23.8. XSL,
XSL-,
p e r e n n i a l s . x s l (23.15)
1090
23. XML-
|^-^^!'1^||
-lOlxlj
FISe
XML) XSL ><St^l
Stout Medal Award
Year
Cultivar
7.50
1984 MyBeUe
1200
1985 StdlaDeOro
1989 Brocaded Gown
11.75
E-L
5.00
1450
. 23.9. XSLT-
p e r e n n i a l s . 1 ( 23.4)
p e r e n n i a l s . x s l ( 23.15)
23.8. XSLT:
JSP-
XSLT-
JSP-. HTML- ,
. , Netscape 4.7
HTML- THEAD, TBODY TFOOT,
Internet Explorer 4.x (
2.4).
XML- p e r e n n i a l s .xml ( 23.4) .
, JavaServer Page
D a y l i l i e s . j s p ( 23.18). XSL- p e r e n n i a l s - i e . x s l (
23.16) Internet Explorer,
THEAD, TBODY TFOOT. - p e r e n n i a l s - n s . x s l ( 23.17)
Netscape.
, x s l t r a n s f o r m . t l d ,
23.19.
x s l t r a n s f o r m JSP D a y l i l i e s . j s p .
cwp. t a g s . X s l T r a n s f o r m T a g .
: xml ( XML-;
), x s l i e (XSL- Internet Explorer)
x s l n s (XSL- Netscape; ). ,
x s l n s ,
- Internet Explorer.
. 20.7.
X s l T r a n s f o r m T a g 23.20. d o S t a r t T a g
F i l e XML- XSL-, XSL-
U s e r - A g e n t , HTTP-.
XSLT-
X s l T r a n s f o r m e r ( 23.12), J s p W r i t e r .
2 3 . 8 . XSLT.
1091
,
. . 23.10
Tomcat. DTD- (
p e r e n n i a l s . d t d ) , 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 / d t d s / , , d t d s (. . 23.10)
DOCTYPE :
<!DOCTYPE p e r e n n i a l s
SYSTEM
"dtds/perennials.dtd">
cwp/Daylilies.jsp
L cwp-tags/xsltransform.tid
WEB-INF/classes/cwp/perennials.xml
perennials-ie.xml
perennials-ns.xsl
XslTransformer.class
U dtds/perennials.dtd
L tags/XslTransformTag.class
. 23.10. Tomcat
2 3 . 1 6 . p e r e n n i a l s - i e . x s l
<?xml v e r s i o n = " 1 . 0 " ? >
< ! THEAD, TBODY TFOOT. >
< ! Internet Explorer 4.x
. -->
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="l.0">
<xsl: output method="htrril"/>
<xsl:template match="/">
<TABLE CELLPADDING="3" RULES="GROUPS" ALIGN="CENTER">
<CAPTION>Stout Medal Award</CAPTION>
<COLGROUP>
<COL ALIGN="CENTER"/>
<COL ALIGN="LEFT"/>
1092
23. XML-
<COL ALIGN="CENTER"/>
</COLGROUP>
<COLGROUP ALIGN="RIGHT"/>
<THEAD>
<TR>
<TH>Year</TH>
<TH>Cultivar</TH>
<TH>Bloom Season</TH>
<TH>Cost</TH>
</TR>
</THEAD>
<TBODY>
< ! daylily,
award, name
Stout Medal. >
<xsl:apply-templates
select="/perennials/daylily[award/name= * Stout Medal"/>
</TBODY>
<TFOOT>
<TR>
<TD C0LSPAN="4">E-early M-midseason L-late</TD>
</TR>
</TFOOT>
</TABLE>
</xsl:template>
<xsl:template match="daylily">
<TR>
<TD><xsl:value-of select="award/year"/></TD>
<TD><xsl:value-of select="cultivar"/></TD>
<!-- bloom. >
<TD><xsl:value-of select="bloom/@code"/></TD>
<TD><xsl:value-of select="cost"/></TD>
</TR>
</xsl:template>
</xsl:stylesheet>
2 3 . 1 7 . p e r e n n i a l s - n s . x s l
<?xml version="l.0"?>
< ! ,
. >
< ! Netscape. -->
<xsl:stylesheet version="l."
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
<TABLE CELLPADDING="3" B0RDER="1" ALIGN="CENTER">
<CAPTION>Stout Medal Award</CAPTION>
<TR>
<TH>Year</TH>
<TH>Cultivar</TH>
<TH>Bloom Season</TH>
<TH>Cost</TH>
23.8. XSLT...
</TR>
< ! daylily,
award, name
Stout Medal. >
<xsl:apply-templates
select="/perennials/daylily[award/name=*Stout Medal']"/>
<TR>
<TD C0LSPAN="4" ALIGN="CENTER">
E-early M-midseason L-late</TD>
</TR>
</TABLE>
</xsl:template>
<xsl:template match="daylily">
<TR>
<TD><xsl:value-of select="award/year"/></TD>
<TD><xsl:value-of select="cultivar"/></TD>
< ! bloom. >
<TD ALIGN="CENTER"><xsl:value-of select="bloom/@code"/></TD>
<TD ALIGN="RIGHT"><xsl:value-of select="cost"/></TD>
</TR>
</xsl:template>
</xsl:stylesheet>
23.18.Daylilies.j sp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Daylilies</title>
</head>
<body>
<%@ taglib uri="cwp-tags/xsltransform.tld" prefix="cwp" %>
<H1 ALIGN="CENTER">Katie's Favorite Daylilies
<P>
<cwp:xsltransform xml='perennials.xml'
xslie='perennials-ie.xsl'
xslns='perennials-ns.xsl'
/>
</body>
</html>
23.19.xsltransform.tld
<?xml version="1.0" encoding="ISO-8859-l" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN'
"http://Java.sun.com/j2ee/dtds/web-jsptaglibrary_l_l.dtd">
<taglib>
1093
1094
23. XML-
<tlibversion>l.0</tlibversion>
<jspversion>l. /jspversion>
<shortname>cwp</shortname>
<urn></urn>
<info>
A tag library from Core Web Programming,
http://www.corewebprogramming.com/.
</info>
<tag>
<name>xsltransform</name>
<tagclass>cwp.tags.XslTransformTag</tagclass>
<info>Applies xslt transform based on browser type.</info>
<attribute>
<name>xml</name>
<required>yes</required>
</attribute>
<attribute>
<name>xslie</name>
<required>false</required>
</attribute>
<attribute>
<name>xslns</name>
<required>true</required>
</attribute>
</tag>
</taglib>
23.20.XslTransformTag.Java
package cwp.tags;
import
import
import
import
import
import
import
/**
*
*
*
*
java.io.*;
javax.servlet.*;
javax.servlet.jsp.*;
javax.servlet.http.*;
javax.servlet.j sp.tagext.*;
javax.xml.transform.*;
cwp.XslTransformer;
,
XML- HTML-, XSLT.
XSL-,
Internet Explorer,
Netscape ( ).
V
public class XslTransformTag extends TagSupport {
private static final String FS =
System.getProperty("file.separator");
private static final int IE = 1;
private static final int NS = 2;
private String xml, xslie, xslns;
2 3 . 8 . XSLT...
1095
1096
23. XML-
//
// User-Agent, HTTP-.
private int browserType(HttpServletRequest request) {
int type = NS;
String userAgent = request.getHeader("User-Agent");
if ((userAgent != null) &&
(userAgent.indexOf("IE") >=0)) {
type = IE;
}
return(type);
b-^^lS, '.
j 4-Bdck * 4
^-^ S\ ^
ji
i^-
jYear Cultivar
|1965 Luxury Lace
7.50
11984 My Bene
12.00
11.75
E-L
5.00
14.50
. 23.11.
p e r e n n i a l s . xml
JSP-.
Internet Explorer 5.0,
Windows 2000
IgjOone
)ifw Sioemxm^it
:\
^ ^ ^ ^ ' ^
rfa
Cultivar
111.75;
i 7.50 1
112.00;
E-L
\ 5.00;
i 14.50 i
f^^r-
,DoBi4itD
2iM^m ME^iM.^^^J
. 23.12.
p e r e n n i a l s . xml
JSP-.
Netscape 4.7,
Windows 98
23.8. XSLT...
1097
23.9.
III, ,
. ,
XML- DOM, SAX XSLT.
JavaServer Pages, -
JDBC. ,
.
( , ?)
,
, JavaScript ,
, .
JavaScript- Web-
. , JavaScript-
, HTML-, .
-JzJS^-r
JAVASCRIPT
...
24. JavaScript: Web-
25. JavaScript
JAVASCRIPT:
WEB-
...
HTML- Web-.
, .
, .
JavaScript.
JavaScript Web-.
JavaScript
Web-.
JavaScript CGI-.
JavaScript .
Java JavaScript.
JavaScript Java.
J~y\3J^ZJ
, JavaScript Java.
JavaScript -- ; JavaScript
Web- . Java
,
, , , ,
. JavaScript-
HTML-, ,
. , ,
Web-. JavaScript-
, .
, Java-,
(AWT, Swing, Java 2D), ,
, RMI JDBC.
JavaScript ( 1.0 1.5)
JavaScript 2.0, Mozilla Organization ( h t t p : / / w w w . m o z i l l a . o r g / ) .
JavaScript 1.0 Netscape
Netscape Navigator 2.0. Netscape JavaScript (European Com
puter Manufacturers Association) . 1997 .
ECMAScript, -262,
JavaScript 1.1, Navigator .. Netscape
Navigator 4.0-4.05 JavaScript 1.2.
1998 . -262,
ISO/IEC 16262. ECMAScript Navigator
4.06 JavaScript 1.3.
I n f i n i t y NaN. JavaScript 1.4
.
-262,
1999 . , Netscape Navigator 6,
JavaScript 1.5, ECMAScript.
1102
24. JavaScript...
JavaScript , Microsoft
ECMAScript JScript.
Microsoft
(Internet Information Server, Windows Scripting Host, Visual Studio),
JScript, JScript,
Internet Explorer. JavaScript 1.1
Internet Explorer .; JavaScript 1.2
-262 Internet Explorer 4.Ox. Internet Explorer 5.0x
JavaScript 1.3 JavaScript 1.4. Internet Explorer
-262 JavaScript 1.5.
JavaScript 1.2
( , Netscape 4, Internet Explorer 4 ).
. DOM
(Document Object Model ) DHTML
. DOM
.
ECMAScript
h t t p : / / w w w . e c m a . c h / e c m a l / S T A N D / E C M A - 2 62.HTM
, JavaScript,
Netscape
http://developer.netscape.com/tech/javascript/
Microsoft JScript
http://msdn.microsoft.com/scripting/
, Mozilla Organization
http://www.mozilla.org/js/
D o c u m e n t Object M o d e l
http://www.w3.org/DOM/
JavaScript .
(R. Allen Wyke), . (Jason D. Gilliam)
(Charlton Ting) Pure JavaScript (JavaScript 1.4), a (Danny
Goodman) Dynamic HTML, The Definitive Reference (jdiVdScvipi 1.2).
JavaScript Web- . -,
HTML- . , JavaScript
.
. , JavaScript,
: Web-,
2 4 . 1 . HTML-
1103
, CGI-, cookie, ,
Java JavaScript JavaScript Java-.
. 25
, JavaScript 1.2.
2 4 . 1 .
L-
JavaScript- SCRIPT
Web-. , ,
, SCRIPT. JavaScript-
24.1. - JavaScript
, , .
2 4 . 1 . JavaSchpt- Web-
<BODY>
HTML-
<SCRIPT T y P E = " t e x t / j a v a s c r i p f >
Java Script-,
// >
</SCRIPT>
HTML-
HTML-
</BODY>
JavaScript-;
SRC <SCRIPT>.
HTML-
d o c u m e n t . w r i t e ,
. 24.2,
. 24.1.
2 4 . 2 . F i r s t S c r i p t . h t m l
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0 / / E N " >
<HTML>
<HEAD>
< T I T L E > F i r s t J a v a S c r i p t Page</TITLE>
</HEAD>
<BODY>
< H l > F i r s t J a v a S c r i p t Page</Hl>
<SCRIPT T Y P E = " t e x t / j a v a s c r i p t " >
1104
2 4 . JavaScript..
^^^^p.
^b:^6>^iiD^";-l 'jy;;^]|ycgguvjsag;^,..
. 24.1.
JavaScript
JavaScript-
HTML-. JavaScript-
HTML- .
24.3, . 24.2 24.3
Netscape Navigator Microsoft Internet
Explorer. r e f e r r i n g Page
"+" . ,
, ,
document . w r i t e . ,
document . w r i t e l n document . w r i t e
"\" .
Web-, ,
HTML-
. Web-
.
(.
L3).
HTML-,
HTML-.
2 4 . 1 . HTML-
24.3. ShowInfo.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Extracting Document Info with JavaScript</TITLE>
</HEAD>
<BODY BGCOLOR="WHITE">
<Hl>Extracting Document Info with JavaScript</Hl>
<HR>
<SCRIPT TYPE="text/javascript">
<?
function referringPage() {
if (docioment. ref errer. length = = 0 ) {
return("<I>none</I>");
} else {
return (dociiment. referrer) ;
}
}
document.writeln
("Document Info:\n" +
"<UL>\n" +
" <LIXB>URL: </B> " + document. location + "\n" +
" <LIXB>Modification Date:</B> " + "\n" +
document.lastModified + "\n" +
" <LIXB>Title:</B> " + docianent. title + "\n" +
" <LIXB>Ref erring page:</B> " + ref err ingPage () + "\n" +
"</UL>");
document.writeln
("Browser Info:" + "\n" +
"<UL>" + "\n" +
" <LIXB>Name:</B> " + n a v i g a t o r . appName + " \ n " +
" <LIx:B>Version:</B> " + navigator.appVersion + "\n" +
"</UL>");
// >
</SCRIPT>
<HR>
</BODY>
</HTML>
1105
1106
24. JavaScript...
JDixi|
yniHi'iiiiiniiniJiHiiimiifffwiHi'nm
URL: http://www.corewebprogramming.coin/JavaScnpt/ShowInfo.html
Modification Date: Wednesday, April 11, 2001 17:19:10
Title: Extracting Document Info with JavaScript
Referring page: none
Browser Info:
Name: Netscape
Version: 4.7 [en] (Win98.1)
iDocument: Oortt
.^...<^....
. 24.2. showinfo,
Netscape 4.7,
Windows 98
^
Extracting Document Info with JavaScript
"^
Document Info:
Browser Info:
Name: Microsoft Internet Explorer
Version: 4.0 (compatible; MSIE 5 5. Windows 98)
d
2 0
| My Computer
. 24.3. showinfo,
Internet Explorer 5.0,
Windows 98
2 4 . 1 . HTML-
1107
, JavaScript- HTML-.
, . ,
, JavaScript, <SCRIPT>
</SCRIPT>, , .
. ,
JavaScript " / / " "<! - - "
, . ,
. ,
HTML 2.0, " - - " ,
, , "< !" ">". , ,
< ! Foo Bar >
,
< ! Foo Bar >
. , HTML 2.0,
:
<!
var X = 3;
if (>2) //
doOneThing();
else
doAnotherThing();
// >
<!
var X = 3;
var = - - ;
/ / >
//
, JavaScript ,
,
:
<SCRIPT LANGUAGE="JavaScript">
<!
languageVersion = "1.0";
// >
</SCRIPT>
<SCRIPT LANGUAGE="JavaScriptl.l">
<!
languageVersion = "1.1";
// >
</SCRIPT>
<SCRIPT LANGUAGE="JavaScriptl.4">
<!
1108
24. JavaScript.
languageVersion = "1.4";
// >
</SCRIPT>
<SCRIPT LANGUAGE="JavaScriptl.5">
<!
languageVersion = "1.5";
// >
</SCRIPT>
, TYPE=" t e x t / j a v a s c r i p t " .
TYPE
JavaScript. Netscape 6 .
24.2.
JavaScript HTML- Web, HTML- .
. , :
,
, ,
,
. 24.4
, d o n t C l i c k
o n C l i c k . . 24.4 24.5.
( BUTTON)
JavaScript;
HTML-. , d o n t C l i c k
( BODY), HEAD.
, HTML-.
2 4 . 4 . D o n t C l i c k . html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
<TITLE>Simple J a v a S c r i p t B u t t o n < / T I T L E >
<SCRIPT T Y P E = " t e x t / j a v a s c r i p t " >
function dontClick0 {
a l e r t ( " I t o l d you n o t t o c l i c k ! " ) ;
}
/ / >
</SCRIPT>
</HEAD>
<BODY BGCOLOR="WHITE">
<Hl>Simple JavaScript Button</Hl>
<FORM>
Transitional//EN">
24.3. JavaScript
1109
<INPUT TYPE="BUTTON"
VALUE="Don't Click Me"
onClick="dontClick() ">
</FORM>
</BODY>
</HTML>
t^nfflffimfmrfflf
^jjijU;p|MI|^juUt
"D
d
;^;>*
. 24.4. Web-
. 24.5. ,
24.3. JavaScript
JavaScript Java .
, , i f , "? :", w h i l e , f o r , b r e a k
c o n t i n u e , Java. JavaScript 1.2
s w i t c h , Java,
, , c a s e , .
+ ( ), - , *, / , ++, - - , &&, | |
, Java.
, ,
,
. ;
.
, Netscape
JavaScript- (. 24.6). , URL " j a v a s c r i p t : " .
, , Loca
tion (, " j a v a s c r i p t .-Math, c o s (Math. P I / 4 ) *2");
. Netscape, Internet Explorer.
p-ffwfffUHim^
|^"(afx^|
1.414213S6237309S1
javascnpt typein
JKath. cos (Math. PI/4) *2|
Clear Console
I Close I
. 24.6. Netscape
JavaScript-
1110
24. JavaScript...
Java JavaScript ,
JavaScript .
, ( JavaScript
) , . ,
. ,
:
v a r X = 5 ; / /
X = 5 . 5 ; / /
X = " f i v e p o i n t f i v e " ; / /
f u n c t i o n .
, .
.
function square() {
return( * ) ;
}
function factorial(n) {
if (n <= 0) {
return(1);
} else {
return(n * factorial(n - 1));
}
}
function printHeading(message) {
document.writeln("<Hl>" + message + "</Hl>");
}
, :
: fun = Math.sin;
^rt("sin(pi/2)=" + fun(Math.PI/2));
. 24.7.
JavaiSaipt Alert
stn(pi/2)-1
. 24.7. JavaScript ,
,
.
.
24.3. JavaScript
1111
Math.sin = Math.cos; / / He
alert("Yikes! sin(pi/2)=" + Math.sin(Math.PI/2));
. 24.8.
|7111
. 24.8. JavaScript
, - Java,
JavaScript , , ,
JavaScript- .
JavaScript .
JavaScript
(), .
, . :
var t e s t = new O b j e c t O ;
t e s t . f i e l d l = "Value 1"; / / f i e l d l
test.field2 = 7 ;
/ / f i e l d 2
,
"" . ,
. , ,
undefined. ( ==) n u l l
t r u e .
JavaScript
"" ,
{ !:!,
2:2,
... :
j ect 1 ob j ect2 .
var objectl
object1.x =
objectl. =
objectl.z =
= new ObjectO;
3;
4;
5;
1112
24. JavaScript...
for/in
Java C++, JavaScript ,
. f o r / i n .
for(fieldName in object) {
doSomethingWith(fieldName);
}
(, f i e l d ) ,
o b j e c t . f i e l d , o b j e c t [ " f i e l d " ] .
.
24.5. ,
HTML-, .
Internet Explorer 5.0 . 24.9.
2 4 . 5 . F o r i n . html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
<TITLE>For/In Loops</TITLE>
<SCRIPT
Transitional//EN">
TYPE="text/javascript">
<!
f u n c t i o n makeObjectTable(name, o b j e c t ) {
d o c \ a a e n t . w r i t e l n ( " < H 2 > " + name + "</H2>");
doc\iment.writeln("<TABLE BORDER=l>\n" +
" <TRXTH>Field<TH>Value") ;
f o r ( f i e l d in object) {
document, w r i t e l n (" <TRXTD>" + f i e l d +
"<TD>" + o b j e c t [ f i e l d ] ) ;
}
dociament.writeln("</TABLE>") ;
}
// >
</SCRIPT>
</HEAD>
<BODY BGCOLOR="WHITE">
<Hl>For/In Loops</Hl>
<SCRIPT TYPE="text/javascript">
<!
var test = new Object();
test.fieldl = "Field One";
test.field2 = "Field Two";
test.fields = "Field Three";
makeObjectTable("test", test);
// >
24.3. JavaScript
1113
</SCRIPT>
</BODY>
</HTML>
,
this
JavaScript Java. ,
, , ,
t h i s .
new t h i s Object.
Ship.
function Ship(x, , speed, d i r e c t i o n ) {
t h i s . x = x;
t h i s . = ;
t h i s . s p e e d = speed;
this.direction = direction;
}
makeObjectTable
BODY , ,
. 24.10.
var shipl = new Ship(0, , 1, 90);
makeObjectTable("shipl", shipl);
:'1111111|||]|'11^!11^114
1For/In Loops
-^
i
Ships
shipl
1 test
1 1 Reld Value
Held Value
field 1 Reld One
field2PieldTwo
fields Reld
1^
1 |x
|0
;y
0
1 ;speed '1
1 jdirecbon '90
. 24.9. for/in
1
1
^_^
. 24.10.
1114
2 4 . JavaScript...
JavaScript
. . ,
S h i p , move, :
function degreesToRadians(degrees) {
return(degrees * Math.PI / 180.0);
}
function move() {
var angle = degreesToRadians(this.direction);
this.x = this.x + this.speed * Math.cos(angle);
this. = this. + this.speed * Math.sin(angle);
}
function Ship(x, y, speed, direction) {
this.x = x;
this. = ;
this.speed = speed;
this.direction = direction;
this.move = move;
}
v a r a n g l e
JavaScript .
, , JavaScript
, a n g l e .
,
. ,
v a r .
var.
, .
. 24.11.
v a r s h i p l = new S h i p ( 0 , , 1, 9 0 ) ;
makeObjectTable("shipl ( o r i g i n a l l y ) " ,
shipl.move();
makeObjectTable("shipl ( a f t e r move)",
shipl);
shipl);
24.3. JavaScript
1115
Ships
shipl (originally)
Value
Field
X
0 _
speed
direcbon 90
fiinchon moveO { var angle = degreesToRadians
(tbs direction); this.x = this.x +this, speed * Math.cos
(angle); this = this + this.speed * Math. sin(angle);)
Value
6 123031769111886e-17
speed
direction 90
move
_J
^ Done
'^
. 24.11.
prototype
p r o t o t y p e .
,
p r o t o t y p e ,
. ,
. S h i p .
p r o t o t y p e move m a x S p e e d .
f u n c t i o n S h i p ( x , , s p e e d , d i r e c t i o n )
t h i s . x = x;
t h i s . y = y;
this.speed = speed;
this.direction = direction;
}
new Ship(0, 0, 0, 0) ;
Ship.prototype.move = move;
Ship.prototype.maxSpeed = 50;
1116
24. JavaScript...
JavaScript , Java.
A r r a y , .
v a r s q u a r e s = new A r r a y ( 5 ) ;
for(var i=0; i<squares.length;
vals[i] = i * i;
i++) {
/ / ,
v a r s q u a r e s = new A r r a y ( 0 , 1, 4, 9, 1 6 ) ;
v a r a r r a y l = new A r r a y C ' f e e " , " f i e " , " f o " , "fum") ;
/ / " " ,
v a r 2 = [ " f e e " , " f i e " , " f o " , "fum" ] ;
, .
JavaScript
. , ,
, [''"].
[ _].
. . 24.12.
v a r a r r a y O b j = new O b j e c t O ;
arrayObj[0] = "Index zero";
arrayObj[10] = "Index t e n " ;
a r r a y O b j . f i e l d l = " F i e l d One";
a r r a y O b j [ " f i e l d 2 " ] = " F i e l d Two";
makeObj e c t T a b l e ( " a r r a y O b j " ,
arrayObj);
li9
^^^
i ^ ^ 3 4^ A ^ rf a ffl
Array/Object Duality
arrayObj
Field
jo
Value
b d e x zero
Index ten
.E>J^-..~.v.;^-. A'~
-^.J.
. 24.12.
;
. (,
) ,
, .
makeOb j e c t T a b l e ( 24.5).
2 4 . 4 . JavaScript Web-
1117
24.4. JavaScript
Web-
JavaScript ,
JavaScript- Web-,
-. ,
, , HTML-,
, Internet Explorer Netscape Navigator.
, , ,
Web- ,
. ,
. Web-
, .
-, Web-, ,
, ,
.
, ,
-.
Netscape 4.0 w i n d o w . i n n e r W i d t h w i n d o w . i n n e r H e i g h t , . 24.6
JavaScript-, , , . . 24.13
24.14 .
, ,
HEAD, , BODY.
. -,
. -,
Web-. -, HEAD
BODY, , HEAD,
, ,
, .
, .
^^^'.
JavaScnpt'0yHKi4HH HEAD,
.
^^
,
. JavaScript ,
, , ,
.
1118
2 4 . JavaScript.
JavaScript ,
. ,
,
, , ,
.
2 4 . 6 . s t r a w b e r r i e s , h t m l
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
<TITLE>Strawberries</TITLE>
<SCRIPT
Transitional//EN">
TYPE="text/javascript">
<!
function image(url, width, height) {
r e t u r n ( ' < I M G SRC="' + u r l + " " +
' WIDTH=' + w i d t h +
' HEIGHT=' + h e i g h t + ' > ' ) ;
}
function strawberryl(width) {
return(image("Strawberryl.gif",
width,
Math.round(width*l.323))
width,
Math.round(width*!.155))'
function strawberry2(width) {
return(image("Strawberry2.gif",
}
/ / >
</SCRIPT>
</HEAD>
<BODY BGCOLOR="WHITE">
<HR>
<SCRIPT
TYPE="text/javascript">
<!
var imageWidth = window.innerWidth/4;
var fontSize = Math.min(7, Math.round(window.innerWidth/100));
}
document.writeln
('<TABLE>\n' +
<TR><TD>' + strawberryl(imageWidth) + '\n' +
<TH><FONT SIZE=' + fontSize + '>\n' +
"Doubtless God <I>could</I> have made\n' +
a better berry, but doubtless He\n' +
never did."</FONT>\n' +
<TD>' + strawberry2(imageWidth) + '\n' +
'</TABLE>');
// >
</SCRIPT>
<HR>
2 4 . 4 . JavaScript Web-
>41??
"Doubtless God
could hsi\e made
a better berry,
but doubtless He
never did."
Strawberries are my favonte garden crop; a fresh strawberry picked five minutes ago makes the dry and woody grocery
store variety seem like a totally different fruit My favonte vanebes are Surecrop and Cardinal
S 4>=
,A ..?i(^ .^.. . ^ , , .
. 24.13.
'???
^^ ^ -^ 9 ^ Jfll
. ^
'U^i>
"Doubtless
Goi could
kave made
. 24.14.
1119
1120
24. JavaScript...
Netscape ( Internet Explorer) JavaScript-
n a v i g a t o r . p l u g i n s , ,
.
P l u g i n , name, d e s c r i p t i o n , f i l e n a m e l e n g t h
MimeType.
, , , ,
MIME-. MimeType
t y p e (, -, " t e x t / h t m l " ) , d e s c r i p t i o n
(), e n a b l e d P l u g i n ( P l u g i n , )
s u f f i x e s ( , MIME-;
). 24.3, ""
. ,
, , .
if
, .
, ,
-, n a v i g a t o r . m i m e T y p e s .
if
(navigator.mimeTypes["application/postscript"])
addPostScriptLink();
25.19.
24.7 ,
MIME-,
. ,
Netscape 4.7, . 24.15.
14.7. Plugins.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Plug-ins Supported</TITLE>
<SCRIPT TYPE="text/javascript">
<!
function printRow(plugin) {
document.write
(" <TR><TD>" + plugin.name + "\n" +
"
<TD>" + plugin.description + "\n" +
<TD>");
document.write(plugin[0].type);
|[gJD|)CJ|
Plugins Supported
Plugin
'Headspace Beatnik
Player Stub VI.0.0 1
Description
Headspace Player Stub for
Netsc^e Conimunicator
iSmartDownload
Plugin
|11110-1
:appEcation/idp
iappEcation/x-java-bean;version=l. 1.2
i^plicationyx-java-applet;version=l.l 2
^application/x-java-bean;version=l 1 3
appIication/x-java-applet,version=l. 1 3
apphcation/x-java-bean;version=l. 2
application/x-java-applet,version=l 2
application/x-ipa-plugin
^^: Done
. 24.15. ,
Netscape 4.7
1121
1122
24. JavaScript.
24.5. JavaScript
Web-
, JavaScript-, Web-
,
HTML-. JavaScript-
. , Web-
, ,
.
"" . , ,
. JavaScript
,
.
d o c u m e n t . i m a g e s Image;
IMG .
, SRC ,
URL. ,
.
function changelmage() {
document.images[0].src =
"images/new-image.gif";
.}
(,
, )
.
,
. , JavaScript
NAME IMG. ,
<IMG SRC="cool-image.jpg" NAME="cool"
WIDTH=75 HEIGHT=25>
TO :
f u n c t i o n improvelmage() {
document.images["cool"].src
= "way-cool.jpg";
Web-
. c l i c k B u t t o n , ,
, , 1/10 ,
. s e t Image
s e t T i m e o u t . s e t l m a g e c l i c k B u t t o n ,
1123
setTimeout JavaScript.
s e t Timeout , JavaScript-,
. setTimeout ,
, ,
, .
function setlmage(name, image) {
document.images[name].src = image;
}
function clickButton(name, graylmage) {
var origlmage = document.images[name].src;
setImage(name, graylmage);
var resetString =
"setlmageC" + name + " \ '" + origlmage + " ' ) " ;
setTimeout(resetString, 100);
}
, , -, , -, ,
.
onCliclc <>.
< HREF="locationl.html"
onClick="clickButton('Buttonl*,
'images/Buttonl-Down.gif')">
<IMG SRC="images/Buttonl-Up.gif" NAME="Buttonl"
WIDTH=150 HEIGHT=25></A>
<A HREF="location2.html"
onClick="clickButton('Button2',
* images/Button2-Down.gif')">
<IMG SRC="images/Button2-Up.gif" NAME="Button2"
WIDTH=150 HEIGHT=25></A>
,
.
, Image (. 25.12) SRC
. , Image
; ,
.
imageFiles = new Array("images/Buttonl~Up.gif",
"images/Buttonl-Down.gif",
"images/Button2-Up.gif",
"images/Button2-Down.gif");
imageObjects = new Array(imageFiles.length);
for(var i=0; i<imageFiles.length; i++) {
imageObjects[i] = new Image(150, 25);
imageObjects[i].src = imageFiles[i];
}
1124
24. JavaScript...
24.8 .
, ,
.
.
24.8. ImageButton.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>JavaScript Image Buttons</TITLE>
<SCRIPT TYPE="text/javascript">
imageFiles = new Array("images/Buttonl-Up.gif",
"images/Buttonl-Down.gif",
"images/Button2-Up.gif",
"images/Button2-Down.gif");
imageObjects = new Array(imageFiles.length);
for(var i=0; i<imageFiles.length; i++) {
imageObjects[i] = new Image(150, 25);
imageObjects[i].src = imageFiles[i];
}
function setImage(name, image) {
document.images[name].src = image;
}
function clickButton(name, graylmage) {
var origlmage = document.images[name].src;
setlmage(name, graylmage);
var resetString =
"setlmageC" + name + "', '" + origlmage + " ' ) " ;
setTimeout(resetString, 100);
}
// >
</SCRIPT>
</HEAD>
<BODY>
<Hl>JavaScript Image Buttons</Hl>
<A HREF="locationl.html"
onClic>:="clickButton('Buttonl', 'images/Buttonl-Down.gif')">
<IMG SRC="images/Buttonl-Up.gif" NAME="Buttonl"
WIDTH=150 HEIGHT=25></A>
<A HREF="location2.html"
onClic}<:= "clickButton ( 'Button2 ', ' images/Button2-Down. gif') ">
<IMG SRC="images/Button2-Up.gif" NAME="Button2"
WIDTH=150 HEIGHT=25></A>
</BODY>
</HTML>
1125
^^"
,
""
, .
. ,
,
. 24.9 ,
. ,
"" , NAME IMG (.
r e g u l a r l m a g e F i l e n e g a t i v e l m a g e F i l e ) .
onMouseOver.
. 24.10 24.11.
. 24.16.
, 4; ,
JavaScript-.
2 4 . 9 . HxghPeaksNavBar.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>High P e a k s l ^ a v i g a t i o n Bar</TITLE>
<SCRIPT
<l
TYPE="text/javascript">
/ / " F o o " ,
"images/Foo.gif".
function regularlmageFile(imageName) {
r e t u r n ( " i m a g e s / " + imageName + " . g i f " ) ;
}
/ / "Bar",
"images/Bar-Negative.gif".
f u n c t i o n negativelmageFile(imageName) {
r e t u r n ( " i m a g e s / " + imageName + " - N e g a t i v e . g i f " ) ;
}
/ / .
/ / , , imageNames[0],
/ / "".
/ / images/.gif images/Home-Negative.gif.
f u n c t i o n cachelmages(index) {
r e g u l a r l m a g e O b j e c t s [ i n d e x ] = new Image(150, 2 5 ) ;
regularlmageObjects[index].src =
regularlmageFile(imageNames[index]);
n e g a t i v e l m a g e O b j e c t s [ i n d e x ] = new Image(150, 2 5 ) ;
negativelmageObjects[index].src =
negativelmageFile(imageNames[index]);
}
1126
24. JavaScript...
2 4 . 5 . JavaScript ...
onMouseOver="highlight('Austria')"
onMouseOut="unHighlight('Austria')">
<IMG SRC="iinages/Austria.gif"
NAME="Austria"
WIDTH=150 HEIGHT=25 BORDER=0></A>
<TR><TD><A HREF="Switzerland.html"
TARGET="Main"
onMouseOver="highlight('Switzerland')"
onMouseOut="unHighlight('Switzerland')">
<IMG SRC="images/Switzerland.gif"
NAME="Switzerland"
WIDTH=150 HEIGHT=25 BORDER=0></A>
</TABLE>
</BODY>
</HTML>
1127
1128
24. JavaScript...
CO
Netscape 4.0 . HTML-
, .
. 5.12. JavaScript 1.2
d o c u m e n t . l a y e r s ,
L a y e r . LAYER.
d o c u m e n t .
l a y e r s [ " " ] ;
d o c u m e n t . _ . ,
HTML: LAYER,
ILAYER .
24.12 , .
, , (. 24.17).
,
, (. 24.18).
,
,
. L a y e r 25.15;
v i s i b i l i t y ( show h i d d e n ) (
). m o v e T o A b s o l u t e ( ) moveBy (
).
24.5.
JavaScript .
1129
NEPAL
jueniu
swrrzERum
High Peaks Travel Inc.
Tired of the same old vacations in Cleveland? Tour
the high peaks with High Peaks Travel!
We have package deals for beginner, experienced,
and cxpett climbers, discount priced (*) for
budget-conscious traveller
HPT is currently arranging
tnps to the following exciting
locations:
Tibet
Nepal
Austna
Switzerland
Sign up todayl
|^1;;|^
^ W ^ B B ^ . g P . ,v^
. 24.16.
, ""
Netscape 4;
LAYERS HTML 4.0
Netscape 6. Internet Explorer
(DOM).
, ,
h t t p : / / w w w . c o r e w e b p r o g r a r n m i n g . c o m / . ,
, LAYER,
Netscape 6 Internet Explorer, h t t p : / / s i t e s . n e t s c a p e ,
net/ekrock/standards.html.
2 4 . 1 2 . Camps, htmX
//W3C//DTD HTML 4 . 0
<!DOCTYPE HTML PUBLIC
<HTML>
<HEAD>
<TITLE>Camps on K-3</TITLE>
<SCRIPT
TYPE="text/javascript">
Transitional//EN">
1130
24. JavaScript.
function hideCamps() {
// Netscape 4.
document.layers["baseCamp"].visibility = "hidden";
document.layers["highCamp"].visibility = "hidden";
// document.baseCamp.visibility = "hidden";
}
function moveBaseCamp() {
baseCamp.moveBy(1, 3) ;
if (baseCamp.pageX < 130) {
setTimeout("moveBaseCamp{)", 10);
}
// "" ,
// ,
// .
function showBaseCamp() {
hideCamps();
baseCamp = document.layers["baseCamp"];
baseCamp.moveToAbsolute(0, 20);
baseCamp.visibility = "show";
moveBaseCamp();
}
function moveHighCamp() {
highCamp.moveBy(2, 1 ) ;
if (highCamp.pageX < 110) {
setTimeout("moveHighCamp()", 10);
}
}
// "" , ,
// ,
// .
function showHighCamp() {
hideCamps();
highCamp = document.layers["highCamp"];
highCamp.moveToAbsolute(0, 65);
highCamp.visibility = "show";
moveHighCamp();
}
// >
</SCRIPT>
</HEAD>
<BODY>
<IMG SRC="images/peak4.gif" WIDTH=511 HEIGHT=600 ALIGN="LEFT">
<Hl>Camps on K-3</Hl>
The High Peaks Tours trip to the summit:
<UL>
<LI>Day 1: Travel to Base Camp
<LI>Day 2: Climb to High Camp
1131
24.6. JavaScript
HTML-
JavaScript-
, , .
, ,
, ,
, ,
-. d o c u m e n t . f o r m s Form,
. ,
, ,
d o c u m e n t ,
.
1132
24. JavaScript.
var f i r s t F o r m = document.forms[0];
/ / <FORM NAME="orders" , . . >
var orderForm = d o c u m e n t . f o r m s [ " o r d e r s " ] ;
/ / <FORM NA]yiE="register" . . . >
var r e g i s t r a t i o n F o r m = d o c u m e n t . r e g i s t e r ;
Form elements,
Element. ,
, .
var f i r s t E l e m e n t = f i r s t F o r m . e l e m e n t s [ 0 ] ;
/ / <INPUT . . . NAME="quantity">
var q u a n t i t y F i e l d = o r d e r F o r m . e l e m e n t s [ " q u a n t i t y " ] ;
/ / <INPUT . . . NAME="submitSchedule">
var submitButton = r e g i s t e r . s u b m i t S c h e d u l e ;
BHMBHMHMMMHMHHDSSl
I
L
^LA
^
^^^H|
r^^^l
1
1
1
1
1
1
1
1
\///
, Show 8as Camp
|-#|1?'1
HHeC^mps |
J
^
. 24.17.
;Docw*tDom
'' - "-^^''feaaBtJu^Lxa-^^^,-' 4
Netscape 4.7,
1133
:4<:'^^UitIlS'^Tl'^Z^nj
Camps on -3
The High Peaks Tours trip to the
summit;
Day 1: Travel to Base Camp
Day 2: Climb to High Camp
Day 3; Ascend summit,
return to H J ^ Camp
Day 4: Descend to Base
Camp
Day 5: Return Home
: 1 ^ 1 1 ^ :
^^
. 24.18. Show Base Camp
,
.
(
onSubmit FORM). , JavaScript
( onFocus onBlur),
( onChange).
: (
, ) (
).
Element Form 25.6 25.8.
24.13 ,
SUBMIT.
, .
.
1134
24. JavaScript...
,
. (
o n C h a n g e )
, .
. 24.19.
2 4 . 1 3 . C h e e k T e x t . h t m l
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
<TITLE>On-Line T r a i n i n g < / T I T L E >
<SCRIPT
<!
Transitional//EN">
TYPE="text/javascript">
/ /
function describeLanguage() {
s t a t u s = " E n t e r an i m p o r t a n t Web l a n g u a g e " ;
}
/ / .
function c l e a r S t a t u s O {
s t a t u s = "";
}
//
/ / , .
// , ,
//
// .
function checkLanguage() {
var field = document.langForm.langField;
// document.forms["langForm"].elements["langField"]
var lang = field.value;
var prefix = lang.substring(0, 4).toUpperCase();
if (prefix != "JAVA") {
alert("Sorry, '" + lang + "* is not valid.\n" +
"Please try again.");
field.value = ""; // Erase old value
field.focus 0 ;
// Give keyboard focus
}
}
// >
</SCRIPT>
</HEAD>
<BODY BGCOLOR="WHITE">
<Hl>On-Line Training</Hl>
<FORM ACTION="cgi-bin/registerLanguage" NAME="langForm">
To see an introduction to any of our on-line training
113
c o u r s e s , p l e a s e e n t e r t h e name of an i m p o r t a n t Web
programming l a n g u a g e below.
<P>
<B>Language:</B>
<INPUT TYPE="TEXT" NAME="langField"
onFocus="describeLanguage()"
onBlur="clearStatus() "
onChange="checkLanguage()">
<P>
<INPUT TYPE="SUBMIT" VALUE="Show It To Me">
</FORM>
</BODY>
</HTML>
'||||11|||||
Jji
i ^ ^ ^ ^ ^ a t a rfa
On-Line Training
To see an introduction to any of our on-line training courses, please
enter the name of an important Web programming language below.
Language: | v i s u a l B a s i c
'Show IITo Me
ei^i'
BBS
^EOtftP,;J,^j|^,
. 24,19.
,
,
, . ,
,
, ,
SUBMIT. , ,
,
. , on S u b m i t
FORM, f a l s e , .
, ,
, .
, JavaScript p a r s e i n t p a r s e F l o a t .
, -
1136
24. JavaScript...
. JavaScript,
, , ,
NaN (Not Number ),
isNaN ( == , NaN==NaN
f a l s e ) . 24.1, JavaScript
, .
, 24.14,
. Internet Explorer 5.0
. 24.20.
2 4 . 1 4 . Numbers, h t m l
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
< T I T L E > T e s t i n g Numbers</TITLE>
<SCRIPT
Transitional//EN">
TYPE="text/javascript">
function isint(numString) {
/ / p a r s e i n t , NaN
return(!isNaN(parseint(numString)));
}
/ / >
</SCRIPT>
</HEAD>
<BODY BGCOLOR="WHITE">
<SCRIPT
<!
TYPE="text/javascript">
function testint(numString) {
return("<TR><TD>" + numString +
"<TD>" + p a r s e i n t ( n u m S t r i n g ) +
"<TD>" + i s I n t ( n u m S t r i n g ) + " X n " ) ;
}
document.writeln
( " < H l > T e s t i n g f o r Numbers i n J a v a S c r i p t 1 . 2 + < / H l > \ n " +
"<TABLE B0RDER=5 CELLSPACING=5>\n" +
"<TR><TH>Input<TH>Parsed Value<TH>Legal I n t e g e r ? \ n " +
testlntC'O") +
testint("10") +
testint("-10") +
testint("FF") +
testint("#FF") +
testint("123abc") +
testint("abcl23") +
"</TABLE>");
/ / >
1137
</SCRIPT>
</BODY>
</HTML>
ii!ll4!i4H.i.lH
le
)*M
BOS
Favorte
lock
true
1 10
'lO
true
i -10
-10
true
^,FF
NaN
false
''#FF
NaN
false
123abc 123
true
^ abcl23 NaN
false
iUJ^N'
"r^iaf%^-
. 24.20.
, p a r s e i n t NaN
24.15 , ,
.
, .
,
SUBMIT,
.
. ,
c h e c k R e g i s t r a t i o n . ,
, ,
.
. 24.21 24.22.
1138
24. JavaScript...
El
{ status = ""; }
function promptSerial0
//
//
//
//
//
//
function isint(string) {
var val = parseint(string);
return(val > 0 ) ;
// :
// 1) Age .
/ / 2 ) Rank .
// 3) Rank .
// 4) Serial number .
// ,
// .
function checkRegistration() {
var ageField = document.registerForm.ageField;
if (!isInt(ageField.value)) {
alert("Age must be an integer.");
return(false);
}
var rankField = document.registerForm.rankField;
if (isInt(rankField.value)) {
alert("Use rank name, not rank number.");
return(false);
}
if (rankField.value == "") {
alert("Missing rank.");
return(false);
}
var serialField = document.registerForm.serialField;
if (!isInt(serialField.value)) {
Camp Registration
Agcijie"
Rank:}Geek
Senal Number |#FFAA|
!^^pf
~Bi^m(>iiM:^j^^.j^:^m.^^<j
. 24.21.
.
. 24.22. ,
1139
1140
2 4 . JavaScript.
24.7. JavaScript
cookie
cookie ,
Web-. Cookie .
cookie ;
, JavaScript d o c u m e n t . c o o k i e .
. d o c u m e n t ,
c o o k i e , , cookie,
Cookie HTTP-. ,
cookie n a m e l , name2 ,
d o c u m e n t . c o o k i e :
"name1=vail; name2=val2; name3=val3"
, cookie
d o c u m e n t . c o o k i e . cookie
, S e t C o o k i e -. cookie
19.1, .
document.cookie = "namel=vall";
d o c u m e n t . c o o k i e = "name2=val2; e x p i r e s = " + someDate;
d o c u m e n t . c o o k i e =?= " n a m e 3 = v a l 3 ; p a t h = / ; d o m a i n = t e s t . com";
, d o c u m e n t . c o o k i e ,
cookie . Cookie ,
,
. Netscape, Internet
Explorer 5.0 .
!
Internet Expiorer 4.x cooicie,
, .
1141
cookie "Widgets
R Us", 24.16. ,
cookie.
, ; Register Account.
Web- (
), cookie
.
, . -,
, ,
onLoad BODY. ,
Web-
. -, cookie c o o k i e Val. cookie (, "name2")
cookie (, " n a m e l = v a l l ; n a m e 2 = v a l 2 ; n a m e 3 = v a l 3 " ) .
, (.. " v a l 2 " ) .
function cookieVal(cookieName, cookieString) {
var startLoc = cookieString.indexOf(cookieName);
i f ( S t a r t L o c == - 1 ) {
returnC'");
/ / c o o k i e .
}
v a r sepLoc
v a r endLoc
i f (endLoc
endLoc =
= cookieString.indexOf{"=", startLoc);
= cookieString.indexOf(";", startLoc);
== - 1 ) { / / " ; " .
cookieString.length;
return(cookieString.substring(sepLoc+1,
endLoc));
S t r i n g : i n d e x O f
s u b s t r i n g . i n d e x O f .
,
. i n d e x O f , S t r i n g l a s t l n d e x O f ,
).
, -1.
s u b s t r i n g ;
, .
, , ,
. c o o k i e V a l
, s p l i t .
; ,
. S t r i n g 25.31.
c o o k i e V a l
cookie (, , " b a r " )
" f o o = a ; b a r = ; b a z = c " ) (, ,
"quux" " f o o = a ; b a r = ; b a z = c " ) . ,
-, c o o k i e V a l
n u l l ; ,
" cookie ".
, .
1142
24. JavaScript...
. 24.23 24.24
Internet Explorer 5.0. cookie
. ,
cookie , ,
URL, :
javascript:alert(document.cookie)
24.16. Widgets. html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Widgets "R" Us</TITLE>
<SCRIPT TYPE="text/javascript">
<!
// , ,
// , cookie.
function storeCookies() {
var expires = "; expires=Monday, 01-Dec-Ol 23:59:59 GMT";
var first = document.widgetForm.firstField.value;
var last = document.widgetForm.lastField.value;
var account = document.widgetForm.accountField.value;
document.cookie = "first=" + first + expires;
document.cookie = "last=" + last + expires;
document.cookie = "account=" + account + expires;
}
// cookie .
function registerAccount() {
StoreCookies();
alert("Registration Successful.");
}
// cookie cookie
// .
function cookieVal(cookieName, cookieString) {
var startLoc = cookieString.indexOf(cookieName);
if (StartLoc == -1) {
return(""); // cookie .
}
var sepLoc = cookieString.indexOf("=", startLoc);
var endLoc = cookieString.indexOf(";", startLoc);
if (endLoc == -1) { // ";".
endLoc = cookieString.length;
}
return(cookieString.substring(sepLoc+1, endLoc));
}
// cookie ,
// .
function presetValues() {
1143
1^ vBrffliHMiijiBmiffl3r
~}
Widgets "R" Us
Widgets "R" Us
1 Widget Name' j
1
l4eg9tasrA<xooot
[^^'
'{gjOone
Submit Ofdef
d
,3Done
. 24.23.
.
Register Account
;(%(]"
. 24.24.
Loreen
,
Web-,
1144
24. JavaScript.
24.8. JavaScript
JavaScript .
f r a m e s Window ,
( Window), .
p a r e n t t o p ,
. Window
25.35. , ,
URL
. , ,
, 4.
URL
l o c a t i o n ,
.
f r a m e s , JavaScript-
. ,
f r a m e ,
l o c a t i o n . .
someFrame.frames["frameName"].location
= "url";
HTML
, :
someFrame.frames.frameName.location
= "url";
, .
p a r e n t , t o p
f r a m e s . ,
.
25.35.
24.17 HTML- ,
: G e t U R L . h t m l ( 24.18) D i s p l a y U R L . h t m l ( 24.19).
, ,
URL. Show URL
. ,
, . ,
:
f u n c t i o n showURLO {
v a r u r l = document . u r l F o r m . u r l F i e l d . valuedparent. displayFrame . l o c a t i o n = u r l ;
}
24.8. JavaScript
1145
, o n C l i c k :
<INPUT TYPE="BUTTON" VALUE="Show URL"
onClick="showURL()">
Ha . 24.25 24.26 , Internet
Explorer.
2 4 . 1 7 . ShowURL.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
<TITLE>Show a URL</TITLE>
</HEAD>
Frameset//EN">
24.18. GetURL.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Choose a URL</TITLE>
<SCRIPT TYPE="text/javascript">
<!
function showURL() {
var url = document .urlForm.urlField. valuedparent .displayFrame. location = url;
// parent.frames["displayFrame"]location = url;
}
function preloadUrlO {
if (navigator.appName == "Netscape") {
document.urlForm.urlField.value =
"http://home.netscape.com/";
} else {
document.urlForm.urlField.value =
"http://www.microsoft.com/";
}
}
// >
</SCRIPT>
</HEAD>
1146
24. JavaScript...
SIZE=35>
</BODY>
</HTML>
2 4 . 1 9 . DisplayURL. html
<!DOCTYPE HTML PUBLIC " - / / W 3 C / / D T D HTML 4 . 0 T r a n s i t i o n a l / / E N " >
<HTML>
<HEAD> < T I T L E > D i s p l a y URL</TITLE>
</HEAD>
<BODY BGCOLOR="WHITE">
< H 2 > E n t e r a URL i n t h e t e x t f i e l d a b o v e . P r e s s
" S h o w URL" t o d i s p l a y i t i n t h i s
frame.</H2>
</BODY>
</HTML>
HQQj^l
iCTBirewRrai
s.^^a^^ amm
)imt go ^^ \
'4Eh- '^# ^*
Choose a URL
XJRL: | h t t p : / / h o m e . n e t s c a p e . com/
r-
1 Enter a URL in the textfleld above. Press "Show URL" to display it in this
j frame.
1 "
lOooumfHt.Pfirte
J4
. 24.25. Netscape,
24.8.
JavaScript
1147
^ ^' -a A ^ ^ rf's
Choose a URL
SH^wURl I
XJRL" [http://hoine.netscape.com/
Scree_n_J<Ln9s
Tax..Tjrnfi
EntfirtainniEnt
HOT D t A L S
M
M u s t - H a v e s ! J.Crew
Spring 2 0 0 1 for M e n
Victoria's S e c r e t ; Sv
2 0 0 1 Collection
Swfully Delicious;
G o u r m e t Body Peint
FarcwGit 'Friends'?
4VLftrHtR
.i^H>'l
EH
^|
r:^^. ,>
Web-, , .
,
, .
. -,
. ,
, .
, , .
? !
. -,
.
, ,
. , ,
,
, .
JavaScript
f e c u s ( ) .
showURL, G e t U R L . h t m l
.
f u n c t i o n showURLO {
var u r l = document.urlForm.urlField.value;
parent.displayFrame.location = url;
/ / Give frame t h e i n p u t f o c u s
parent.displayFrame.focus 0 ;
}
1148
24. JavaScript.
HTML- .
o n C l i c k AREA,
TARGET, o n S u b m i t FORM.
f o c u s .
Java. ,
Java-.
, JavaScript-.
( JavaScript).
JavaScnpt-. , ,
LiveConnect
Web-.
Java
Java JavaScript-
. ,
Java.lang.System.out.println{"Hello
Console");
2 4 . 9 . Java JavaScript
1149
24.20. C a l l J a v a . h t m l
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
<HEAD>
<TITLE>Calling Java</TITLE>
</HEAD>
<BODY>
<Hl>Calling Java</Hl>
<SCRIPT TYPE="text/javascript">
document.writeln
("This browser uses a virtual machine from " +
Java.lang.System.getProperty("Java.vendor") + " . " ) ;
var pt = new Java.awt.Point(3, 5 ) ;
pt.translate(7, 5 ) ;
document.writeln("<P>");
document.writeln("Translating (3,5) by (7,5) yields (" +
pt.X + "," + pt. + " ) . " ) ;
// >
</SCRIPT>
</BODY>
</HTML>
Calling Java
This browser uses a virtual machine from Netscape Communications Corporation.
Translating (3.5) by (7.5) yields (10,10)
. 24.27. JavaScript-
Java , Web-
Java JavaScript-
. -, , ,
JavaScript-. , ,
,
, . -, JavaScript
Java. ,
, J a v a . l a n g . S y s t e m . o u t .
p r i n t I n j a v a . u t i l . S t r i n g T o k e n i z e r ,
.
1150
24. JavaScript...
JavaScript-
, Java
, JavaScript. JavaScript ,
Java-, ""
JavaScript-. JavaScript-
d o c u m e n t . a p p l e t s , ,
, d o c u m e n t . a p p l e t N a m e , a p p l e t N a m e
. JavaScript- ,
p u b l i c . , , A c o u s t i c s
Web-
. Web-
:
<APPLET CODE="Acoustics" WIDTH=10 HEIGHT=10
NAME="acoustics">
</APPLET>
g e t S i g n a l E x c e s s :
function signalExcess(...) {
return(document.acoustics.getSignalExcess
(...));
24.21 Web- ,
.
, .
JavaScript -, Web (. 24.28 24.22),
I n e t A d d r e s s . g e t L o c a l H o s t .
, Web-,
,
(. 24.29, 24.23). ,
, (. 24.30, 24.24).
2 4 . 2 1 . Wonder-Widget. h t m l
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
<TITLE>WonderWidget</TITLE>
<SCRIPT
<!
TYPE="text/javascript">
function c o n t a i n s ( s t r i n g , substring) {
return(string.indexOf(substring)
!= - 1 ) ;
}
Transitional//EN">
2 4 . 9 . Java JavaScript
function showResume() {
if (contains(document.gethost.getHost(),
"widgets-r-us.com")) {
location = "ResumeLoyal.html";
} else {
location = "ResumeReal.html";
}
return(false) ;
}
// >
</SCRIPT>
</HEAD>
<BODY BGCOLOR="WHITE">
<Hl>WonderWidget</Hl>
<APPLET CODE="GetHost" WIDTH=10 HEIGHT=10 NAME="gethost">
</APPLET>
Description:
<UL>
<LI>Name: Wonder Widget
<LI>Serial Number: 1544X
<LI>Cost: $7.95 (plus 22.50 shipping and handling)
<LI>Designer:
<A HREF="ResumeLoyal.html" onClick="return(showResume())">
J. Random Hacker</A>
</BODY>
</HTML>
24.22.GetHost.java
import Java . applet .Appletsimport java.awt.*;
import java.net.*;
public class GetHost extends Applet {
private String host;
public void initO {
setBackground(Color.white);
try {
host = InetAddress.getLocalHost().toString();
} catch(UnknownHostException uhe) {
host = "Unknown Host";
}
}
public String getHost () {
return(host);
}
}
1151
1152
24. JavaScript.
^ W o n d e t W k ^ l ^ Netscape
^^ y'^ J - ^
1;
i;
WonderWidget
Description:
Name: WonderWidget
Senal Number: 1544X
Cost $7 95 (plus 22.50 shipping and handling)
Designer J Fvandom Hacker
' ''--i.^
lis
Dcxumertl, bont
;^
i^
5l ~> *si'
iM -
. 24.28.
,
dk Vtew go Qomnnfiirlicata
: ^'^ -r
3 ^Jt ^
Widgets R Us
J. Random Hacker has been a loyal employee of Widgets R. Us, Inc,
for five years During that time he has selflessly worked on a number of
projects that have greatly benefited the company. His most recent
achievement is the Wonder W-dpet.
i:i!
^^
. 24.29. " J .
Random Hacker"
w i d g e t s - r - u s
JavaScript-,
Vievt go CommunKatot
J. Random Hacker
looking for job!
For the last five years, I've been undeald and underappreciated by
Widgets R Us, Inc. Now^ I'm ready to take my immense talents'
elsewhere. Who will open the bidding?
:a^ ~4^>-
J - ' ZM \ ^
. 24.30. ,
,
Web- " ",
2 4 . 2 3 . ResumeLoyal. html
<!DOCTYPE HTML PUBLIC " - / / W 3 C / / D T D HTML 4 . 0
<HTML>
<HEAD>
<TITLE>Widgets R Us</TITLE>
</HEAD>
<BODY BGCOLOR="WHITE">
<Hl>Widgets R Us</Hl>
Transitioanl//EN">
2 4 . 9 . Java JavaScript
1153
,
, ,
JavaScript-. :
" ?".
.
-,
. ,
, HTML, Java.
-, , , , Java-
, ,
SUBMIT . Java- .
-, JavaScript
, . , 24.25
Web-, "",
. Start Stop
. JavaScript . 24.31 24.32.
1154
24. JavaScript..
V
public class RandomCircles extends Applet
implements Runnable {
private boolean drawCircles = falserpublic void initO {
setBackground(Color.white);
}
public void startCircles() {
Thread t = new Thread(this);
t.start 0 ;
}
public void run() {
Color[] colors = { Color.lightGray, Color.gray,
Color.darkGray, Color.black };
int colorlndex = 0;
int X, y;
int width = getSize().width;
int height == getSize () .heightsGraphics g = getGraphics();
drawCircles = true;
while(drawCircles) {
X = (int)Math.round(width * Math.random());
= (int)Math.round(height * Math.random());
g.setColor(colors[colorlndex]);
colorlndex = (colorlndex + 1 ) % colors.length;
g.fillOvaKx, y, 10, 10);
pause(0.1) ;
}
}
public void stopCircles() {
drawCircles = false;
}
private void pause(double seconds) {
try {
Thread.sleep((int)(Math.round(seconds * 1000.0)));
} catch(InterruptedException ie) {}
}
1155
1156
24. JavaScript.
!
^ ^ i^BS
liiP
|
^
^
1
li
JfciM
k^J^yM'MW'M^'en
llff?:]
i-liiitiliiiiee^
i#rii:-lfils*
^ ;
{
'|*<^
:;^oid:^^lpiag^^
|||
W#'-JH
;^jpi*iielifiiiiii
|:, |;.viiiii;iiiillil:lft
1 [j Start Simulatlorts
1 _,frrr^
eiisi
Stop feul^tldns j
- ; ^ j - r r - -71^^^.,, ^^ ^
, , ^^ ^ _^^^^
;;,::-1-.;>.:, v^
:!
. 24.32.
.
Java JavaScript
2 4 . 1 0 . JavaScript Java
1157
2 4 . 1 0 . JavaScript Java
LiveConnect Java- JavaScript, JavaScript.
n e t s c a p e . j a v a s c r i p t . J S O b j e c t JavaScript-,
. ,
e v a l JavaScript-.
e v a l , -
JavaScript, Java. JavaScript Java,
.
1. JSObject.
2. JSObject ,
3. JavaScript- .
4. JavaScript-.
5. JavaScript-.
6. JavaScript-.
7. Web-.
.
J S O b j e c t
J S O b j e c t Netscape 4 JAll-
j a v a 4 0 .
. Windows 98
NetscapeInstallPath\Program\Java\Classes\
N e t s c a p e I n s t a l l P a t h ,
Netscape. , ,
Find () .
UNIX ,
Netscape.
:
Unix> cd / u s r / l o c a l
Unix> f i n d . -name j a v a 4 0 - p r i n t
, CLASS PATH;
Java JAR-.
a p p l e t v i e w e r CLASSPATH ,
. Netscape, Internet
Explorer , CLASSPATH, ,
CLASSPATH .
JAR-, j a r x f
j a v a 4 0 . j a r , J S O b j e c t . c l a s s .
, , ,
Netscape. , J S O b j e c t
, .
1158
24. JavaScript.
JSObject
:
import n e t s c a p e . j a v a s c r i p t . J S O b j e c t ;
JavaScript-
, ,
getWindow JSObject:
JSObject window =
JSObject.getWindow(this);
//
this=ae
JSOb j e c t .
JavaScript-
JavaScript,
getMember. getMember
JavaScript-. :
JSObject document =
(JSObject)window.getMember("document");
S t r i n g cookies =
(String)document.cookie;
JSObject someForm =
(JSObject)document.getMember("someFormName");
JSObject someElement =
(JSObject)someForm.getMember("someElementName");
g e t S l o t .
JavaScript-
setMember. :
document.setMember("bgColor", " r e d " ) ;
someElement.setMember("value", " t e x t f i e l d v a l u e " ) ;
, setMember Object,
. ,
, i n t i n t V a l u e I n t e g e r
new I n t e g e r ( i n t V a l u e ) ;
. , ,
JavaScript-, e v a l (. ).
JavaScript-
JavaScript- c a l l ,
JavaScript-, ,
e v a l . c a l l ;
e v a l . :
S t r i n g [ ] message = { "An a l e r t message" };
w i n d o w . c a l l ( " a l e r t " , message);
window.eval("alert('An a l e r t message')");
1159
Web-
Web-, ,
.
.
MAY SCRIPT APPLET. :
<APPLET CODE=... WIDTH=... HEIGHT=... MAYSCRIPT>
</APPLET>
Web-
, ,
, Web-,
,
. , ,
; PARAM.
, (
<BODY> <PARAM>).
Web- . LiveConnect
Document .
, , 24.27 24.28.
2 4 . 2 7 . MatchColor. 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 netscape.javascript.JSObject;
public class MatchColor extends Applet {
public void initO {
JSObject window = JSObject.getWindow(this); // this=ae
JSOb ject document = (JSOb ject) window. getMember ("dociMnent") ;
// , "#ffOOOO"
String pageColor = (String)document.getMember("bgColor");
// , parseint("ff0000", 16) --> 16711680
int bgColor =
Integer.parseint(pageColor.substring(1, 7 ) , 16);
setBackground(new Color(bgColor));
}
}
1160
24. JavaScript...
<BODY BGCOLOR="RED">
<Hl>MatchColor</Hl>
<APPLET CODE="MatchColor.class" WIDTH=300 HEIGHT=300 MAYSCRIPT>
</APPLET>
</BODY>
</HTML>
,
. 24.29 Web,
: , , ,
. HTML-,
.
, HTML-,
.
, .
. 24.33.
2 4 . 2 9 . E v e r e s t . html
<1D0CTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
<TITLE>Design Your T r e k ! < / T I T L E >
</HEAD>
<BODY>
Transitional//EN">
2 4 . 1 0 . JavaScript Java
24.30.Everest.java
import
import
import
import
/**
*
*
*
*
*
*
*
*
*
*
Java.applet.Applet;
java.awt.*;
Java.awt.event.^;
netscape.j avascript.JSObject;
, .
HTML-, .
HTML-.
, -
2 9000 . HTML-
highPeaksForm,
costField altitudeField.
<APPLET ...> MAYSCRIPT.
V
public class Everest extends Applet {
private Image mountainsprivate JSObject window, document, highPeaksForm,
costField, altitudeField;
private int width, heightspublic void init() {
setBackground(Color.lightGray);
mountain = getlmage(getCodeBase(), "images/peakS.gif");
width = getSize (). widthsheight = getSize().height;
// ,
preparelmage(mountain, width, height, this);
setLayout(new BorderLayout());
Font sliderFont = new Font("Helvetica", Font.BOLD, 18);
LabeledCostSlider costSlider =
new LabeledCostSlider("Specify a maximum cost:",
SliderFont, 2000, 20000, 5000,
this);
add(costSlider, BorderLayout.SOUTH);
addMouseMotionListener(new MouseMotionAdapter() {
//
// 29000 ( ) ( ).
//
// JavaScript.
public void mouseMoved(MouseEvent event) {
1161
1162
24. JavaScript...
E v e r e s t , .
L a b e l e d C o s t S l i d e r
. 24.33. L a b e l e d C o s t S l i d e r 24.31.
C o s t S l i d e r ( 24.32) S l i d e r (
24.33) ,
. S l i d e r S c r o l l b a r
Text F i e Id.
2 4 . 1 0 . JavaScript Java
tniglyj
Design Your
Trek!
"I i. jee a bstaig of the treks ttat loterest
you, tract tbe dusked ahitude (t^ to
29,000 feet) liie cost you
your budget can afford. Tlxea
dwose "Show Treks" belofw. Well
show 8 list of pk&ned
Travel expedmons that arc under i b ^
price and reach the desired altitude or
hi^cr'
You car. enter vabcs directly b the
testfields. AJternativdy, select a cost
with the sSder, Also, cbcking the mouse
on the mmwitajn peak '-^^i^ ^^'^ tv..
altitude.
Desired AJtthiid^
Mkdmnin Cost:
. 24.33.
HTML-
1163
1164
24. JavaScript...
maxValue^
initialValue,
app) ;
add(slider, BorderLayout.CENTER);
}
}
24.32.CostSlider.java
/** Slider,
* Everest setCostField
* .
24.33.Slider.java
import j ava.awt.*;
import Java.awt.event.*;
/**
*
*
*
*
*
*
,
( Scrollbar) (
TextField) .
, , setEditable(true),
.
,
,
. ,
. ,
20, - 320,
30 , 10%
.
1165
1166
24. JavaScript.
setTextFieldValue();
doAction(scrollbar.getValue());
}
/** Scrollbar, Slider. */
public Scrollbar getScrollbar() {
return(scrollbar);
}
/** TextField, Slider */
public TextField getTextField() {
return(textfield);
}
/ ,
* .
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
d.height = textfield.getPreferredSize().height;
d.width = Math.max(d.width, preferredWidth);
return(d);
}
public Dimension getMinimumSize() {
return(getPreferredSize() ) ;
}
/** ,
* .
* ( 150).
public int getPreferredWidth {
return(preferredWidth) ;
}
/** ,
* .
* ( 150).
public void setPreferredWidth(int preferredWidth) {
this.preferredWidth = preferredWidth;
}
/** */
public int getValue {
return(scrollbar.getValue());
}
/ .
* ,
*
* .
*/
V
public String getText() {
return(textfield.getText() ) ;
}
/ .
"^ ,
* , ,
* .
V
public void setText(String text) {
textfield.setText(text) ;
}
/** Font,
* .
* Courier 12 .
public Font getFontO {
return(textfield.getFont());
}
/** , . */
public void setFont(Font textFieldFont) {
textfield.setFont(textFieldFont);
}
/** . */
public int getFontSize() {
return(getFont().getSize());
}
1167
1168
24. JavaScript.
/** ,
* [ .
V
public void setFontSize(int size) {
setFont(new Font("Monospaced", Font.BOLD, size));
}
/** ,
* . ,
* ,
* .
* ,
* .
* .
V
public boolean isEditableO {
return(textfield.isEditable());
}
/** ,
* .
public void setEditable(boolean editable) {
textfield.setEditable(editable);
}
// ,
// .
private void setTextFieldValue () {
int value = scrollbar.getValue();
int digits = numDigits(scrollbar.getMaximum());
String valueString = padString(value, digits);
textfield.setText(valueString);
}
// ,
//
// .
private String padString(int value, int digits) {
String result = String.valueOf(value);
for(int i=result.length 0 ; i<digits; i++) {
result = " " + result;
}
return(result + " " ) ;
}
// .
private static final double LNIO = Math.log(10.0);
private static int numDigits(int num) {
return(1 + (int)Math.floor(Math.log((double)num)/LNIO));
}
2 4 . 1 0 . JavaScript Java
1169
V
public class ScrollbarPanel extends Panel {
private Insets insets;
public ScrollbarPanel(int margins) {
setLayout(new BorderLayout());
setMargins(margins);
}
public Insets insets 0 {
return(insets) ;
}
public int getMarginsO {
return(insets.top);
}
public void setMargins(int margins) {
this.insets = new Insets(margins, 0, margins, 0 ) /
}
}
JSObject
JSObject . JSObject
f i n a l , . . .
public Object call(String methodName, Object[] args)
JavaScript- .
public Object eval(String javaScriptCode)
JavaScript-.
public Object getMember(String propertyName)
getMember .
.
public Object getSlot(int array Index)
.
.
1170
24. JavaScript...
p u b l i c static J S O b j e c t g e t W i n d o w ( A p p l e t applet)
JavaScript- Window,
, .
public void r e m o v e M e m b e r ( S t r i n g p r o p e r t y N a m e )
removeMember .
public void s e t M e m b e r ( S t r i n g p r o p e r t y N a m e , Object value)
.
public v o i d setSlot(int a r r a y l n d e x , Object value)
.
24.11.
, JavaScript
. JavaScript- .
HTML- Web-.
HTML-.
cookie.
Java JavaScript.
Window, Document, N a v i g a t o r
JavaScript 1.2.
, JavaScript-.
JAVASCRIPT
...
, , : Naviga
t o r , P l u g i n , Screen .
, HTML-: window.
Document, L a y e r , Image .
, HTML-
(Form, Text, B u t t o n , S e l e c t ) ,
,
.
: s t r i n g . A r r a y , F u n c t i o n ,
Math, Date .
: RegExp.
Lry\zj.3z:j
JavaScript
. , ,
, JavaScript 1.2. JavaScript 1.2
Netscape, Internet Explorer 4.0 .
JavaScript h t t p : / / d e v e l o p e r .
netscape.com/docs/manuals/javascript.html.
2 5 . 1 . Array
JavaScript
. JavaScript 1.1
A r r a y .
n e w
.
. :
v a r = new A r r a y ( ) ;
[12] = "foo";
/ / .length =
/ / . l e n g t h = 13
n e w Array(length)
.
, l e n g t h - 1 .
n u l l .
1174
25. JavaScript
, JavaScript 1.2,
Netscape.
, , ,
, . Internet
Explorer . Netscape
JavaScript 1.3.
n e w Array(entryO, entry 1 , . . . , entryN)
N, .
[entryO, entry 1 , . . . , e n t r y N ]
"" . ,
:
v a r a l = new A r r a y C ' f o o " , " b a r " , " b a z " ) ;
v a r a2 = [ " f o o " , " b a r " , " b a z " ] ;
length
.
. l e n g t h
, .
, .
, ,
u n d e f i n e d (
n u l l == t r u e ) .
concat(secondArray)
,
, ( s e c o n d A r r a y ) .
join()
j o i n ( d e l i m i t e r String)
,
.
,
, d e l i m i t e r S t r i n g (
).
reverse()
.
.
2 5 . 1 . Array
1175
slice(startlndex)
slice(startlndex, endlndex)
s l i c e ,
s t a r t l n d e x endlndex, . s t a r t l n d e x
, endlndex .
sort()
sort(comparisonFunction)
(. . s o r t )
, .
( c o m p a r i s o n F u n c t i o n ) .
.
, "" ,
, "", ,
"" . ,
maxSpeed .
function slower(carl, 2) {
return(carl.maxSpeed - car2.maxSpeed);
}
25.1
( maxSpeed). . 25.1.
25.1. Sort.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
<HEAD>
<TITLE>Sorting</TITLE>
<SCRIPT TYPE="text/javascript">
<!
function makeObjectTable(name, object) {
document.writeln("<H2>" + name + "</H2>") ;
document.writeln("<TABLE BORDER=l>\n" +
" <TR><TH>Field<TH>Value") ;
for(field in object) {
document.writeln(" <TR><TD>" + field + "<TD>" +
object[field]);
}
document.writeln("</TABLE>");
}
// >
</SCRIPT>
</HEAD>
<BODY>
<Hl>Sorting</Hl>
<SCRIPT TYPE="text/javascript">
<!
1176
25. JavaScript
function carStringO {
return("Car{" + this.maxSpeed + " } " ) ;
}
function Car(maxSpeed) {
this.maxSpeed = maxSpeed;
this.toString = carString;
}
function slower(carl, car2) {
return(carl.maxSpeed - car2.maxSpeed);
}
var cars = new Array(new Car(10), new Car(20),
new Car(30), new Car(25),
new Car(15), new Car(5));
// ~ >
</SCRIPT>
<TABLE>
<TR><TD>
<SCRIPT TYPE="text/javascript">
<!
makeObjectTable("Original Car Array", cars);
// >
</SCRIPT>
<TD><PRE>
</PRE>
<TD><SCRIPT TYPE="text/javascript">
<!
cars.sort(slower) ;
makeObjectTable("Sorted Array (slow to fast)", cars)
// >
</SCRIPT>
</TABLE>
</BODY>
</HTML>
file
'
yw
Favorite
lixjl
Hefc ""
"H
Sorting
Original Car Array
Field
Value
Sorted Arra
Vle
Car{lO}
10
Cttr{5}
Cai{20}
il
C<u-{10}
.Car{ 30} :
{15}
:Car{25}
;3
Car {20}
:{15}
|4
4{25}
Car{5}
,5
Car{30)
J Dane
:/<:?<-1'1"
''^iAifCcnpdtmW^%
. 25.1. JavaScript
,
25.2. Button
1177
25.2. Button
B u t t o n , .. ,
<INPUT TYPE="BUTTON" . . . >.
B u t t o n ,
<INPUT TYPE="SUBMIT"
...>H<INPUT
TYPE="RESET"
. . . > ,
SUBMIT RESET S u b m i t R e s e t .
B u t t o n e l e m e n t s ,
, , d o c u m e n t . f ormName . b u t t o n N a m e ,
f ormName , a b u t t o n N a m e .
form
, , Form,
, .
name
NAME,
name. .
type
B u t t o n b u t t o n .
SUBMIT RESET s u b m i t r e
s e t . E l e m e n t t y p e ,
. t y p e .
value
,
. SUBMIT
.
blurO
.
clickO
,
, o n C l i c k . SUBMIT
RESET c l i c k s u b m i t r e s e t .
1178
25. JavaScript
focus()
f o c u s .
onblur()
.
o n B l u r , .
<INPUT TYPE="BUTTON" . . .
onBlur="doSomeAction()">
onclickO
o n c l i c k , .
c l i c k o n c l i c k .
o n C l i c k , .
<INPUT TYPE="BUTTON" . . .
onClick="doSomeAction()">
f a l s e , ,
(,
) , . :
<INPUT TYPE="RESET" . . .
onClick="return(maybeReset())">
o n S u b m i t o n R e s e t ,
.
ondblclickO
o n d b l c l i c k .
o n c l i c k .
o n D b l C l i c k ; Macintosh Netscape 6.
onfocusO
on f o c u s , .
o n F o c u s .
25.3. Checkbox
C h e c k b o x , .. ,
<INPUT TYPE="CHECKBOX" . . . >. )^
Checkbox e l e m e n t s , ,
, d o c u m e n t . f ormName . checkboxName, f ormName
, a checkboxName .
25.3. Checkbox
1179
checked
, , ,
, ,
.
defaultChecked
d e f a u l t C h e c k e d , ,
.
CHECKED .
form
, , Form,
.
, , ,
NAME.
type
" c h e c k b o x " .
t y p e E l e m e n t ,
, f o r m , e l e m e n t s .
t y p e .
value
, , ,
,
, .
blurO
.
clickO
,
, o n C l i c k .
focus()
f o c u s .
1180
25. JavaScript
onblur()
.
o n B l u r , .
<INPUT TYPE="CHECKBOX" . . .
onBlur="doSomeAction()">
onclickO
o n c l i c k ,
. c l i c k o n c l i c k .
o n C l i c k .
onfocusO
o n f OCUS , .
on F o c u s .
25.4. Date
D a t e
.
n e w Date()
D a t e , .
n e w Date(year, m o n t h , day)
D a t e , .
n e w Date(year, m o n t h , day, h r s , m i n s , sees)
D a t e , .
n e w Date("month day, year hrs:mins:secs")
D a t e .
(month), . :
var bOay = new Date("January 30, 1962 00:00:00");
new Date(millisecondsSinceEpoch)
D a t e ,
, .. (GMT)
1970 .
25.4. Date
1181
, p a r s e D a t e UTC
D a t e , "" D a t e (..
). D a t e . p a r s e D a t e
Date.UTC. s o m e D a t e O b j e c t .
m e t h o d ( a r g s ) , s o m e D a t e O b j e c t D a t e , m e t h o d , a a r g s
.
getDateO
setDate(dayOfMonth)
. 1 31.
getDayO
g e t Day .
; , 6 .
getHoursO
setHours(hours)
.
23.
getMinutesO
setMinutes(minutes)
g e t M i n u t e s ,
g e t H o u r s . s e t M i n u t e s
.
59.
getMonthO
setMonth(monthlndex)
.
() 11 ().
getSecondsO
setSeconds(seconds)
, )',
g e t M i n u t e s . 59.
1182
25. JavaScript
getTimeO
setTime(millisecondsSincepoch)
g e t T i m e , s e t T i m e ,
(GMT) 1 1970 .
getTimezoneOffsetO
GMT .
getFuUYearO
setFullYear(year)
, g e t F u l l Y e a r , , D a t e ,
, . , s e t F u l l Y e a r ,
D a t e ,
1 1970 . , D a t e . ,
g e t F u l l Y e a r / s e t F u l l Y e a r JavaScript 1.0
,
, , .
parse(dateString)
D a t e .
D a t e . p a r s e .
,
, 1
1970 . p a r s e IETF,
Internet ( t o G M T S t r i n g ) . :
// .
var dateString = "Wed, 3 Sep 1997 08:30:00 -0700";
var dl = new Date(Date.parse(dateString));
// .
document.writeln(dl.toLocaleString());
p a r s e "Month Day, Y e a r "
(" , "),
( ). IETF
(, EDT).
toGMTStringO
, ,
GMT. IETF (.
parse).
toLocaleStringO
t o L o c a l e S t r i n g ,
D a t e .
.
25.5. Document
1183
UTC(year, m o n t h , day)
UTC(year, m o n t h , day, hrs)
UTC(year, m o n t h , day, h r s , mins)
UTC(year, m o n t h , day, hrs, m i n s , sees)
D a t e .
Date.UTC. ,
, GMT (
, UTC).
, 1 1970 .
. D a t e
HTML-.
25.5. Document
! Window docnent,
, .
w i n d o w , d o c u m e n t , , , d o c u m e n t .
alinkColor
,
. ALINK <BODY>
HEAD (
, BODY). a l i n k C o l o r
.
anchors
a n c h o r s A n c h o r ,
< NAME= . . . >.
applets
)^ A p p l e t ,
<APPLET . . . >.
<APPLET> )^ MAYSCRIPT,
JavaScnpt-.
. 24.9.
bgColor
, .
BGCOLOR
1184
25. JavaScript
<BODY>, . b g C o l o r
, . :
document.bgColor = "red";
document.bgColor = "#OOFFOO"; //
cookie
, , ,
cookie, . c o o k i e
cookie, ( . 24.7).
domain
d o m a i n , Internet-,
. . JavaScript
,
(, ,
Java-.
JavaScript Java . 24.9.
embeds
)' J a v a O b j e c t ,
EMBED .
Java-,
, . e m b e d s
p l u g i n s .
fgColor
,
. f g C o l o r
TEXT <BODY> ,
HEAD . f g C o l o r )^ .
forms
, Form,
<FORM . . . >.
Form 25.8.
images
Image,
<IMG . . . >. . 24.5.
lastModified
l a s t M o d i f i e d .
, Web-
, , l a s t M o d i f i e d .
)' .
25.5. Document
1185
linkColor
.
, ,
. l i n k C o l o r
LINK <BODY>
HEAD . )' .
links
L i n k ,
< HREF. . . >.
location
l o c a t i o n , ,
L o c a t i o n , window, l o c a t i o n , URL,
. d o c u m e n t . URL
URL.
plugins
e m b e d s . ,
p l u g i n s P l u g i n , J a v a O b j e c t
, , .
, ,
n a v i g a t o r . p l u g i n s .
referrer
r e f e r r e r (, ),
URL . ,
Web-.
.
title
t i t l e , <TITLE>.
.
URL
, URL . .
vlinkColor
.
, ,
. v l i n k C o l o r
VLINK <BODY>
HEAD . v l i n k C o l o r .
1186
25. JavaScript
close()
.
, . o p e n
c l o s e .
getSelectionO
g e t S e l e c t i o n , .
()
open(mimeType)
o p e n ( m i m e T y p e , "replace")
.
, w r i t e
w r i t e l n . o p e n
-.
"replace",
, .
write(argl, a r g 2 , . . . , argN)
w r i t e l n ( a r g l , a r g 2 , . . . , argN)
;
.
Document . o n l o a d
o n u n l o a d <BODY> Window,
Document.
25.6. Element
E l e m e n t
e l e m e n t s Form. Form d o c u m e n t . f o r m s
, , d o c u m e n t . f ormName,
f ormName . e l e m e n t s
E l e m e n t , : B u t t o n , Checkbox
.. ,
.
E l e m e n t .
;
.
25.6. Element
1187
checked
Checkbox Radio.
defaultChecked
Checkbox Radio.
defaultValue
FileUpload, Password, Text Textarea.
form
Element HTML, .
length
S e l e c t .
name
Element
HTML- NAME.
options
Select.
selectedlndex
Select.
type
JavaScript LI Element
. t y p e
: b u t t o n , checkbox, f i l e , hidden, password, r a d i o , r e s e t ,
select-one, select-multiple,submit,text textarea.
value
Element ,
. .
,
Element.
.
1188
25. JavaScript
blurO
E l e m e n t
H i d d e n .
clickO
Button, Checkbox, Radio, Reset Submit.
focus()
E l e m e n t
H i d d e n .
select()
E l e m e n t ,
, : F i l e U p l o a d , P a s s w o r d , T e x t T e x t a r e a .
E l e m e n t .
onblur()
E l e m e n t
H i d d e n .
onchange()
F i l e U p l o a d , P a s s w o r d , T e x t T e x t a r e a .
onclickO
Button, Checkbox, Radio, Reset
Submit.
ondblclick()
B u t t o n , R e s e t S u b m i t .
onfocus()
E l e m e n t
H i d d e n .
25.7. FileUpload
F i l e U p l o a d ,
<INPUT TYPE="FILE" . . . >.
e l e m e n t s , Form.
25.7. FileUpload
1189
form
, ,
Form, .
name
NAME,
. name .
type
f i l e . t y p e
E l e m e n t ,
.
value
v a l u e ,
VALUE. .
blurO
.
focus()
.
select()
. ,
, .
onblurO
.
o n b l u r o n B l u r , :
<INPUT TYPE="FILE" . . .
onBlur="doSomeAction()">
onchange()
on c h a n g e ,
.
o n C h a n g e .
1190
25. JavaScript
onfocusO
o n f o c u s , o n F o c u s ,
.
25.8. Form
Form HTML- Form. Form
d o c u m e n t . f o r m s . ,
d o c u m e n t . f ormName, f ormName .
action
, URL,
. a c t i o n ,
.
elements
e l e m e n t s , E l e
m e n t . ,
HTML-. E l e m e n t 25.6.
encoding
, .
ENCTYPE.
e n c o d i n g , .
method
, METHOD,
g e t , p o s t . m e t h o d
, .
target
t a r g e t , ,
, .
TARGET.
reset()
o n r e s e t , ,
t r u e ,
, . ,
RESET.
25.9. Function
1191
submit()
,
o n s u b m i t .
onreset()
RESET
r e s e t . o n r e s e t
onReset.
<FORM A C T I O N = " . . . "
...
onReset="return(maybeReset())">
onsubmit()
o n s u b m i t SUBMIT.
s u b m i t o n s u b m i t .
o n S u b m i t .
<FORM A C T I O N = " . . . " . . .
onSubmit="return(validateEntries ())">
o n s u b m i t . 24.6.
25.9. Function
F u n c t i o n JavaScript.
n e w Function(argOName,... , a r g N N a m e , bodyString)
.
,
.
function square() { return( * ) ; }
square = new Function("", "return( * )");
arguments
,
. a r g u m e n t s
.
:
1192
25. JavaScript
function sum {
var t o t a l = 0;
f o r ( v a r i=0; i < a r g u m e n t s . l e n g t h ; i++) {
t o t a l = t o t a l + arguments[i];
}
return(total) ;
}
arity
, ,
, .
a r i t y ,
arguments . l e n g t h .
caller
Function,
.
, c a l l e r n u l l .
.
prototype
p r o t o t y p e ,
. p r o t o t y p e .
24.3.
F u n c t i o n ,
Obj e c t .
. F u n c t i o n
HTML-.
25.10. Hidden
Hidden ,
<INPUT TYPE="HIDDEN" . . . >.
e l e m e n t s Form. ,
document. formName . elementName,
formName , elementName .
2 5 . 1 1 . History
1193
form
, ,
Form, .
name
, , ,
NAME.
type
t y p e h i d d e n .
value
,
.
2 5 . 1 1 . History
H i s t o r y .
JavaScript, .
H i s t o r y h i s t o r y Window, .
w i n d o w , h i s t o r y h i s t o r y .
current
JavaScript- URL . c u r
r e n t .
length
URL,
.
next
, n e x t , URL
. .
1194
25. JavaScript
previous
p r e v i o u s ,
URL .
.
.
forwardO
.
go(n)
(
) ( ) .
. H i s t o r y
HTML-.
25.12. Image
Image , HTML-
<IMG SRC=" . . . " . . . >. Image
d o c u m e n t . i m a g e s . ,
d o c u m e n t . imageName, imageName
.
JavaScript. . 24.5.
n e w I m a g e ( w i d t h , height)
I m a g e ,
. Image , ,
s r c ,
. ,
s e t Image .
Image . 24.5.
2 5 . 1 2 . Image
1195
border
,
, .
b o r d e r , ,
BORDER IMG.
complete
, ,
, , .
height
h e i g h t ,
HEIGHT, , HEIGHT ,
. .
hspace
h s p a c e
. ;
HSPACE.
lowsrc
Netscape ( Internet Explorer) LOWSRC
IMG, ,
.
, LOWSRC,
l o w s r c . , .
name
, ,
, NAME.
src
, URL
, . s r c , .
vspace
v s p a c e , ,
.
VSPACE.
width
w i d t h ,
WIDTH, , WIDTH ,
. .
1196
25. JavaScript
onabort()
,
, S t o p ,
Web-. o n a b o r t
o n A b o r t , .
<IMG S R C = " . . . "
...
onAbort="takeSomeAction()">
onerror()
o n e o r , ,
, .
o n e o r .
<IMG S R C = " . . . " . . .
onError="alert Error loading
image')">
n u l l o n E r r o r .
<IMG SRC="..." ...
onError ="null">
onload()
o n l o a d , .
s r c .
o n l o a d onLoad.
<IMG S R C = " . . . "
...
onLoad="startImageAnimation()">
s t a r t l m a g e A n i m a t i o n
s r c , , , s t a r t l m a g e A n i m a t i o n .
25.13. JavaObject
J a v a O b j e c t JavaScript- Java ()
d o c u m e n t . e m b e d s , Java-.
,
f o r / i n . , (reflection), Java 1.1 .
2 5 . 1 4 . JavaPackage
1197
25.14. JavaPackage
J a v a P a c k a g e J a v a , n e t s c a p e , s u n
P a c k a g e s Window. Java-;
, J a v a . l a n g . S y s t e m . g e t P r o p e r t y .
. 24.9.
25.15. Layer
Netscape 4.0 , ,
. LAYER ILAYER,
. . 24.5.
, Netscape 6.0 HTML 4.0
LAYER ILAYER .
n e w Layer(width)
L a y e r .
s r c l o a d .
n e w Layer(width, parentLayer)
, .
above
, ,
.
background
. b a c k g r o u n d
, . :
someLayer.background.src = "bricks.gif";
below
, ,
.
bgColor
, b g C o l o r ,
, , . :
someLayer.bgColor = " b l u e " ;
1198
25. JavaScript
anotherLayer.bgcolor = "#FFOOFF";
thirdLayer.bgColor = null; //
clip
, , ,
. c l i p , t o p , c l i p . b o t t o m , c l i p , l e f t ,
clip.right, clip.width clip.height.
document
Document. ,
, .
left
. l e f t .
name
name ID
NAME.
pageX
(
) . , .
pageY
(
) . pageY , .
parentLayer
p a r e n t L a y e r ,
. Window.
.
siblingAbove
, .
, ,
. s i b l i n g A b o v e .
siblingBelow
, .
, ,
. s i b l i n g A b o v e .
src
, , , URL,
.
25.15. Layer
1199
top
. t o p , .
visibility
v i s i b i l i t y .
show ( ), h i d e , h i d d e n ( ) i n h e r i t
( ).
, .
zindex
,
.
, .
z i n d e x , .
l o a d ( s o u r c e S t r i n g , width)
, (.
s r c ) .
moveAbove(layer)
moveAbove .
moveBelow(layer)
moveBelow .
m o v e B y ( d x , dy)
.
m o v e T o ( x , )
,
. . l e f t t o p .
m o v e T o A b s o l u t e ( x , )
m o v e T o A b s o l u t e ,
(. pageY).
resizeBy(dWidth, d H e i g h t )
(. c l i p . w i d t h c l i p . h e i g h t ) .
1200
25. JavaScript
resizeTo(width, h e i g h t )
r e s i z e T o (.
clip.width clip.height).
onblurO
, .
o n B l u r LAYER ILAYER.
,
, :
function blurHandler() { ... }
someLayer.onblur = blurHandler;
onfocus()
.
on F o c u s .
onload()
o n l o a d (
, ).
o n L o a d .
onmouseout()
o n m o u s e o u t ,
. onMouseOut.
onmouseoverO
o n m o u s e o v e r ,
. o n M o u s e O v e r .
25.16. Link
L i n k ,
< HREF=. . .>. , Windows,
L i n k .
)^ d o c u m e n t . l i n k s .
NAME, <> NAME
.
25.16. Link
1201
hash
,
( "#"). h a s h , .
host
_: .
hostname
hostname , .
href
URL , .
pathname
pathname URL,
. , .
port
, ,
. p o r t , .
protocol
, , , .
.
search
s e a r c h ,
(, "?," ISMAP "?=1&=2"
). , .
target
t a r g e t , TARGET.
, . , , ,
,
framel,
:
for(var i=0; i<document.links.length; i++) {
document.links[i].target = "framel";
}
1202
25. JavaScript
, , .
onclickO
.
f a l s e , .
o n c l i c k onClick, :
< H R E F = " . . . "
...
onClick="return(maybeCancel() ) ">
ondblclick()
.
o n c l i c k . o n d b l c l i c k Macintosh
Netscape 6.
onmouseout()
,
. onmouseover onmouseout
,
, .
. 24.5. onmouseout
onMouseOut.
onmouseover()
,
. onmouseover
onMouseOver. onMouseOver t r u e ,
URL .
.
25.17. Location
L o c a t i o n URL
window.location.
hash
,
( "#"). hash , .
25.17. Location
1203
host
_: .
hostname
hostname , .
href
URL , .
pathname
pathname URL,
. , .
port
, ,
. p o r t , ,
protocol
, , , .
.
search
s e a r c h ,
(, "?," ISMAP "?=1&:=2"
). , .
s e a r c h
CGI-, .
URL
l o c a t i o n . s e a r c h ( u n e s c a p e 25.31).
reloadO
reload(true)
.
, ,
.
.
replace(newURL)
,
newURL. .
1204
25. JavaScript
25.18. Math
M a t h HTML-.
. M a t h
, Java- J a v a . l a n g . M a t h .
M a t h ,
M a t h . p r o p e r t y N a m e M a t h . m e t h o d N a m e { . . . ) , p r o p e r t y N a m e
, a m e t h o d N a m e .
, ,
.
.
LN10
In(10) log^(lO).
LN2
1(2), log^(2).
LOG10E
logio(e).
LOG2E
lg(e) log2(e).
PI
.
SQRT1_2
1/2.
SQRT2
2.
2 5 . 1 8 . Math
1205
abs(num)
(num).
ceil(num)
c e i l ,
(num).
exp(num)
^
num
floor(num)
c e i l , ,
(num).
log(num)
(num).
JavaScript
(, 10 2).
1()
= 12()
12()
, , :
exponent
pow b a s e
random()
r a n d o m 0.0 1.0 ( 0.0
, 1.0 ).
1206
2 5 . JavaScript
round(num)
, num,
. . 5 .
sqrt(num)
s q r t num.
, NaN.
,
. :
function degreesToRadians(degrees) {
return(degrees * Math.PI / 180);
}
acos(num)
,
num. .
asin(num)
, } num.
atan(num)
1 .
atan2(y, )
a t a n 2 0 ( , ) ,
( , ) .
/ - .
cos(radians)
, .
sin(radians)
, .
tan(radians)
, .
2 5 . 1 9 . MimeType
1207
2 5 . 1 9 . MimeType
MimeType MIME-. n a v i g a t o r . m i m e T y p e s
-, ,
, . ,
Adobe Acrobat
, Acrobat .
, .
d o c u m e n t . w r i t e l n ( ' F o r more i n f o r m a t i o n , s e e ' ) ;
i f ( n a v i g a t o r . m i m e T y p e s [ " a p p l i c a t i o n / p d f " ] != n u l l ) {
document.writeln
('<A H R E F = " m a n u a l . p d f " > t h e w i d g e t m a n u a l < / A > . ' ) ;
} else {
document.writeln
(*<A H R E F = " m a n u a l . t e x t " > t h e w i d g e t m a n u a l < / A > . ' ) ;
}
MIME- . . 19.1.
description
, , ,
-.
enabledPlugin
e n a b l e d P l u g i n P l u g i n ,
-.
, e n a b l e d P l u g i n
n u l l . .
suffixes
, -.
. s u f f i x e s
.
type
application/postscript.
. MimeType
HTML-.
1208
25. JavaScript
2 5 . 2 0 . Navigator
N a v i g a t o r .
n a v i g a t o r Window, ..
N a v i g a t o r w i n d o w . n a v i g a t o r n a v i g a t o r .
N a v i g a t o r . 25.2
, , .
. 25.2 25.3.
appCodeName
, ,
. Internet Explorer Netscape M o z i l l a .
appName
, Netscape Micro
soft Internet Explorer. appName .
appVersion
a p p V e r s i o n , ,
, .
language
l a n g u a g e , ,
. e n .
mimeTypes
MimeType,
, ,
(. 25.19).
platform
p l a t f o r m ,
. , Windows 95, 98 N T
Win32. p l a t f o r m .
plugins
P l u g i n ,
. . 24.4.
2 5 . 2 0 . Navigator
1209
userAgent
, U s e r A g e n t . u s e r A g e n t .
. 25.2 25.3 .
, 25.2.
BTiorxl
''
. .. 3 <-^r ^ ^ .,s r
The Navigator Object
Property
t si\
Value
1 appCodeName Mozilla
1 appName
Netscape
appVersion
4 7 [en] (Wm98, )
userAgent
j^*i ::;]}
Document Done
The Navigatof O b ^ t
File
. 25.2. Navigator,
Netscape 4.7,
Windows 98
%^in View
FgYorftes
Tods fc^dp
~3
Value
appCodeName Mozilla
appName
app Version
userAgent
J
<] Done
i-jMyConnpirfef
. 25.3.
Navigator,
Internet Explorer 5.0,
Windows 98
2 5 . 2 . N a v i g a t o r . htll
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4 . 0
<HTML>
<HEAD>
<TITLE>The N a v i g a t o r O b j e c t < / T I T L E >
Transitional//EN">
1210
25. JavaScript
"<TD>" + object[propertyName]);
}
document.writeln("</TABLE>");
}
// >
</SCRIPT>
</HEAD>
<BODY BGCOLOR="WHITE">
<SCRIPT TYPE="text/javascript">
<!
var propNames = new Array("appCodeName", "appName",
"appVersion", "userAgent");
makePropertyTable("The Navigator Object", navigator, propNames);
// >
</SCRIPT>
</BODY>
</HTML>
javaEnabledO
t r u e , Java Java . f a l s e .
taintnabled()
t r u e ,
NSENABLETAINT. JavaScript-
. Netscape
JavaScript 1.2
. JavaScript
h t t p : / / d e v e l o p e r . n e t s c a p e . c o m / d o c s / m a n u a l s / j s / c l i e n t / j sguide/sec.htm.
. N a v i g a t o r
HTML-.
2 5 . 2 1 . Number
Number ,
. .
Number .propertyName, p r o p e r t y -
2 5 . 2 1 . Number
1211
Name . Number ,
t o S t r i n g , .
new Number(value)
Number ,
v a l u e .
MAX_VALUE
MAX_VALUE , JavaScript.
MIN_VALUE
MIN_VALUE , JavaScript.
NaN
NaN (not-a-number ).
isNaN.
== , NaN
( Number. NaN ==- Number. NaN)
f a l s e .
NEGATIVE J N F I N I T Y
,
.
,
toStringO
, t o S t r i n g
{10).
toString(radix)
,
, r a d i x . , , -
1212
25. JavaScript
25.3, ,
. Netscape 4.7,
Windows 98, . 25.4.
2 5 . 2 2 . Object
i-
1213
::-:: ::%;?:::;>
J -C
Basel
Base 8 Base 16
1 ^
1
2
'^
2
4
10
100
11
11
^
'5
7^
101
no
111
1000
10
;iooi
11
10
1010
'l2
15
nil
17
144
100
nooioo
512
1000
1000
i n n O l O O O 1750
t^f-^
8
5
1
1
64
200
3e8
DocumenJ Done
1
1
1
;^
. 25.4. Number
valueOfO
, Number.
. Number
HTML-.
2 5 . 2 2 . Object
Ob j e c t , .
Ob j e c t JavaScript.
n e w ObjectO
Ob j e c t .
n e w Object(primitiveValue)
Number,
S t r i n g , B o o l e a n F u n c t i o n .
{propl:vall, prop2:val2,..., propNrvalN)
, "" .
1214
25. JavaScript
constructor
, , JavaScript, .
prototype
p r o t o t y p e O b j e c t , , , ,
. ,
, .
. 24.3.
assign(value)
,
.
a s s i g n .
eval(javaScriptCode)
.
toStringO
t o S t r i n g , .
valueOfO
, , ,
(. 15.21).
25.23. Option
O p t i o n OPTION SELECT.
o p t i o n s S e l e c t , ,
, e l e m e n t s Form.
n e w Option()
new Option(text)
n e w O p t i o n ( t e x t , value)
n e w O p t i o n ( t e x t , value, d e f a u l t S e l e c t e d )
n e w O p t i o n ( t e x t , value, d e f a u l t S e l e c t e d , s e l e c t e d )
O p t i o n ,
S e l e c t , o p t i o n s .
25.24. Password
1215
defaultSelected
, ,
O p t i o n . d e f a u l t S e l e c t e d
SELECTED .
index
, ,
O p t i o n o p t i o n s S e l e c t .
selected
, ,
, . s e l e c t e d
, .
text
t e x t , SELECT.
, .
value
,
S e l e c t .
VALUE ,
.
. o n b l u r , o n f o c u s o n c h a n g e
O p t i o n , S e l e c t .
25.24. Password
P a s s w o r d , .. HTML-,
< INPUT TYPE=" PAS SWORD" . . . >.
P a s s w o r d e l e m e n t s Form.
, d o c u m e n t .
f ormName. passwordName, f ormName , a passwordName
.
1216
25. JavaScript
defaultValue
, , ,
VALUE.
form
f o r m Form,
. .
name
name )' NAME.
type
password.
value
,
. , UNIX
, , ,
.
blurO
.
focus()
.
select()
. ,
, .
onblurO
, .
o n B l u r .
onchange()
o n c h a n g e ,
, .
o n C h a n g e .
25.25. * Plugin
1217
onfocus()
, .
on F o c u s .
onkeydown()
,
. onkeydown f a l s e ,
.
onkeypress()
o n k e y p r e s s
onkeydown. o n k e y p r e s s
, o n k e y d o w n . o n k e y p r e s s f a l s e ,
.
onkeyupO
o n k e y u p , .
25.25. Plugin
,
n a v i g a t o r . p l u g i n s . ,
, , ;
e m b e d s Document. P l u g i n
. ,
MimeType. P l u g i n
MimeType . ^ 24.4.
description
, , ,
.
filename
f i l e n a m e ,
. .
, length
l e n g t h MimeType .
name
.
document.plugins.
1218
25. JavaScript
. P l u g i n
HTML-.
25.26. Radio
R a d i o ,
<INPUT TYPE="RADIO" . . . >.
R a d i o e l e m e n t s
Form. R a d i o , ,
,
d o c u m e n t . formName. r a d i o N a m e , formName , r a d i o N a m e
.
checked
, , ,
. c h e c k e d ,
.
defaultChecked
d e f a u l t C h e c k e d , ,
.
CHECKED .
form
, , Form,
.
name
name
NAME. ,
.
.
type
r a d i o . E l e m e n t
t y p e ,
, f o r m . e l e m e n t s . t y p e
.
25.27. RegExp
1219
value
, v a l u e
CGI- .
, .
blurO
.
clickO
,
, o n C l i c k .
c l i c k , c h e c k e d .
focus()
.
onblurO
o n b l u r , .
o n B l u r , .
<INPUT TYPE="RADIO" . . .
onBlur="doSomeAction()">
onclickO
, c l i c k . o n c l i c k
o n C l i c k .
onfocus()
o n f e c u s ,
. o n F o c u s .
25.27. RegExp
Netscape 4.0 RegExp,
. , S t r i n g
m a t c h , r e p l a c e , s e a r c h s p l i t .
n e w RegExpC'pattern")
.
, , -
1220
25. JavaScript
(. . 15.1). +
( ), * (,
) ? (
).
.
, :
" 'z', '', ' ,
( ) '',
'd', ''".
var re = new RegExp("za+bc*d?e");
RegExp t e s t ,
t r u e , 1.
! r e ,
, t e s t
true:
re.test("zabcde");
re.test("xxxxxzabcdexxxxx");
re.test("zaaaabcde") ;
re.test("zaaaabde") ;
re.test("zaaaabe");
re.test("XXzaabcccccdeYY") ;
n e w RegExpC'pattern", "g")
,
. S t r i n g m a t c h ,
, ,
. "g" , ,
. ,
m a t c h S t r i n g .
m a t c h ,
" " , ,
" " " a b b b b c " .
var
var
var
var
var
str = "abcabbbbcABCABBBBC";
rel = new RegExp("ab+c");
re2 = new RegExp ("ab-t-c", " g " ) ;
resultl = str.match(rel);
result2 = str.match(re2);
n e w RegExpC'pattern", "i")
.
n e w RegExpC'pattern", "gi")
. ,
25.27. RegExp
1221
, "",
"abbbbc", "ABC" "".
var str = "abcabbbbcABCABBBBC";
var re = new RegExp("ab+c", "gi");
var result = str.match(re);
/pattern/
new
RegExp ( " p a t t e r n " ). ,
:
var rel = /ab+c/;
var 2 = new RegExp("ab+c");
25.31.
/pattern/g
new
RegExp ( " p a t t e r n " , ' ' g " ) .
/pattern/i
new
RegExp ( ' ' p a t t e r n " , ' ' i " ) .
/pattern/gi
new
RegExp ( ' ' p a t t e r n " , " g i " ) .
RegExp,
. RegExp.
propertyName, propertyName . ($_,
$* ..) , Perl.
input
$_
exec t e s t ,
.
Text, TextArea, S e l e c t Link
. , .
lastMatch
$8
,
.
exec.
1222
25. JavaScript
lastParen
$+
, ,
, .
e x e c .
leftContext
$^
,
, .
. l e f t C o n t e x t ($ )
e x e c .
multiline
$*
, ,
. ,
e x e c .
t r u e .
rightcontext
$'
,
, .
e x e c .
$1
$2
$9
,
.
e x e c .
RegExp,
.
compile(pattern,
flags)
2 5 . 2 7 . RegExp
1223
exec(string)
e x e c ( s t r i n g )
RegExp.
, ..
s o m e R e g E x p ( s t r i n g ) s o m e R e g E x p . e x e c ( s t r i n g ) .
exec()
, e x e c ( R e g E x p . i n p u t ) .
test(string)
, ( s t r i n g )
, ,
t r u e f a l s e . s o m e R e g E x p . t e s t ( s t r i n g ) ,
s t r i n g , s e a r c h ( s o m e R e g E x p ) .
. RegExp
HTML-.
RegExp
"+", "*" "?". . 25.1
. ,
, ,
. , " / + /
" a b b b c " , , "Xxabbbc",
"XXabbbcYYYY" ..
2 5 . 1 . ,
. ,
/ + / "" " a b b b b b c " , " "
. ,
/ * / " " , " " " a b b b b b c "
. ,
/ ? / " " "",
"abbbbbc"
1224
25. JavaScript
. 25.1
. ,
/ . / " " " a q c " , " "
"abbe"
\
.
,
. , / \ * * /
"", " * " " * * * * * "
{)
, , ""
RegExp $^
1 I 2
1 2 . , / f | b a r /
" f o o t b a l l " " b a r s t o o l "
{}
. ,
/ {3 } / " a b b b c " , " a b b e "
"abbbbc"
{, }
. ,
/ { 3 , } / " a b b b c " " a b b b b c " ,
" a b b e "
{ n l ^ 2 }
1 , 2
[12 . . .en]
. ,
/ [1] * / "", " a p p l e " " a l l p e " .
"-". , [ a - z ]
,
[ 0-7 ] (
7) ..
[ ^ele2 . . .en]
, .
, / ["^pl] * / " " " a q q x x e " ,
" a p p l e " " a l l p e "
\b,
(\) (\). ,
/ \ / " ", "",
/ \ / "", " "
\w,
\W
, (\w),
, (\W).
\w [ A - Z a - z 0 - 9 _ ] , \W ['^A-Zaz0-9_]
\ci,
\D
( \ d ) , ( \ D ) .
[ 0 - 9 ] [ ^ 0 - 9 ]
\f,
\t'
\,
^"^
\.
, ,
,
2 5 . 2 8 . 1 Reset
1225
. 25.1
\ S;, \ S
,
( \ s ) , , . (\S).
\ s [ \ f \ n \ r \ t \ v ] , a \ S - - [^\f \ n \ r \ t \ v ]
//
, ASCII-
25.28. Reset
R e s e t RESET ,
<INPUT TYPE="RESET ! " . . . > . R e s e t
e l e m e n t s Form. ,
, R e s e t d o c u m e n t .
formName. r e s e t B u t t o n N a m e , formName , r e s e t B u t t o n N a m e
RESET.
form
, ,
Form, RESET.
, ,
NAME, . name
.
type
r e s e t . t y p e
E l e m e n t ,
. .
value
v a l u e . v a l u e
, .
blurO
RESET .
clickO
,
RESET, o n C l i c k .
c l i c k r e s e t .
1226
25. JavaScript
onblur()
, RESET .
o n b l u r o n B l u r .
<INPUT TYPE="RESET" . . .
onBlur="doSomeAction()">
onclick()
o n c l i c k ,
RESET. c l i c k .
o n C l i c k , .
<INPUT TYPE="RESET" . . .
onClick="doSomeAction()">
o n c l i c k f a l s e , .
:
<INPUT TYPE="RESET" . . .
onClick="return(maybeReset())">
o n R e s e t ,
.
ondblclickO
.
o n c l i c k .
o n D b l C l i c k . Macintosh Netscape 6.
onfocus()
on f o c u s , RESET .
on F o c u s .
25.29. Screen
S c r e e n , s c r e e n ,
.
availHeight
, , (
) ,
, Windows 98.
2 5 . 3 0 . Select
1227
availWidth
, ,
( ) ,
.
colorDepth
c o l o r D e p t h ,
. .
height
h e i g h t , , .
width
w i d t h , , .
pixelDepth
,
. p i x e l D e p t h .
. S c r e e n
HTML-.
25.30. Select
S e l e c t HTML-,
<SELECT . . . >. S e l e c t e l e m e n t s
2, . ,
d o c u m e n t . formName.
s e l e c t N a m e , formName , s e l e c t N a m e SELECT.
25.4 ,
, .
Web-.
1228
25. JavaScript
25.4.SelectColor.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Changing the Background Color</TITLE>
<SCRIPT TYPE="text/javascript">
<!
function setBackgroundColor() {
var selection = document.colorForm.colorSelection;
document.bgColor =
selection.options[selection.selectedlndex].value;
}
// >
</SCRIPT>
</HEAD>
<BODY BGCOLOR="WHITE">
<Hl>Changing the Background Color</Hl>
<FORM NAME="colorForm">
<SELECT NAME="colorSelection"
onChange="setBackgroundColor ()">
<OPTION VALUE="#FFFFFF" SELECTED>White
<OPTION VALUE="#COCOCO">Gray
<OPTION VALUE="#FFOOOO">Red
.<OPTION VALUE="#OOFFOO">Green
<OPTION VALUE="#OOOOFF">Blue
</SELECT>
</FORM>
</BODY>
</HTML>
form
Form, SELECT.
f o r m .
length
l e n g t h , ,
O p t i o n , SELECT. l e n g t h
o p t i o n s . l e n g t h .
name
name , NAME.
.
2 5 . 3 0 . Select
1229
options
o p t i o n s Option,
S e l e c t . Option .
selectedlndex
s e l e c t e d l n d e x .
, -1.
SELECT MULTIPLE,
. s e l e c t e d l n d e x
, .
type
, MULTIPLE,
t y p e s e l e c t - o n e , s e l e c t m u l t i p l e . .
blurO
SELECT .
focus()
focus SELECT .
onblurO
, .
o n b l u r onBlur,
.
<SELECT . . .
onBlur="doSomeAction()">
onchange()
onchange ,
.
25.4.
onfocus()
onf OCUS , .
onFocus.
1230
25. JavaScript
2 5 . 3 1 . String
S t r i n g . HTML, JavaScript-.
new String(value)
S t r i n g .
length
, ,
.
anchor(name)
anchor ,
< NAME="name"> </>. ,
"Chapter One".anchor("Chi")
:
'< NAME="Chl">Chapter One</A>'
bigO
,
<BIG> </BIG>.
blinkO
,
<BLINK> </BLINK>.
boldO
b o l d ,
<> </>. ,
"Wow".italics () . b o l d O
:
"<B><I>Wow</I></B>"
charAt(index)
c h a r At , ,
.
JavaScript, .
2 5 . 3 1 . String
1231
charCodeAt()
charCodeAt(index)
charCodeAt ().
ISO Latin-1 , .
127 ASCII-.
concat(suffixString)
.
:
var newString = stringl.concat(string2);
var newString = stringl + string2;
escape(stri]ig)
Ha e s c a p e S t r i n g , a . ,
e s c a p e ,
. URL- .
,
URL. , "+",
"%20". . 25.5
.
alert(escape("Hello,
world!"));
. 25.5. escape
RL-
URL- u n e s c a p e .
fixedO
,
<></>.
fontcolor(colorName)
f o n t c o l o r ,
<FONT COLOR="colorName"> </FONT>.
fontsize(size)
,
<FONT SIZE=/?^^^>H</FONT>.
1232
25. JavaScript
fromCharCode(codeO, c o d e l , . . . , c o d e N )
, ISO Latin-1.
S t r i n g .
S t r i n g . f r o m C h a r C o d e ( . . . ) . ,
h e l l o S t r i n g HELLO.
var helloString =
String.fromCharCode(72,
79);
indexOf(substring)
indexOf(substring, startlndex)
,
.
, -1. ,
t r u e , :
function contains(string, possibleSubstring) {
return(string.substring(possibleSubstring) != - 1 ) ;
}
,
.
,
startlndex.
italics()
, <1>
</1>.
lastIndexOf(substring)
lastIndexOf(substring, startlndex)
,
,
-1. ,
, .
link(url)
, <
HREF="url">H</A>.
match(regExp)
,
, ,
m a t c h . ,
, "", " a b b b b c " , "ABC" "".
v a r s t r = "abcabbbbcABCABBBBC";
var re = /ab+c/gi;
var r e s u l t = s t r . m a t c h ( r e ) ;
2 5 . 3 1 . String
1233
s t r = "0123456789";
str2 = str.sliced, 5 ) ;
//
str3 = str.substring(1, 5 ) ; //
str4 = str.sliced, - 2 ) ;
//
"1234"
"1234"
"1234567"
small()
,
<SMALL> </SMALL>.
splitO
s p l i t , .
. s p l i t ,
-.
1234
25. JavaScript
split(delimChar)
,
.
- delimChar . ,
,
"f ", "bar" "baz" ( ):
var t e s t = " f o o , b a r , b a z " . s p l i t ( " , " ) ;
- ,
, .
s p l i t , j o i n Array.
split(regExp)
s p l i t -,
. ,
,
"f ", "bar" "baz" ( ).
var s t r = " f o o , b a r , , , , , , b a z " ;
var re = / , + / ;
var r e s u l t = s t r . s p l i t ( r e ) ;
split(separator, limit)
,
l i m i t . -
RegExp.
strike()
,
<STRIKE> </STRIKE>.
sub()
,
<SUB>H</SUB>.
substr(startlndex, numChars)
s u b s t numChars,
s t a r t Index.
substring(startlndex, endlndex)
,
, s t a r t Index e n d l n d e x (,
s t a r t Index, , ,
endlndex, ). t e s t
" i s " :
var t e s t = " t h i s i s a t e s t " . s u b s t r i n g ( 5 ,
7);
2 5 . 3 2 . Submit
1235
supO
, <SUP>
H</SUP>.
toLowerCase()
t o L o w e r C a s e ,
.
toUpperCase()
t o U p p e r C a s e ,
.
unescape(string)
u n e s c a p e S t r i n g ,
. , u n e s c a p e ,
. u n e s c a p e URL-
. : "+" .
. S t r i n g
HTML-.
25.32. Submit
S u b m i t SUBMIT ,
<INPUT TYPE="SUBMIT" . . . > . S u b m i t
e l e m e n t s Form. SUBMIT,
, S u b m i t
d o c u m e n t . formName. s u b m i t B u t t o n N a m e , formName ,
s u b m i t B u t t o n N a m e -- .
form
, ,
Form, SUBMIT.
name
SUBMIT NAME,
. name .
type
s u b m i t . t y p e
E l e m e n t , OHQ
. t y p e .
1236
25. JavaScript
value
v a l u e .
, .
blurO
SUBMIT .
clickO
,
SUBMIT, o n C l i c k . c l i c k
s u b m i t .
focus()
SUBMIT .
onblur()
, SUBMIT .
o n b l u r o n B l u r , .
<INPUT TYPE="SUBMIT" ... onBlur="doSomeAction()">
onclick()
o n c l i c k ,
SUBMIT. c l i c k o n c l i c k .
o n C l i c k .
<INPUT TYPE="SUBMIT" ... onClick="doSomeAction()">
o n c l i c k f a l s e ,
. :
<INPUT TYPE="SUBMIT" . . .
onClick="return(maybeSubmit())">
o n S u b m i t
, .
ondblclick()
.
o n c l i c k . o n d b l c l i c k
o n D b l C l i c k . Macintosh
Netscape 6.
25.33. Text
1237
onfocus()
, SUBMIT .
on F o c u s .
25.33. Text
T e x t ,
<INPUT TYPE="TEXT" . . . >. T e x t
e l e m e n t s Form, .
, ,
d o c u m e n t . formName. t e x t f i e l d N a m e , formName ,
t e x t f i e l d N a m e .
defaultValue
d e f a u l t V a l u e ,
)^ VALUE.
form
, ,
Form, )' .
name
NAME .
.
type
t y p e , , t e x t .
value
,
. v a l u e , .
blurO
.
focus()
f o c u s )' .
selectO
. ,
, .
1238
25. JavaScript
onblurO
,
. 1^ o n B l u r .
onchange()
o n c h a n g e ,
.
o n C h a n g e .
onfocus()
,
. o n f e c u s o n F o c u s .
onkeydownO
,
. o n k e y d o w n f a l s e ,
. o n k e y d o w n
.
onkeypress()
o n k e y p r e s s
o n k e y d o w n . o n k e y p r e s s
, o n k e y d o w n . o n k e y p r e s s f a l s e ,
.
onkeyupO
o n k e y u p , .
25.34. Textarea
T e x t a r e a HTML-,
<TEXTAREA . . .> </TEXTAREA>.
T e x t a r e a e l e m e n t s Form,
. , ,
d o c u m e n t . formName. t e x t a r e a N a m e ,
formName , t e x t a r e a N a m e .
defaultValue
d e f a u l t V a l u e ,
.. , <TEXTAREA>
</TEXT ARE >. .
25.34. Textarea
1239
form
, ,
Form, .
name
name NAME.
.
type
t y p e t e x t a r e a .
value
v a l u e ,
. , ,
,
.
blurO
.
focus()
focus .
select()
. ,
, .
onblur()
,
. onBlur.
onchange()
onchange
.
onChange.
onfocus()
,
. on focus on Focus.
1240
25. JavaScript
onkeydown()
,
. onkeydown f a l s e ,
. onkeydown .
onkeypress()
on k e y p r e s s
o n k e y d o w n . o n k e y p r e s s
, o n k e y d o w n . o n k e y p r e s s
f a l s e , .
onkeyupO
o n k e y u p , .
25.35. Window
Window .
window, ,
. , , ,
1 w i n d o w , d o c u m e n t , d o c u m e n t .
,
w i n d o w , l o c a t i o n . ,
l o c a t i o n .
closed
, ,
. c l o s e d .
defaultStatus
d e f a u l t S t a t u s ,
. , .
document
D o c u m e n t , .
Document . 25.5. d o c u m e n t
.
frames
f r a m e s ,
Window. )' .
25.35. Window
1241
history
H i s t o r y , .
h i s t o r y .
innerHeight
i n n e r H e i g h t
. , .
.
innerWidth
innerWidth
. , .
.
. 24.4.
Java
Java Package,
j ava . *. , , ,
J a v a . l a n g . M a t h , random() Java Console
Java . l a n g . System, o u t . p r i n t l n . Java
.
length
, frames . l e n g t h .
location
l o c a t i o n L o c a t i o n , URL,
.
URL, document. URL. l o c a t i o n
, .
.
locationbar
Netscape
v i s i b l e l o c a t i o n b a r , L o c a t i o n .
t r u e ( 1) f a l s e ( 0).
Math
Math.
menubar
Netscape
v i s i b l e menubar, .
t r u e ( 1) f a l s e ( 0).
1242
25. JavaScript
name
.
name. , .
navigator
, , ,
N a v i g a t o r .
netscape
n e t s c a p e J a v a P a c k a g e ,
n e t s c a p e . *. , .
opener
(),
o p e n e r .
, .
outerHeight
o u t e r H e i g h t
. , .
. 100x100
() .
outerWidth
o u t e r W i d t h
. , .
Packages
J a v a P a c k a g e ,
. P a c k a g e s .
pageXOffset
,
.
. p a g e X O f f s e t ,
, s c r o l l T o s c r o l l B y .
pageYOffset
,
. p a g e Y O f f s e t
, , s c r o l l T o s c r o l l B y .
parent
, ,
. w i n w i n . p a r e n t
w i n .
25.35. Window
1243
personalbar
Netscape
v i s i b l e p e r s o n a l b a r ,
( ). t r u e
( 1) f a l s e ( 0).
screen
Window,
. ,
. Screen, s c r e e n , . 25.29.
scrollbars
v i s i b l e s c r o l l b a r s ,
.
t r u e ( 1) f a l s e ( 0).
self
window.
s e l f .
status
,
. s t a t u s , ..
JavaScript-
, , , ,
.
statusbar
v i s i b l e s t a t u s b a r ,
.
t r u e ( 1) f a l s e ( 0).
sun
JavaPackage,
s u n . *. sun
.
tags
t a g s .
toolbar
v i s i b l e t o o l b a r ,
Netscape.
t r u e ( 1) f a l s e ( 0).
1244
25. JavaScript
top
,
. ,
. t o p .
window
window, ,
s e l f .
alert(message)
a l e r t .
, ..
,
Back .
blurO
b l u r ;
.
captureEvents(eventType)
.
clear Interval(intervallD)
s e t I n t e r v a l .
( i n t e r v a l l D ) c l e a r I n t e r v a l , .
clear T i m e o u t ( t i m e o u t l D )
s e t T i m e o u t .
( t i m e o u t I D ) c l e a r T i m e o u t ,
.
close()
. ,
, , -
.
confirm(questionString)
, ,
. ,
t r u e . C a n c e l
25.35. Window
1245
f a l s e . ' \ ' ,
.
enableExternalCapture()
disableExternalCapture()
.
.
findO
ind(searchString)
find(searchString,
caseSensitivityFlag, backwardFlag)
f i n d .
, Find,
. ,
. ,
( t r u e ,
), (
t r u e ). ,
t r u e , f a l s e .
focus()
f o c u s .
.
forwardO
.
handleEvent(event)
c a p t u r e E v e n t s ,
h a n d l e E v e n t .
home()
, ..
,
.
m o v e B y ( x , )
moveBy .
Netscape
,
.
1246
2 5 . JavaScript
m o v e T o ( x , )
moveBy . Netscape
,
.
open(url, name)
o p e n ( u r l , n a m e , features)
o p e n ( u r l , n a m e , features, replaceFlag)
. w i n d o w . o p e n
d o c u m e n t . o p e n , window
. URL , .
, d o c u m e n t . name
JavaScript
TARGET , BASE, AREA FORM. r e p l a c e F l a g
, ( t r u e )
( f a l s e ) . f e a t u r e s
( !)
. f e a t u r e s ,
.
^.
. 25.2. 25.5
w i n d o w , o p e n ; . 25.6-25.9. , .
24.10.
!
.
, .
2 5 , 2 . ,
open
alwaysLowered
yes/no
""
.
alwaysRaised
yes/no
dependent
yes/no
2 5 . 3 5 . Window
1247
. 25.2
directories
yes/no
hotkeys
yes/no
" "
innerHeight
.
Unix .Xdefaults
innerWidth
.
Unix .Xdefaults
location
yes/no
Location
menubar
yes/no
OuterHeight
outerWidth
Resizable
yes/no
ScreenX
ScreenY
Scrollbars
yes/no
status
yes/no
yes/no
yes/no
, Back Forward
Home Stop
yes/no
titlebar
toolbar
z-lock
1248
25. JavaScript
print()
, ..
, Print. ,
, JavaScript .
prompt(message)
p r o m p t ( m e s s a g e , defaultText)
.
, . d e f a u l t T e x t
.
releaseEvents(eventType)
.
resizeBy(x, )
r e s i z e B y
.
r e s i z e T o ( x , )
r e s i z e T o .
routeEvent(event)
h a n d l e E v e n t
.
scrollBy(x, )
) .
s c r o l l T o ( x , )
,
.
s e t I n t e r v a l ( c o d e , delay)
,
c l e a r l n t e r v a l .
s e t T i m e o u t ( c o d e , delay)
s e t T i m e o u t , JavaScript-
. .
, c l e a r T i m e o u t ,
, s e t T i m e o u t . ,
' s e t T i m e o u t ,
.
25.35. Window
1249
stopO
s t o p , ..
, Stop.
onblurO
. o n b l u r ,
, o n B l u r <BODY>
<FRAMESET>.
<BODY o n B l u r = " a l e r t ( ' W e w i l l m i s s
you')">
</BLUR>
,
, .
o n f o c u s .
ondragdropO
Netscape
.
o n D r a g D r o p .
onerrorO
.
, .
function reportError() {
return(!confirm("An error occurred.\n" +
"Please report i t to\n" +
"gates@microsoft.com.\n\n"
"See more d e t a i l s ? " ) ) ;
onerror = reportError;
t r u e , . ,
, ,
. o n e r r o r ,
n u l l , .
onfocus()
.
o n f o c u s o n F o c u s <BODY>
<FRAMESET>. .
<FRAMESET
ROWS=...
onFocus="alert('Welcome back')">
</FRAMESET>
1250
25. JavaScript
onload()
o n l o a d .
n L o a d <BODY>
<FRAMESET>. ,
, ,
.
onmove()
onmove (
, ).
onMove.
<BODY o n M o v e = " a l e r t ( ' H e y ,
...>
</BODY>
onresize()
o n r e s i z e ,
JavaScript- .
o n R e s i z e .
onunloadO
onunload , .
onUnload
<BODY> <FRAMESET>.
25.5. OpenWindows. htJttl
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Opening Windows with JavaScript</TITLE>
<SCRIPT TYPE="text/javascript">
function openSmallWindow() {
window.open("http://home.netscape.com/",
"smallWindow",
"width=375,height=125");
function openMediumWindow() {
window.open("http://home.netscape.com/",
"mediumWindow",
"width=550,height=225," +
"menubar,scrollbars,status,toolbar");
}
function openBigWindow() {
window.open("http://home.netscape.com/",
25.35. Window
"bigWindow",
"width=850,height=450," +
"directories, location,meniibar, " -l"scrollbars,status,toolbar");
}
// >
</SCRIPT>
</HEAD>
<BODY>
<Hl>Opening Windows with JavaScript</Hl>
<FORM>
<INPUT TYPE="BUTTON" VALUE="Open Small Window"
onClick="openSmallWindow()">
<INPUT TYPE="BUTTON" VALUE="Open Medium Window"
onClick="openMediumWindow()">
<INPUT TYPE="BUTTON" VALUE="Open Big Window"
onClick="openBigWindow()">
</FORM>
</BODY>
</HTML>
iie
gdk
yieM
jgo
i;;oiiRurk!to(
Ueip
^^ -ii^ # 3 ^ ^ a ^:rfe a;
Opening Windows with Java^icript
'^~^^^1^
. 25.6. OpenWindows.html
|
Netscape
(vw<t<t<
Vt^fivai
Screen Klnas
To>
. 25.7. window.open
,
, , .
( Netscape Comnnunications Corp.)
1251
1252
25. JavaScript
33
Netscape.com - Netscape
Fte
Edit
View
60
Communicatof
f.r ^.
Help
,1
:J
Satut<}ay. F e b r u a r v 24, 2 0 0 1
^-^-
Screen Kings
Tax Time
Doctffnent: Done
'--^^
J '"^
. 25.8. ,
. ( Netscape Communications Corp.)
!
:' .' 4 -' .^ si i 'S 1;
^
Bookmafks
^imtentMrnage
.^'
SI
' What's Related
? WebMa* ^ i Contact
^ 1 Poopte
ReaiPlajjw
-':^ ^^I^J.^,^^^^!^^^
Screen Kings
TdX Time
KurtRusftll nd Kvin
Costner led 4 99 of
HOTDTAiS K M
M u s t - H a v e s ; J.Crew
Spring 2 0 0 1 for M e n
2 0 0 1 Collection
Entertelflsiisnt
NBC's sitcom flagship is
sinking - IS it t i m e t o
put us out of its m i s e r y '
ra
.. r '
4 \ f WV
S^M.
G o u r m e t Body Paint
^ 'Friorids'?
Tt^il Us W h d t Y u u
Think
T a k e our survey
forecasting t h e year
ahead.
.iSQ.OOQ
tBaasi
business
(' '^'^'^
Doc^nent Don
d
...-..;::.^...;:
. 25.9. ,
. ( Netscape Communications Corp.)
25.35. Window
1253
25.36.
, . . ,
HTML, Java JavaScript , Web . ,
, .
HTML, ,
. Java, ,
, RMI JDBC. , CGL
. , .
, ,
.
JavaScript-. ,
, , ,
, .
, - .
, .
!
1254
D
Document Object Model, 1051; 1052
Document Type Definition, 1051
DOM, 1051; 1052
DTD, 1051
E
ECMA, 1101
ECMAScript, 1101
Enterprise JavaBeans, 193
European Computer Manufacturers
Association, 1101
Extensible Style sheet Language for
Transformations, 1051
GIF89A, 94;712
H
HTML, 37
HTML-, 785; 1190
HTML-, 41
-, 39; 751
-, 997; 1007
HyperText Markup Language, 35
HyperText Transfer Protocol, 39
IMAP4, 193
Internet Explorer, 36
ISO, 85
JAR-, 246
Java, 179
Java 2D, 359
Java API, 196
Java Database Connectivity, 192; 719; 1017
Java Development Kit, 192
Java Foundation Classes, 359
Java Naming and Directoiy Interface, 193
Java Plug-In, 332; 359; 926
Java Runtime Environment, 332
JavaBeans, 192; 932
JavaHelp, 595
JavaMail, 193
JavaScript, 80; 904; 1101; 1173
JavaServer Pages, 193; 901
JavaServer Web Development Kit, 822
JAXP, 193; 1052; 1054
JDBC, 192; 719; 1017
JDBC-, 1017; 1018
JDK, 192
JNDI, 193
JRE, 332
JRun, 821
JScript, 1102
JSP,901
JSWDK, 822
JVM, 183
LiteWebServer, 821
LWS, 821
M
MDI, 575
1-, 50; 93; 1207
Model view controller architecture, 978
Multiple Document Interface, 575
N
Netscape, 37
Tomcat, 821
Transformation API for XML, 1079
TrAX, 1079
PHP, 903
POP3, 193
V
VBScript, 903
VRML, 101
QuickTime, 94
R
Remote Method Invocation, 192; 719; 756
Resin, 821
RMI, 192; 719; 756
RMI-IIOP, 193
RMI-, 757
RMI-, 757
RPC, 756
RSA, 681
X
XML, 193; 1051
XPath, 1078
XSL, 1077; 1078
XSLT, 1051; 1078
XSLT-, 1079
1255
1256
Z-, 551
Z-, 551
, 166
, 233
, 234
, 836
, 91
, 794
, 708
GIF-, 94
, 708
, 192
, 101; 194; 311
, 258; 1204
--
, 546; 603; 978
, 41
, 365
, 46
, 187
, 946
, 242
, 297
, 159
catch, 302
finally, 302; 305
try, 302
, 253
, 919
-, 271
,295
JavaScript Java, 1148
, 643
)' Java, 183
, 445
, 62
, 401
, 140
, 545; 651
, 575
, 192; 401
, 386
, 568
, 94
, 142
, 130; 132
, 598
Swing- , 649
, 273
, 272; 317
, 692
, 340
Java JavaScript, 1148
, 57; 59
, 904; 905; 1018
, 223
, 90; 1200
, 719
, 745
,672
, 79
, 359; 371
, 371
, 371
Java, 253
, 334
, 690
, 812
, 836
, 66
, 836
, 1180
, 545; 651; 704
, 603; 634
, 902
, 904; 910
HTML , 43
,848
, 297
, 36
javadoc, 224
,673
, 214
, 493
, 1110
, 629
, 1122
HTML-, 1103
, 902; 913
, 419
BorderLayout, 422
BoxLayout, 439
CardLayout, 427
FlowLayout, 420
GridBagLayout, 432
GridLayout, 425
, 224
}^, 1183
, 104; 1217
, 1120
, 230
, 603; 621
, 366
, 366
, 318
, 830
, 688
, 833
, 757
, 56
HTTP-, 841
1257
, 66
, 1018
, 125
, 42
, 373
, 370
, 1018
GET, 991
POST, 991; 1007
, 58
, 1046
, 1046
, 124
, 145; 254
, 892
, 1194
, 209
, 209
, 209
, 830
Java, 195
JSP, 977
, 235
, 757
, 395
, 61
, 302
, 306
JavaScript-, 1148; 1150
, 757
,
, 98; 806
, 98; 806
, 146
, 36; 137
, 403
1258
, 946
, 144
, 719
, 745
, 496; 794; 1177
JavaScript, 798
RESET, 1225
SUBMIT, 1235
, 504
, 853
, 786
, 42
, 460
Canvas, 456
ScrollPane, 474
, 42
JavaScript, 1173
, 211
, 42; 472
, 535
, 546
, 367
, 362
, 367
, 367
, 544
, 254; 726
Java, 253
, 363
, 530; 567
JavaScript, 142
, 88
, 209
, 359; 378
, 210
JavaScript, 1114; 1173
, 842
, 786
, 219
, 294
, 190; 666
, 677
, 486
, 546
, 604
,
612; 627
, 192
, 210; 247
URL, 892
, 1020
, 230
, , 42
, 38
, 402
, 386; 389
, 307
, 409
, 61; 165
, 366
, 248
, 316
, 126
JavaScript, 1108
, 395
, 67; 68
JavaScript Java, 1157
, 163
, 364
, 186; 207
JavaScript, 1111
, 673
, 395
- , 186
-
, 207
, 726
, 666
, 746
, 1240
Dialog, 486
FileDialog, 489
Frame, 475
Window, 491
, 510; 802
, 258
, 65
javadoc, 227
, 58
, 42
, 166
URL, 46
, 660
, 242
, 469
, 583
, 108
1259
, 130; 132
, 218
, 891; 918
, 230
, 1019
, 792; 1215
, 841; 853; 864
, 208
, 518; 790; 1237
, 242
, 530
, 836
, 946
, 720
, 813
, 665; 832
, 658
Swing, 658
,138
, 912
, 905; 912
, 544; 546
, 146
JSP , 902
, 359; 386
, 1079
, 194; 311
, 255
HTML-, 1131
, 781
, 781
, 359
, 370; 376
, 364
HTML, 43
, 546
, 255
, 368
, 368
, 146
, 833
, 1214
, 61; 64
1260
, 130
cookie LavaScript, 1140
JavaScript, 1144
, 40
, 113
DOM, 1053
SAX, 1064
, 726
, 757
, 79
, 254
, 35
, 443
, 1226
, 564
, 535; 1227
, 507; 802
, 295
, 396
)^ , 1219
, 297
, 365
, 230
, 179; 214
, 138
JavaScript, 1173
, 208
, 622
, 895
, 721
, 364; 390
, 386
,138; 143
,719; 745
, 1019
) , 817
, 193; 817
, 192; 999
,482
, 848
Java, 253
, 673
, 674
, 676
Class, 676
, 676
, 674
, 904; 908
, 811; 892
, 1192
, 167; 1128; 1197
, 391
, 395
JavaScript, 1173
, 626
, 645
, 713
, 492
, 1107
FTP-, 725
, 1017; 1019
, 720
, 1223
H T T P 1.1, 845
Java Servlet, 820
JavaServer Pages, 820
, 603; 604
, 61; 65; 165
,1193
,367
, 286
, 186; 280
, 280
, 403
, 209
, 214
, 526
, 83
Java, 547
MacOS, 547
Metal, 547
Motif, 547
Windows, 547
, 381
, 364
, 381
HTML, 43
, 284; 1230
, 253
, 781; 836
,853
, 66; 71
DOM, 1053
, 230
, 1101
, 246
, 946; 947
, 83
, 839
, 688
, 501; 595; 799; 1178
, 93; 117
, 78; 1190
, 991
, 37; 111; 1144; 1240
JavaScript, 1110; 1191
, 66
, 712
, 904
, 523; 589; 792; 1238
, 55
, 956
, 65
,359
, 381
, 544
, 756
, 757
, 186; 280
JavaScript-, 1148; 1153
, 257
, 857
, 2 5 8 ; 259
, 381
, 256
, 495
, 258; 265
, 60; 85
, 311
,
, 1210
, , 256
, 274
, 359; 381
, 207
, 50; 55
, 291
, 902; 904
, 50; 83
, 1186
1261
-
,
Web.
.
..
..
..
.. , ..
"".
101509, , . , . 43, . 1.
. . 090230 23.06.99
.
28.12.2001. 70x100/16.
NewBaskerville. .
. . . 112. .-. . 66,5.
5000 . 2515.
" "
,
.
197110, -, ., 15.