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

-

-
2012

681.3.06
32.973.26-018.2
12

. .
12

Java 7. .: -, 2012. 768 .: . ( )


ISBN 978-5-9775-0735-6
, ,
Java. , - Java, Swing, Java 2D,
, , . Java SE 7: , ,
" ", NIO2, . , JSP
JSTL. .
Core Java API.

681.3.06
32.973.26-018.2

:

.
.

02429 24.07.00. 31.08.11.


70 1001/16. . . . . 61,92.
1800 .
"-", 190005, -, ., 29.
-
77.99.60.953..005770.05.09 26.05.2009 .
.

" ""
199034, -, 9 , 12

ISBN 978-5-9775-0735-6

. ., 2011
, "-", 2011

.......................................................................................................................... 19
Java? .............................................................................................................................. 20
............................................................................................................................ 21
Java- ...................................................................................................... 24
JDK? .............................................................................................................................. 25
JRE? .............................................................................................................................. 27
JDK? .................................................................................................................... 27
JDK? ................................................................................................................ 28
Java....................................................................................................... 30
Microsoft............................................................................................................. 30
Java ........................................................................................................................... 31
Java ........................................................................................................................ 32
............................................................................................................................... 33

I. JAVA ....................................... 35
1. , ...................................... 37
Java ............................................................................................................ 37
................................................................................................................................. 40
..................................................................................................................................... 42
...................................................................................................................................... 42
..................................................................................................................................... 42
..................................................................................................................... 43
................................................................................................................................. 43
.................................................................................................................................... 44
............................................................................................................................................. 45
..................................................................................... 45
..................................................................................................................... 47
............................................................................................................ 47
........................................................................................................................... 48
............................................................................................................................ 48
............................................................................................. 49
......................................................................................... 49
........................................................................................................ 50

.................................................................................................... 52
................................................................................................... 52
........................................................................................................................... 53
........................................................................................................................... 54
.............................................................................................................. 54
....................................................................................................... 55
........................................................................................................................... 56
................................................................................................................ 56
........................................................................................................................... 56
..................................................................................................................................... 56
............................................................................................................. 57
..................................................................................................................................... 58
........................................................................................................................................ 59
..................................................................................................... 59
............................................................................................................... 59
........................................................................................................................... 61
................................................................................................................... 62
continue ................................................................................................... 64
break ...................................................................................................................... 65
........................................................................................................................... 65
................................................................................................................ 65
......................................................................................................................................... 67
......................................................................................................... 69
.................................................................................................................................... 71
......................................................................................................... 71

2. - Java ....................... 73
.................................................................................................... 73
- .................................................... 76
............................................................................................................................ 76
................................................................................................................................ 79
.................................................................................................................... 80
.......................................................................................................................... 81
KISS ....................................................................................................................... 83
........................................................................................................................... 84
? .................................................................................................... 84
.............................................................................................. 86
.............................................................................................................. 87
.................................................................................................... 88
Java ........................................................................................ 89
........................................................................................................................... 90
.................................................................................................... 90
.................................................................................................. 91
Object ................................................................................................................................... 92
.................................................................................................................... 93
new ................................................................................................................................ 94
........................................................................................................................... 94
............................................................................................................ 94
Complex ............................................................................................................................... 96

main().................................................................................................................................. 99
.............................................................................. 100
............................................................................................................... 101
...................................................................................................................... 103
" " "" ................................................................................... 107
.................................................................................................................................. 108
....................................................................................................... 108

3. , .................................................... 109
......................................................................................................................... 110
.................................................................................................. 111
................................................................................................. 113
.......................................................................................................... 115
Java- ................................................................................................................................... 116
................................................................................................................................. 117
.............................................................................................................................. 121
............................................................................................................... 124
Design patterns ............................................................................................................................. 126
MVC ............................................................................................. 126
Singleton ................................................................................................................ 127
.................................................................................................................................. 129
....................................................................................................... 129

II. JAVA API ................................ 131


4. - generics ...................................................................... 133
......................................................................................................................... 134
......................................................................... 136
(generics) ................................................................................................. 137
(wildcard type) ............................................................................................... 140
.............................................................................................................. 141
Boolean .............................................................................................................................. 142
Character ........................................................................................................................... 143
BigInteger .......................................................................................................................... 146
BigDecimal ........................................................................................................................ 148
Class................................................................................................................................... 152
....................................................................................................... 155

5. ..................................................................................... 156
String.................................................................................................................................. 157
.............................................................................................................. 157
......................................................................................................................... 162
.................................................................................................................. 162
..................................................................................................... 162
........................................................................................ 163
....................................................................................................... 163
...................................................................................... 164
........................................................................................................... 164
................................................................................................. 166

........................................................................................................... 167
................................................................................................. 167
....................................................................................... 168
..................................................................................................... 168
................................................................... 168
........................................................... 168
......................................................................................................................... 169
StringBuilder ...................................................................................................................... 169
...................................................................................................................... 169
..................................................................................................... 170
...................................................................................................... 170
....................................................................................................... 171
............................................................................................................. 171
..................................................................................................... 171
...................................................................................................... 171
.................................................................................................. 172
StringTokenizer .......................................................................................................... 172
.................................................................................................................................. 173
....................................................................................................... 173

6. -...................................................................................... 174
Vector ................................................................................................................................. 174
.............................................................................................................. 175
.......................................................................................... 175
......................................................................................................... 176
.................................................................................................. 176
................................................................................... 176
, ............................................................................... 176
............................................................................................... 177
......................................................................................................... 177
Stack ................................................................................................................................... 178
Hashtable ........................................................................................................................... 179
Hashtable ........................................................................................... 180
Hashtable....................................................................................... 180
...................................................................................... 180
.......................................................................... 181
Hashtable ................................................................ 181
......................................................................................................... 181
Properties ................................................................................................................... 182
Collection .................................................................................................................. 185
List............................................................................................................................. 185
Set .............................................................................................................................. 186
SortedSet ........................................................................................................... 186
NavigableSet ..................................................................................................... 187
Queue ........................................................................................................................ 188
BlockingQueue .................................................................................................. 188
Deque ........................................................................................................................ 188
BlockingDeque .................................................................................................. 189

Map ........................................................................................................................... 190


Map.Entry ..................................................................................... 191
SortedMap ......................................................................................................... 191
NavigableMap ................................................................................................... 191
- ................................................................................................ 192
Iterator ...................................................................................................................... 193
ListIterator ........................................................................................................ 194
, ........................................................................................................ 195
................................................................................................... 196
........................................................................................................................................ 196
......................................................................................................................... 197
, .............................................................................................. 197
..................................................................................................... 197
............................................................................................ 197
............................................................................................... 198
......................................................................................................................... 199
, ................................................................................................. 199
......................................................................................................... 199
................................................................................................ 200
............................................................................................................ 200
Collections .................................................................................................. 200
......................................................................................................................... 201
.................................................................................................................................. 202
....................................................................................................... 202

7. - ......................................................................................... 203
..................................................................................................................... 203
............................................................................................................ 203
................................................................................................. 203
............................................................................................................ 204
......................................................................................................... 204
............................................................................................................ 205
........................................................................................ 205
- ............................................................................................. 206
................................................................................................................. 206
....................................................................................................... 208
............................................................................................. 208
Calendar .................................................................................................................... 209
GregorianCalendar.............................................................................................. 209
.......................................................................................... 210
...................................................................................................... 211
............................................................................................................... 211
....................................................................................................... 212

III.
.......................................................................... 213
8. ............................... 215
.............................................................................................................. 217
AWT .............................................................................................................. 220

Swing .............................................................................................................. 221


................................................................................... 222
System Tray .......................................................................................................................... 223
Splash Screen ........................................................................................................................ 224
.................................................................................................................................. 224
....................................................................................................... 224

9. .......................................................................... 226
Graphics ............................................................................................................. 226
.................................................................................................................... 226
......................................................................................................................... 228
....................................................................................................... 228
Polygon ...................................................................................................................... 229
......................................................................................................................... 230
Graphics ........................................................................................ 230
............................................................................................................... 231
........................................................................................................ 231
................................................................................................................ 231
FontMetrics ................................................................................................................ 235
......................................................................................................................... 238
Java 2D ................................................................................................................. 238
........................................................................................................ 240
AffineTransform ......................................................................................................... 240
......................................................................................................................... 243
Java 2D ....................................................................................... 243
BasicStroke ................................................................................................................ 243
GeneralPath ............................................................................................................... 246
GradientPaint TexturePaint ................................................................................. 247
LinearGradientPaint RadialGradientPaint.......................................................... 249
Java 2D ............................................................................................. 250
............................................................................................. 254
......................................................................................................................... 256
.................................................................................................................................. 256
....................................................................................................... 256

10. AWT.................................................................. 257


Component ......................................................................................................................... 257
Cursor ................................................................................................................................ 259
..................................................................................................... 259
......................................................................................................................... 260
............................................................................................................................... 260
Container ........................................................................................................................... 261
............................................................................................................................... 262
Label ................................................................................................................ 262
............................................................................................................................... 262
Button .............................................................................................................................. 262
............................................................................................................................... 263
Checkbox ............................................................................................................ 263
............................................................................................................................... 263

CheckboxGroup ......................................................................................................... 263


....................................................................................... 264
Choice................................................................................................ 265
............................................................................................................................... 266
List ................................................................................................................................... 266
............................................................................................................................... 267
.................................................................................................... 268
TextComponent .......................................................................................................... 268
...................................................................................................................... 269
TextField ........................................................................................................ 269
...................................................................................................................... 269
TextArea ............................................................................................................ 269
...................................................................................................................... 270
Scrollbar ..................................................................................................... 272
............................................................................................................................... 272
Panel .......................................................................................................................... 274
ScrollPane ................................................................................................................. 275
Window ...................................................................................................................... 276
............................................................................................................................... 276
Frame ........................................................................................................................ 277
............................................................................................................................... 277
Dialog ........................................................................................................................ 279
............................................................................................................................... 280
FileDialog.................................................................................................................. 282
............................................................................................................................... 282
......................................................................................... 283
Canvas .............................................................................................................. 283
"" ........................................................................................ 285
......................................................................................................................... 287
............................................................................................................................ 287
.................................................................................................................... 292
....................................................................................................... 295

11. Swing .............................................. 296


Swing ........................................................................................................... 297
Swing .................................................................................................... 299
JComponent ...................................................................................................... 299
MVC Swing ..................................................................................... 300
JLabel .................................................................................................................... 302
................................................................................................................................. 304
JButton ........................................................................................................... 306
JToggleButton ................................................................................... 306
JCheckBox ......................................................................................... 308
JRadioButton ........................................................................................ 308
......................................................................................................................... 309
JComboBox................................................................................ 310
JList ............................................................................................................ 311
...................................................................................... 312

10

......................................................................................................................... 314
JSpinner ................................................................................................................. 314
JScrollBar ............................................................................................ 316
JSlider .................................................................................................................. 316
......................................................................................................................... 318
JProgressBar ..................................................................................................... 318
JTree ........................................................................................................ 318
Swing ................................................................................. 322
JMenuBar ............................................................................................. 322
JMenu ............................................................................................................... 323
JMenuItem.............................................................................................. 323
JPopupMenu ............................................................................ 325
JColorChooser ................................................................................. 326
......................................................................................................................... 328
JFileChooser ...................................................................................... 328
FileFilter ........................................................................................... 328
................................................................................. 330
..................................................................................... 330
.................................................................................................. 331
Swing ..................................................................................................................... 333
....................................................................................................... 333

12. ........................................................................... 334


JTextComponent ....................................................................................................... 334
.............................................................................................. 334
Segment .......................................................................................... 335
.......................................................................................... 336
......................................................................................................... 336
.................................................................................. 337
.............................................................................................. 337
............................................................................... 337
................................................................................................. 338
............................................................................................... 338
......................................................................................... 339
........................................................................................................................................ 339
......................................................................................... 341
......................................................................................................................... 341
......................................................................... 342
................................................................................................ 343
......................................................................................................... 343
.................................................................................................... 344
JTextField ................................................................................................................. 344
JPasswordField ............................................................................................ 347
JFormattedTextField .................................................................................... 347
JTextArea............................................................................................................. 348
JEditorPane ............................................................................................... 349
JTextPane ..................................................................................................................... 350
....................................................................................................... 350

11

13. ...................................................................................................... 351


JTable ................................................................................................................................ 351
............................................................................................................ 353
........................................................................................................ 353
TableColumn .......................................................................... 358
.................................................................................................. 358
JTableHeader ...................................................................... 358
.................................................................................................... 360
..................................................................................................... 361
............................................................................................................. 364
......................................................................................................... 367
........................................................................................................ 369
........................................................................................................................... 370
....................................................................................................... 371

14. Swing .................................. 372


FlowLayout ................................................................................................................ 372
BorderLayout ............................................................................................................. 374
GridLayout ................................................................................................................. 376
CardLayout ................................................................................................................ 377
GridBagLayout........................................................................................................... 379
Swing ...................................................................................................................... 381
JPanel ...................................................................................................................... 381
JScrollPane ........................................................................................... 382
JSplitPane ................................................................................................. 384
JTabbedPane ...................................................................................... 385
Box .......................................................................................................... 387
BoxLayout ............................................................................ 387
- ......................................................................................... 388
SpringLayout................................................................................. 389
Spring ........................................................................................................... 390
Constraints ............................................................................................ 391
.......................................................................................... 392
JToolBar .................................................................... 393
Action ....................................................................................................... 395
JLayeredPane ............................................................................................ 396
JRootPane ............................................................................................... 397
JWindow ...................................................................................................................... 399
JDialog .................................................................................................... 400
JFrame ........................................................................................... 401
JInternalFrame ....................................................................................... 402
JDesktopPane ................................................................................................ 404
JOptionPane.................................................................................... 405
ProgressMonitor ............................................................................... 409
.................................................................................................................................. 410
....................................................................................................... 411

15. .................................................................................. 412


............................................................................................................. 416
................................................................................................. 417
......................................................................................................................... 418

12

ActionEvent ................................................................................................................... 418


........................................................................................................ 419
......................................................................................................................... 422
-......................................................................................................................... 422
.................................................................................................... 423
............................................................................................... 424
......................................................................................................................... 425
TextEvent............................................................................................................... 425
ChangeEvent .............................................................................................. 426
..................................................................................................... 426
ComponentEvent ........................................................................................................... 427
ContainerEvent ............................................................................................................. 428
C FocusEvent.................................................................................................................... 428
ItemEvent ...................................................................................................................... 428
AdjustmentEvent ........................................................................................................... 429
................................................................................ 431
......................................................................................................... 432
................................................................................................ 434
....................................................................................................... 435

16. ................................................................................... 436


EmptyBorder ......................................................................................................... 438
LineBorder ............................................................................................. 438
BevelBorder ..................................................................................................... 439
SoftBevelBorder ................................................................ 439
EtchedBorder .................................................................................................. 440
MatteBorder .......................................................................................... 440
TitledBorder ................................................................................................ 441
CompoundBorder .......................................................................................... 444
.................................................................................................... 445
....................................................................................................... 450

17. ................................................ 451


L&F ............................................................................................................. 453
L&F......................................................................................................... 455
L&F ................................................................................................................. 457
L&F ......................................................................................................................... 457
L&F ................................................................................................. 459
Java L&F ............................................................................................................................ 462
....................................................................................................... 465

18. ...................................................................................................... 466


................................................................................................................................. 472
................................................................................................... 472
<applet> ............................................................................................................. 475
............................................................................................... 476
................................................................................................................................. 477
................................................................................................. 477
....................................................................................... 477
MediaTracker .................................................................................................... 478

13

................................................................................................................................. 480
....................................................................................................................... 480
Swing ..................................................................................................... 481
JApplet............................................................................................................................. 482
................................................................................................................................. 483
.................................................................................................................................. 484
....................................................................................................... 484

19. Swing ............................................................................ 485


............................................................................................. 485
........................................................................................ 486
............................................................................................................... 486
Drag and Drop.................................................................................................. 491
Timer ......................................................................................................... 492

20. .................................................................................. 494


"-" ............................................................................................ 494
- .................................................................................................................. 497
............................................................................... 498
........................................................................................ 499
............................................................................. 500
......................................................................................................................... 501
....................................................................................... 501
Java 2D ........................................................................... 504
.......................................................................... 504
........................................................................... 507
........................................................................................ 508
.......................................................................................... 509
......................................................................................................................... 510
..................................................................................................................................... 510
............................................................ 512
......................................................................................................................... 516
............................................................................................................................................. 516
Java................................................................................................. 517
Java .............................................................................................. 522
......................................................................................................................... 524
....................................................................................................... 525

IV. JAVA .................................... 527


21. ................................................ 529
..................................................................................................... 530
......................................................................................................................... 533
throws................................................................................................... 533
throw ............................................................................................................................ 536
.......................................... 536
- .................................................................................................. 537
............................................................................................... 538
......................................................................................................................... 538

14

................................... 539
.......................................................................................... 539
.................................................................................................................................. 541
....................................................................................................... 541

22. .............................................................................................. 542


Thread ................................................................................................................................ 545
................................................................................................... 550
..................................................................... 552
......................................................................................................... 557
- ................................................................................................................. 558
................................................................................................................. 559
.................................................................................................................................. 559
....................................................................................................... 559

23. / .............................................................. 560


/ ............................................................................................................. 565
................................................................................................... 568
......................................................................... 569
........................................................... 570
.............................................................................. 570
.................................................................................... 570
.......................................................... 570
- ................................................................ 570
................................................................... 570
Console ...................................................................................................................... 571
......................................................................................................................... 572
/ ................................................................................................................ 572
................................................................................................... 574
NIO2 .................................................................................... 576
/ ..................................................................................................... 578
/ ........................................................................... 579
......................................................................................................................... 581
Java .......................................................................................................... 582
UTF-8 ................................................................................................................ 582
DataOutputStream ..................................................................................................... 582
.............................................................................................................. 584
......................................................................................................................... 585
.................................................................................................... 585
.............................................................................................................. 587
Java ............................................................................................................................... 590
Java 2D ........................................................................................................ 592
....................................................................................................................... 596
.......................................................................... 598
....................................................................................................... 599

24. Java ............................................................................. 601


WWW............................................................................................................................ 604
......................................................................................................................... 607

15

TCP ........................................................................................................... 608


proxy- ..................................................................................................... 611
......................................................................................................................... 612
UDP .......................................................................................................... 612
......................................................................................................................... 614
....................................................................................................... 614

V. WEB- JAVA ................................................................. 617


25. Web- Java ............................................................................ 619
jar .............................................................................................................................. 619
.................................................................................................................. 620
MANIFEST.MF ......................................................................................... 622
INDEX.LIST ............................................................................................................... 623
JavaBeans ............................................................................................................... 624
JDBC ........................................................................................... 625
....................................................................................................... 629

26. .................................................................................................... 631


Web- ......................................................................................................................... 632
Servlet........................................................................................................................ 633
................................................................................................... 634
ServletConfig ..................................................................................................... 637
............................................................................................................... 639
Service....................................................................................................................... 639
ServletRequest ................................................................................................... 640
ServletResponse ................................................................................................. 641
......................................................................................................... 641
GenericServlet.................................................................................................................... 642
HTTP ........................................................................................................ 643
HttpServletRequest ............................................................................................ 643
HttpServletResponse .......................................................................................... 645
HttpServlet ................................................................................................................. 646
............................................................................................................ 646
HttpServlet................................................................................... 647
............................................................................................................. 652
....................................................................................................................................... 655
.................................................................................................. 660
.......................................................................................... 661
....................................................................................................... 664

27. JSP ............................................................................................ 665


() JSP .............................................................................................. 668
EL ....................................................................................................... 671
JSP............................................................................................................ 672
JavaBean........................................................................................... 674
.......................................................................... 675
.......................................................................................................... 676

16

............................................................................................................... 677
- ....................................................................... 679
.................................................................................. 681
............................................................................................ 682
............................................................................ 684
.............................................................................. 686
........................................................... 690
JSP ............................................................................................... 690
JSTL ........................................................................................ 692
core ................................................................................................................... 693
xml .................................................................................................................... 696
fmt .................................................................................................................... 696
sql ..................................................................................................................... 697
fn ...................................................................................................................... 697
Frameworks................................................................................................................................... 697
JavaServer Faces ........................................................................................................................... 698
....................................................................................................... 703

28. Java XML .............................................................. 704


DTD ............................................................................................................................ 709
XML............................................................................................................ 711
XML .................................................................................................................................. 713
XSD ........................................................................................ 714
.................................................................................................. 714
................................................................................................................ 714
........................................................................................................ 714
............................................................................................................... 715
.......................................................................................................... 715
........................................................................... 715
.............................................................................................. 716
...................................................................................................................... 716
......................................................................................................................... 717
............................................................................................................... 718
................................................................................. 719
............................................................................................. 719
........................................................................ 720
......................................................... 720
................................................................ 721
...................................................................... 723
: .......................................................................................... 724
............................................................................................................... 726
XSD .......................................................................................... 728
....................................................................... 730
XML ............................................................................ 731
............................................................................................. 732
.......................................................................................................... 732
XML ............................................................................................................. 733
XML SAX2 ............................................................................ 734

17

XML StAX ............................................................................. 741


XML Java ............................................................................. 743
JDO ................................................................................................................. 744
XML DOM API...................................................................... 745
Node .................................................................................................................. 746
Document .......................................................................................................... 747
Element .............................................................................................................. 748
DOM- ......................................................................................................... 751
XML.................................................................................. 752
XSL .................................................................................................................. 754
XML HTML ............................................................................... 756
....................................................................................................... 757

.................................................................................................... 758
.............................................................................................. 760


, , , . ,
, . ... - . ,
, , , . .
. :
, 1996 .;
, "" FAQ (Frequently Asked Questions);
, , ( , , , );
,
;
Java, "How to...?";
,
;
- ,
Java ;
Java.

, Java XXI .
, , , , , ,
, .

20

, .
, . " Java".
. , .
, .
, .
Java .
, Java Web-, , .
Android Java. Java Web-.
. , . Swing Java.
XML. Java.
, , , .
, !

Java?
, . , Java ( "", ).
, , Java, , .
Java ( Java 23 1995 .) ,
.
Java .
, Java . JavaBeans, Java , CORBA.

(servlets), JSP (JavaServer Pages) EJB (Enterprise JavaBeans). JDBC. ,
Java , Oracle, Linux, MacOS X,
AIX. ? , Java
. -
.
Java
, , , Java. Smalltalk,

21

Pascal, C++ ., , , .
, , , : . Java - ,
Pascal . Java
, ,
.
, Java
Java, : Clojure, Scala, Jython,
Pascal C++, - Java:
.
Java - ,
Algol, Pascal.
, Java ,
. Java.
, Java- , , Java
.
Java , (deprecated), , , , . -
.


.
I , .
- Java, , /.
1 , , , ,
, Java. Java, ,
.
2 - :
, , , , , . ""
,
.

22

Java. , , ,
.
3 ,
, .
Java API.
II ,
Java,
. , .
- .
4 Java,
,
, .
5 , ,
Java, , ,
.
6 , Java ,
.
7 -, , ,
.
III () AWT (Abstract Window Toolkit) Swing . Java , . Java, .
.
Swing
MS Windows, X Window System ., .
8 AWT,
. Swing, AWT.
9 ,
, Java.
10 ,
AWT , AWT.
11 ,
Swing.
12 Swing.

23

13 Swing.
14 , AWT Swing .
15
, , Java.
16 , Swing.
17 Swing ,
, , .
18, -, Java-,
, .
19 Swing, .
20 AWT.
IV Java, .
,
, .
Java .
, .
21 Java ,
.
22 Java
(threads) .
23 Java / .
24 Java, -
.
V Web- Java, , , .
25 Java, Web: JAR, JavaBeans,
JDBC.
26 .
27 JSP,
Web-.
, 28 XML Java
XML.

24

Java-
, , ,
Java, ("", ""
source), .
, . .
. , , :
,
.
, Java, ,
Java
, - ,
Java (Java Virtual Machine, JVM). Java . , Java ,
.
JVM , 1 , JVM
- (bytecodes), 2 3 . 1,8 . JVM
Java (Virtual Machine Specification, VMS). ,
, Java.
Java , , , -. , (dynamic binding).
.
, , Java, -. - . ,
. - ,
. -. , , JVM.
, .
Java "Write once, run anywhere" " , ".
- . , -
, ,
. . JIT-
(Just-In-Time),
,
. .
Sun Microsystems HotSpot

25

Java. , ,
.
Sun Microsystems picoJava, JVM. Java- . -. Java
JVM , , -,
.
. Java,
JVM .
JVM . JavaOS, .
Java . Andriod Java,
Dalvik, Linux.
, , MS Windows 2000/XP/Server 2003, Red Hat Linux, Fedora Core Linux,
SUSE Linux . , . "" .
, JVM , -
-. Java, . -, ,
, ,
-. ,
C/C++ , "" (native methods). "" .
Oracle, Sun Microsystems Java,
: , , , . JDK (Java
Development Kit). .
. , JDK IBM.

JDK?
JDK :
- javac;
java, JVM;
jre ( );

26

appletviewer, ;
jdb;
javap;
jar;
javadoc;
""
javah;

keytool;
native2ascii, ;
rmic rmiregistry ;
serialver, ;
"" ;
Java API (Application Programming Interface).

JDK :
. .

javac_g, java_g

Sun Microsystems JDK,


.
1996 . JDK 1.0, 1.0.2. Java API 8 .
JDK 1.0.2
5 , 8 .
1997 . JDK 1.1, , 1.1.8,
1998 . 23 , 8,5
30 .
JDK Java API classes.zip ,
.
JDK .
JDK 1.2 1998 . 57 .
20
17 .
130 , 80 .
, Java Sun Java 2 Platform, Standard Edition, J2SE, Java 2. 57 ,
Core API, Java 2 JDK 1.2 , Standard Extension API.
J2SE JDK 1.5.0, 2004 ., , Core API (Application Programming Interface).
46
.

27

Java: Java 2 Platform, Standard Edition


5.0, J2SE 5.0 JDK 5.0, JDK 1.5.0.
J2SE 5.0, JDK 1.5.0_22, 3 2009 .
, 2007 ., 2
Java Platform, Standard Edition 6, Java SE 6 JDK 6. , , JDK 1.6.0_26.
2011 Java SE 7 JDK 1.7.0,
.
Java SE JDK : MS Windows, Solaris, Linux, ,
HTML .
. , MS Windows Java SE JDK 1.7.0
jdk-7-windows-i586.exe , jdk-7-fcs-bin-b147-apidocs-27_jun_2011.zip.
http://www.oracle.com/
technetwork/java/javase/downloads/index.html.
Web- V Java
Platform, Enterprise Edition (Java EE). Java SE, , SDK (Software Development Kit),
Java EE API . .
Java EE SDK Java SE Java SE
JDK. , , Java EE
SDK, Java SE JDK.
Java EE , JBoss,
GlassFish , Java EE.
JDK Oracle JRE (Java Runtime
Environment).

JRE?
JRE
-, java ( jre) . JDK, , . Oracle JRE ,
, ,
Java, .
JRE JDK, Oracle .

JDK?
, JDK .
- : , http://www.oracle.com/

28

technetwork/java/javase/downloads/index.html - , . , (directory) , , /usr/java/jdk1.7.0. , .


, , jdk1.7.0, :
bin ;
db ;
demo , JDK;
docs , ;
include "" ;
jre JRE;
lib ;
sample , JDK;
src JDK,

src.zip.
-! JDK , Java. . ,
JDK,
. Java "", .

zip- jar-, src.zip.

PATH,
bin, /usr/java/jdk1.7.0/bin. , Java, JAVA_HOME,
JDK, /usr/java/jdk1.7.0.
Java, ,
java -version

JDK?
JDK ,
, MS Windows X Window System,
Command Prompt MS Windows.
UNIX, Linux, BSD , Xterm.
Java , Notepad,
WordPad MS Windows, vi, emacs UNIX.
, java. , , MyProgram.java, .

29

javac
:
javac MyProgram.java

,
, class. , , MyProgram,
MyProgram.class, -.
, ,
. , . JDK , ""
.
- java, -, (
):
java MyProgram


.
, ( MS
Windows exe)
. Java .
class- - JAR. ,
25. JDK MS Windows jar java, jar-.
, ( bat MS Windows
Shell- UNIX), java .
Java- (launcher) Java.
JDK: java.exe , , Java
Java main().
Java src/launcher. . , ,
Java Launcher SyncEdit, http://www.syncedit.com/software/javalauncher/,
Advanced Installer for Java Caphyon, http://www.advancedinstaller.com/.
, , Java, , .
AOT (Ahead-Of-Time) compiler. ,
GCC (GNU Compiler Collection) GCJ,
-, , - .

30

, "", , .

Java
Java, 1996 ., IDE (Integrated Development Environment) Java,
. , Eclipse, IntelliJ IDEA, NetBeans,
JDK,
, .
JDK. , Eclipse
.
JDK , JBuilder Embarcadero IBM Rational Application Developer.
, JDK. ,
Java.
, . .
RAD (Rapid Application Development).
- , -,
, ; -,
; -, , , .
Java CASE-. , Rational Rose Java.
Java, , NetBeans IDE, http://netbeans.org/.
, Java.

Microsoft
, , ,
. , , , , Microsoft Java.
, , Microsoft
Java, ,
Visual Studio. - ActiveX.
, - ,
ActiveX. "" Java -,
Microsoft.
Sun Microsystems Microsoft Visual J++.
Java Microsoft -, ""
, -, Visual J++. Visual Studio .NET 2005

31

J# (J sharp), - JVM, .NET Framework CLR. J#


Visual Studio .NET.
Java, Sun
"" Java, Pure Java, "" -. -, , , "" "100 % Pure Java".
, Sun Java Plug-in,
, JRE "".

Java
, Java
. ,
Java . Oracle
Java:
http://www.oracle.com/technetwork/java/index.html Java,

JDK;
http://forums.oracle.com/forums/category.jspa?categoryID=285 Java;
http://www.java.net/ , Java.

IBM http://www.ibm.com/developer/java/,
.
Microsoft Java
http://www.microsoft.com/mscorp/java/default.mspx.
:
http://www.artima.com/forums/ , Java;
http://www.developer.com/java/ Java;
http://www.freewarejava.com/ Java ;
http://www.jars.com/ Java Review Service;
http://www.javable.com/ c , Java;
http://javaboutique.internet.com/ ;
http://www.javalobby.com/ , Java;
http://www.javaranch.com/ Java;
http://www.javaworld.com/ ;
http://www.jfind.com/ ;
http://www.jguru.com/ ;
http://java.sys-con.com/ Java;
http://www.theserverside.com/ Java-;
http://www.codeguru.com/Java/ , -

32

http://securingjava.com/ ;
http://www.servlets.com/ ;
http://www.javacats.com/ Java Java.

:
http://www.mindviewinc.com/Index.php / ,

;
http://www.davidreilly.com/ ,

Java.
, , , . ,
, .

Java
, .
.
James Gosling, Bill Joy, Guy Steele,
Gilad Bracha, "The Java Language Specification, Third Edition".
http://java.sun.com/docs/books/jls/,
400 .
Java Tim
Lindholm, Frank Yellin, "The Java Virtual Machine Specification, Second Edition".
http://java.sun.com/docs/books/vmspec/.
"" Java , . :
., ., . Java. 3- .: .
. .: "", 2001. 624 .: .
Java
., Java. . . . .: , 2008.
223 . , .
Oracle Java Tutorial, : http://download.
oracle.com/javase/tutorial/ /. : Mary
Campione, Kathy Walrath, "The Java Tutorial, Second Edition: Object-Oriented
Programming for the Internet".
Java API , James
Gosling, Frank Yellin and the Java Team, "The Java Application Programming Interface",
Volume 1: Core Packages; Volume 2: Window Toolkit and Applets.

33

,
.
,
, ; ; "" , , "
", , , , , .


Java
1.

2.

- Java

3.

,

, , ,
.
, . , .
, " ",
.
Java , JLS (Java Language Specification), . , , Java, , , , :
Java .
, ,
" ", . , , .

Java
, ,
"Hello, World!". .
1.1 . ,
Java.
1.1. Java
class HelloWorld{
public static void main(String[] args){
System.out.println("Hello, XXI entury World!");
}
}

I. Java

38

, ! Java.
, Java, -

, (class).
class, ,

, HelloWorld. ,
, (class body).
-

, (method). , .
. -

main, . , , main.
, ( -

(returns)) ,
. , . .
void, .

(parameters) . , ,
. main() , ,
. Java API String,
. ,
args.
-

(modifiers). : public ,
; static main() . , , ,
main() .

, ,
, .

, , (method body),

.
, main() ,
System.out.println "Hello, XXI entury World!".
,
.
System.out.println , System, Java API,
out, Java
API, PrintStream, println(). ,
.

1. ,

39

println()
, , MS-DOS
Prompt, Command Prompt Xterm .
, ln,
println print line. Java API
print(), . , Pascal.
Java SE 5 (Java Standard Edition) System.out.printf(), . 23,
.
. Java ,
main, Main, MAIN " " Java.
String, System , main .
, Century century, ""
, .

Java .

. ,
helloworld helloWorld, Java- , "Code Conventions for the Java Programming Language",
http://www.oracle.com/technetwork/java/codeconv-138413.html.
:
() ; -

, ;
;

, ;
;

, .
, , JLS, . 6.8, Java .
, ,
:

? - ,
. .
"Code Conventions" ,
(
, ),
, (indent) .
, - ,
(Notepad), emacs vi. , -

I. Java

40

. , main(). . Java main() , , . java.



, main(), .

HelloWorld.java
. , :
javac HelloWorld.java

-, HelloWorld.class
.
-,
( !):
java HelloWorld

:
Hello, XXI Century World!


class .

. 1.1 , Command Prompt MS Windows 2003.

. 1.1. Command Prompt

- , Eclipse NetBeans,
""
.

, . . ,

1. ,

41

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

, ;
/* , -

, */ (
);
/** ,

, */.
.
,
, . . Java ,
JDK javadoc,
HTML .

javadoc, @.
JDK.
( 1.2).
1.2.
/**
* ...
* @author ()
* @version 1.0 ( )
*/
class HelloWorld{ // HelloWorld
//
public static void main(String[] args){
// args
/*
* */
System.out.println("Hello, XXI entury World!");
// ,
//
// System.out.println("Farewell, XX entury!");
}
}

, . , , ( ),
.

I. Java

42

, 1.2. - @author @version javadoc. - , javadoc . , @see


HTML, @deprecated, ,
.
.
javadoc , . , XDoclet
,
.
/**...*/ Xdoclet,
.
, , Java SE, ,
. /**...*/, , . ,
- @Deprecated, ,
. , .
, JDK,
. .
.
. , 3.

Java .
. .

:
: +5, -7, 12345678;
, b B: 0b1001, 0B11011;
, : 027, -0326, 0777 ( -

8 9);

, , ,
.

1. ,

43

, x X: 0xff0a,
0xFC2D, 0X45a8, 0X77FF (

).
: 1_001_234, 0xFC_2D.
int (. ).
"L" ( L
l), long (. ): +25L, -037l, 0xffL, 0XDFDFl.

l,
.


:
: 37.25, -128.678967, +27.035;
: 2.5e34, -0.345e-25, 37.2E+4; -

E; .
F f, float (. ): 3.5f,
-45.67F, 4.7e-5f. D ( d): 0.045D, -456.77889d,
double, , double.

, . :
, ,
( ): 'a', 'N', '?';
, :
'\n'

LF (Line Feed) ASCII 10;

'\r'

CR (Carriage Return) 13;

'\f'

FF (Form Feed) 12;

'\b'

BS (Backspace) 8;

'\t'

HT (Horizontal Tabulation) 9;

'\\' ;
'\"' ;
'\''

I. Java

44

0 255 ,


: '\123' S, '\346' CP1251.
,
,
.
'\377' 255;
Unicode

u :
S, '\u0416' .

'\u0053'

char (. ).

Unicode '\u0410' , '\u042F' , '\u0430' , '\u044F' .

, Unicode,
.

Java Unicode.

.
, , , , ,
. , ,
.
:
" \n "
"\"\" !"


, .

, .
" " + ""

" ". , . .
, (+);
( ) , :
" , " +
" "

1. ,

45

, Unicode, "":
System.out.println("\u0429\u043e\u0441\u0441\u0438\u044f");

, MS Windows Command Prompt


Terminal, Unicode
(- CP866) Unicode.
Unicode (glyphs) ,
Unicode.

Unicode .

(names) , ,
( (identifiers)) (qualified names).
Java Java (Java letters) 09, .
(, 2e3: 2000,0 ?)
Java ,
($) (_), .

. Java
.

:
a1
aName

my_var
theName

var3_5
a2Vh36kBnMt456dX

_var

veryLongVarName

l, ,
, .
, "Code Conventions".
Character, Java API, , , : isJavaIdentifierStart(),
, Java, isJavaIdentifierPart(), , , , (_)
($).
Java, class, void, static, , .
(qualified name) , , , System.out.println.


, Java, : (primitive types) (reference types).

I. Java

46

(arrays), (classes)
(interfaces). Java SE 5 (enum).
. ( )
, boolean, (numeric) .
(integral1) (floating-point).
: byte, short, int, long, char.
, int, JLS
char . , , , 2 + '', Unicode
'\u0416' ''. 1046,
1048.
, 2 + "", , ,
, ,
"2".
: float double.
. 1.2 Java.

. 1.2. Java

, . ,
, ,
. . , . . .

"integral" . The Java Language Specification, Third Edition. James Gosling, Bill Joy, Guy Steele, Gilad Bracha
(. ). .

1. ,

47

Java (strongly typed language).


boolean ,
2 > 3, .
: true () false (). Java.
:
boolean b = true, bb = false, bool2;

,
bool2 = true, ; b == bb b != bb, .


Java :
(NOT) ! ( );
(AND) & ();
(OR) | ( );
(XOR) ^ ().

boolean,
true false. ,
, . 1.1.
1.1.
b1

b2

!b1

b1 & b2

b1 | b2

b1 ^ b2

true

true

false

true

true

false

true

false

false

false

true

true

false

true

true

false

true

true

false

false

true

false

false

false

:
;
, ;
, ;
, .

, "To be or not to be" :
2b | ! 2b.

I. Java

48


:
(conditional-AND) &&;
(conditional-OR) ||.

.
,
, . . true
false.
,
(n != 0) && (m/n > 0.001) (n == 0) || (m/n > 0.001),
.

Java .

1. b bb, . " " , b & bb && !bb | b.


2. (!b || bb) && (bb ^ b).


Java, JLS, ( , ) . . 1.2. ,
Pentium.
1.2.

()

byte

128 127

short

32 768 32 767

int

2 147 483 648 2 147 483 647

long

9 223 372 036 854 775 808 9 223 372 036 854 775 807

char

'\u0000' '\uFFFF', 0 65 535

char ,
int, 4 , .
:
byte b1 = 50, b2 = -99, b3;
short det = 0, ind = 1, sh = 'd';

1. ,

49

int i = -100, j = 100, k = 9999;


long big = 50, veryBig = 2147483648L;
char c1 = 'A', c2 = '?', c3 = 36, newLine = '\n';

, char, . , ,
.
: , , ,
, .
, 50 b1, ,
00110010, 99 b2 ,
: 99 , 01100011,
, 10011100, , 10011101.
, ; , 1, , . ,
,
. , , , ,
A B, A B.
, .
. ,
. Java .


, , .


:
+ ();
- ();
* ();
/ ( , );
( ) % ();
( ) ++;
( ) --.

.
, ,
(

I. Java

50

), 5/2 2, 2,5, 5/(-3) 1. , .


, .

Java .

:
, . 5/2.0 5.0/2 5.0/2.0, 2,5
.
:
a % b = a (a / b) * b

, 5%2 1, 5%(-3) 2, . . 5 = (-3) * (-1) + 2, (-5)%3


2, 5 = 3 * (-1) 2.
,
, 5++ (a + b)++.
, i++ 99, j-- 99.
, : ++i, --j.
: ()

. ()
, .
, (k++) + 5 10004,
k 10000. (++k) + 5
10005, k 10000.


int, ,
long. long.

(promotion) byte, short, char. int, ,
long, long. int long,
long. , .
.
, 1.3, , . 1.3.
1.3.
class InvalidDef{
public static void main(String[] args){
byte b1 = 50, b2 = -99;

1. ,

51

short k = b1 + b2;
// !
System.out.println(k= + k);
}
}

. 1.3.

, InvalidDef.java, 4, (possible loss of precision). (found)


(required) , , ( )
, , .
( ) (1 error).
.
(narrowing) int short. ,
.
short k = (short)(b1 + b2);

.
, . ,
byte b = (byte)300;

b 44. , 300,
100101100, 00101100.
(widening) ,
.
int long, , , ,
.

Java .

I. Java

52


Java :
>;
<;
>=;
<=;
==;
!=.

, ,
=> .
: true,
3 != 5; false, 3 == 5.
. ,
a < x < b.
Java , , a < x,
true false, Java , , b, .
(a < x) && (x < b), ,
a < x && x < b, .


. (bitwise) , , " ".
Java :
(complement) ~ ();
(bitwise AND) &;
(bitwise OR) |;
(bitwise XOR) ^.

,
int long, , , . . 1.3.
1.3.
n1

n2

~n1

n1 & n2

n1 | n2

n1 ^ n2

1. ,

53

b1 == 50, 00110010, b2 == -99,


10011101.
byte int. 32- b1 0...00110010,
b2 1...10011101. :
~b2 == 98, 0...01100010;
b1 & b2 == 16, 0...00010000;
b1 | b2 == -65, 1...10111111;
b1 ^ b2 == -81, 1...10101111.

32 .
, ~x (-x)1.

Java :
<<;
>>;
>>>.

,
. , , , .
, b1 << 2 2
0...00110010 b1, 0...011001000,
200. ; ,
32- , .
b2 << 2 1...10011101 .
1...1001110100, 396.
, n 2 n.
b1 >> 2 0...00001100, 12, b2 >> 2
1...11100111, 25, . . ,
. .

, .
. ,
b2 >>> 2 001...100111, 1 073 741 799.
10011101
b2, . . 0...00100111, b2 , :
(b2 & 0xFF) >>> 2.

.

I. Java

54

3. 'D' + 5?
, , :
4. (b1 + 1) % (++b2 / b1++).
5. (b1 < 1) && (b2 == -99) || (ind >= 0).
6. (b1 | 1) & (big ^ b1).
7. (b1<<3 + 1<<2) % (b2>>5 / b1>>>2).


Java : float double. ,
, IEEE 7541985 .
:
, POSITIVE_INFINITY -

, 3.0*6e307 ;
NEGATIVE_INFINITY, -

, -3.0*6e307
;
" ", NaN (Not a Number) , ,

.
4 .
, ,
, 0.0 == -0.0
, true.
.
, , . . 1.4.
C/C++
Java %, ++ --
.

1.4.

float

3,4 1038 < |x| < 3,4 1038

78

double

1,7 10308 < |x| < 1,7 10308

17

1. ,

55

:
float x = 0.001f, y = -34.789F;
double z1 = -16.2305, z2;

, .
:
double,
double;

, float, float;
.


(simple assignment operator)
(=), , ,
: x = 3.5, y = 2 * (x 0.567) / (x + 2), b = x < y, bb = x >= y && b.
: , , , . .
, , : , , , .
,
3.5 = x. x = y x, y, y = x y.
11
(compound assignment operators): +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>=. , .
:
x = a

x = ( x)(x a)

, ind short 1. ind += 7.8 8, ind.


ind = (short)(ind + 7.8).
, ,
. :
byte b = 1;
b = b + 10;
b += 10;

// !
// !

b + 10 b int,
int , , b

I. Java

56

.
byte.

8. x = y = z = 1?
9. x += y -= z /= x + 2?


.
, . . true false, ,
, , :
x < 0 ? 0 : x
x > y ? x y : x + y

. . true,
.
. false,
, .
n == 0 ? m : m / n, . , .

10. x > 0 ? x : -x?


11. x > y ? x : y?
12. x > y ? y : x?

, , (expressions). , , , , 2 + true.
.
: x + y + z
(x + y) + z. :
x = y = z x = (y = z).

.
.
-

1. ,

57

.
int a = 3, b = 5;

b + (b = 3) 8;
(b = 3) + b 6. b += (b = 3) 8, .
C/C++
C++ 8.

. a b
b += a += b += 7

20. ,
, b 12, , , b, 5.

a += b += 7;
b += a;

27, b, 12.
C/C++
C++ 27.

.
, . . , .
, .
.
, . " ". . ,
, .


.
.
1. ++ --.
2. ++ --, ~ !.
3. ().
4. *, / %.
5. + -.
6. : <<, >>, >>>.

I. Java

58

7. : >, <, >=, <=.


8. : ==, !=.
9. &.
10. ^.
11. |.
12. &&.
13. ||.
14. ?:.
15. : =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>=.
Java, .
C/C++
Java "", for.

, , ,
, , .
: -, ,
, , - .
. (statements) . ,
.
: , ,
, .
Java :
( );
-;
;
if;
while, do-while, for;
switch;
break, continue return;
, {};
.

1. ,

59

Java,
.

Java goto.

.
,
(expression statement). , . ,
.
P ASCAL
Java , .

.
, .


, .
, {x = 5; y = 7;}. , {}.
,
.


.
.
. , .


(if-then-else statement)
. Java :
if () 1 else 2

. .
true, 1,
, 2 . , if. " then" .
false, 2, 1 (" else").

60

I. Java

, else (if-then statement):


if () 1

, false, ,
.
then,
else. .
"Code Conventions"
, :
if (a < x){
x = a + b;
} else {
x = a b;
}

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

("dangling else"):
int ind = 5, x = 100;
if (ind >= 10) if (ind <= 20) x = 0; else x = 1;

if else, ?
x 100 1? ,
, Java, : else if, else.
x 100.
:
if (ind > 10) {if (ind < 20) x = 0;} else x = 1;

, . .
, :
if (ind >= 10 && ind <= 20) x = 0;
else x = 1;

1.4
ax2 + bx + c = 0 , .

1. ,

61

1.4.
class QuadraticEquation{
public static void main(String[] args){
double a = 0.5, b = -2.7, c = 3.5, d, eps=1e-8;
if (Math.abs(a) < eps)
if (Math.abs(b) < eps)
if (Math.abs(c) < eps)
//
System.out.println(" ");
else
System.out.println(" ");
else
System.out.println("x1 = x2 = " +(-c / b));
else {
//
if((d = b*b 4*a*c)< 0.0){
//
d = 0.5 * Math.sqrt(-d) / a;
a = -0.5 * b/ a;
System.out.println("x1 = " +a+ " +i " +d+", x2 = " +a+ " i " +d);
} else {
//
d = 0.5 * Math.sqrt(d) / a;
a = -0.5 * b / a;
System.out.println("x1 = " +(a + d)+ ", x2 = " +(a d));
}
}
}
}

abs() sqrt() , Java API


Math. ,
, . , , 0,00000001.
, println() , ,
, .
" "

a, b ? . System.in.read(byte[] bt), ,
bt ASCII, . ,
Double(new String(bt)).doubleValue(). ? 23.
, ,
(. 21).

13. y, x + 1, x < 0,
x + 2, 0 <= x < 1, x + 10 .

I. Java

62

14. , z true,
M(x, y) , false .


while :
while ()

. true, , . ,
, false.
false, . , , . while
, .
, :
int i = 0;
double s = 0.0;
while ((s += 1.0 / ++i) < 10);

i , ,
s 10. . , ,
, , .
:
while (true)

, - ,
break, 1.5. ,
<Ctrl>+<C> UNIX Task Manager Windows.
, {}.
do-while :
do while ()

, . , true.
P ASCAL
do-while , .

,
do-while .

1. ,

63

, - f(x), [a; b]
. 1.5 ,
(, ).
1.5.
class Bisection{
static double f(double x){
return x*x*x 3*x*x + 3;
// - ...
}
public static void main(String[] args){
double a = 0.0, b = 1.5, c, y, eps = 1e-8;
do{
c = 0.5 *(a + b); y = f(c);
if (Math.abs(y) < eps) break;
// .
// [a; c] :
if (f(a) * y < 0.0) b = c;
// , . b c
// :
else a = c;
// a c
// , [a; b]
} while(Math.abs(b-a) >= eps);
System.out.println("x = " +c+ ", f(" +c+ ") = " +y);
}
}

Bisection : main()
f(x). f() :
, :
return

main() break, , .
static f(). , f()
main(), .
for :
for (1; ; 2)

1.
, . ,
. , .
. , true,
, 2.

64

I. Java

. , 2
. . false, .
,
1;
while (){

2;
}

, continue, 2 - .
1 . .
for : ,
, . :
for (;;)

- .
for , , ,
int s = 0;
for (int k = 1; k <= N; k++) s += k * k;
// k

N .
Java for, "for-each",
. , .

continue
continue . . continue
. continue
:
for (int i = 0; i < N; i++){
if (i == j) continue;
s += 1.0 / (i j);
}

:
continue
, , Java, ,
.

1. ,

65

. .
P ASCAL
.

, .

break
break .

break

, .
.
M1: { //
M2: { //
M3: { // ...
if (- ) break M2;
// true,
}
//
}
//
}

, , .
, break .

15. , .
16. , , 2 .


switch . -
( long) ,
. :

I. Java

66
switch (){
case 1: 1
case 2: 2
case N: N
default: Def
}

byte, short, int, char,


long. , , , , , long.
-,
String, . . , ,
3.4 28.9.
. , , .
, .
, , .
("fall through labels") , Def, .
, Def
. default . default , .
, case ,
, .
P ASCAL
switch .

"" . break, switch.


,
case. case . .
switch (dayOfWeek){
case 1: case 2: case 3: case 4: case 5:
System.out.println(" "); break;
case 6: case 7:
System.out.println(" "); break;
default:
System.out.println(" ");
}

,
:

1. ,

67

switch (dayOfWeek){
case "Mon": case "Tue": case "Wed": case "Thu": case "Fri":
System.out.println(" "); break;
case "Sat": case "Sun":
System.out.println(" "); break;
default:
System.out.println(" ");
}


break,
.

, ,
.
Java ,
. .
(declaration).
(reference) , .
, ,
, , ,

double[] a, b;

a b double. . ,
:
int i = 0, ar[], k = -1;

i k ar.
(instantation). , , , - . Java new , , ,
.
,
a = new double[5];
b = new double[100];
ar = new int[50];

.
0. a : a[0],
a[1] ... a[4]. a[5] . -

I. Java

68

, long, a[i+j], a[i%5], a[++i].


Java ,
. Java
.
(initialization).
. ,
a[0] = 0.01; a[1] = -3.4; a[2] = 2.89; a[3] = 4.5; a[4] = -6.7;
for (int i = 0; i < 100; i++) b[i] = 1.0 / i;
for (int i = 0; i < 50; i++) ar[i] = 2 * i + 1;

:
double[] a = new double[5], b = new double[100];
int i = 0, ar[] = new int[50], k = -1;

, . , :
double[] a = {0.01, -3.4, 2.89, 4.5, -6.7};

:
a = new double[] {0.1, 0.2, -0.3, 0.45, -0.02};

, new,
:
System.out.println(new char[] {'H', 'e', 'l', 'l', 'o'});

,
. ,
a = b a b 100
double .
"" null,
:
ar = null;

, , ,
.

, a == b, a != b. , ; ,
.

Java , .

length. .

1. ,

69

. ,
, a.length 5, b.length 100, ar.length
50.
length a :
a[a.length 1], a[a.length 2] . . :
double aMin = a[0], aMax = aMin;
for (int i = 0; i < a.length; i++){
if (a[i] < aMin) aMin = a[i];
if (a[i] > aMax) aMax = a[i];
}
double range = aMax aMin;

. , 1.
, , , . Java SE 5,
Java for, "for-each", . "for-each":
double aMin = a[0], aMax = aMin;
for (double x : a){
if (x < aMin) aMin = x;
if (x > aMax) aMax = x;
}
double range = aMax aMin;

, for x , .
.
, , : (a[2] + a[4]) / a[0] . .
C/C++
Java , -
'\u0000'.


Java . :
char[][] c;


char[] c[];

char c[][];

I. Java

70

:
c = new char[3][];

, , -. -:
c[0] = new char[2];
c[1] = new char[4];
c[2] = new char[3];

c.length 3, c[0].length 2, c[1].length


4 c[2].length 3.
, c[0][0] = 'a', c[0][1] = 'r', c[1][0] = 'r',
c[1][1] = 'a', c[1][2] = 'y' . .

Java .

:
int[][] d = new int[3][4];

:
int[][] inds = {{1, 2, 3}, {4, 5, 6}};

1.6 , 10 , .
1.4 .
1.6.
class PascalTriangle{
public static final int LINES = 10;
//
public static void main(String[] args){
int[][] p = new int[LINES][];
p[0] = new int[1];
System.out.println(p[0][0] = 1);
p[1] = new int[2];
p[1][0] = p[1][1] = 1;
System.out.println(p[1][0] + " " + p[1][1]);
for (int i = 2; i < LINES; i++){
p[i] = new int[i+1];
System.out.print((p[i][0] = 1) + " ");
for (int j = 1; j < i; j++)
System.out.print((p[i][j] = p[i1][j-1] + p[i1][j]) + " ");
System.out.println(p[i][i] = 1);
}
}
}

1. ,

71

. 1.4. Command Prompt

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


1. Java?
2. Java?
3. main()?
4. ?
5. ?
6. ?
7. 032?
8. 02?
9. " "?
10. " "?
11. 3.45 % 2.4?
12. 12 | 14 & 10?
13. 3 << 4?

72

I. Java

14. ?
15. continue ?
16. break ?
17. ?
18. ?
19. ?
20. , ?

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


, , ,
. , .
: FORTRAN, Algol , . ,
, . , , .
: , . ,
. . ,

. .
.
.
, , , ,

74

I. Java

, .
, . .
, Pascal,
. , .
:
. "" . .
,
.
, . . , Pascal,
" + = ".
.
. ,
- . ,
.
,
.
,
, , (public) , , , , (private) .
. (interface),
(implementation) . , , , , ,
. -. Turbo Pascal
, "" (header) .
++, , . Java ,
interface, .
, (incapsulation) . . , "" ,
- , . , , .
, , ,
- . .

2. - Java

75

, ,
,
. , .
: ?
: , ,
; , , ,
, .
, , , . : , , , , , , . -
: , , , , , , , ,
. .
, ,
.
,
. (object-oriented programming),
(OOP) .
. .
,
, , - . , . , . , .
, , .
. ,
, width height,
, (x, y)
, , , , Times New Roman,
color, , .
, - , , move(), - size(),
iconify(), - . ! , : ,
, .
, , "" ,
: ", , ",
,
, !

76

I. Java

-
. , - ,
(object-oriented analysis, OOA). - , (object-oriented
design, OOD).
-
. ?
? ? ? - ,
. .

-
. ,
- . , ,
, . .

- , , . , , :
. ,
. , ,
.
,
.
, , , , , , , .
,
. .
,
. " ",
? , , .
, , . , ? , -

2. - Java

77

, .
.
, , . ,
, .
? . "
". . "",
"".
: " ". "" , , - , , , .
"" , "", "", " ", " ", " ". " "
, , , .
" " -
? " "? -, " " , , .
, - , .
, , , .
-
(classes). . , , ,
.
.
, ,
, . , . (class fields). ,
, . ,
.
, ,
. (class methods).
, , . ,
, .
(nested classes),
, , , . "" . ,
(class members).
-

I. Java

78

, ,
Java.
:
class Automobile{
int maxVelocity;
// , .
int speed;
// , .
int weight;
// , .
// ...
void moveTo(int x, int y){
// , (x, y).
// x y , .
int a = 1;
// a , .
// .
// (x, y)
}
// ...
}

P ASCAL
Java , .

, , (instances) . , (. 1).
: , , .
Automobile lada2110, fordScorpio, oka;

new , , .
lada2110 = new Automobile();
fordScorpio = new Automobile();
oka = new Automobile();

, .
, , , new Automobile().
(constructor) , .
, ,
. :
lada2110.maxVelocity = 150;
fordScorpio.maxVelocity = 180;
oka.maxVelocity = 350;
// ?
oka.moveTo(35, 120);

2. - Java

79

, Java String.

int strlen = " String".length();

"" length(), String, . strlen,


24. ,
Java, .
. , ,
. , , .

, Automobile ? , . ,
? . ,
? ? : .
.
. , .
(pets): (cats), (dogs),
(cows) . :
class Pet{
//
Master person;
//
int weight, age, eatTime[];
// , ,
int eat(int food, int drink, int time){
//
// ...
if (time == eatTime[i]) person.getFood(food, drink);
//
}
void voice();
// ,
// ...
}

, ,
Pet:
class Cat extends Pet{
int mouseCatched;
void toMouse();
//
}
class Dog extends Pet{
void preserve();
}

// , :
//
//

// :
//

I. Java

80

, ,
Pet. . Dog
Pet , Dog. , :
Dog tuzik = new Dog(), sharik = new Dog();

:
tuzik.age = 3;
int p = sharik.eat(30, 10, 12);

:
class Pointer extends Dog{ ... }
class Setter extends Dog{ ... }

//
//

, , . extends
"", , Dog (extension) Pet.
, : ,
. , Dog (subclass) Pet, Pet (superclass) Dog.
: ,
, -, -, ,
, .
(inheritance) ,
, Dog Pet.
.
Master. :
class Master{
//
String name;
// ,
//
void getFood(int food, int drink); //
// ...
}

. "", "", "", "", "",


"" .
- .
, eat(). ,
getFood().
message. "". "", "" "-

2. - Java

81

". "" .
" ", : " "?
, .
, . -

person.
. ,
, .
, , ,

. .
Chappi, ,
. (polymorphism)
.
, -

. " "
" ", .
, sharik, eat(), ,
person,
. person.getFood(food, drink).
(contract) ,
, sharik (responsibility) , person
getFood(),
.

, - (modularity).
: .
, , .
Java private
. :
private int mouseCatched;
private String name;
private void preserve();

,
, tuzik sharik.preserve().
Master
private void getFood(int food, int drink);

getFood() sharik
.

I. Java

82

, private public, :
public void getFood(int food, int drink);

.
++
Java private, public protected
.

. : "
".
,
(access methods), (get
method) (set method). get set, .
Java, ( -
Java JavaBeans), .
Master name :
public String getName(){
return name;
}
public void setName(String newName){
name = newName;
}

, set, . , , . .
is-, true false. , Master
, , :
public boolean isEmpty(){
return name == null;
}

name, :
if (master01.isEmpty()) master01.setName("");

, , . ,
, , (low
coupling) . . ,

2. - Java

83

.
, , , (high cohesion). , ,
, .
, (Karl J. Lieberherr), . : " m()
, , m(),
, m()".
, , , . , ,
.
? Pet
private Master person;

sharik.person? , .
, ,
.
, , Java (protected) , protected, sharik person Pet, Pet :
protected Master person;

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

.
, , ,
.

KISS
,
KISS . :
"Keep It Simple, Stupid!"
, , ,
. , , . - -

84

I. Java

. ,
.
, , . ,
. , . , , .
. . Java
. , .

. ,
.

1. .
2. .
3. .

?
, class,
. "Code Conventions"
.
class (class modifiers).
public, abstract, final, strictfp. protected, private, static.
.
, , , ,
, .
, , , , , , . 1.
public, protected, private, static, final, transient, volatile.
, JLS ,
. .
void,
, , , , , .
.

2. - Java

85

public, protected, private, abstract,


static, final, synchronized, native, strictfp. .
. - final.
. ,
.

, , .
.
, , .
.
2.1 ,
1.5.
2.1.
class Bisection2{
private static double final EPS = 1e-8; // .
private double a = 0.0, b = 1.5, root;
// .
public double getRoot(){return root;}
// root.
private double f(double x){
return x*x*x 3*x*x + 3;
// - .
}
private void bisect(){
//
// .
double y = 0.0;
// .
do{
root = 0.5 *(a + b);
y = f(root);
if (Math.abs(y) < EPS) break;
// . .
// [a; root] :
if (f(a) * y < 0.0) b = root;
// , , b root.
// :
else a = root;
// a root
// , [a; b] .
} while(Math.abs(b-a) >= EPS);
}
public static void main(String[] args){
Bisection2 b2 = new Bisection2();
b2.bisect();
System.out.println("x = " +
b2.getRoot() +
// .
", f() = " +b2.f(b2.getRoot()));
}
}

86

I. Java

f() : ,
x, . bisect() : , b2 . bisect() Bisection2, (private).



. , , . - ,
.
.
: .
, ,
. , , .
, . , , , , .
Java, ,
. , :
class Dummy1{
private static void f(int a){
a = 5;
}
public static void main(String[] args){
int x = 7;
System.out.println(": " + x);
f(x);
System.out.println(": " + x);
}
}

7 f(), a, - x.
. - -, ,
, , . , ,
-. .

2. - Java

87

class Dummy2{
private static void f(int[] a){
a[0] = 5;
}
public static void main(String[] args){
int[] x = {7};
System.out.println(": " + x[0]);
f(x);
System.out.println(": " + x[0]);
}
}

x , , a. a ,
x. , ": 7", ": 5". , ,
f() , , .
.
:
class Dummy3{
private static void f(int[] a){
a = new int[]{5};
}
public static void main(String[] args){
int[] x = {7};
System.out.println(": " + x[0]);
f(x);
System.out.println(": " + x[0]);
}
}

7. f()
, , a
x, . a ,
{5}, x , - {7}.
P ASCAL

++

Java .


, (signature) . , .
, / .

I. Java

88


, , .

, Automobile moveTo(int x, int y),


.
moveTo(String destination)
:
oka.moveTo("");

(overloading). . , 1 println(), ,
.
println, . , . PrintStream, print() println().


, , , :
class Truck extends Automobile{
void moveTo(int x, int y){
// - ...
}
// - , Truck...
}

.
Truck, :
Truck gazel = new Truck();

gazel.moveTo(25, 150), Truck. (overriding) .



. ,
, , . , , "" .

, @Override,
2.2. ,
.
,
. public , protected , .

2. - Java

89

? , , super, super.moveTo(30, 40).


, , this, this.moveTo(50, 70),
.
, .
, "", " ",
"", " ".

Java
. Pet voice(). Chorus,
2.2.
2.2.
abstract class Pet{
abstract void voice();
}
class Dog extends Pet{
int k = 10;
@Override
void voice(){
System.out.println("Gav-gav!");
}
}
class Cat extends Pet{
@Override
void voice(){
System.out.println("Miaou!");
}
}
class Cow extends Pet{
@Override
void voice(){
System.out.println("Mu-u-u!");
}
}
public class Chorus{
public static void main(String[] args){
Pet[] singer = new Pet[3];
singer[0] = new Dog();
singer[1] = new Cat();
singer[2] = new Cow();

I. Java

90
for (Pet p: singer)
p.voice();
}
}

. 2.1 . !

. 2.1. Chorus

singer[]. singer[] Pet,


: Dog, Cat, Cow.
, , . Java .
++
Java .

Pet abstract. Pet


voice() .

4. .
5. .
6. .


Pet voice() , .

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

2. - Java

91

? , .
? , ?
2.2.
singer[] Dog, Cat, Cow, -
Pet , Pet. . , , k Dog, singer[0].k. "",
. , , , , . ,
.
, , , , :
void voice(){}

, . , .
.


final, . . ,
, .
sin(), cos() . Math. , Math.cos(x)
x. , .
, ,
(private).
final ,
.
final , . , , Math:
public final class Math{ . . . }

final .
final , ( , , )
, . .
Java :
public final int MIN_VALUE = -1, MAX_VALUE = 9999;

"Code Conventions" ,
.

92

I. Java

Object
Java Object.
, . .
extends , Pet, Java
Object, :
class Pet extends Object{ . . . }

.
Object , Java. , Object.
,
, equals(), , ,
. :
Object obj1 = new Dog(), obj2 = new Cat();
if (obj1.equals(obj2)) ...

- : obj1 , . , , obj2.equals(obj1),
obj2, .
1, :
obj1 == obj2; obj1 != obj2;

, ,
.
equals() , Object : . ; , , " " Object,
. , String equals()
, ,
, 5.
Object, , hashCode()
, , . . Java. hashCode(),
Object, - .
hashCode() .
Object, ,
toString(). ,
String. Object toString() ,
hashCode(). toString() , Java , , -

2. - Java

93

println(). toString() , , .


, new, , . ,
"", ?
"" (class constructor).
. . .
. ,

Java (default constructor), , ,


, ,
.
,
, .
.

void, : public, protected


private.

, .

.
:

,
super() , ;
,
this() , .
super() , , , , ,
.
,
, return, , .
. , , / .
, ,
, . , , . ,

94

I. Java

, . . .
,
Object.

new
, new.
.

, :
double a[] = new double[100];

.
.
, .
, false,
null.
new .
"" :
Dog k9 = new Dog();

:
new Dog().voice();

voice().
, Java, .
, new , , .

7. , 46.


,
.
. .
(instance variables) .
, , . ,
Automobile . (class variables).

2. - Java

95

, .
Java static. 2.3 number.
2.3.
class Automobile{
private static int number;
Automobile(){
number++;
System.out.println("From Automobile constructor:" +
" number = " + number);
}
}
public class AutomobileTest{
public static void main(String[] args){
Automobile lada2105
= new Automobile(),
fordScorpio = new Automobile(),
oka
= new Automobile();
}
}

, . 2.2.

. 2.2.

, ,
Automobile.number, , lada2105.number,
, . , , .
,
static. static
, , Java
, , , .

I. Java

96

.
.
,
.
.
, .
( ), .
Math, ,
Math.abs(x), Math.sqrt(x). System.out.println().
main() , .
(class methods),
, (instance methods).
:
this super;
;
;
, -

, .
1.5 f()
2.1 b2 Bisection2, f() .
static.

,
. , ,
, static, ,
:
static int[] a = new a[10];
static{
for (int k: a) a[k] = k * k;
}

, , ,
, .
, , : " ,
!" :

, .

Complex
. , , -

2. - Java

97

. , , Java. .
2.4 , , . , , ().
2.4. Complex
class Complex{
private static final double EPS = 1e-12; // .
private double re, im;
// .
// :
Complex(double re, double im){
this.re = re; this.im = im;
}
Complex(double re){this(re, 0.0);}
Complex(){this(0.0, 0.0);}
Complex(Complex z){this(z.re, z.im);}
// :
public double getRe(){return re;}
public double getIm(){return im;}
public Complex getZ(){return new Complex(re, im);}
public void setRe(double re){this.re = re;}
public void setIm(double im){this.im = im;}
public void setZ(Complex z){re = z.re; im = z.im;}
// :
public double mod(){return Math.sqrt(re * re + im * im);}
public double arg(){return Math.atan2(re, im);}
// : ?
public boolean isReal(){return Math.abs(im) < EPS;}
public void pr(){
//
System.out.println(re + (im < 0.0 ? "" : "+") + im + "i");
}
// Object:
public boolean equals(Complex z){
return Math.abs(re z.re) < EPS &&
Math.abs(im z.im) < EPS;
}
public String toString(){
return "Complex: " + re + " " + im;
}
// , +=, -=, *=, /=
public void add(Complex z){re += z.re; im += z.im;}
public void sub(Complex z){re -= z.re; im -= z.im;}
public void mul(Complex z){
double t = re * z.re im * z.im;
im = re * z.im + im * z.re;
re = t;
}

98

I. Java

public void div(Complex z){


double m = z.re * z.re + z.im * z.im;
double t = re * z.re im * z.im;
im = (im * z.re re * z.im) / m;
re = t / m;
}
// , +, -, *, /
public Complex plus(Complex z){
return new Complex(re + z.re, im + z.im);
}
public Complex minus(Complex z){
return new Complex(re z.re, im z.im);
}
public Complex asterisk(Complex z){
return new Complex(
re * z.re im * z.im, re * z.im + im * z.re);
}
public Complex slash(Complex z){
double m = z.re * z.re + z.im * z.im;
return new Complex(
(re * z.re im * z.im) / m, (im * z.re re * z.im) / m);
}
}
// Complex.
public class ComplexTest{
public static void main(String[] args){
Complex z1 = new Complex(),
z2 = new Complex(1.5),
z3 = new Complex(3.6, -2.2),
z4 = new Complex(z3);
System.out.println();
// .
System.out.print("z1 = "); z1.pr();
System.out.print("z2 = "); z2.pr();
System.out.print("z3 = "); z3.pr();
System.out.print("z4 = "); z4.pr();
System.out.println(z4);
// toString().
z2.add(z3);
System.out.print("z2 + z3 = "); z2.pr();
z2.div(z3);
System.out.print("z2 / z3 = "); z2.pr();
z2 = z2.plus(z2);
System.out.print("z2 + z2 = "); z2.pr();
z3 = z2.slash(z1);
System.out.print("z2 / z1 = "); z3.pr();
}
}

. 2.3 .

2. - Java

99

. 2.3. ComplexTest

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

java main() ,
.
java . ,
. , .
2.5, ,
, main() .

I. Java

100
2.5. main()
class Echo{
public static void main(String[] args){
for (String s: args)
System.out.println("arg = " + s);
}
}

. 2.4 .

. 2.4.

, .
main().
/++
Java ,
main(), args[0]. argc
args.length, . .
:
System.getProperties().list(System.out);


. 2.4,
. Java main(). :
class VarArgs{
private static int[] args1 = {1, 2, 3, 4, 5, 6};
private static int[] args2 = {100, 90, 80, 70};

2. - Java

101

public static int sum(int[] args){


int result = 0;
for (int k: args) result += k;
return result;
}
public static void main(String[] args){
System.out.println(Sum1 = + sum(args1));
System.out.println(Sum2 = + sum(args2));
}
}

Java .
, .
, .
public static int sum(int... args){
int result = 0;
for (int k: args) result += k;
return result;
}

.
public static void main(String[] args){
System.out.println(Sum1 = + sum(1, 2, 3, 4, 5, 6));
System.out.println(Sum2 = + sum(100, 90, 80, 70));
}


Java . , ,
.
(scope) ? ? ? 2.6
.
2.6.
class ManyVariables{
static int x = 9, y;

static{

x = 99;
}

// .
// .
// y 0.
// .
//
// .
// !

I. Java

102
int a = 1, p;

// .
// ,
//
// .
// p 0.
// .
//
// .
// !

p = 999;
}
static void f(int b){
int a =

int c;

// b ,
// .
2;
// "a".
// f()
// "a".
// , f().
//
// .
= 555; // ! .
= 333; // , .

{ int c
int x
}
// x .
for (int d = 0; d < 10; d++){
// d .
int a = 4;
// !
int e = 5;
// , for.
e++;
// .
System.out.println("e = " + e);
// "e = 6".
}
// d e .
}
public static void main(String[] args){
int a = 9999; // ,
// main().
f(a);
}
}

,
. '\u0000', false, null.
. , . , .
!
, .

2. - Java

103

2.6 :
(instance initialization). , , .
, static- , . , static-
. ,
? ,
, .


, , (nested) .
, (inner) . . "" , , .
? ,

.
, -

? , ,
, !
, ,

?
. , new
.
?..

, .
- (member
classes), , (local classes), / . , ,
.
- static.
-
, . (nested top-level classes), . . ,
.
(inner).
.
, , ,
. (anonymous classes).
2.7 .

I. Java

104
2.7.

class Nested{
static private int pr; // pr ,
// A AB.
String s = "Member of Nested";
// .
static class A{
// Nested.A
private int a = pr;
String s = "Member of A";
// A .
static class AB{
// Nested.A.AB
private int ab = pr;
String s = "Member of AB";
}
}
// Nested .
class B{
// Nested.B
private int b = pr;
String s = "Member of B";
// B .
class BC{
// Nested.B.BC
private int bc = pr;
String s = "Member of BC";
}
void f(final int i){ // final i j
// D.
final int j = 99;

//
//

class D{
// D f().
private int d = pr;
String s = "Member of D";
void pr(){
// ,
// "s".
System.out.println(s + (i+j)); // "s" "this.s".
System.out.println(B.this.s);
System.out.println(Nested.this.s);
System.out.println(AB.this.s); // .
System.out.println(A.this.s);
// .
}
}
D d = new D();
// , f().
d.pr();
// f().

}
}
void m(){
new Object(){

// ,
// .

2. - Java

105

private int e = pr;


void g(){
System.out.println("From g());
}
}.g(); // .
}
}
public class NestedClasses{
public static void main(String[] args){
Nested nest = new Nested();
//
// .
Nested.A theA = nest.new A(); //
// new. .
Nested.A.AB theAB = theA.new AB(); // .
// new .
Nested.B theB = nest.new B();
// .
Nested.B.BC theBC = theB.new BC();
theB.f(999);
// .
nest.m();
}
}

? -?
, , .
, , . KISS
.
.
, Nested ,

pr. Java .
,
.
Java -

this : Nested.this, B.this.


,

, ,
Object.
, .
,

, new nest.new, theA.new, theB.new.


,

new .

. .
.

106

I. Java

? .
? super

, this.
? .
?.. KISS!!!

, , :
Nested$1$D.class D, Nested;
Nested$1.class ;
Nested$A$AB.class Nested.A.AB;
Nested$A.class Nested.A;
Nested$B$BC.class Nested.B.BC;
Nested$B.class Nested.B;
Nested.class Nested;
NestedClasses.class main().

"" , ,
. , , . . .
, . Java .
.
. , . . , final. . , private,
.
. Java ,
, , , .
person Master Pet. Master ,
Pet, Master (inner)
. :
class Pet{
// .
class Master{
// .
string name; // , .
// ...

2. - Java

107

void getFood(int food, int drink); // .


// ...
}
int weight;
// .
int age;
// .
Date eatTime[]; // , .
int eat(int food, int drink, Date time){ // .
// .
if (time == eatTime[i]) person.getFood(food, drink);
// ...
}
void voice(); // , .
// .
}

,
.
-. , Master, Pet
?
, ? " " "".

" " ""


. , .
, , , . - "" ?
,
Master Pet " Master Pet"
" Master Pet". , " " " "? : "
" " "? ,
,
.
" " - "a
class A is a class B", "is-a".
" " - "a class A has a class B",
"has-a".
"is-a" "-",
, .
"has-a" "-" .

108

I. Java

: "
Master Pet" " Master Pet"?
, , . Master Pet ,
. Master Pet.


-
Java. ,
[36].
, . "" . II III
.
Java .


1. ?
2. ?
3. - ?
4. ?
5. ?
6. ?
7. ?
8. Java?
9. ?
10. ?
11. ?
12. Java?
13. ?
14. ?
15. ?
16. main() ?
17. main() ?

,

Java API .
.
. , - , . ,
, .
Java
(packages). Java .
(subpackages).
.
.
class ( -), , . .
(namespace). ,
, .
, .
, , . , : ..
(fully qualified name).
, -,
, , .
, , , , . ,
, . ,
.
, private, protected public , "" .
private, protected, public,
(default access), . . . -

110

I. Java

public,
, , public, .
, .
?


, java-
package ;

:
package mypack;

mypack ,
, mypack. ,
.
. , ,
subpack, :
package mypack.subpack;


subpack mypack.
, -
package mypack.subpack.sub;

. . .
package ; , .
Java mypack, subpack class- -.
A, B : mypack.A, mypack.subpack.B.
"Code Conventions"
. , , ,
. , ,
, :
com.sun.developer

.
. ?
(unnamed package),
(current working directory) .

3. ,

111

class- , java-.
. . , Java . Java .
, Java SE 7 API java, javax, org.
java applet, awt, beans, dyn, io, lang, math, net, nio, rmi,
security, sql, text, util . , ( ) java.awt
, color, datatransfer, dnd, event, font, geom, im,
image, print.
, Java SE API .


.
. , , . 3.1.

. 3.1.

Base.java : Inp1, Base Derivedp1,


p1. Base
, f() Inp1 Derivedp1 Base. . . 3.1
.
Base.

3.1. Base.java p1
package p1;
class Inp1{
public void f(){
Base b = new Base();
//
b.priv = 1; // "priv has private access in p1.Base"
b.pack = 1;
b.prot = 1;

I. Java

112
b.publ = 1;
}
}

public class Base{


private int priv = 0;
int pack = 0;
protected int prot = 0;
public
int publ = 0;
}
class Derivedp1 extends Base{
public void f(Base a){
//
a.priv = 1;
// "priv has private access in p1.Base"
a.pack = 1;
a.prot = 1;
a.publ = 1;
//
priv = 1;
// "priv has private access in p1.Base"
pack = 1;
prot = 1;
publ = 1;
}
}

3.1, , private,
.
Inp2.java : Inp2 Derivedp2, Base.
p2.
Base. . 3.2 .
, Base p1 public, p2 .
3.2. Inp2.java p2
package p2;
import p1.Base;
class Inp2{
public static void main(String[] args){
Base b = new Base();
//
b.priv = 1;
// "priv has private access in p1.Base"
//
b.pack = 1;
// "pack is not public in p1.Base;
// cannot be accessed from outside package"
//
b.prot = 1;
// "prot has protected access in p1.Base"
b.publ = 1;
}
}
class Derivedp2 extends Base{
public void f(Base a){

3. ,
//
//

a.priv = 1;
a.pack = 1;

//

= 1;
1;
1;
1;

a.prot
a.publ =
//
priv =
//
pack =

//
//
//
//

113

"priv has private access in p1.Base"


"pack is not public in p1.Base; cannot
be accessed from outside package"
"prot has protected access in p1.Base"

// "priv has private access in p1.Base"


// "pack is not public in p1.Base; cannot
// be accessed from outside package"

prot = 1;
publ = 1;
super.prot = 1;
}
}

, , .
, public,
. , protected, ,
, .
, .
. 3.1 .
3.1.

private

"package"

protected

public

* protected- .


, class-, - , ,
.
. D:\jdk1.3\MyProgs\ch3
classes Base.java Inp2.java, 3.1 3.2. 3.2
.
.
1. classes p1 p2.
2. Base.java p1 p1 .

I. Java

114

. 3.2.

3. Base.java, p1 : Base.class, Inp1.class,


Derivedp1.class.
4. Inp2.java p2.
5. classes.
6. , p2\Inp2.java.
7. java p2.Inp2.
2 3 class- ,
p1. class-
.
5 6 , Inp2.java p1.Base, p1\Base.class, .
, (7)
.
(options) , .
1. -d , :
javac -d classes Base.java

classes p1 class.
2. -classpath ,
classes, p1:
javac -classpath classes -d classes Inp2.java

, -d, classes p2
class-, "" p1,
-classpath.
3. classes.
4. java p2.Inp2.
"" , ,
MS-DOS.

3. ,

115

, , IDE, Eclipse NetBeans,


.
. 3.3 Command Prompt .

. 3.3.


3.2 import.
?
, : , , java.lang.
. ,
3.2 Base p1.Base.

I. Java

116

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

import , *. .

import p1.*;

, , public.
.
, ? , .
java.lang , .
import,
.
Java SE 5 import, import static.
,
import static java.lang.Math.*;

Math .
double r = Math.cos(Math.PI * alpha);

,
double r = cos(PI * alpha);

, import
"" .
C/C++
import include
.

Java-
Java.
package.
import.
.

3. ,

117

.
public-.
, .

, ,
.
"Code Conventions" , ,
.
Java . , class- .

, ,
, . 3.4, .
"", Object. D B , . 3.4, . (multiple inheritance).
. , B C
, . 3.4, . "" .

. 3.4.

, f(), D. , f() ,
, . . A.f()? , B ? , : .f() C.f()? , ,
.
-, f(). KISS.
,
. ,
.
Java
.
extends .
super .
, - ?
, Automobile,

I. Java

118

Truck Car.
Pickup. , .
Java . , ,
, .
(interface), ,
, .
, ,
, class-.
interface, public, , , .
public , .
interface , extends
- . ,
, , , ,
.
, .
. , , abstract . , static final . .
,
public.
:
interface
interface
interface
interface

Automobile{ . . . }
Car extends Automobile{ . . . }
Truck extends Automobile{ . . . }
Pickup extends Car, Truck{ . . . }

, , . , ,
, .
, ,
?
, (implementation). , . ,
, implements , , .
:
interface Automobile{ . . . }
interface Car extends Automobile{ . . . }
class Truck implements Automobile{ . . . }
class Pickup extends Truck implements Car{ . . . }

3. ,

119

:
interface Automobile{ . . . }
interface Car extends Automobile{ . . . }
interface Truck extends Automobile{ . . . }
class Pickup implements Car, Truck{ . . . }

,
, . , abstract.
Pickup f(), Car, Truck ? .
Pickup. -.
, Java - , .
, , , , ,
.
, . , - . .
3.3 , ""
2.2.
3.3.
interface Voice{
void voice();
}
class Dog implements Voice{
@Override
public void voice(){
System.out.println("Gav-gav!");
}
}
class Cat implements Voice{
@Override
public void voice(){
System.out.println("Miaou!");
}
}
class Cow implements Voice{
@Override
public void voice(){

I. Java

120
System.out.println("Mu-u-u!");
}
}
public class Chorus{
public static void main(String[] args){
Voice[] singer = new Voice[3];
singer[0] = new Dog();
singer[1] = new Cat();
singer[2] = new Cow();
for (Voice v: singer)
v.voice();
}
}

Voice Pet, 2.2.


: ? .
, - ,
Object.
, ,
.
, . , .
, , :
, public,
, .
,
. , Voice.
, , 3.4.
3.4.
interface Lights{
int RED
= 0;
int YELLOW = 1;
int GREEN = 2;
int ERROR = -1;
}
class Timer implements Lights{
private int delay;
private static int light = RED;

3. ,

121

Timer(int sec){delay = 1000 * sec;}


public int shift(){
int count = (light++) % 3;
try{
switch (count){
case RED:
Thread.sleep(delay); break;
case YELLOW: Thread.sleep(delay/3); break;
case GREEN: Thread.sleep(delay/2); break;
}
}catch(Exception e){return ERROR;}
return count;
}
}
class TrafficRegulator{
private static Timer t = new Timer(1);
public static void main(String[] args){
for(int k = 0; k < 10; k++)
switch(t.shift()){
case Lights.RED:
System.out.println("Stop!"); break;
case Lights.YELLOW: System.out.println("Wait!"); break;
case Lights.GREEN: System.out.println("Walk!"); break;
case Lights.ERROR: System.err.println("Time Error"); break;
default:
System.err.println("Unknown light."); return;
}
}
}

, Lights, , .
Timer . shift() . sleep()
Thread , . try{}catch(){},
21.
TrafficRegulator Lights
Lights.RED . . , RED, YELLOW GREEN
.

3.4, , , ,
. Java SE 5
(enumerations). ,
, . Lights, 3.4,
, :
enum Lights{ RED, YELLOW, GREEN, ERROR }

122

I. Java

, . ,
. , , ? Lights.
Java ,
enum ,
java.lang.Enum. extends, , . ,
Java API.
Enum , 3.5.
3.5.
enum Lights { RED, YELLOW, GREEN, ERROR }
public class EnumMethods{
public static void main(String[] args){
for (Lights light: Lights.values()){
System.out.println(": " + light.getDeclaringClass());
System.out.println(" : " + light.ordinal());
}
}
}

, -, ,
Lights. light Lights. values(), ,
. , , light.
-, , .
getDeclaringClass() Enum. 3.5 Lights.
-, , ,
0, 1, 2 . . ordinal() Enum.
. ,
, . , , Enum, values(), .
Lights.
, ERROR
1 shift() .
:
TrafficRegulator

enum Lights{
RED(0), YELLOW(1), GREEN(2), ERROR(-1);
private int value;private int currentValue = 0;
Lights(int value){
this.value = value;}
public int getValue(){ return value; }

3. ,

123

public Lights nextLight(){


currentValue = (currentValue + 1) % 3;
return Lights.values()[currentValue];
}
}

, ,
value. Lights
. 3.6.
3.6.
enum Lights{
RED(0), YELLOW(1), GREEN(2), ERROR(-1);
private int value;
private int currentValue = 0;
Lights(int value){
this.value = value;
}
public int getValue(){ return value; }
public Lights nextLight(){
currentValue = (currentValue + 1) % 3;
return Lights.values()[currentValue];
}
}
class Timer {
private int delay;
private static Lights light = Lights.RED;
Timer(int sec){
delay = 1000 * sec;
}
public Lights shift(){
Lights count = light.nextLight();
try{
switch (count){
case RED:
Thread.sleep(delay);
break;
case YELLOW: Thread.sleep(delay/3); break;
case GREEN: Thread.sleep(delay/2); break;
}
}catch(Exception e){
return Lights.ERROR;
}
return count;
}
}

I. Java

124
public class TrafficRegulator{
public static void main(String[] args){
Timer t = new Timer(1);

for (int k = 0; k < 10; k++)


switch (t.shift()){
case RED:
System.out.println("Stop!"); break;
case YELLOW: System.out.println("Wait!"); break;
case GREEN: System.out.println("Walk!"); break;
case ERROR: System.err.println("Time Error"); break;
default:
System.err.println("Unknown light."); return;
}
}
}

, ,
. - .
. , ordinal().
. 3.7
,
eval()
Operation.
3.7.
public enum Operation{
PLUS { double eval(double
MINUS { double eval(double
TIMES { double eval(double
DIVIDE{ double eval(double

x,
x,
x,
x,

double
double
double
double

y){
y){
y){
y){

return
return
return
return

x
x
x
x

*
/

y;
y;
y;
y;

}},
}},
}},
}};

abstract double eval(double x, double y);


public static void main(String[] args){
double x = -23.567, y = 0.235;
for (Operation op: Operation.values())
System.out.println(op.eval(x, y));
}
}


, 1, , "at-sign", "". , @Override, 2.2,
:
public @interface Override{ }

3. ,

125

(marker
annotation). ,
-. ,
, default
. ,
public @interface MethodDescription{
int id();
String description() default "[Method]";
String date();
}

id, name date. name


, Method.
-
(annotation type).

, . .
" " .
:
@MethodDescription(
id = 123456,
description = "Calculation method",
date = "04.01.2008"
)
public int someMethod(){
. . .
}

, value(), :
public @interface Copyright{
String value();
}


, " ":
@ Copyright("2008 My Company")
public class MyClass{
. . .
}

, - Java, , . , .
Java,
. ,
(design patterns).

126

I. Java

Design patterns
. : " " " ", , .
? .
, .
, , , ,
, . : ,
, . . . : , , . : , , .
MVC.

MVC
.
, (Controller), -

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

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

,
, .
, .
? .
, ,
. - , ? , .
? .
80- Smalltalk
MVC (Model-View-Controller). , , , ,
.

3. ,

127

. ,
, , , , . , MVC.
, , .
- MVC
. setXxx(), .
. getXxx() isXxx() .
MVC . , , setXxx() ,
. , ,
, .
"-" (subscribe-publish). ,
fireXxx(), ,
getXxx() isXxx() .
.
MVC Swing,
11.
90- XX , MVC. ,
.

Singleton
, , . , ,
. Singleton,
3.8.
3.8. Singleton
final class Singleton{
private static Singleton s = new Singleton(0);
private int k;
private Singleton(int i){ // .
k = i;
}
public static Singleton getReference(){ // .
return s;
}

128

I. Java

public int getValue(){return k;}


public void setValue(int i){k = i;}
}
public class SingletonTest{
public static void main(String[] args){
Singleton ref = Singleton.getReference();
System.out.println(ref.getValue());
ref.setValue(ref.getValue() + 5);
System.out.println(ref.getValue());
}
}

Singleton .
. s
Singleton , .
getReference(), s setValue() getValue().
Singleton ,
.
[7].
" " (Gang of Four), , , "GoF".
"design patterns".
. "", " ", " ".
GoF 23 , :
: Factory, Abstract Factory, Singleton, Builder, Prototype;
: Adapter, Bridge, Composite, Decorator, Facade,

Flyweight, Proxy;
: Chain of Responsibility, Command, Interpreter, Iterator,

Mediator, Memento, Observer, State, Strategy, Template, Visitor.


++. [8]
Java. . [9]. [10]
design patterns.
, design patterns .
, - ,
. : "
...", , design
patterns.
, .

3. ,

129

.
Java,
. , , ,
IV. II III , Core API. .
Java, , , .
-.


1. Java?
2. , , ?
3. "" ,
?
4. , ?
5. ?
6. main() (public)?
7. , ?
8. Java , ?
?
9. Java ? ?

II


Java API
4.

- generics

5.

6.

7.

- generics
Java - . , ,
, Java .
. Java .
, ,
.
Java -
(wrapper) . , ,
, , , ,
.
. 4.1 Java.
java.lang .
Number, , , , : byteValue(), doubleValue(), floatValue(), intValue(),
longValue(), shortValue().
- Byte, Short, Integer, Long, Float Double. -,
Integer, , .
equals(), Object,
, Character Boolean

. 4.1.

134

II. Java API

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

0, ;
(1), ,

- , Boolean, false, true;


(+1), -

, true, false.

int compare(xxx a, xxx b);

, a b,
boolean, byte, short, char, int, long, float, double, ,
compareTo(), .

Xxx valueOf(xxx a);

xxx boolean, byte, short, char, int, long, float,


double, . , .
-?


-
String, ,
: Byte.parseByte(), Double.parseDouble(), Float.parseFloat(), Integer.parseInt(),
Long.parseLong(), Short.parseShort(). String, , .
, , . . ,
,
.
MAX_VALUE MIN_VALUE, .
Double Float POSITIVE_INFINITY, NEGATIVE_INFINITY, NaN,
1, isNaN(), isInfinite().
, floatToIntBits() doubleToLongBits(), , , int long .
. -

4. - generics

135

,

intBitsToFloat() longBitsToDouble().
toBinaryString(), toHexString() toOctalString() Integer
Long int long,
, , , .
4.1 , . 4.2 .

. 4.2.

4.1.
class NumberTest{
public static void main(String[] args){
int i = 0;
short sh = 0;
double d = 0;
Integer k1 = Integer.valueOf(55);
Integer k2 = Integer.valueOf(100);
Double d1 = Double.valueOf(3.14);
try{
i = Integer.parseInt(args[0]);
sh = Short.parseShort(args[0]);
d = Double.parseDouble(args[1]);
d1 = new Double(args[1]);
k1 = new Integer(args[0]);
}catch(Exception e){}
double x = 1.0 / 0.0;
System.out.println("i = " + i);
System.out.println("sh = " + sh);

II. Java API

136

System.out.println("d = " + d);


System.out.println("k1.intValue() = " + k1.intValue());
System.out.println("d1.intValue() = " + d1.intValue());
System.out.println("k1 > k2? " + k1.compareTo(k2));
System.out.println("x = " + x);
System.out.println("x isNaN? " + Double.isNaN(x));
System.out.println("x isInfinite? " + Double.isInfinite(x));
System.out.println("x == Infinity? " + (x == Double.POSITIVE_INFINITY));
System.out.println("d = " + Double.doubleToLongBits(d));
System.out.println("i = " + Integer.toBinaryString(i));
System.out.println("i = " + Integer.toHexString(i));
System.out.println("i = " + Integer.toOctalString(i));
}
}

parseInt() ,
4.1 try{}catch(){}.
21.
Java SE 5 JDK java.util.concurrent.atomic, ,
, AtomicInteger AtomicLong, .
. addAndGet(), getAndAdd(), incrementAndGet(),
getAndnIncrement(), decrementAndGet(), getAndDecrement, getAndSet(), set()
.


4.1 ,
:
Integer k1 = Integer.valueOf(55);

- , . Java, .
Integer k1 = 55;

k1 .
Java : , ,
. , . , (auto boxing) .
. k1
, ,
int n = k1;

k1 Integer 55. ,
intValue() Integer,
.

4. - generics

137

.
.
class AutoBox{
static int f(Integer value){
return value; // .
}
public static void main(String[] args){
Integer n = f(55);
}
}

main() 55
f() . f() n
Integer.
,
k1++ (k1 + k2 / k1), ! ,
!

(generics)
Java
(generics), , . ,
(generic)
class MyGenericClass<T>{
private T data;
public MyGenericClass(){}
public MyGenericClass(T data){
this.data = data;
}
public T getData(){
return data;
}
public void setData(T data){
this.data = data;
}
}

data , T. , . T
Type.
- , . :
class MyGenericClassDemo{
public static void main(String[] args){
MyGenericClass<Integer> iMyGen = new MyGenericClass<Integer>(55);

II. Java API

138

Integer n = iMyGen.getData();
MyGenericClass<Double> dMyGen = new MyGenericClass<Double>(-37.3456);
Double x = dMyGen.getData();
}
}

,
, ( " ", "diamond operator"). , Java 7, , :
class MyGenericClassDemo{
public static void main(String[] args){
MyGenericClass<Integer> iMyGen = new MyGenericClass<>(55);
Integer n = iMyGen.getData();
MyGenericClass<Double> dMyGen = new MyGenericClass<>(-37.3456);
Double x = dMyGen.getData();
}
}

. , , , , , .
double. 4.2
- .
4.2.
class Average<T extends Number>{
T[] data;
public Average(T[] data) { this.data = data; }
public double average(){
double result = 0.0;
for (T t: data) result += t.doubleValue();
return result / data.length;
}
public static void main(String[] args){
Integer[] iArray = {1, 2, 3, 4};
Double[] dArray = {3.4, 5.6, 2.3, 1.24};
Average<Integer> iAver = new Average<>(iArray);
System.out.println("int average = " + iAver.average());
Average<Double> dAver = new Average<>(dArray);
System.out.println("double average = " + dAver.average());
}
}

4. - generics

139

, ,
T Number. , T
. , average() doubleValue()
Number, , T Number .
, .
<T extends SomeClass> ,
T. , <T super SomeClass>,
T SomeClass .
. :
class MyGenericClass2<S, T>{
private S id;
private T data;
public MyGenericClass2(){}
public MyGenericClass2(S id, T data){
this.id = id;
this.data = data;
}
public S getId(){
return id;
}
public void setId(S data){
this.id = id;
}
public T getData(){
return data;
}
public void setData(T data){
this.data = data;
}
}

, S, T
. ,
, . ,
. :
public MyGenericClass2<S, T> makeClass2(S id,
MyGenericClass<T> data){
return new MyGenericClass2(id, data.getData());
}

, 4.3.

II. Java API

140

4.3.
public class MyGenericClass2Demo<S, T>{
public MyGenericClass2<S, T>
makeClass2(S id, MyGenericClass<T> data){
return new MyGenericClass2(id, data.getData());
}
public static void main(String[] args){
MyGenericClass<Double> dMyGen = new MyGenericClass<>(34.456);
MyGenericClass2Demo<Long, Double> d =
new MyGenericClass2Demo<>();
MyGenericClass2<Long, Double> ldMyGen2 =
d.makeClass2(123456L, dMyGen);
}
}

(wildcard type)
,
, , :
Number n = new Long(123456L);
Number d = new Double(27.346);

, :
Number[] n = new Long[100];

? ,
4.3 :
MyGenericClass2<Number, Number> n =
d.makeClass2(123456L, dMyGen);

// !

. , - B A,
, G<B> G<A>.

(wildcard type), .
" " " ". ,
:
MyGenericClass2<? extends Number, ? extends Number> n = // .
d.makeClass2(123456L, dMyGen);

MyGenericClass2<Long, ? extends Number> n =


d.makeClass2(123456L, dMyGen);

// .

4. - generics

141


MyGenericClass2<?, ?> n =
d.makeClass2(123456L, dMyGen);


MyGenericClass2 n =
d.makeClass2(123456L, dMyGen);

, .
<? extends Type>, " Type,
Type", <? super Type>, "
Type, Type".
, , :
public MyGenericClass2<S, T> makeClass2(S id,
MyGenericClass<? extends Number> data){
return new MyGenericClass2(id, data.getData());
}

, , . :
Average<? extends Number> a =
// !
new Average<? extends Number>(iArray);
Average<? extends Number>[] a =
// !
new Average<? extends Number>[10];

( ) :
Average<? extends Number>[] a =
new Average<?>[10];

// .


, .
(type parameters) . , 4.4.
4.4.
public class MyGenericClass2Demo{
public <S, T> MyGenericClass2<S, T>
makeClass2(S id, MyGenericClass<T> data){
return new MyGenericClass2(id, data.getData());
}

142

II. Java API

public static void main(String[] args){


MyGenericClass<Double> dMyGen = new MyGenericClass(34.456);
MyGenericClass2Demo d =
new MyGenericClass2Demo();
MyGenericClass2<Long, Double> ldMyGen2 =
d.makeClass2(123456L, dMyGen);
}
}

makeClass2() , , MyGenericClass2Demo,
<S, T>.
public <S extends Number, T extends Number>
MyGenericClass2<S, T>
makeClass2(S id, MyGenericClass<T> data){
return new MyGenericClass2(id, data.getData());
}

4.4, ,

.
,
, .
, ,
.
(Angelika Langer), Java Generics FAQ, http://
www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html.

Boolean
, , .
Boolean(String s) , true, s
"true" , false
.
valueOf(boolean b) Boolean boolean.
,
Boolean b = new Boolean("true");

Boolean b = Boolean.valueOf(true);


Boolean b = true;

4. - generics

143

booleanValue() , .
parseBoolean(String s) true, s "true" , false .

Character
.

digit(char ch, in radix);

ch radix
int.

forDigit(int digit, int radix);

digit (
char) radix.
Character.MIN_RADIX
Character.MAX_RADIX.
toString() , , .
toLowerCase(), toUpperCase(), toTitleCase() , , .
Unicode,
.

getName(int code);

Unicode- code.

, :
isDefined() , Unicode;
isDigit() , Unicode;
isIdentifierIgnorable() , -

;
isISOControl() , ;
isBmpCodePoint() , \u0000\uFFFF;
isSupplementaryCodePoint() , \uFFFF;
isJavaIdentifierPart() , -

144

II. Java API

isJavaIdentifierStart() , ;
isLetter() , Java;
isLetterOrDigit() , Unicode;
isLowerCase() , ;
isSpaceChar() , Unicode;
isTitleCase() , ;
isUnicodeIdentifierPart() ,

Unicode;
isUnicodeIdentifierStart() , Unicode;
isUpperCase() , ;
isWhitespace() , .

, , ,
Java API.
4.5 , . 4.3
.
4.5. Character CharacterTest
class CharacterTest{
public static void main(String[] args){
char ch = '9';
Character c1 = Character.valueOf(ch);
System.out.println("ch = " + ch);
System.out.println("c1.charValue() = " +
c1.charValue());
System.out.println("number of 'A' = " +
Character.digit('A', 16));
System.out.println("digit for 12 = " +
Character.forDigit(12, 16));
System.out.println("c1 = " + c1.toString());
System.out.println("ch isDefined? " +
Character.isDefined(ch));
System.out.println("ch isDigit? " +
Character.isDigit(ch));
System.out.println("ch isIdentifierIgnorable? " +
Character.isIdentifierIgnorable(ch));
System.out.println("ch isISOControl? " +
Character.isISOControl(ch));
System.out.println("ch isJavaIdentifierPart? " +
Character.isJavaIdentifierPart(ch));
System.out.println("ch isJavaIdentifierStart? " +
Character.isJavaIdentifierStart(ch));

4. - generics

145

System.out.println("ch isLetter? " +


Character.isLetter(ch));
System.out.println("ch isLetterOrDigit? " +
Character.isLetterOrDigit(ch));
System.out.println("ch isLowerCase? " +
Character.isLowerCase(ch));
System.out.println("ch isSpaceChar? " +
Character.isSpaceChar(ch));
System.out.println("ch isTitleCase? " +
Character.isTitleCase(ch));
System.out.println("ch isUnicodeIdentifierPart? " +
Character.isUnicodeIdentifierPart(ch));
System.out.println("ch isUnicodeIdentifierStart? " +
Character.isUnicodeIdentifierStart(ch));
System.out.println("ch isUpperCase? " +
Character.isUpperCase(ch));
System.out.println("ch isWhitespace? " +
Character.isWhitespace(ch));
}
}

. 4.3. Character CharacterTest

Character Subset UnicodeBlock, UnicodeBlock


, InputSubset, Subset,
. 4.1. Unicode.
, Java
Character, .

146

II. Java API

-
.

BigInteger
.
Java , , .
, Java API BigInteger, java.math.
Number, ,
doubleValue(), floatValue(), intValue(), longValue(). byteValue() shortValue()
, Number.
BigInteger , . , . .
.
BigInteger ( ), . :
BigInteger(String value) ,

, ;
BigInteger(String value, int radix) value, radix;
BigInteger(byte[] value) ,
value, .
ZERO, ONE TEN , BigInteger.
toByteArray() .
BigInteger , BigInteger:
abs() , ,
this;
add(x) this + x;

and(x) this & x;


andNot(x) this & (~x);
divide(x) this / x;
divideAndRemainder(x) BigInteger, -

this x;
gcd(x) this -

x;

4. - generics

147

max(x) this x;
min(x) this x;
mod(x) this x;
modInverse(x) , this, x;
modPow(n, m) this, n, m;
multiply(x) this * x;
negate() , ;
not() ~this;
or(x) this | x;
pow(n) , , n;
remainder(x) this % x;
shiftLeft(n) this << n;
shiftRight(n) this >> n;
signum() sign(x);
subtract(x) this x;
xor(x) " " this ^ x.

4.6 , . 4.4 .
4.6. BigInteger BigIntegerTest
import java.math.BigInteger;
class BigIntegerTest{
public static void main(String[] args){
BigInteger a = new BigInteger("99999999999999999");
BigInteger b = new BigInteger("88888888888888888888");
System.out.println("bits in a = " + a.bitLength());
System.out.println("bits in b = " + b.bitLength());
System.out.println("a + b = " + a.add(b));
System.out.println("a & b = " + a.and(b));
System.out.println("a & ~b = " + a.andNot(b));
System.out.println("a / b = " + a.divide(b));
BigInteger[] r = a.divideAndRemainder(b);
System.out.println("a / b: q = " + r[0] + ", r = " + r[1]);
System.out.println("gcd(a, b) = " + a.gcd(b));
System.out.println("max(a, b) = " + a.max(b));
System.out.println("min(a, b) = " + a.min(b));
System.out.println("a mod b = " + a.mod(b));
System.out.println("1/a mod b = " + a.modInverse(b));
System.out.println("a^n mod b = " + a.modPow(a, b));

II. Java API

148

System.out.println("a * b = " + a.multiply(b));


System.out.println("-a = " + a.negate());
System.out.println("~a = " + a.not());
System.out.println("a | b = " + a.or(b));
System.out.println("a ^ 3 = " + a.pow(3));
System.out.println("a % b = " + a.remainder(b));
System.out.println("a << 3 = " + a.shiftLeft(3));
System.out.println("a >> 3 = " + a.shiftRight(3));
System.out.println("sign(a) = " + a.signum());
System.out.println("a b = " + a.subtract(b));
System.out.println("a ^ b = " + a.xor(b));
}
}

. 4.4. BigInteger BigIntegerTest

, 4.6
java.math.

BigDecimal
BigDecimal java.math.
:
BigInteger int. ,
76,34862 7 634 862 BigInteger 5
int. ,
, Integer.MAX_VALUE.

4. - generics

149

BigDecimal
, :
ROUND_CEILING ;
ROUND_DOWN , ;
ROUND_FLOOR ;
ROUND_HALF_DOWN ,

;
ROUND_HALF_EVEN ,

;
ROUND_HALF_UP ,

;
ROUND_UNNECESSARY , ,

;
ROUND_UP , .

ZERO, ONE TEN , BigDecimal.


BigDecimal .
Java 2.
BigDecimal(BigInteger bi) bi,

;
BigDecimal(BigInteger mantissa, int scale) mantissa -

scale ; scale , ;
BigDecimal(double d) -

d; d NaN, ;
BigDecimal(String val) val, -

Java.

, .
, , ,
, BigDecimal(0.1), , ,
. . 4.5. , BigDecimal("0.1"), 1.
MathContext .
doubleValue(), floatValue(), intValue(), longValue().
ZERO, ONE TEN , BigDecimal.
.
BigDecimal. x

150

II. Java API

BigDecimal, n int, r , :
abs() this;
add(x) this + x;
divide(x, r) this / x r;
divide(x, n, r) this / x

r;
max(x) this x;
min(x) this x;
movePointLeft(n) n ;
movePointRight(n) n ;
multiply(x) this * x;
negate() ;
scale() ;
setScale(n) n;
setScale(n, r) n -

r;
signum() , ;
subtract(x) this x;
toBigInteger() , ;
unscaledValue() ;
upl() .

4.7 , . 4.5 .
Java SE 5 BigDecimal .
4.7. BigDecimal BigDecimalTest
import java.math.*;
class BigDecimalTest{
public static void main(String[] args){
BigDecimal x = new BigDecimal("-12345.67890123456789");
BigDecimal y = new BigDecimal("345.7896e-4");
BigDecimal z = new BigDecimal(new BigInteger("123456789"), 8);
System.out.println("|x| = " + x.abs());
System.out.println("x + y = " + x.add(y));
System.out.println("x / y = " + x.divide(y, BigDecimal.ROUND_DOWN));
System.out.println("x / y = " + x.divide(y, 6, BigDecimal.ROUND_HALF_EVEN));
System.out.println("max(x, y) = " + x.max(y));
System.out.println("min(x, y) = " + x.min(y));

4. - generics

151

System.out.println("x << 3 = " + x.movePointLeft(3));


System.out.println("x >> 3 = " + x.movePointRight(3));
System.out.println("x * y = " + x.multiply(y));
System.out.println("-x = " + x.negate());
System.out.println("scale of x = " + x.scale());
System.out.println("increase scale of x to 20 = " + x.setScale(20));
System.out.println("decrease scale of x to 10 = " +
x.setScale(10, BigDecimal.ROUND_HALF_UP));
System.out.println("sign(x) = " + x.signum());
System.out.println("x y = " + x.subtract(y));
System.out.println("round x = " + x.toBigInteger());
System.out.println("mantissa of x = " + x.unscaledValue());
System.out.println("mantissa of 0.1 =\n= " +
new BigDecimal(0.1).unscaledValue());
}
}

. 4.5. BigDecimal BigDecimalTest

. ,
. .
4.8,
. 4.6.
4.8.
import java.math.*;
class Calc{
public static void main(String[] args){
if (args.length < 3){

II. Java API

152

System.err.println("Usage: java Calc operand operator operand");


return;
}
BigDecimal a = new BigDecimal(args[0]);
BigDecimal b = new BigDecimal(args[2]);
switch (args[1].charAt(0)){
case '+': System.out.println(a.add(b));
break;
case '-': System.out.println(a.subtract(b)); break;
case '*': System.out.println(a.multiply(b)); break;
case '/': System.out.println(a.divide(b,
BigDecimal.ROUND_HALF_EVEN)); break;
default : System.out.println("Invalid operator");
}
}
}

. 4.6.

. 4.6 ? UNIX , .
, Java.
(shell) ,

. , Java ,
, .
. Java ,
.

Class
Object, Java, , , .
Object.

4. - generics

153

Class , . , , , , ,
, , , .
Class , Java getClass()
Object, :
String s = " ";
Class c = s.getClass();

,
Class, . (reflection). ,
.
forName(String class) Class Class
, , :
Class c1 = Class.forName("java.lang.String");

Class class:
Class c2 = java.lang.String.class;

isAnnotation(), isArray(), isInterface(), isEnum(), isPrimitive() , , , , .


, , , getDeclaredClasses(), getDeclaredConstructors(),
getDeclaredMethods(), getDeclaredFields() : Class, Constructor,
Method, Field .
java.lang.reflect ,
, Class .
getClasses(), getConstructors(), getInterfaces(), getMethods(), getFields() , , .
getSuperclass() , getPackage()
, getModifiers() .
Modifier java.lang.reflect.
4.9 , . 4.7 .
4.9. Class ClassTest
import java.lang.reflect.*;
class ClassTest{
public static void main(String[] args){
Class c = null, c1 = null, c2 = null;

II. Java API

154
Field[] fld = null;
String s = "Some string";
c = s.getClass();
try{
c1 = Class.forName("java.lang.String");
c2 = java.lang.String.class;
if (!c1.isPrimitive())
fld = c1.getDeclaredFields();
}catch(Exception e){}
System.out.println("Class
c: "
System.out.println("Class
c1: "
System.out.println("Class
c2: "
System.out.println("Superclass c: "
System.out.println("Package
c: "
System.out.println("Modifiers c: "
for(int i = 0; i < fld.length; i++)
System.out.println(fld[i]);

+
+
+
+
+
+

//
//
// String

c);
c1);
c2);
c.getSuperclass());
c.getPackage());
c.getModifiers());

}
}

, , , . try{}catch(){}.
21.

. 4.7. Class ClassTest

Java SE 5 Class : Class<String> String, Class<Long> Long . . , Class ,


.

4. - generics

155


1. Java ?
2. - ?
3. BigInteger?
4. BigDecimal?
5.
-?
6. Java ?
7.
?
8. ?
9. , ?


. , Java .
String StringBuilder.
StringBuilder, ,
StringBuffer, 23.
StringBuilder Java, Java SE 5,
.
CharSequence,
. :
length() ;
charAt(int pos) , pos .

, ;
subSequence(int start, int end) ,
start

end .

,
, , , .
, char
byte,
.
? String - , , .
.
String .
, StringBuilder StringBuffer, , ,
. , String, Java StringBuilder StringBuffer, ,
String. , :
String s = "" + " " + "";

5.

157

:
String s = new StringBuffer().append("").append(" ")
.append("").toString();

StringBuffer StringBuilder,
append() "", " ", "", StringBuffer StringBuilder String toString().
, Unicode,
. char.

String
, .
.


String -:
String s1 = " .";

, , :
String s2 = " String, " +
" ";


String s = "",
, String s = null,
.

new. String :
String() ;
String(String str) :
, ;
String(StringBuffer str) StringBuffer;
String(StringBuilder str) StringBuilder;
String(byte[] byteArray) byteArray;
String(char[] charArray) charArray Unicode;
String(byte[] byteArray, int offset, int count) -

byteArray, offset count ;


String(char[] charArray, int offset, int count) , -

Unicode;

158

II. Java API

String(int[] intArray, int offset, int count) ,

Unicode, ,
Unicode, ;

String(byte[] byteArray, String encoding) , ,

Unicode- encoding;
String(byte[] byteArray, int offset, int count, String encoding) ,

String(byte[] byteArray, Charset charset) , ,

Unicode- , charset;
String(byte[] byteArray, int offset, int count, Charset charset) ,
.
offset, count encoding
.
, byteArray,
Unicode- ASCII- . ASCII-, .
Unicode
. '\u0000'
'\u00FF' Unicode, Latin1. , , .
, " " (locale) ( MS Windows Regional Options (
) Control Panel ( )), ,
, Unicode, .
MS Windows CP1251.
ASCII- CP1251,
Java . '\u0400'
'\u04FF' Unicode.
:
MS-DOS CP866;
UNIX KOI8-R;
Apple Macintosh MacCyrillic;
ISO8859-5.
, 11100011 (0xE3 ) CP1251
, CP866 , KOI8R , ISO8859-5 , MacCyrillic .
ASCII- ,
CP1251, Unicode- Java .
,
encoding charset ,
.

5.

159

5.1 .
, "" :
byteCp1251 "" CP1251;
byteCp866 "" CP866;
byteKOI8R "" KOI8-R.

.
, c[] s1, , CP866, s2. , s3 .
5.1.
class StringTest{
public static void main(String[] args){
String winLikeWin = null, winLikeDOS = null, winLikeUNIX = null;
String dosLikeWin = null, dosLikeDOS = null, dosLikeUNIX = null;
String unixLikeWin = null, unixLikeDOS = null, unixLikeUNIX = null;
String msg = null;
byte[] byteCp1251 = {
(byte)0xD0, (byte)0xEE, (byte)0xF1,
(byte)0xF1, (byte)0xE8, (byte)0xFF
};
byte[] byteCp866 = {
(byte)0x90, (byte)0xAE, (byte)0xE1,
(byte)0xE1, (byte)0xA8, (byte)0xEF
};
byte[] byteKOI8R = {
(byte)0xF2, (byte)0xCF, (byte)0xD3,
(byte)0xD3, (byte)0xC9, (byte)0xD1
};
char[] c = {'', '', '', '', '', ''};
String s1 = new String(c);
String s2 = new String(byteCp866);
// MS Windows
String s3 = "";
System.out.println();
try{
// Cp866 MS Windows
msg = new String("\"\" ".getBytes("Cp866"), "Cp1251");
winLikeWin = new String(byteCp1251, "Cp1251");
//
winLikeDOS = new String(byteCp1251, "Cp866");
winLikeUNIX = new String(byteCp1251, "KOI8-R");
dosLikeWin = new String(byteCp866, "Cp1251");
//
dosLikeDOS = new String(byteCp866, "Cp866");
//
dosLikeUNIX = new String(byteCp866, "KOI8-R");
unixLikeWin = new String(byteKOI8R, "Cp1251");
unixLikeDOS = new String(byteKOI8R, "Cp866");
unixLikeUNIX = new String(byteKOI8R, "KOI8-R");
//

160

II. Java API


System.out.print(msg + "Cp1251: ");
System.out.write(byteCp1251);
System.out.println();
System.out.print(msg + "Cp866 : ");
System.out.write(byteCp866);
System.out.println();
System.out.print(msg + "KOI8-R: ");
System.out.write(byteKOI8R);
}catch(Exception e){
e.printStackTrace();
}
System.out.println();
System.out.println();
System.out.println(msg + "char array
:
System.out.println(msg + "default encoding:
System.out.println(msg + "string constant :
System.out.println();
System.out.println(msg + "Cp1251 -> Cp1251:
System.out.println(msg + "Cp1251 -> Cp866 :
System.out.println(msg + "Cp1251 -> KOI8-R:
System.out.println(msg + "Cp866 -> Cp1251:
System.out.println(msg + "Cp866 -> Cp866 :
System.out.println(msg + "Cp866 -> KOI8-R:
System.out.println(msg + "KOI8-R -> Cp1251:
System.out.println(msg + "KOI8-R -> Cp866 :
System.out.println(msg + "KOI8-R -> KOI8-R:

" + s1);
" + s2);
" + s3);
"
"
"
"
"
"
"
"
"

+
+
+
+
+
+
+
+
+

winLikeWin);
winLikeDOS);
winLikeUNIX);
dosLikeWin);
dosLikeDOS);
dosLikeUNIX);
unixLikeWin);
unixLikeDOS);
unixLikeUNIX);

}
}

MS Windows 2000, . 5.1.

. 5.1. MS Windows 2000

5.

161

Unicode
byteCp1251, byteCp866 byteKOI8R. write()
FilterOutputStream java.io.
Java, c[], byteCp866 -.
.
, CP866, CP1251. ?
.
1, Command Prompt
MS Windows CP866.
, "\"\" " , CP866, msg.
. 5.1
codes.txt. MS Windows CP1251.
. 5.2 codes.txt Notepad ().

. 5.2.

, -. Unicode
, ,
.
9 24, ,

, . Java
Unicode.
, , Java Unicode .
:
copyValueOf(char[] charArray);
copyValueOf(char[] charArray, int offset, int length);

162

II. Java API


. ,
char[] c = {'C', '', '', '', '', '', '', '', '', ''};
String s1 = String.copyValueOf(c);
String s2 = String.copyValueOf(c, 3, 7);

s1 "", s2 "".

1. .


(concatenation), (+). ,
, .
, . :
String attention = ": ";
String s = attention + " ";

+= :
attention += s;

+ , . , ,
"2" + 2 + 2, "222". 2 + 2 + "2",
"42", .
"2" + (2 + 2), "24".
concat(), :
String s = attention.concat(" ");


, . . ,
length():
String s = "Write once, run anywhere.";
int len = s.length();


int len = "Write once, run anywhere.".length();

- String.
, , length.
, . 4.7, . ,
, , , String.

5.

163

isEmpty(), Java SE 6, true,


, .


ind ( )
charAt(int ind). ind , , . ,
char ch = s.charAt(3);

ch 't'.
toCharArray().
dst, ind , begin end ,
getChars(int begin, int end, char[] dst, int ind) void.
end begin , , ind ind + (end begin) 1.
:
dst == null;
begin ;
begin end;
end ;
ind ;
ind + (end begin) dst.length.

,
char[] ch = {'', '', '', '', '', ' ', '', '', '', '', ''};
" ".getChars(2, 8, ch, 2);

:
ch = {'', '', '', '', '', '', ' ', '', '', '', ''};

, ASCII, getBytes().
Unicode ASCII .
, - ,
getBytes(String encoding) getBytes(Charset encoding).
5.1 msg. "\" \"" CP866-
Command Prompt MS Windows.


substring(int begin, int end) begin
end .
end begin. , long.

164

II. Java API

substring(int begin) begin


.
, end begin ,
.

end,

,
String s = "Write once, run anywhere.";
String sub1 = s.substring(6, 10);
String sub2 = s.substring(16);

sub1 "once", sub2 "anywhere.".


split(String regExp) , , regExp,
. .
,
String s = "Write:once,:run:anywhere.";
String[] sub = s.split(":");

sub[0] "Write", sub[1] "once,",


sub[2] "run", sub[3] "anywhere.".
split(String regExp, int n) n . n
, .
String[] sub = s.split(":", 2);

sub sub[0],
"Write", sub[1], "once,:run:anywhere.".
,
regExp . (regular
expression) , , . , - , :
String[] word = s.split(\\s+);


== . , . ,
String s1 = "- ";
String s2 = " ";

s1 == s2 false.

5.

165

true , ,
s1 = s2.
, s3 :
String s3 = "- ";

s1 == s3 true, ,
"- "
s1, s3. ,
String .
, , , . .
equals(Object obj), Object,
true, obj null, String, , ,
. false.
equalsIgnoreCase(Object obj) , ,
, .
, s2.equals(" ") false, s2.equalsIgnoreCase("
") true.
compareTo(String str) int, :
1. this str ,
, , k
.
2. this.charAt(k) str.charAt(k), . .
Unicode .
3. this.length() str.length(), . .
.
4. , 0.
str null, .
, equals() true.
compareToIgnoreCase(String str) ,
,
this.toUpperCase().toLowerCase().compareTo(
str.toUpperCase().toLowerCase());

.
Unicode , . , '\u0401',
, '\u0451'.

166

II. Java API

,
RuleBasedCollator java.text.
this len
str
regionMatches(int ind1, String str, int ind2, int len);

ind1 this, ind2 str. false :


ind1 ind2 ;
ind1 + len ind2 + len ;
.

, .
, :
regionMatches(boolean flag, int ind1, String str, int ind2, int len);

flag true, , false .


.
ch this
indexOf(int ch), 1, ch
this .
, "".indexOf('') 1.
, , this.charAt(k++) == ch, true.
ch this indexOf(int ch, int ind). ch ind.
ind < 0, , ind ,
, . . 1.
, "".indexOf('', indexOf('') + 1) 3.
ch this
lastIndexOf(int ch). . ch
, 1.
, "".lastIndexOf('') 5.
ch this lastIndexOf(int ch, int ind),
, ind. ind ,
; ind < 0, 1.

5.

167


.
sub this
indexOf(String sub). sub 1, sub this. , "".indexOf("") 4.
, - ind,
indexOf(String sub, int ind). ind < 0, ; ind
, , . . 1.
sub this
lastIndexOf(String sub),
sub this 1, sub this.
sub this, ind lastIndexOf(String str, int ind). ind
, ; ind < 0, 1.
, this sub, startsWith(String sub), true,
this sub , sub .
sub this, ind startsWith(String sub, int ind). ind , false.
, this sub, endsWith(String sub). , true,
sub sub .
, if (fileName.endsWith(".java")) Java.
, sub == null.
, , .


toLowerCase() ,
, . . .
toUpperCase() , , . . .
.
,
toLowerCase(Locale loc);
toUpperCase(Locale loc);

168

II. Java API


replace(char old, char new) ,
old new. old ,
.
, " ".replace('', '')
" ".
.


replace(String old, String new) , old new. old ,
.
replaceAll(String oldRegEx, String new) ,
oldRegEx new. old
, .
oldRegEx ,
.
replaceFirst(String oldRegEx, String new) ,
, , .
.


trim() , , '\u0020'.


Java
.
String valueOf(type elem)
boolean, char, int, long, float, double, char[]
Object.
valueOf(char[] ch, int offset, int len)
ch, offset len .
, toString(),
Object. .
valueOf() toString() . , toString().
elem - :
"" + elem. elem.toString().

5.

169

2. .
3. .
4. .

StringBuilder
StringBuilder .
(capacity),
16 . .
, ,
.
,
ensureCapacity(int minCapacity);

, minCapacity
. .
N.
Max(2 * N + 2, minCapacity)

, .
setLength(int newLength) .
, '\u0000'.
, ,
, , '\u0000'.
.
newLength , .
C
, .

, String,
length(), capacity().
StringBuilder .

StringBuilder :
StringBuilder() 16 ;
StringBuilder(int capacity) capacity;
StringBuilder(String str) str.length() + 16,

str;
StringBuilder(CharSequence str) , str.

170

II. Java API


StringBuilder append(),
. ,
, .
append(String str) str .
str == null, "null".
StringBuffer CharSequence.
append(type elem) boolean, char, int, long,
.

float, double,

str sub , :
append(char[] str);
append(char[] sub, int offset, int len);

, append(harSequence sub, int offset, int len), CharSequence.


, append(Object obj), . obj
toString().


insert() ,
, . , , .
, .
, . , .
insert(int ind, String str) str
ind. str == null, "null".
,
String s = new StringBuilder(" ").
insert(4, "").toString();

s == " ".
sb.insert(sb.length(), "xxx") , sb.append("xxx").
insert(int ind, type elem) boolean, char,
int, long, float, double, .
str sub , :
insert(int ind, char[] str);
insert(int ind, char[] sub, int offset, int len);

: insert(int ind, Object obj). obj


toString().

5.

171

:
insert(int ind, harSequence str);
insert(int ind, CharSequence sub, int start, int end);

CharSequence.


delete(int begin, int end) , begin
end ; end ,
.
,
String s = new StringBuilder(" ").
delete(4, 6).toString();

s == " ".
begin , end, .
begin == end, .


deleteCharAt(int ind) ind.
.
ind ,
.


replace(int begin, int end, String str) ,
begin end , end
, , str.
begin , end, .
, replace() delete()
insert().


reverse() .
,
String s = new StringBuilder(" ").
reverse().toString();

s == " ".

II. Java API

172


(parsing) ,
. - (parser), . , : YACC, LEX .
split().
. , - , .
java.util StringTokenizer, .

StringTokenizer
StringTokenizer java.util ,
.
, StringTokenizer(String str), , str , , '\t',
'\n' '\r'. .
, StringTokenizer(String str, String delimeters),
delimeters, :
StringTokenizer(",:-", " \t\n\r,:-");

. ,
, , , , .
delimeters . .
:
StringTokenizer(String str, String delimeters, boolean flag);

flag true, , false


. :
StringTokenizer("a (b + c) / b * c", " \t\n\r+*-/()", true);

:
nextToken() ;
hasMoreTokens() true, ,
false,

, countTokens(), .
, nextToken(String newDelimeters), " " . newDelimeters;
, nextToken().
, nextElement() hasMoreElements(),
Enumeration. nextToken() hasMoreTokens().

5.

173

( 5.2).
5.2.
import java.util.*;
class MyParser{
public static void main(String[] args){
String s = ", ";
StringTokenizer st = new StringTokenizer(s, " \t\n\r,.");
while(st.hasMoreTokens()){
// - ,
//
System.out.println(st.nextToken());
}
}
}

- -: Vector, Stack
, . .

Java.
, JDK. . , , .
ZIP- src.zip, JDK, D:\jdk1.7.0.
jdk1.7.0 , , src,
, JDK, .


1. Java , ?
2. String StringBuilder?
3. StringBuffer StringBuilder?
4. : append()
StringBuilder?
5. : split() StringTokenizer?

-
5.2 . ?
. ,
, , , .
. , .
, , , .
,
.
, ,
, .
Java Vector,
Object.

Vector
Vector java.util Object, , . .
0, 1, 2 . . , .
, (size) ,
(capacity) . ,
ensureCapacity(int minCapacity)
trimToSize().
Java 2 Vector , . , -.
. , Java.

6. -

175


:
Vector() 10 ;
Vector(int capacity) capacity;
Vector(int capacity, int increment)
capacity

increment, -

;
Vector(Collection c) .

capacity , .
. , , . Vector ,
,
(generic) , , :
Vector<String> v = new Vector<String>();

, " ",
Vector<String> v = new Vector<>();

,
String.
.


add(Object element) (
addElement(Object element)).
add(int index, Object element) insertElementAt(Object element,
int index) index. ,
, ,
.
addAll(Collection coll) coll.
addAll(int index, Collection coll) index coll.
:
Vector v = new Vector();
v.add(new Date());
v.add(" ");
v.add(new Integer(10));
v.add(20);

.
: 10 -

176

II. Java API

Integer, . a : add() 20, .


set(int index, Object element)
index, element (
setElementAt(Object element, int index)).


size().
capacity() .
isEmpty() true, .


firstElement(), lastElement(), get(int index)
elementAt(int index).
Object. , :
String s = (String)v.get(1);

, ,
Vector<String> v = new Vector<>();
v.add("First");
v.add("Second");

,
String s = v.get(1);

Object[] toArray()
toArray(Object[] a). a,
.

,
contains(Object element) true, element .
containsAll(Collection c) true,
.

6. -

177


element:
indexOf(Object element) -

;
indexOf(Object element, int begin) , begin -

;
lastIndexOf(Object element)

;
lastIndexOf(Object element, int start) start

.
, 1.


remove(Object element) element. true, .
remove(int index) index
Object.

removeElement(Object element) removeElementAt(int index),

void:
.

removeRange(int begin, int end), . begin end .


coll removeAll(Collection coll).
, setSize(int newSize).
, coll, retainAll(Collection coll).

clear(),
setSize(0).
. 6.1 5.2,
.
removeAllElements()

6.1.
import java.util.*;
class MyParser{
public static void main(String[] args){
Vector<String> v = new Vector<>();
String s = ", .";
StringTokenizer st = new StringTokenizer(s, " \t\n\r,.");

II. Java API

178

while (st.hasMoreTokens()){
//
v.add(st.nextToken());
//
System.out.println(v.firstElement()); //
System.out.println(v.lastElement()); //
v.setSize(4);
//
v.add(".");
// .
v.set(3, "");
// 3.
for (int i = 0; i < v.size(); i++)
// .
System.out.print(v.get(i) + " ");
System.out.println();
for (String s: v)
// .
System.out.print(s + " ");
System.out.println();
}
}

Vector , Object, ,
, .
. , .
. .

Stack
Stack Vector.
Stack java.util .
(stack)
, , , . LIFO (Last In First Out,
).
Stack().
, "" , , .
Vector Stack , :
push(Object item) item ;
pop() ;
peek() , ;
empty() , ;
search(Object item) item . -

1, 2 . . , 1.

6. -

179

6.2 ,
, .
6.2.
import java.util.*;
class StackTest{
static boolean checkParity(String expression, String open, String close){
Stack<String> stack = new Stack<>();
StringTokenizer st = new StringTokenizer(expression,
" \t\n\r+*/-(){}", true);
while (st.hasMoreTokens()){
String tmp = st.nextToken();
if (tmp.equals(open)) stack.push(open);
if (tmp.equals(close)) stack.pop();
}
if (stack.isEmpty()) return true;
return false;
}
public static void main(String[] args){
System.out.println(
checkParity("a (b (c a) / (b + c) 2)", "(", ")"));
}
}

, .

Hashtable.

Hashtable
Hashtable Dictionary. " ". . .
" . . " , , .
. "
", " ", " ", " 1975" . .
.
Hashtable (size) ,
: (capacity) ,
(load factor) ,
.

180

II. Java API

Hashtable
Hashtable :
Hashtable() 101 -

0,75;
Hashtable(int capacity) capacity

0,75;
Hashtable(int capacity, float loadFactor) -

capacity loadFactor;
Hashtable(Map f) Hashtable, -

f, , f,
11, 0,75.
,
.
(generics) :
Hashtable<Integer, String> h = new Hashtable<Integer, String>();

, " ",
Hashtable<Integer, String> h = new Hashtable<>();

.
.

Hashtable
Hashtable :
Object put(Object key, Object value) "key value", key

, value key, .
null, .
null, ;
void putAll(Map f) f.

- key hashCode() equals(),


Object.


get(Object key) key Object , .
, .

6. -

181


containsKey(Object key) true,
key.
containsValue(Object value) contains(Object value) true, value.
isEmpty() true, .

Hashtable
values() value Collection.
, .
keySet() key
Set. Set , .
entrySet() "key value" Set. Set , .
, Hashtable : , .
toString() , .
elements() keys()
Enumeration.


remove(Object key) key, ,
, null, key .
clear() , .
6.3 , Hashtable , . 6.1 .
6.3.
import java.util.*;
class PhoneBook{
public static void main(String[] args){
Hashtable<String, String> yp = new Hashtable<>();
String name = null;
yp.put("John",
"123-45-67");
yp.put("Lennon", "567-34-12");
yp.put("Bill",
"342-65-87");
yp.put("Gates", "423-83-49");
yp.put("Batman", "532-25-08");
try{
name = args[0];

II. Java API

182

}catch(Exception e){
System.out.println("Usage: java PhoneBook Name");
return;
}
if (yp.containsKey(name))
System.out.println(name + "'s phone = " + yp.get(name));
else
System.out.println("Sorry, no such name");
}
}

. 6.1.

Properties
Properties Hashtable ,
, String.
" ",
.
Properties :
Properties() ;
Properties(Properties default) default.

Hashtable Properties :
, - :
String getProperty(String key)

key;

String getProperty(String key, String defaultValue)


key; , defaultValue;

setProperty(String key, String value) , key

, , key ;
load(InputStream in) in;
list(PrintStream out) list(PrintWriter out)

out;

6. -

183

store(OutputStream out, String header) out

header.
6.4 . 6.2
Java.
6.4.
class Prop{
public static void main(String[] args){
System.getProperties().list(System.out);
}
}

. 6.2.

II. Java API

184

Vector, Stack, Hashtable, Properties . , Java ,


Java Collections Framework. . 6.3. . , .
, List, Set, Queue
Map.
List Vector,
Map Hashtable.
List, Set Queue ,
Collection.

NavigableSet

Deque
LinkedBlockingDeque BlockingDeque
ArrayDeque
. 6.3. -

Map Java Collections


Framework, Map . . 6.4.

AbstractMap
HashMap
LinkedHashMap
WeakHashMap
TreeMap
Arrays
Bitset
Collections
Dictionary
Hashtable

Map

SortedMap
NavigableMap
Map.Entry
Properties

. 6.4. -

6. -

185

, Java Collections Framework, (. 4),


,
.
, , Java API, .

Collection
Collection java.util List, Set
Queue. , :
boolean add(Object obj) obj ;
false,

, ; true, ;
boolean addAll(Collection coll) coll

;
void clear() ;
boolean contains(Object obj) obj ;
boolean containsAll(Collection coll)
coll

boolean isEmpty() , ;
Iterator iterator() ;
boolean remove(Object obj) ;
false,

, true, ;

boolean removeAll(Collection coll) , -

;
boolean retainAll(Collection coll) ,

coll;
int size() ;
Object[] toArray() ;
Object[] toArray(Object[] a) a,

List
List java.util, Collection, . (sequence). , ,
. Set List
.

186

II. Java API

Vector List.
List Collection , index :
void add(int index, Object obj) obj index;

, index, , ;
boolean addAll(int index, Collection coll) coll;
Object get(int index) , index;
int indexOf(Object obj) obj -

int lastIndexOf(Object obj) obj

ListIterator listIterator() ;
ListIterator listIterator(int index) -

index;
Object set(int index, Object obj) , index,

obj;
List subList(int from, int to) from -

to .

Set
Set java.util, Collection, , . (set). , .
Set , add()
, .
SortedSet.

SortedSet
SortedSet java.util, Set, ,
, - Comparator.
, , ,
.
:
Comparator comparator() ;
Object first() , ;

6. -

187

SortedSet headSet(Object toElement) ,

toElement ;
Object last() , ;
SortedSet subSet(Object fromElement, Object toElement) -

fromElement toElement ;
SortedSet tailSet(Object fromElement) ,

fromElement .

NavigableSet
NavigableSet java.util, SortedSet, , .
, ,
.
null, :
Object lower(Object elem) ,

elem;
Object floor(Object elem) ,

elem;
Object higher(Object elem) ,

elem;
Object ceiling(Object elem) -

, elem.
:
NavigableSet subSet(Object fromElement, boolean fromInclusive,

Object toElement,

boolean toInclusive)

fromElement
,

fromInclusive == true,

fromInclusive == false, toElement toInclusive;


NavigableSet headSet(Object toElement, boolean inclusive) ,

toElement inclusive;
NavigableSet tailSet(Object fromElement, boolean inclusive) ,

fromElement inclusive.
, :
Object pollFirst() -

;
Object pollLast()

188

II. Java API

Queue
Queue java.util, Collection,
. , , . .
FIFO (First In First Out,
).
Queue Collection ,
:
Object element() , .

, ;

Object peek() , .

element() ;
Object remove() . , ;
Object poll() .
remove() ;
boolean offer(Object obj) true,
.

BlockingQueue
BlockingQueue java.util.concurrent, Queue,
, , . , , , , . , ,
, , .
:
Object take() , -

, ;
void put(Object element) element ,

, ;
int drainTo(Collection coll, int num) num

, coll, ;
int drainTo(Collection coll) , -

coll .

Deque
Deque (double ended queue) java.util,
, , .

Queue,

6. -

189

Deque Queue , :
Object getFirst() , . -

element() Queue. ,
;
Object getLast() , . -

, ;
Object peekFirst() , .

peek() Queue. ;
Object peekLast() , . -

;
void addFirst(Object obj) ;
void addLast(Object obj) .
add() Collection;

boolean offerFirst(Object obj) true,

;
boolean offerLast(Object obj) true,

. offer() Queue;
Object removeFirst() . -

remove() Queue. ,
;
Object removeLast() . -

, ;
Object pollFirst() . -

poll() Queue. removeFirst() ;


Object pollLast() .

removeLast() ;
boolean removeFirstOccurrence(Object obj)
obj true, . , ;

boolean removeLastOccurrence(Object obj)

true, . , .

obj

BlockingDeque
BlockingQueue java.util.concurrent, Queue
Deque, , ,
. ,
, , , -

190

II. Java API

. , ,
, , .
:
Object takeFirst() ,

, . take() BlockingQueue;
Object takeLast() ,

, ;
void putFirst(Object element) element ,

, . put()
BlockingQueue;

void putLast(Object element) element ,

, .

Map
Map java.util ,
, " ".
, ,
(map).
(dictionary) (associative array).
.
, " ".
Hashtable Map.
Map , :
boolean containsKey(Object key) key;
boolean containsValue(Object value) value;
Set entrySet()

, Map.Entry;
Object get(Object key) , key;
Set keySet() ;
Object put(Object key, Object value) "key value",

, key, ;
void putAll(Map m) m;
Collection values() .

Map Map.Entry,
.

6. -

191

Map.Entry
, entrySet():
getKey() getValue() ;
setValue(Object value) .

SortedMap
SortedMap, Map, Map. , , Comparator.
, ,
, , , .
, :
Comparator comparator() ;
Object firstKey() , ;
SortedMap headMap(Object toKey) toKey -

;
Object lastKey() , ;
SortedMap subMap(Object fromKey, Object toKey) -

fromKey toKey ;
SortedMap tailMap(Object fromKey) ,
fromKey .

NavigableMap
NavigableMap java.util, SortedMap, , .
, ,
. null, :
Map lowerEntry(Object key)

, key;
Object lowerKey(Object key) ,

key;
Map floorEntry(Object key)

, key;
Object floorKey(Object key) ,

key;
Map higherEntry(Object key)

, key;

192

II. Java API

Object higherKey(Object key) -

, key;
Map ceilingEntry(Object key) -

, key;
Object ceilingKey(Object key) -

, key.
:
NavigableMap subMap(Object fromKey, boolean fromInclusive, Object toKey, boolean
toInclusive)

fromKey

fromInclusive == true,

fromInclusive == false, toKey


toInclusive;
,

NavigableMap headMap(Object toKey, boolean inclusive) , -

toKey
inclusive;
boolean inclusive) ,
fromKey inclusive.

NavigableMap tailMap(Object fromKey,

, :
Map pollFirstEntry() -

;
Map pollLastEntry() -

-
, .
, . , Java Collections Framework -.
java.util.
AbstractCollection Collection, iterator(), size().
AbstractList List, get(int) size().
, .
AbstractSequentialList List, listIterator(int index) size().

ListIterator.
AbstractSet Set, , AbstractCollection.

6. -

193

AbstractQueue Queue, , AbstractCollection.


AbstractMap Map,
entrySet().
, Java API -.
Vector, Stack, Hashtable Properties, ArrayList,
LinkedList, HashSet, TreeSet, HashMap, TreeMap, WeakHashMap .
Iterator, ListIterator,
Comparator Arrays Collections.

, .

Iterator
7080- , , : , , ,
, , .
: , , , .
, , , [11].
90- , , .
, . Java Collections
Framework Iterator,
. iterator(), Iterator . ,
, , , Iterator .
StringTokenizer, 5.
Iterator :
hasNext() true, ;
next()

Object;
remove() .

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

194

II. Java API

remove() , . , remove()
, , .
6.5 6.1 . , List "for-each".
6.5.
6.5.
Vector<String> v = new Vector<>();
String s = ", .";
StringTokenizer st = new StringTokenizer(s, " \t\n\r,.");
while (st.hasMoreTokens()){
//
v.add(st.nextToken()); // .
}
System.out.println(v.firstElement()); // .
System.out.println(v.lastElement()); // .
v.setSize(4);
// .
v.add(".");
// .
v.set(3, "");
// 3.
// List
// :
for (int i = 0; i < v.size(); i++)
// .
System.out.print(v.get(i) + " ");
System.out.println();
// :
Iterator it = v.iterator();
// .
try{
while (it.hasNext())
// ,
System.out.println(it.next()); // .
}catch(Exception e){}
// for-each:
for (String s: v)
// .
System.out.println(s); // .

ListIterator
ListIterator Iterator,
, .
,
.

6. -

195

ListIterator :
void add(Object element) element ;
boolean hasPrevious() true, ,

;
int nextIndex() ;

, ;
Object previous() ;
int previousIndex() ;
void set(Object element) element;

next() previous().
, , , ,
. , , "" . 6.5 try{}catch(){}.
6.5 ListIterator.
// 6.1...
// ...
ListIterator lit = v.listIterator();
// .
// .
try{
while(lit.hasNext())
// ,
System.out.println(lit.next());
//
// .
// .
// .
while(lit.hasPrevious())
System.out.println(lit.previous());
}catch(Exception e){}

, next() previous()
.
, , - Java.

,
ArrayList
ArrayList Vector,

List Iterator.
, . ArrayList Vector , ArrayList . , . 22.

196

II. Java API

ArrayList :
ArrayList() ;
ArrayList(Collection coll) , -

coll;
ArrayList(int initCapacity) initCapacity.

ArrayList Chorus 3.3, .


public class Chorus{
public static void main(String[] args){
List<Voice> singer = new ArrayList<>();
singer.add(new Dog());
singer.add(new Cat());
singer.add(new Cow());
for (Voice v: singer)
v.voice();
}
}


LinkedList List, Queue Deque. Iterator ListIterator, .
, , . LinkedList . , null.
LinkedList :
LinkedList() ;
LinkedList(Collection coll) ,
coll.

LinkedList .
.

ArrayDeque Queue Deque.


LinkedList . , null.
, , ,
Stack LinkedList.
ArrayDeque :
ArrayDeque() ;
ArrayDeque(Collection coll) ,
coll;
ArrayDeque(int numElement) numElement.

6. -

197

1. 6.1 .

,
HashMap Map, Iterator.
HashMap Hashtable . :
HashMap() 0,75;
HashMap(int capacity) capacity

0,75;
HashMap(int capacity, float loadFactor) -

capacity loadFactor;
HashMap(Map f) HashMap, -

f, , f, 11, 0,75.
WeakHashMap HashMap , , , .


LinkedHashMap Map.
, , . .
:
linkedHashMap() 16 ;
LinkedHashMap(int capacity) capacity ;
LinkedHashMap(int capacity, float loadFactor) capacity

loadFactor;
LinkedHashMap(int capacity, float loadFactor, boolean order) -

capacity , loadFactor order, ;


LinkedHashMap(Map sf) , sf.


TreeMap SortedMap.
, .
, , Comparator.

II. Java API

198

:
TreeMap() ;
TreeMap(Comparator c) ,

c;
TreeMap(Map f) , f,

;
TreeMap(SortedMap sf) , sf

.
, ,
entrySet(), :
Iterator it = tm.entrySet().iterator();

, .


Comparator :
int compare(Object obj1, Object obj2) , obj1

- obj2; , ;
, obj1 obj2. , , ,
,
;
boolean equals(Object obj) obj,
true,

- , .

,
, SortedMap .
.
6.6 Complex 2.4. ComplexCompare,
Comparator. 6.7
.
6.6.
import java.util.*;
class ComplexCompare implements Comparator{
public int compare(Object obj1, Object obj2){
Complex z1 = (Complex)obj1, z2 = (Complex)obj2;
double re1 = z1.getRe(), im1 = z1.getIm();
double re2 = z2.getRe(), im2 = z2.getIm();
if (re1 != re2)
return (int)(re1 re2);

6. -

199

else if (im1 != im2)


return (int)(im1 im2);
else return 0;
}
public boolean equals(Object z){
return compare(this, z) == 0;
}
}

2. 6.3 .

,
HashSet
HashSet

Set Iterator.
, -

.
HashSet :
HashSet() 0,75;
HashSet(int capacity) capacity

0,75;
HashSet(int capacity, float loadFactor) -

capacity loadFactor;
HashSet(Collection coll) ,
coll,

, coll, 11, 0,75.


LinkedHashSet Set Iterator.
, , . .
LinkedHashSet , :
LinkedHashSet() 16 0,75;
LinkedHashSet(int capacity) capacity -

0,75;
LinkedHashSet(int capacity, float loadFactor)
capacity loadFactor;

LinkedHashSet(Collection coll) , coll,

0,75.

II. Java API

200


TreeSet SortedSet Iterator.
TreeSet . .
, , Comparator.
, ,
- , .
TreeSet , :
TreeSet() ;
TreeSet(Comparator c) , -

c;
TreeSet(Collection coll) , coll,

;
TreeSet(SortedMap sf) , sf,

.
6.7 , .
ComplexCompare, 6.6.
6.7.
TreeSet<Complex> ts = new TreeSet<>(new ComplexCompare());
ts.add(new Complex(1.2, 3.4));
ts.add(new Complex(-1.25, 33.4));
ts.add(new Complex(1.23, -3.45));
ts.add(new Complex(16.2, 23.4));
Iterator it = ts.iterator();
while (it.hasNext())
((Complex)it.next()).pr();
// for (Complex z: ts) z.pr(); // .


. . Collections.

Collections
Collections , ,
Collections. ,
JDK, .

6. -

201

, , ,
.
,
List. Collections :
static void sort(List coll) -

coll, List;
static void sort(List coll, Comparator c) coll ,

c.
:
static int binarySearch(List coll, Object element) element -

coll
, ;
, element ,
;
static int binarySearch(List coll, Object element, Comparator c) , -

, c.
:
static Object max(Collection coll) -

coll;
static Object max(Collection coll, Comparator c) , -

c;
static Object min(Collection coll) -

coll;
static Object min(Collection coll, Comparator c) , -

c.
"" :
static void shuffle(List coll) ;
static void shuffle(List coll, Random r) -

r.
reverse(List coll) .
copy(List from, List to) from to.
fill(List coll, Object element)
coll element.
Collections .

3. , , .

202

II. Java API

, , Java
. ,
.
,
, .


1. ?
2. ?
3. ?
4. List Set?
5. List Queue?
6. Deque Queue?
7. Java NavigableSet NavigableMap?
8. ?
9. ?
10. ?
11. ?
12. ?
13. - ?
14. Vector, ArrayList?
15. Iterator "for-each"?
16. - ""?

-
, , , , .


Arrays java.util . .


Arrays
.
:
static void sort(type[] a);

type : byte, short, int, long, char, float,


double Object.
from to :
static void sort(type[] a, int from, int to);


Object , c, Comparator:
static void sort(Object[] a, Comparator c);
static void sort(Object[] a, int from, int to, Comparator c);


element
.

204

II. Java API

:
static int binarySearch(type[] a, type element);

type (byte, short, int, long, char, float, double)


Object.
, from to :
static int binarySearch(type[] a, int from, int to, type element);

:
static <T> int binarySearch(T[] a, T element, Comparator<? Super T> c);
static <T> int binarySearch(T[] a, int from, int to, T element,
Comparator<? Super T> c);

element , ,
c.
.
, ,
, .


Arrays
value:
static void fill(type[], type value);
static void fill(type[], int from, int to, type value);

type Object.


Arrays, ,
type:
static type[] copyOf(type[] a, int newLength);

a, . a
newLength, newLength a, , newLength.
:
static <T> T[] copyOf(T[] a, int newLength);

:
static <T, U> T[] copyOf(U[] a, int newLength, Class<? extends T[]> newType);

7. -

205

, from
to, copyOfRange().
. :
static type[] copyOfRange(type[] a, int from, int to);

to , -
.
:
static <T> T[] copyOfRange(T[] a, int newLength, int from, int to);

:
static <T, U> T[] copyOfRange(U[] a, int from, int to, Class<? extends T[]> newType);


Arrays :
static boolean equals(type[] a1, type[] a2);

type Object.
true, ,
.
:
static boolean deepEquals(Object[] a1, Object[] a2);

, .


Arrays :
static String toString(type[] a);

type Object.
,
.
String.valueOf(type).
:
static String deepToString(Object[] a);

. .

II. Java API

206

-
Arrays - :
static int hashCode(type[] a);

type Object.
List, -
List.hashCode().
:
static int deepHashCode(Object[] a);

- .
.
7.1
Arrays.
7.1. Arrays
import java.util.*;
class ArraysTest{
public static void main(String[] args){
int[] a = {34, -45, 12, 67, -24, 45, 36, -56};
Arrays.sort(a);
for (int i: a)
System.out.print(a[i] + " ");
System.out.println();
Arrays.fill(a, Arrays.binarySearch(a, 12), a.length, 0);
for (int i: a)
System.out.print(a[i] + " ");
System.out.println();
}
}


, -. , ..
( ): 27.06.2011. // ( ): 06/27/11.
, "",
Locale java.util. language country. -

7. -

207

variant, , : "WIN", "MAC",


"POSIX".

.
(. . 6.2):
user.language = ru
user.region = RU
file.encoding = Cp1251

//
//
// CP1251

. ,
, , Locale.getDefault().
, .
Locale :
Locale(String language, String country);
Locale(String language, String country, String variant);

language ,
ISO639, : "ru", "fr", "en". country ,
ISO3166, : "RU", "US", "GB". variant , , , "Traditional".
"ru_RU", "en_GB", "en_US", "en_CA" . .
:
Locale.setDefault(Locale newLocale);

Locale
, locale:
String getCountry() ;
String getDisplayCountry() ,

;
String getDisplayCountry(Locale locale) .

.
, JVM (Java Virtual
Machine, Java), , :
Locale[] getAvailableLocales();
String[] getISOCountries();
String[] getISOLanguages();

208

II. Java API



java.util: Calendar Date.
Date , 1 1970 . 00:00:00
. " " UNIX,
"Epoch".
Date .
, Epoch ,
, System.currentTimeMillis().
Date . Date() , , , Date(long millisec) .
, , long getTime(),
setTime(long newTime).
:
boolean after(long when) true, when ;
boolean before(long when) true, when ;
boolean after(Object when) true, when Date -

.
, ,
int, when; , ; , when:
int compareTo(Date when);
int compareTo(Object when) when Date, -

.
, Date,
Calendar.


(time zone),
(Daylight Savings Time, DST), TimeZone
java.util. SimpleTimeZone.
SimpleTimeZone ,
getDefault(), , , .
,
, ,
getDefault(), ,
, useDaylightTime(),
setDefault(TimeZone zone).

7. -

209

Calendar
Calendar , : , , . Java API GregorianCalendar.
Calendar , / :
Calendar
Calendar
Calendar
Calendar

getInstance();
getInstance(Locale loc);
getInstance(TimeZone tz);
getInstance(TimeZone tz, Locale loc);

JANUARY DECEMBER,
MONDAY SUNDAY.
int getFirstDayOfWeek(),
setFirstDayOfWeek(int day), :
setFirstDayOfWeek(Calendar.MONDAY);

.
get(int field) , field.
Calendar
:
ERA

WEEK_OF_YEAR

DAY_OF_WEEK

SECOND

YEAR

WEEK_OF_MONTH

DAY_OF_WEEK_IN_MONTH

MILLISECOND

MONTH

DAY_OF_YEAR

HOUR_OF_DAY

ZONE_OFFSET

DATE

DAY_OF_MONTH

MINUTE

DST_OFFSET

set(int field, int value), , , .


set() , ,
.
setTime(Date d), , d .

GregorianCalendar
: BC (Before
Christ) AD (Anno Domini).
, / :
GregorianCalendar();
GregorianCalendar(int year, int month, int date);
GregorianCalendar(int year, int month, int date, int hour, int minute);
GregorianCalendar(int year, int month, int date, int hour, int minute, int second);
GregorianCalendar(Locale loc);
GregorianCalendar(TimeZone tz);
GregorianCalendar(TimeZone tz, Locale loc);

210

II. Java API


setGregorianChange(Date date).
15 1582 .
14 1918 ., , greg :
GregorianCalendar greg = new GregorianCalendar();
greg.setGregorianChange(new
GregorianCalendar(1918, Calendar.FEBRUARY, 14).getTime());

, ,
isLeapYear().


, DateFormat SimpleDateFormat
java.text.
DateFormat :
SHORT : 27.07.11 17:32; -

: 07/27/11 5:32 PM;


MEDIUM : 27.07.2011 17:32:45;

;
LONG :

27 2011 . 17:32:45 GMT+03:00;


FULL , LONG;

.
DEFAULT, MEDIUM.
SimpleDateFormat ,
- , :
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh.mm");
System.out.println(sdf.format(new Date()));

: 27-07-2011 17.32.
d , M , y , h
, m .
SimpleDateFormat.
DateFormatSymbols.
SimpleDateFormat. getInstance() DateFormat,
DateFormat. , , .
format() DateFormat
, .
Date.

7. -

211

:
System.out.println("LONG: " + DateFormat.getDateTimeInstance(
DateFormat.LONG, DateFormat.LONG).format(new Date()));

System.out.println("FULL: " + DateFormat.getDateTimeInstance(


DateFormat.FULL,DateFormat.FULL, Locale.US).format(new Date()));


, ,
double random() java.lang.Math.
,
.
Random java.util. :
Random(long seed) ,

seed;
Random() .

, nextBoolean(), nextDouble(), nextFloat(), nextGaussian(), nextInt(), nextLong(),


nextInt(int max) bytes nextBytes(byte[] bytes).
0,0 1,0 .
: max, max
.


, copyOf() copyOfRange()
Arrays(), System
java.lang, Java. , . :
static void arraycopy(Object src, int src_ind, Object dest, int dest_ind, int count);

, src, count ,
src_ind, , dest,
dest_ind.
, , , .
null.

212

II. Java API

src dest , . , , .

int[] arr = {5, 6, 7, 8, 9, 1, 2, 3, 4, 5, -3, -7};
System.arraycopy(arr, 2, arr, 1, arr.length 2);

{5, 7, 8, 9, 1, 2, 3, 4, 5, -3, -7, -7}.


System
(run time).
Runtime.
Runtime JVM
. getRuntime().
.
freeMemory() totalMemory() ,
JVM , ,
long. ,
.
exit(int status) JVM status. , . System,
.
halt(int status) JVM. .
loadLibrary(String libName)
libName.
load(String fileName)
fileName, .
, System
.
gc() (garbage
collection). Java
, . - System.gc().
, exec() . .
, Runtime.getRuntime().exec("notepad") Notepad
() MS Windows.
exec() Process, . destroy() , exitValue()
. waitFor()
, .

III



8.

9.

10.

AWT

11.

Swing

12.

13.

14.

Swing

15.

16.

17.

18.

19.

Swing

20.



,
. . , ,
.
, ,
, . , , ,
, ,
: , , ,
.
: MS Windows, X Window System, Macintosh.
: , , , , . . API, , .

: MFC, Motif, OpenLook, Qt, Tk, Xview, OpenWindows, OpenGL, GTK+ .
, .
Java , Java . , .
JDK : , .
Java .
Java , , .
, .
-, .

216

III.

peer-.
Java, peer-, AWT
(Abstract Window Toolkit). , Java
peer-, (peer-to-peer) , .
AWT ,
: MS Windows, Motif, OpenLook, OpenWindows, ,
AWT, "" .
, peer-,
. Java .
- peer- "" (native) ,
++, JDK.
JDK 1.1 AWT .
, Java peer. "" (lightweight),
, peer-, "" (heavy).
"" ,
(look and feel). , ,
- : "Motif", "Metal",
"Windows 95" - , .
"" PL&F (Pluggable
Look and Feel). "plaf".
"" Java,
Swing. AWT,
Swing , , AWT.
Swing JDK 1.1. Java SE JDK AWT
, "100 % Pure Java".
Java SE AWT Swing,
, ,
Java 2D, , DnD (Drag and
Drop).
, Java SE / Input Method Framework
/,
, Accessibility.
Java SE: AWT, Swing, Java 2D, DnD, Input Method
Framework Accessibility Java, JFC (Java Foundation Classes).
,
AWT Swing.

8.

217


()
(component) . ""
, -, . , ,
. , , , , , (). .
, , , .
, , AWT Component
, Component. Component .
AWT.
(container). "", . , Java Container . JComponent
Swing.
Component ,
Container
add().
Container , Component.
, ,
- , .
, ,
. , , .
:
(title bar),

,
;
(border), .

Frame.
AWT, Frame, 8.1. , .
8.1. AWT
import java.awt.*;
class TooSimpleFrame extends Frame{
public static void main(String[] args){

III.

218

Frame fr = new TooSimpleFrame();


fr.setSize(400, 150);
fr.setVisible(true);
}
}

TooSimpleFrame Frame, .
fr, setSize()
400 150 . ,
. ,
.
setVisible(true). , , AWT, , ,
,
, setVisible(true).
, . , , . , ,
,
. , <Alt>+<F4>.
, <Ctrl>+<C>.
8.2 8.1 , .
8.2.
import java.awt.*;
import java.awt.event.*;
class SimpleFrame extends Frame{
SimpleFrame(String s){
super(s);
setSize(400, 150);
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
System.exit(0);
}
});
}
public static void main(String[] args){
new SimpleFrame(" ");
}
}

, SimpleFrame, Frame,
s .

8.

219

,
addWindowListener(), .

, WindowAdapter.
windowClosing(), .
exit() System.
.
15,
, AWT,
.
, . . , ,
"Hello, XXI Century World!", , . 8.3
, . 8.1 .
8.3.
import java.awt.*;
import java.awt.event.*;
class HelloWorldFrame extends Frame{
HelloWorldFrame(String s){
super(s);
}
public void paint(Graphics g){
g.setFont(new Font("Serif", Font.ITALIC|Font.BOLD, 30));
g.drawString("Hello, XXI Century World!", 20, 100);
}
public static void main(String[] args){
Frame f = new HelloWorldFrame(", XXI !");
f.setSize(400, 150);
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
System.exit(0);
}
});
}
}

. 8.1. -

220

III.

paint() Component. Frame , .


paint() g Graphics, ,
, drawString().
20
100 . , H.
, "Serif" 30 , , . Font,
setFont() Graphics.
.
8.3, , , main().
, AWT , , . AWT.

AWT
. 8.2 AWT.
: Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, TextArea,
TextField, MenuBar, Menu, PopupMenu, MenuItem, CheckboxMenuItem. , Canvas "" ,
Component "" .

. 8.2. AWT

8.

221

Panel, ScrollPane, Window, Frame, Dialog, FileDialog.


"" Panel, ""
Container.
, , ,
, .
. 8.2 Swing
JComponent, JWindow, JFrame, JDialog, JApplet.

Swing
Swing
javax.swing JFrame, 8.4.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

EXIT_ON_CLOSE JFrame,
. ,
WindowConstants, :
DISPOSE_ON_CLOSE , , -

;
DO_NOTHING_ON_CLOSE ;
HIDE_ON_CLOSE . .

Swing

setBackground(Color.WHITE),
8.4. Swing

import java.awt.*;
import javax.swing.*;
class SimpleFrame extends JFrame{
SimpleFrame(String s){
super(s);
setBackground(Color.WHITE);
setSize(400, 150);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g){
g.setFont(new Font("Serif", Font.ITALIC|Font.BOLD, 30));
g.drawString("Hello, XXI Century World!", 20, 100);
}
public static void main(String[] args){
new SimpleFrame(" ");
}
}

III.

222

paint() Component, ,
8.3. , Swing.



, ,
html. , . , txt
. ,
.
Desktop java.awt. , :
browse(URI file) ,
file;

mail() ;
mail(URI mailto) , "To",

"Cc", "Subject", "Body" , mailto;


edit(File file) ,
file,

file;

open(File file) file;


print(File file) file ,

.
,
Desktop ,
getDesktop(). , isDesktopSupported().
, Desktop :
Desktop d = null;
if (Desktop.isDesktopSupported())
d = Desktop.getDesktop();

,
- Desktop

public boolean isSupported(Desktop.Action action);

Action:
BROWSE ;
MAIL ;

8.

223

EDIT , ;
OPEN ;
PRINT .

, Desktop :
if (d.isSupported(Desktop.Action.BROWSE))
d.browse(new URI("http://www.bhv.ru"));
if (d.isSupported(Desktop.Action.MAIL))
d.mail();
if (d.isSupported(Desktop.Action.EDIT))
d.edit(new File("/home/user/java/src/MyDesktop.java");
if (d.isSupported(Desktop.Action.OPEN))
d.open(new File("/home/user/java/src/MyDesktop.java");
if (d.isSupported(Desktop.Action.PRINT))
d.print new File("/home/user/java/src/MyDesktop.java");

System Tray
Java (notification
area), (system tray) .
. java.awt
SystemTray. add(TrayIcon icon) icon , remove(TrayIcon icon) .
.
, , TrayIcon.
. , , , ,
. 15.
,
.
:
TrayIcon icon = null;
if (SystemTray.isSupported()){
SystemTray tray = SystemTray.getSystemTray();
Image im = Toolkit.getDefaultToolkit.getImage("myicon.gif");
icon = new TrayIcon(im);
tray.add(icon);
}


SystemTray. 15.

224

III.

Splash Screen
(splash screen) - ,
. ,
-splash. , name.gif, :
java splash:name.gif SimpleFrame

,
java jar SimpleFrame.jar

MANIFEST.MF, 25.
- SplashScreen
java.awt. setImageURL(URL image)
, Graphics2D
createGraphics(). -
update(). :
SplashScreen splash = SplashScreen.getSplashScreen();
if (splash != null){
Graphics2D g = splash.createGraphics();
g.setPaintMode();
g.drawString("Loading...", 100, 200);
// . ., , 9.
g.update();
}

, AWT . . .
.
Java:
KL Group, JBCL, SWAT, SWT .
, .
,
AWT Swing
, , .


1. ?
2. ?

8.

3. ?
4. .
5. ?
6. ?
7. Swing AWT?
8. AWT Swing?
9. AWT?

225


, . . Component,
(graphics context).
. Color,
Font.
,
(0, 0) , Ox
, Oy . .
Graphics Graphics2D,
Java 2D. , .
Graphics Graphics2D.
Java ,
Graphics
getGraphics() Component paint() update().
,
Graphics.

Graphics
, ,
. setColor(Color newColor), newColor Color.
getColor(), Color.


, Java, , Color.
.

9.

227

,
Color(int red, int green, int blue);

, red, green blue . RGB. 0


( ) 255 (
). , :
Color pureRed = new Color(255, 0, 0);
Color pureGreen = new Color(0, 255, 0);

- pureRed - pureGreen.

0.0 ( ) 1.0 ( ):
Color(float red, float green, float blue);

:
Color someColor = new Color(0.05f, 0.4f, 0.95f);

,
Color(int rgb);

. 1623 , 815 , 07
. :
Color c = new Color(0xFF8F48AF);

0x8F, 0x48,
0xAF.
:
Color(int red, int green, int blue, int alpha);
Color(float red, float green, float blue, float alpha);
Color(int rgb, boolean hasAlpha);

, , .
. 255 1.0, , , , . 0 0.0,
, . ,
.
-,
2431, hasAlpha true. hasAlpha false, 255, ,
rgb.
, ,
255 1.0.

228

III.

,
Color(ColorSpace cspace, float[] components, float alpha);

(color model) RGB,


: CMYK, HSB, CIE XYZ, ColorSpace.
HSB
getHSBColor(float hue, float saturation, float brightness);

,
Color, Color. "Code Conventions" JDK : black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red,
white, yellow. JDK , : BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED,
WHITE, YELLOW. .
SystemColor, Color, , , , , , .

.
Color : getRed(),
getGreen(), getBlue(), getAlpha(), getRGB(), getColorSpace(), getComponents().
brighter() darker()
. , , ,
.
, RGB
HSB :
float[] RGBtoHSB(int red, int green, int blue, float[] hsb);
int HSBtoRGB(int hue, int saturation, int brightness);

, .

1. .


,
drawLine(int x1, int y1, int x2, int y2);

(x1, y1)
(x2, y2).
, , (x, y) drawLine(x, y, x, y)
. , , .

9.

229

:
drawRect(int x, int y, int width, int height) ,

,
(x, y), width height ;
draw3DRect(int x, int y, int width, int height, boolean raised) -

, , raised
true, , raised false;
drawOval(int x, int y, int width, int height) , -

, . width == height, ;
drawArc(int x, int y, int width, int height, int startAngle, int arc) -

, , .
arc startAngle.
Ox. ,
;
drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) -

.
, arcWidth arcHeight, ;
drawPolyline(int[] xPoints, int[] yPoints, int nPoints) -

(xPoints[i], yPoints[i]) nPoints;


drawPolygon(int[] xPoints, int[] yPoints, int nPoints) ,

;
drawPolygon(Polygon p) , -

p Polygon.
Polygon .

Polygon
, , .
:
Polygon() ;
Polygon(int[] xPoints, int[] yPoints, int nPoints)

(xPoints[i], yPoints[i]) nPoints. .



addPoint(int x, int y);

contains() , , , :

230
boolean
boolean
boolean
boolean
boolean
boolean

III.
contains(int x, int y);
contains(double x, double y);
contains(Point p);
contains(Point2D p);
contains(double x, double y, double width, double height);
contains(Rectangle2D rectangle);

intersects() ,
, ,
, :
boolean intersects(double x, double y, double width, double height);
boolean intersects(Rectangle2D rectangle);

getBounds() getBounds2D() Rectangle


Rectangle2D , .

2. : ", , , ".

Graphics
Graphics. ,
: fillRect(), fill3DRect(), fillArc(), fillOval(), fillPolygon(),
fillRoundRect(). , , .
, ,
:
public void paint(Graphics g){
Color initColor = g.getColor();
// .
g.setColor(new Color(0, 0, 255));
// .
// .
g.fillRect(0, 0, getSize().width 1, getSize().height 1);
g.setColor(initColor);
// .
// ...
}

, Graphics .
, ( setBackground() Component). ,

Graphics2D, Java 2D. , setBackground(Color c).
Graphics2D, Graphics
.

9.

231


,
Graphics :

(x, y),

drawString(String s, int x, int y) s;


drawBytes(byte[] b, int offset, int length, int x, int y) length -

b, offset;
drawChars(char[] ch, int offset, int length, int x, int y) length -

ch, offset.
, ,
AttributedCharacterIterator. :
drawString(AttributedCharacterIterator iter, int x, int y);

(x, y)
(baseline) .


setFont(Font newFont) Graphics
.
getFont() .
Java, , Font. ,
.


Font (glyphs) , .
:
Font(Map attributes) attributes .


java.awt.font. Java 2D
;

TextAttribute

Font(String name, int style, int size) name, style

size . JDK 1.1,


Java 2D .
0,376 , , 1/72 . -
1/72 0,351 . - .
name ,
"Courier New", "Dialog", "DialogInput", "Monospaced", "Serif", "SansSerif",
"Symbol". (logical font names).
name == null, .

232

III.

style Font:
BOLD ;
ITALIC ;
PLAIN .

(bolditalic) ,
Font.BOLD|Font.ITALIC, 8.3.

(font face name) (font name).
, .
, "Serif" (family)
"Times New Roman",
"Times New Roman Bold", "Times New Roman Italic". ,
.
:
Font[] fonts = Toolkit.getGraphicsEnvironment.getAllFonts();
for (Font f: fonts)
System.out.println(f.getFontName());

Java SE Lucida. JDK,


, .
Java :
fontconfig.properties;

fontconfig.2003.properties;

fontconfig.Me.properties;

fontconfig.RedHat.properties

fontconfig.2000.XP.properties;

. .

fontconfig.XP.properties;

JDK jdk1.7.0/jre/lib -
lib JDK ,
.
, src, ,
bfc.
Java . , fontconfig.properties, .
fontconfig.properties,
.
.
9.1 fontconfig.properties.src Java
SE 7 MS Windows.

9.
9.1. fontconfig.properties.src
#
# Copyright 2003, 2010, Oracle and/or
its affilates. All rights reserved.
#
# Version
version=1
# Component Font Mappings
allfonts.chinese-ms936=SimSun
allfonts.chinese-gb18030=SimSun-18030
allfonts.chinese-hkscs=MingLiU_HKSCS
allfonts.devanagari=Mangal
allfonts.dingbats=Wingdings
allfonts.lucida=Lucida Sans Regular
allfonts.symbol=Symbol
allfonts.thai=Lucida Sans Regular
serif.plain.alphabetic=Times New Roman
serif.plain.chinese-ms950=MingLiU
serif.plain.hebrew=David
serif.plain.japanese=MS Mincho
serif.plain.korean=Batang
serif.bold.alphabetic=Times New Roman Bold
#
serif.italic.alphabetic=Times New Roman Italic
#
serif.bolditalic.alphabetic=Times New Roman Bold Italic
#
sansserif.plain.alphabetic=Arial
#
monospaced.plain.alphabetic=Courier New
#
dialog.plain.alphabetic=Arial
#
dialoginput.plain.alphabetic=Courier New
#
# Search Sequences
sequence.allfonts=alphabetic/default,dingbats,symbol
#
# Exclusion Ranges
exclusion.alphabetic=0700-1e9f,1f00-20ab,20ad-f8ff
exclusion.chinese-gb18030=0390-03d6,2200-22ef,2701-27be
exclusion.hebrew=0041-005a,0060-007a,007f-00ff,20ac-20ac
# Monospaced to Proportional width variant mapping
# (Experimental private syntax)
proportional.MS_Gothic=MS PGothic
proportional.MS_Mincho=MS PMincho
proportional.MingLiU=PMingLiU

233

234

III.

# Font File Names


filename.Arial=ARIAL.TTF
filename.Arial_Bold=ARIALBD.TTF
filename.Arial_Italic=ARIALI.TTF
filename.Arial_Bold_Italic=ARIALBI.TTF
filename.Courier_New=COUR.TTF
filename.Courier_New_Bold=COURBD.TTF
filename.Courier_New_Italic=COURI.TTF
filename.Courier_New_Bold_Italic=COURBI.TTF
filename.Times_New_Roman=TIMES.TTF
filename.Times_New_Roman_Bold=TIMESBD.TTF
filename.Times_New_Roman_Italic=TIMESI.TTF
filename.Times_New_Roman_Bold_Italic=TIMESBI.TTF
filename.SimSun=SIMSUN.TTC
filename.SimSun-18030=SIMSUN18030.TTC
filename.MingLiU=MINGLIU.TTC
filename.PMingLiU=MINGLIU.TTC
filename.MingLiU_HKSCS=hkscsm3u.ttf
filename.David=DAVID.TTF
filename.David_Bold=DAVIDBD.TTF
filename.MS_Mincho=MSMINCHO.TTC
filename.MS_PMincho=MSMINCHO.TTC
filename.MS_Gothic=MSGOTHIC.TTC
filename.MS_PGothic=MSGOTHIC.TTC
filename.Gulim=gulim.TTC
filename.Batang=batang.TTC
filename.GulimChe=gulim.TTC
filename.Lucida_Sans_Regular=LucidaSansRegular.ttf
filename.Mangal=MANGAL.TTF
filename.Symbol=SYMBOL.TTF
filename.Wingdings=WINGDING.TTF

.
, :
"dialog" "Arial";
"dialoginput" "Courier New";
"serif" "Times New Roman";
"sansserif" "Arial";
"monospaced" "Courier New".

, : dialog.italic, dialog.bold . .,
.
9.1, filename, , :
filename.Arial=ARIAL.TTF

, .

9.

235

9.1.
exclusion.alphabetic=0700-1e9f,1f00-20ab,20ad-f8ff

, (glyphs) '\u0700''\u1e9f', '\u1f00''\u20ab' '\u20ad''\uf8ff'.


,
sequence.allfonts=alphabetic/default,dingbats,symbol

Wingdings.
, str drawString(),
Font,
, "Serif". Java
fontconfig.properties, , , Times New
Roman. Unicode-,
str Unicode . ASCII-, str , CharToByteCp1251.
Java SE docs/technotes/guides/intl/
fontconfig.html.
, ,
JDK 1.0 "Helvetica", "TimesRoman", "Courier", JDK 1.1 "SansSerif", "Serif", "Monospaced" .
: , . : . FontMetrics.
Java 2D FontMetrics TextLayout.
, ,
FontMetrics.

FontMetrics
FontMetrics , . FontMetrics, f, getFontMetrics(Font f)
Graphics Component.
[12].
FontMetrics ch
charWidth(ch),
getChars() getBytes(), str stringWidth(str).
.

236

III.

(leading) , , , , , , getLeading().
(ascent) getAscent(), getMaxAscent().
(descent)
getDescent(), getMaxDescent().
, (height) ascent + descent + leading getHeight().
.
. 9.1.

. 9.1.


LineMetrics java.awt.font.
getLineMetrics() FontMetrics.
9.2 , . 9.2
.
9.2.
import java.awt.*;
import javax.swing.*;
class GraphTest extends JFrame{
GraphTest(String s){
super(s);
setBounds(0, 0, 500, 300);
setVisible(true);
}
public void paint(Graphics g){
Dimension d = getSize();
int dx = d.width / 20, dy = d.height / 20;
g.drawRect(dx, dy + 20,
d.width 2 * dx, d.height 2 * dy 20);
g.drawRoundRect(2 * dx, 2 * dy + 20,
d.width 4 * dx, d.height 4 * dy 20, dx, dy);

9.
g.fillArc(d.width / 2 dx, d.height 2 * dy + 1,
2 * dx, dy 1, 0, 360);
g.drawArc(d.width / 2 3 * dx, d.height 3 * dy / 2 5,
dx, dy / 2, 0, 360);
g.drawArc(d.width / 2 + 2 * dx, d.height 3 * dy / 2 5,
dx, dy / 2, 0, 360);
Font f1 = new Font("Serif", Font.BOLD|Font.ITALIC, 2 * dy);
Font f2 = new Font("Serif", Font.BOLD, 5 * dy / 2);
FontMetrics fm1 = getFontMetrics(f1);
FontMetrics fm2 = getFontMetrics(f2);
String s1 = " ";
String s2 = " .";
String s3 = " ";
int firstLine = d.height / 3;
int nextLine = fm1.getHeight();
int secondLine = firstLine + nextLine / 2;
g.setFont(f2);
g.drawString(s3, (d.width-fm2.stringWidth(s3)) / 2, firstLine);
g.drawLine(d.width / 4, secondLine 2,
3 * d.width / 4, secondLine 2);
g.drawLine(d.width / 4, secondLine 1,
3 * d.width / 4, secondLine 1);
g.drawLine(d.width / 4, secondLine,
3 * d.width / 4, secondLine);
g.setFont(f1);
g.drawString(s1, (d.width fm1.stringWidth(s1)) / 2,
firstLine + 2 * nextLine);
g.drawString(s2, (d.width fm1.stringWidth(s2)) / 2,
firstLine + 3 * nextLine);
}
public static void main(String[] args){
GraphTest f = new GraphTest(" ");
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

. 9.2. Graphics

237

238

III.

9.2 Dimension, width height.


getSize() Component
Dimension. 9.2 f GraphTest setBounds() 500 300 .
9.2 ,
,
.
Graphics , .
, , ,
.
:
, , 9.2, , ,
getScreenSize() java.awt.Toolkit .
, ,
KISS.
Graphics, Java 2D, Graphics2D.

3. .

Java 2D
Java 2D, Graphics2D
java.awt, .
, Graphics -

(User Space),
(Device Space): , .
Graphics2D (transform)
.

"", , / /.
AffineTransform. setTransform(). " " transform() translate() concatenate().
, -

, .

9.

239

: , , .,

Shape java.awt.
draw(),
, Shape. fill(), , Shape.
(stroke) (pen). -

Stroke. BasicStroke .
:
(width) ( ) ;
(end cap)
CAP_ROUND, CAP_SQUARE ( ) CAP_BUTT;
(line joins)
JOIN_ROUND, JOIN_BEVEL JOIN_MITER ( );
(dash) ,
,
,
.
Paint. -

. Color (solid) ,
(gradient) , , TexturePaint (pattern fill).
MultipleGradientPaint ,
LinearGradientPaint ,
RadialGradientPaint .
GradientPaint

, . . , Shape,

draw()
. ,
.
, ,

, ,
. , .
, . TextAttribute.
(rendering) (hints),

RenderingHints.
Java 2D , . ,
.

240

III.


(transform) ,
. setTransform() ,
.
AffineTransform java.awt.geom, Color Font .
AffineTransform.

AffineTransform
AffineTransform:
AffineTransform(double a, double b, double c, double d, double e, double f);
AffineTransform(float a, float b, float c, float d, float e, float f);

(x, y)
(a * x + c * y + e, b * x + d * y + f) .
,
. , , ,
.
- {a, b, c, d, e, f} {a, b, c, d}, e = f = 0,
:
AffineTransform(double[] arr);
AffineTransform(float[] arr);

, , :
AffineTransform(AffineTransform at);

:
AffineTransform();

, . 57 (20, 40) , :
AffineTransform at =
new AffineTransform(-1.5, 4.45, -0.56, 34.7, 2.68, 0.01);
g.setTransform(at);

9.

241

, AffineTransform.
getRotateInstance(double angle) angle, -

, . ,
Ox Oy. , angle
.
getRotateInstance(double angle, double x, double y)

(x, y).
getRotateInstance(double vx, double vy) , -

(vx, vy). getRotateInstance(Math.atan2(vx, vy)).


getRotateInstance(double vx, double vy, double x, double y)

(x, y), (vx, vy).


getRotateInstance(Math.atan2(vx, vy), x, y).
getQuadrantRotateInstance(int n) n 90 -

. getRotateInstance(n * Math.PI / 2.0).


getQuadrantRotateInstance(int n, double x, double y) n 90 -

(x, y). getRotateInstance(n *


Math.PI / 2.0, x, y).
getScaleInstance(double sx, double sy) Ox sx ,

Oy sy .
getShareInstance(double shx, double shy) (x, y)
(x + shx * y, shy * x + y).

getTranslateInstance(double tx, double ty) (x, y)


(x + tx, y + ty).

createInverse() , .
:
setTransform(AffineTransform at);
setTransform(double a, double b, double c, double d, double e, double f);
setToIdentity();
setToRotation(double angle);
setToRotation(double angle, double x, double y);
setToRotation(double vx, double vy);
setToRotation(double vx, double vy, double x, double y);
setToQuadrantRotation(int n);
setToQuadrantRotation(int n, double x, double y);
setToScale(double sx, double sy);
setToShare(double shx, double shy);
setToTranslate(double tx, double ty);

, .

242

III.

, :
concatenate(AffineTransform at);
rotate(double angle);
rotate(double angle, double x, double y);
rotate(double vx, double vy);
rotate(double vx, double vy, double x, double y);
quadrantRotate(int n);
quadrantRotate(int n, double x, double y);
scale(double sx, double sy);
shear(double shx, double shy);
translate(double tx, double ty);

, .
, preConcatenate(AffineTransform at), , .
AffineTransform
.
. paint(), 9.2,

import java.awt.geom.*;

, 9.3.
9.3.
// 9.2...
public void paint(Graphics gr){
Graphics2D g = (Graphics2D)gr;
AffineTransform at =
AffineTransform.getRotateInstance(-Math.PI/4.0, 250.0, 150.0);
at.concatenate(
new AffineTransform(0.5, 0.0, 0.0, 0.5, 100.0, 60.0));
g.setTransform(at);
Dimension d = getSize();
// 9.2

paint() g Graphics2D gr Graphics2D. , getRotateInstance()


45 (250.0, 150.0). at AffineTransform. concatenate(),
at,
(100.0, 60.0). , g setTransform().
. , (100.0, 60.0) -

9.

243

. 45
(250.0, 150.0).
. 9.3.

. 9.3.

4. 9.3 , .

Java 2D
Stroke. Java 2D
, , BasicStroke.

BasicStroke
BasicStroke . ,
BasicStroke(float width, int cap, int join, float miter,
float[] dash, float dashBegin);

:
width ;
cap; :
CAP_ROUND

CAP_SQUARE
CAP_BUTT

III.

244

join; :
JOIN_ROUND

;
JOIN_BEVEL , ;
JOIN_MITER ;
miter,
JOIN_MITER;

dash;

, ; ;

dashBegin, dash.

:
BasicStroke(float width, int cap, int join, float miter) ;
BasicStroke(float width, int cap, int join)


JOIN_MITER miter = 10.0f;
BasicStroke(float width) CAP_SQUARE JOIN_MITER miter = 10.0f;
JOIN_ROUND JOIN_BEVEL;

BasicStroke() 1.0f.

, . 9.4
, . 9.4 , .
9.4.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
class StrokeTest extends JFrame{
StrokeTest(String s){
super(s);
setSize(500, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics gr){
Graphics2D g = (Graphics2D)gr;
g.setFont(new Font("Serif", Font.PLAIN, 15));
BasicStroke pen1 = new BasicStroke(20, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,30);
BasicStroke pen2 = new BasicStroke(20, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND);
BasicStroke pen3 = new BasicStroke(20, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL);
float[] dash1 = {5, 20};
BasicStroke pen4 = new BasicStroke(10, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_BEVEL, 10, dash1, 0);

9.
float[] dash2 = {10, 5, 5, 5};
BasicStroke pen5 = new BasicStroke(10, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_BEVEL, 10, dash2, 0);
g.setStroke(pen1);
g.draw(new Rectangle2D.Double(50, 50, 50, 50));
g.draw(new Line2D.Double(50, 180, 150, 180));
g.setStroke(pen2);
g.draw(new Rectangle2D.Double(200, 50, 50, 50));
g.draw(new Line2D.Double(50, 230, 150, 230));
g.setStroke(pen3);
g.draw(new Rectangle2D.Double(350, 50, 50, 50));
g.draw(new Line2D.Double(50, 280, 150, 280));
g.drawString("JOIN_MITER", 40, 130);
g.drawString("JOIN_ROUND", 180, 130);
g.drawString("JOIN_BEVEL", 330, 130);
g.drawString("CAP_BUTT", 170, 190);
g.drawString("CAP_ROUND", 170, 240);
g.drawString("CAP_SQUARE", 170, 290);
g.setStroke(pen5);
g.draw(new Line2D.Double(50, 330, 250, 330));
g.setStroke(pen4);
g.draw(new Line2D.Double(50, 360, 250, 360));
g.drawString("{10, 5, 5, 5,...}", 260, 335);
g.drawString("{5, 10,...}", 260, 365);
}
public static void main(String[] args){
new StrokeTest(" ");
}
}

. 9.4.

245

246

III.

setStroke()
draw() fill().
, draw() Graphics2D,
Shape. , , , , Rectangle2D,
RoundRectangle2D, Line2D, Ellipse2D, Arc2D, Point2D java.awt.geom.
CubicCurve2D QuadCurve2D .
, Double
Float . 9.4 Rectangle2D.Double Line2d.Double
.

GeneralPath
java.awt.geom GeneralPath.
,
, .
, Shape,
GeneralPath.
GeneralPath .
GeneralPath GeneralPath() ,
, GeneralPath(Shape sh).

append(Shape sh, boolean connect);

connect true, .
. (0, 0), (x, y) moveTo(float x, float y).
(x, y) :
lineTo(float x, float y);
quadTo(float x1, float y1, float x, float y);
curveTo(float x1, float y1, float x2, float y2, float x,
float y).

(x, y).
closePath().
:
GeneralPath p = new
p.moveTo(x1, y1);
p.lineTo(x2, y2);
p.lineTo(x3, y3);
p.closePath();

GeneralPath();
// ,
// ,
// ,
// .

9.

247

Paint. Java 2D
Color, GradientPaint,
TexturePaint, MultipleGradientPaint LinearGradientPaint
RadialGradientPaint. Color , ,
GradientPaint TexturePaint.

GradientPaint TexturePaint
GradientPaint .
, M N, . (x1, y1) c1,
N(x2, y2) c2. c1 c2 , N, , MN.
GradientPaint(float x1, float y1, Color c1,
float x2, float y2, Color c2);

MN : c1,
N c2.
,
GradientPaint(float x1, float y1, Color c1,
float x2, float y2, Color c2, boolean cyclic);

cyclic == true MN
.
Point2D.
TexturePaint .
BufferedImage java.awt.image. .
20, ,
Graphics2D.
createGraphics() BufferedImage. , .
TexturePaint. , . :
TexturePaint(BufferedImage buffer, Rectangle2D anchor);

Color, GradientPaint TexturePaint


setPaint(Paint p)
fill(Shape sh).
9.5 . 9.5.
9.5.
import java.awt.*;
import java.awt.geom.*;

248

III.

import java.awt.image.*;
import javax.swing.*;
class PaintTest extends JFrame{
PaintTest(String s){
super(s);
setSize(300, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics gr){
Graphics2D g = (Graphics2D)gr;
BufferedImage bi =
new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB);
Graphics2D big = bi.createGraphics();
big.draw(new Line2D.Double(0.0, 0.0, 10.0, 10.0));
big.draw(new Line2D.Double(0.0, 10.0, 10.0, 0.0));
TexturePaint tp = new TexturePaint(bi,
new Rectangle2D.Double(0.0, 0.0, 10.0, 10.0));
g.setPaint(tp);
g.fill(new Rectangle2D.Double(50,50, 200, 200));
GradientPaint gp =
new GradientPaint(100, 100, Color.white,
150, 150, Color.black, true);
g.setPaint(gp);
g.fill(new Ellipse2D.Double(100, 100, 200, 200));
}
public static void main(String[] args){
new PaintTest(" ");
}
}

. 9.5.

9.

249

LinearGradientPaint RadialGradientPaint
LinearGradientPaint RadialGradientPaint , , .
MultipleGradientPaint.
, GradientPaint, MN, 0.0
1.0 . , :
float[] dist = {0.0f, 0.2f, 1.0f};

:
.
. :
Color[] color = {Color.RED, Color.WHITE, Color.BLUE};

.
,
.
LinearGradientPaint:
LinearGradientPaint(float x1, float y1, float x2, float y2,
float[] dist, Color[] color);

RadialGradientPaint.
RadialGradientPaint(float x, float y, float radius,
float[] dist, Color[] color);

, (x1, y1) N(x2, y2) ,


A(x, y) radius.
MN
MultipleGradientPaint.CycleMethod. Java SE :
NO_CYCLE ( );
REFLECT -

, ;
REFLECT .

:
LinearGradientPaint(float x1, float y1, float x2, float y2,
float[] dist, Color[] color,
MultipleGradientPaint.CycleMethod method);
RadialGradientPaint(float x, float y, float radius,
float[] dist, Color[] color,
MultipleGradientPaint.CycleMethod method);

Point2D.

250

III.

RGB, .
LinearGradientPaint RadialGradientPaint
setPaint(Paint p)
fill(Shape sh).

Java 2D
Font , : , , , ,
, ,
.
TextAttribute.
. 9.1.
9.1.

BACKGROUND

. , Paint

FOREGROUND

. , Paint

BIDI_EMBEDDED

. 1 15

CHAR_REPLACEMENT

, . GraphicAttribute

FAMILY

. String

FONT

. Font

JUSTIFICATION

. Float
0.0 1.0. : JUSTIFICATION_FULL
JUSTIFICATION_NONE

KERLING


, "AWAY". KERLING_ON

LIGATURES

, "float".

LIGATURES_ON
POSTURE

. Float. :
POSTURE_OBLIQUE POSTURE_REGULAR

RUN_DIRECTION

: RUN_DIRECTION_LTR ,
RUN_DIRECTION_RTL

SIZE

. Float

STRIKETHROUGH

. STRIKETHROUGH_ON,

SUPERSCRIPT

. : SUPERSCRIPT_NONE,
SUPERSCRIPT_SUB, SUPERSCRIPT_SUPER

SWAP_COLORS

. SWAP_COLORS_ON,

9.

251
9.1 ()

TRAKING

.
TRAKING_TIGHT ,
TRAKING_LOOSE

TRANSFORM

. AffineTransform

UNDERLINE

. : UNDERLINE_ON,
UNDERLINE_LOW_DASHED, UNDERLINE_LOW_DOTTED, UNDERLINE_LOW_GRAY,
UNDERLINE_LOW_ONE_PIXEL, UNDERLINE_LOW_TWO_PIXEL

WEIGHT

. : WEIGHT_ULTRA_LIGHT,
WEIGHT__EXTRA_LIGHT, WEIGHT__LIGHT, WEIGHT__DEMILIGHT,
WEIGHT__REGULAR, WEIGHT__SEMIBOLD, WEIGHT__MEDIUM,
WEIGHT__DEMIBOLD, WEIGHT__BOLD, WEIGHT__HEAVY, WEIGHT__EXTRABOLD,

WEIGHT__ULTRABOLD
WIDTH

. : WIDTH_CONDENSED, WIDTH_SEMI_CONDENSED,
WIDTH_REGULAR, WIDTH_SEMI_EXTENDED, WIDTH_EXTENDED

, . getAvailableAttributes() Font. :
Font f = new Font("Times New Roman", Font.BOLD, 12);
AttributedCharacterIterator.Attribute[] a = f.getAvailableAttributes();
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);

Font Font(Map attributes), .


, Map:
HashMap, WeakHashMap Hashtable (. 7). :
HashMap hm = new HashMap();
hm.put(TextAttribute.SIZE, new Float(60.0f));
hm.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE);
Font f = new Font(hm);

, 9.2, deriveFont() Font.


Java 2D FontRenderContext,
, .
getFontRenderContext() Graphics2D.
, ,
TextLayout. Java 2D FontMetrics.
TextLayout , .
paint() :
public void paint(Graphics gr){
Graphics2D g = (Graphics2D)gr;

252

III.

FontRenderContext frc = g.getFontRenderContext();


Font f = new Font("Serif", Font.BOLD, 15);
String s = "- ";
TextLayout tl = new TextLayout(s, f, frc);
//
}

TextLayout getXXX(), , ,
draw(Graphics2D g, float x, float y);

TextLayout g, (x, y).


,
getOutline(AffineTransform at);

Shape.
- , 9.6.
9.6. Java 2D
import
import
import
import

java.awt.*;
java.awt.font.*;
java.awt.geom.*;
javax.swing.*;

class StillText extends JFrame{


StillText(String s){
super(s);
setSize(400, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics gr){
Graphics2D g = (Graphics2D)gr;
int w = getSize().width, h = getSize().height;
FontRenderContext frc = g.getFontRenderContext();
String s = "";
Font f = new Font("Serif", Font.BOLD, h/3);
TextLayout tl = new TextLayout(s, f, frc);
AffineTransform at = new AffineTransform();
at.setToTranslation(w/2-tl.getBounds().getWidth()/2, h/2);
Shape sh = tl.getOutline(at);
g.draw(sh);
AffineTransform atsh = new AffineTransform(1, 0.0, 1.5, -1, 0.0, 0.0);
g.transform(at);
g.transform(atsh);
Font df = f.deriveFont(atsh);
TextLayout dtl = new TextLayout(s, df, frc);

9.

253

Shape sh2 = dtl.getOutline(atsh);


g.fill(sh2);
}
public static void main(String[] args){
new StillText(" ");
}
}

. 9.6 .

. 9.6. Java 2D


AttributedString java.text.
AttributedString(String text, Map attributes);

, . addAttibute().
, .
TextLayout LineBreakMeasurer, .
TextLayout , .
(caret) . TextHitInfo,
TextLayout ,
.
, .
GlyphVector createGlyphVector()
Font, setGlyphPosition(),
, , setGlyphTransform(), drawGlyphVector() Graphics2D.
9.7 . 9.7 9.7.
9.7.
import java.awt.*;
import java.awt.font.*;

254

III.

import java.awt.geom.*;
import javax.swing.*;
class GlyphTest extends JFrame{
GlyphTest(String s){
super(s);
setSize(400, 150);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics gr){
int h = 5;
Graphics2D g = (Graphics2D)gr;
FontRenderContext frc = g.getFontRenderContext();
Font f = new Font("Serif", Font.BOLD, 30);
GlyphVector gv = f.createGlyphVector(frc, " ");
int len = gv.getNumGlyphs();
for (int i = 0; i < len; i++){
Point2D.Double p = new Point2D.Double(25 * i, h = -h);
gv.setGlyphPosition(i, p);
}
g.drawGlyphVector(gv, 10, 100);
}
public static void main(String[] args){
new GlyphTest(" ");
}
}

. 9.7.


(rendering) , (hint) Graphics2D:
setRenderingHints(RenderingHints.Key key, Object value);
setRenderingHints(Map hints);


RenderingHints, . 9.2.

9.

255
9.2.

KEY_ANTIALIASING

;
, : VALUE_ANTIALIAS_DEFAULT,
VALUE_ANTIALIAS_ON, VALUE_ANTIALIAS_OFF

KEY_TEXT_ANTIALIASING

. : VALUE_TEXT_ANTIALIASING_DEFAULT,
VALUE_TEXT_ANTIALIASING_ON, VALUE_TEXT_ANTIALIASING_OFF.
LCD- : VALUE_TEXT_ANTIALIAS_GASP,
VALUE_TEXT_ANTIALIAS_LCD_HRGB,
VALUE_TEXT_ANTIALIAS_LCD_HBGR,
VALUE_TEXT_ANTIALIAS_LCD_VRGB,

VALUE_TEXT_ANTIALIAS_LCD_VBGR
KEY_RENDERING

. : VALUE_RENDER_SPEED,
VALUE_RENDER_QUALITY, VALUE_RENDER_DEFAULT

KEY_COLOR_RENDERING

. : VALUE_COLOR_RENDER_SPEED,
VALUE_COLOR_RENDER_QUALITY, VALUE_COLOR_RENDER_DEFAULT

KEY_ALPHA_INTERPOLATION

. :
VALUE_ALPHA_INTERPOLATION_SPEED,
VALUE_ALPHA_INTERPOLATION_QUALITY,

VALUE_ALPHA_INTERPOLATION_DEFAULT
KEY_INTERPOLATION

. : VALUE_INTERPOLATION_BILINEAR,
VALUE_INTERPOLATION_BICUBIC,

VALUE_INTERPOLATION_NEAREST_NEIGHBOR
KEY_DITHERING

. : VALUE_DITHER_ENABLE,
VALUE_DITHER_DISABLE, VALUE_DITHER_DEFAULT

KEY_ALPHA_INTERPOLATION

-. :
VALUE_ALPHA_INTERPOLATION_DEFAULT,
VALUE_ALPHA_INTERPOLATION_QUALITY,

VALUE_ALPHA_INTERPOLATION_SPEED
KEY_STROKE_CONTROL

. : VALUE_STROKE_DEFAULT,
VALUE_STROKE_NORMALIZE, VALUE_STROKE_PURE

,
,
.
paint() :
public void paint(Graphics gr){
Graphics2D g = (Graphics2D)gr;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
//
}

256

III.

, "awt.font.desktophints", Map , . :
public void paint(Graphics gr){
Graphics2D g = (Graphics2D)gr;
Toolkit tk = Toolkit.getDefaultToolkit();
Map map = (Map)(tk.getDesktopProperty("awt.font.desktophints"));
if (map != null) g.addRenderingHints(map);
//
}

5. Java 2D.

, , Java 2D.
, , , . 20
Java 2D , 23 .
Java SE, docs/technotes/guides/2d/spec,
Programmer's Guide to the Java 2D API Java 2D. Java 2D. demo/jfc/Java2D/ ,
Java 2D.


1. AWT?
2. AWT?
3. ?
4. ?
5. ?
6. : , ?
7. ?

10

AWT
, AWT .

Swing, SWAT, SWT .
AWT, .
AWT .
. 8.2. Component Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, TextArea, TextField,
Panel, ScrollPane, Window, Dialog, FileDialog, Frame.
MenuItem, MenuBar,
Menu, PopupMenu, CheckboxMenuItem.
, , . 15.

. ,
, Component.

Component
Component AWT . ,
, :
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT,
.
getXXX(), isXXX(), setXXX().
, , .
(protected),
Component , ,
.
, , ,

258

III.

. getSize(),
Dimension, getHeight() getWidth(), .
setSize(Dimension d) setSize(int width, int height),
, .
, . getPreferredSize()
Dimension, setPreferredSize(Dimension).
.
getMinimumSize() getMaximumSize() Dimension.
setMinimumSize(Dimension) setMaximumSize(Dimension).
. (0, 0) , Ox , Oy , .
. getLocation(), setLocation(), , .
,
getBounds(), Rectangle,
, setBounds(),
.
,
- . isEnabled(), setEnabled(boolean enable).

Graphics, paint(), ,
getGraphics().
Color.
getBackground(), setBackground(Color color).
getForeground(),
setForeground(Color color).
Font, getFont() setFont(Font font).
Locale. getLocale(), setLocale(Locale locale).
, ,
Cursor. getCursor(). "" setCursor(Cursor cursor).


Point.

getMousePosition(),

Cursor.

10. AWT

259

Cursor
, :
CROSSHAIR_CURSOR ,

- ;
DEFAULT_CURSOR ;
HAND_CURSOR " ", - -

;
MOVE_CURSOR , ;
TEXT_CURSOR , ;
WAIT_CURSOR , .

:
E_RESIZE_CURSOR ;
N_RESIZE_CURSOR ;
NE_RESIZE_CURSOR , ;
NW_RESIZE_CURSOR , ;
S_RESIZE_CURSOR ;
SE_RESIZE_CURSOR , ;
SW_RESIZE_CURSOR , ;
W_RESIZE_CURSOR .

type
Cursor(int type).

getPredefinedCursor(int type), Cursor


.
getDefaultCursor().
. , :
Cursor curs = new Cursor(Cursor.WAIT_CURSOR);
someComp.setCursor(curs);

someComp .



. CUSTOM_CURSOR.
createCustomCursor(Image cursor, Point hotspot, String name);

Cursor .
cursor Image. , -

260

III.

20. name , null. hotspot .


, , ,
getBestCursorSize(int desiredWidth, int desiredHeight);

Dimension. . , (0, 0). , , (32, 32). cursor , .


getMaximumCursorColors() ,
256, .
java.awt.Toolkit, . Toolkit , Java ,
. Toolkit
,
Toolkit.getDefaultToolkit().
Window , Frame, Toolkit getToolkit() Window.
:
Toolkit tk = Toolkit.getDefaultToolkit();
int colorMax = tk.getMaximumCursorColors(); // .
Dimension d = tk.getBestCursorSize(50, 50); // d .
int w = d.width, h = d.height, k = 0;
Point p = new Point(0, 0);
//
// .
int[] pix = new int[w * h];
// .
for(int i = 0; i < w; i++)
for(int j = 0; j < h; j++)
if (j < i) pix[k++] = 0xFFFF0000;
// .
else pix[k++] = 0;
// .
// (w, h),
// pix, w.
Image im = createImage(new MemoryImageSource(w, h, pix, 0, w));
Cursor curs = tk.createCustomCursor(im, p, null);
someComp.setCursor(curs);

32 someComp.

1. .

ComponentEvent , , .

10. AWT

261

FocusEvent .
KeyEvent , .
MouseEvent .

Container
Container.
Container Component, .
:
add(Component comp) comp ;
add(Component comp, int index) comp index

, index == -1, ;
add(Component comp, Object constraints)

constraints;
add(String name, Component comp) name.

:
remove(Component comp) comp;
remove(int index) index .

(input focus), .
<Tab> <Shift>+<Tab>. requestFocus()
transferFocus(). , ,
hasFocus(). Component.
(layout manager) , LayoutManager
LayoutManager2. -
: , , ,
. " " " index".

. ,
setLayout(LayoutManager manager);

.
,
setLayout(null).

262

III.

Component ComponentEvent, FocusEvent, KeyEvent, MouseEvent


ContainerEvent.

Label
. Label.
Label ,
.
setText(String text), .
:
Label() ;
Label(String text) text,

;
Label(String text, int alignment) text -

, : CENTER, LEFT, RIGHT.


setAlignment(int alignment).
, , Component, getText() getAlignment(),
setText(String) setAlignment(int).

Label Component: ComponentEvent, FocusEvent, KeyEvent,


MouseEvent.

Button
Button.
Button
, "" , "".
, Button() Button(String label),
label .
getLabel() setLabel(String label)
.
, . 15.

10. AWT

263

Component ComponentEvent, FocusEvent, KeyEvent, MouseEvent


ActionEvent.

Checkbox
Button Checkbox, .
Checkbox .
,

(state) on. off.
on "" . Checkbox on/off true/false .
, Checkbox(), Checkbox(String label), Checkbox(String label, boolean state),
, label off state .
getLabel(), setLabel(String label), getState(), setState(boolean state)
.
Checkbox ,
, . 10.1. , .
(radio buttons). , ,
"" .

Checkbox Component: ComponentEvent, FocusEvent,


KeyEvent, MouseEvent, ItemEvent.

CheckboxGroup
AWT . Checkbox
CheckboxGroup.
CheckboxGroup ,
Checkbox, . CheckboxGroup() :
getSelectedCheckbox(), Checkbox;
setSelectedCheckbox(Checkbox box), .

264

III.


,
CheckboxGroup,
Checkbox(String label, CheckboxGroup group, boolean state);
Checkbox(String label, boolean state, CheckboxGroup group);

,
.
state == true.
. 10.1 , Frame Label , Checkbox,
. Button.
. 10.1.
10.1.
import java.awt.*;
import java.awt.event.*;
class SimpleComp extends Frame{
SimpleComp(String s){
super(s);
setLayout(null);
Font f = new Font("Serif", Font.BOLD, 15);
setFont(f);
Label l1 = new Label(" :", Label.CENTER);
l1.setBounds(10, 50, 120, 30); add(l1);
Label l2 = new Label(" :");
l2.setBounds(160, 50, 200, 30); add(l2);
Checkbox ch1 = new Checkbox("");
ch1.setBounds(20, 90, 100, 30); add(ch1);
Checkbox ch2 = new Checkbox("");
ch2.setBounds(20, 120, 100, 30); add(ch2);
Checkbox ch3 = new Checkbox("");
ch3.setBounds(20, 150, 100, 30); add(ch3);
CheckboxGroup grp = new CheckboxGroup();
Checkbox chg1 = new Checkbox(" ", grp, true);
chg1.setBounds(170, 90, 200, 30); add(chg1);
Checkbox chg2 = new Checkbox(" ", grp, false);
chg2.setBounds(170, 120, 200, 30); add(chg2);
Button b1 = new Button("");
b1.setBounds( 30, 220, 100, 30); add(b1);
Button b2 = new Button("");
b2.setBounds(140, 220, 100, 30); add(b2);
Button b3 = new Button("");
b3.setBounds(250, 220, 100, 30); add(b3);

10. AWT

265

setSize(400, 300);
setVisible(true);
}
public static void main(String[] args){
Frame f = new SimpleComp(" ");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
System.exit(0);
}
});
}
}

. 10.1.

, ,
Frame, add(). , setBounds().
.

Choice
, Choice.
Choice , , , (item) ,
.
Choice() .
add(String text) text.
add() .
insert(String text, int position).
select(String text)
select(int position).

266

III.

remove(String text)
remove(int position), removeAll().
getItemCount().
, pos, getItem(int pos), .
, getSelectedIndex(), , getSelectedItem(), .

Choice Component: ComponentEvent, FocusEvent, KeyEvent,


MouseEvent, ItemEvent.

List
, List.
List ,
. .
:
List() ;
List(int rows) rows ;
List(int rows, boolean multiple) , -

, multiple == true.
item:
add(String item) ;
add(String item, int position) position.

, .
remove(String item), remove(int position), removeAll().
replaceItem(String newItem, int pos)
pos.

getItemCount().
getSelectedItem(), getSelectedIndex().
,
String[] getSelectedItems(),
int[] getSelectedIndexes().
List , .

10. AWT

267

Component ComponentEvent, FocusEvent, KeyEvent, MouseEvent


ActionEvent.
10.2 Choice List ,
10.1, . 10.2 , .
10.2.
import java.awt.*;
import java.awt.event.*;
class ListTest extends Frame{
ListTest(String s){
super(s);
setLayout(null);
setFont(new Font("Serif", Font.BOLD, 15));
Label l1 = new Label(" :", Label.CENTER);
l1.setBounds(10, 50, 120, 30); add(l1);
Label l2 = new Label(" :");
l2.setBounds(170, 50, 200, 30); add(l2);
List l = new List(2, true);
l.add("");
l.add("");
l.add("");
l.setBounds(20, 90, 100, 40); add(l);
Choice ch = new Choice();
ch.add(" ");
ch.add(" ");
ch.setBounds(170, 90, 200,30); add(ch);
Button b1 = new Button("");
b1.setBounds( 30, 150, 100, 30); add(b1);
Button b2 = new Button("");
b2.setBounds(140, 150, 100, 30); add(b2);
Button b3 = new Button("");
b3.setBounds(250, 150, 100, 30); add(b3);
setSize(400, 200);
setVisible(true);
}
public static void main(String[] args){
Frame f = new ListTest(" ");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
System.exit(0);
}
});
}
}

268

III.

. 10.2.


AWT :
TextField, , TextArea,
.
TextComponent, ,
, , .

TextComponent
TextComponent , .
getText() String , .
, .
isEditable(), setEditable(boolean editable).
, , String, ( 0). (caret) getCaretPosition(),
setCaretPosition(int ind) .
, , <Shift>, select(int begin, int end).
begin
end .
selectAll().
setSelectionStart(int ind);


setSelectionEnd(int ind);

10. AWT

269

- , .
getSelectedText(),
getSelectionStart() getSelectionEnd().

Component ComponentEvent, FocusEvent, KeyEvent, MouseEvent


TextEvent.

TextField
TextField . (column). ,
. <Enter> , . .
ActionEvent.
:
TextField() ;
TextField(int columns) columns;
TextField(String text) text;
TextField(String text, int columns) text
columns.

, TextComponent, getColumns()
setColumns(int col).
. - -, , - .

echo , .
, -, echoCharIsSet(); - getEchoChar().
setEchoChar(char echo).

,
setEchoChar(0).

Component ComponentEvent, FocusEvent, KeyEvent, MouseEvent


TextEvent,
<Enter> ActionEvent.

TextArea
TextArea . <Enter> .
, .

270

III.

,
TextArea(String text, int rows, int columns, int scrollbars);

text, rows,
columns scrollbars :
SCROLLBARS_NONE, SCROLLBARS_HORIZONTAL_ONLY, SCROLLBARS_VERTICAL_ONLY, SCROLLBARS_BOTH.
:
TextArea(String text, int rows, int columns) ;
TextArea(int rows, int columns) ;
TextArea(String text) ;
TextArea() .

TextArea :
append(String text) text ;
insert(String text, int pos) pos;
replaceRange(String text, int begin, int end) ,
begin

end , text.

Component ComponentEvent, FocusEvent, KeyEvent, MouseEvent


TextEvent.
. 10.3 (tf1, tf2, tf3 , ) , . tf2 - *.
. 10.3.
10.3.
import java.awt.*;
import java.awt.event.*;
class TextTest extends Frame{
TextTest(String s){
super(s);
setLayout(null);
setFont(new Font("Serif", Font.PLAIN, 14));
Label l1 = new Label(" :", Label.RIGHT);
l1.setBounds(20, 30, 70, 25); add(l1);
Label l2 = new Label(":", Label.RIGHT);
l2.setBounds(20, 60, 70, 25); add(l2);
TextField tf1 = new TextField(30);
tf1.setBounds(100, 30, 160, 25); add(tf1);

10. AWT
TextField tf2 = new TextField(30);
tf2.setBounds(100, 60, 160, 25); add(tf2);
tf2.setEchoChar('*');
TextField tf3 = new TextField(" ", 30);
tf3.setBounds(10, 100, 250, 30); add(tf3);
TextArea ta = new TextArea(" :", 5, 50,
TextArea.SCROLLBARS_NONE);
ta.setEditable(false);
ta.setBounds(10, 150, 250, 140); add(ta);
Button b1 = new Button("");
b1.setBounds(280, 180, 100, 30); add(b1);
Button b2 = new Button("");
b2.setBounds(280, 220, 100, 30); add(b2);
Button b3 = new Button("");
b3.setBounds(280, 260, 100, 30); add(b3);
setSize(400, 300);
setVisible(true);
}
public static void main(String[] args){
Frame f = new TextTest(" ");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
System.exit(0);
}
});
}
}

. 10.3.

271

272

III.

Scrollbar
Scrollbar , AWT Scrollbar
(slider). , .

.
.
(unit)
. (bubble, thumb)
. (block)
.
"" "" , . , .
Adjustable, Scrollbar.
Scrollbar :
Scrollbar() 0100, -

0 10 ;
Scrollbar(int orientation) orientation -

: HORIZONTAL VERTICAL;
Scrollbar(int orientation, int value, int visible, int min, int max) ,

, value, visible,
minmax.
visible . ,
0,1 .
getValue()
.
, 15.6.

Component ComponentEvent, FocusEvent, KeyEvent, MouseEvent


AdjustmentEvent.
10.4 ,
, - 0255, 127. ,
, . ,
p Panel.
.
, . 10.4.

10. AWT

. 10.4.

15.6 "" .
10.4.
import java.awt.*;
import java.awt.event.*;
class ScrollTest extends Frame{
Scrollbar sbRed = new Scrollbar(Scrollbar.VERTICAL, 127, 10, 0, 255);
Scrollbar sbGreen = new Scrollbar(Scrollbar.VERTICAL, 127, 10, 0, 255);
Scrollbar sbBlue = new Scrollbar(Scrollbar.VERTICAL, 127, 10, 0, 255);
Color mixedColor = new Color(127, 127, 127);
Label lm = new Label();
Button b1 = new Button("");
Button b2 = new Button("");
ScrollTest(String s){
super(s);
setLayout(null);
setFont(new Font("Serif", Font.BOLD, 15));
Panel p = new Panel();
p.setLayout(null);
p.setBounds(10,50, 150, 260); add(p);
Label lc = new Label(" ");
lc.setBounds(20, 0, 120, 30); p.add(lc);
Label lmin = new Label("0", Label.RIGHT);
lmin.setBounds(0, 30, 30, 30); p.add(lmin);
Label lmiddle = new Label("127", Label.RIGHT);
lmiddle.setBounds(0, 120, 30, 30); p.add(lmiddle);
Label lmax = new Label("255", Label.RIGHT);
lmax.setBounds(0, 200, 30, 30); p.add(lmax);

273

274

III.

sbRed.setBackground(Color.red);
sbRed.setBounds(40, 30, 20, 200); p.add(sbRed);
sbGreen.setBackground(Color.green);
sbGreen.setBounds(70, 30, 20, 200); p.add(sbGreen);
sbBlue.setBackground(Color.blue);
sbBlue.setBounds(100, 30, 20, 200); p.add(sbBlue);
Label lp = new Label(":");
lp.setBounds(250, 50, 120, 30); add(lp);
lm.setBackground(new Color(127, 127, 127));
lm.setBounds(220, 80, 120, 80); add(lm);
b1.setBounds(240, 200, 100, 30); add(b1);
b2.setBounds(240, 240, 100, 30); add(b2);
setSize(400, 300);
setVisible(true);
}
public static void main(String[] args){
Frame f = new ScrollTest(" ");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
System.exit(0);
}
});
}
}

Panel
10.4 Panel. .
Panel ,
Panel.
Panel , . :
Panel() FlowLayout;
Panel(LayoutManager layout) -

layout.

add():
Panel p = new Panel();
p.add(comp1);
p.add(comp2);

. . , .

10. AWT

275

Panel . .
10.4 0, 127 255 . , , . , . p
. setBounds() p,
Frame. , .
,
,
.

ScrollPane
ScrollPane , , .
. , SCROLLBARS_ALWAYS, ,
( )
SCROLLBARS_AS_NEEDED.
, SCROLLBARS_NEVER,

setScrollPosition().
:
ScrollPane() , -

;
ScrollPane(int scrollbars) , -

.
100 100 ,
setSize(int width, int height).
, , ScrollPane , . Panel, .
,
ScrollPane:
getHAdjustable() getVAdjustable()

Adjustable;
getScrollPosition() Point (x, y)

, ScrollPane;
setScrollPosition(Point p) setScrollPosition(int x, int y)

(x, y).

276

III.

Window
Window , : , , , . .
Window , , add().
. , ,
. - , (owner) (parent) Window. , .
:
Window(Frame f) , f;
Window(Window owner) ,

Window.
.
setVisible(true).
setVisible(false), , ,
isShowing().

setIconImage(Image icon);
setIconImages(List<? extends Image> icons);

,
List<Image> getIconImages();

Window , , . Dialog,
PopupMenu.
toFront() , ,
toBack(). setAlwaysOnTop(true)
. , isAlwaysOnTopSupported(). isAlwaysOnTop().
, , dispose().
BorderLayout.
Toolkit,
getToolkit().

Component ComponentEvent, FocusEvent, KeyEvent, MouseEvent


, ,
WindowEvent.

10. AWT

277

Frame
Frame , ,
. setTitle(String title). . setMenuBar(MenuBar mb). .

Java.
setIconImage(Image icon), icon
Image. , 20.
Frame . Frame
, , (task bar) , ""
.
Frame :
Frame() ;
Frame(String title) title ;
Frame(GraphicsConfiguration gc) gc.
Frame(String title, GraphicsConfiguration gc) title

gc.
Frame , ,
Frame Component, Container Window.
, BorderLayout.

Component ComponentEvent, FocusEvent, KeyEvent, MouseEvent


, ,
WindowEvent.
10.5 Frame,
Label.
<Alt>+<F4> System.exit(0), .
dispose(), .
10.5.
import java.awt.*;
import java.awt.event.*;
class TwoFrames{
public static void main(String[] args){
Fr1 f1 = new Fr1(" ");

278

III.
Fr2 f2 = new Fr2(" ");

}
}
class Fr1 extends Frame{
Fr1(String s){
super(s);
setLayout(null);
Font f = new Font("Serif", Font.BOLD, 15);
setFont(f);
Label l = new Label(" ", Label.CENTER);
l.setBounds(10, 30, 180, 30);
add(l);
setSize(200, 100);
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
System.exit(0);
}
});
}
}
class Fr2 extends Frame{
Fr2(String s){
super(s);
setLayout(null);
Font f = new Font("Serif", Font.BOLD, 15);
setFont(f);
Label l = new Label(" ", Label.CENTER);
l.setBounds(10, 30, 180, 30);
add(l);
setBounds(50, 50, 200, 100);
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
dispose();
}
});
}
}

. 10.5 .
, .

. 10.5.

10. AWT

279

Dialog
Dialog ,
. , , , . Dialog, Window, owner, .
Dialog (modal), , .
, , ,
(scope of blocking).
.
, (modality type).

Dialog.ModalityType:
MODELESS ;
DOCUMENT_MODAL , , -

(document root);
APPLICATION_MODAL , -

;
TOOLKIT_MODAL ,

Toolkit.
The
AWT Modality, docs/api/java/awt/doc-files/Modality.html.
Dialog DEFAULT_MODALITY_TYPE, APPLICATION_MODAL
Java SE 6. setModal(true).
, , , Toolkit
isModalityTypeSupported(Dialog.ModalityType modalityType),
modalityType.
. Window
setModalExclusionType(Dialog.ModalExclusionType excType), Dialog.ModalExclusionType:
NO_EXCLUDE ;
APPLICATION_EXCLUDE , APPLICATION_MODAL,

;
TOOLKIT_EXCLUDE , TOOLKIT_MODAL, -

.
- , ,
, Toolkit
isModalExclusionTypeSupported(Dialog.ModalExclusionType excType).

III.

280

Dialog . :
Dialog(Dialog owner) MODELESS

Dialog(Dialog owner, String title)


MODELESS

title;

Dialog(Dialog owner, String title, boolean modal) ,

DEFAULT_MODALITY_TYPE, modal == true;


Dialog(Dialog owner, String title, boolean modal, GraphicConfiguration gc)

, gc.
, , Frame:
Dialog(Frame
Dialog(Frame
Dialog(Frame
Dialog(Frame
Dialog(Frame

owner);
owner, String title);
owner, boolean modal);
owner, String title, boolean modal);
owner, String title, boolean modal, GraphicsConfiguration gc);

, , Window,
Frame.
Dialog , :
Dialog.ModalityType getModalityType();

,
setModalityType(Dialog.ModalityType type);

. type
, MODELESS.
, .
Java SE isModal(),
, setModal(boolean modal), .
, JDK .

Componen ComponentEvent, FocusEvent, KeyEvent, MouseEvent


, ,
WindowEvent.
10.6 , .
, . . 10.6 .
10.6.
import java.awt.*;
import java.awt.event.*;

10. AWT
class LoginWin extends Dialog{
LoginWin(Frame f, String s){
super(f, s, true);
setLayout(null);
setFont(new Font("Serif", Font.PLAIN, 14));
Label l1 = new Label(" :", Label.RIGHT);
l1.setBounds(20, 30, 70, 25); add(l1);
Label l2 = new Label(":", Label.RIGHT);
l2.setBounds(20, 60, 70, 25); add(l2);
TextField tf1 = new TextField(30);
tf1.setBounds(100, 30, 160, 25); add(tf1);
TextField tf2 = new TextField(30);
tf2.setBounds(100, 60, 160, 25); add(tf2);
tf2.setEchoChar('*');
Button b1 = new Button("");
b1.setBounds(50, 100, 100, 30); add(b1);
Button b2 = new Button("");
b2.setBounds(160, 100, 100, 30); add(b2);
setBounds(50, 50, 300, 150);
}
}
class DialogTest extends Frame{
DialogTest(String s){
super(s);
setLayout(null);
setSize(200, 100);
setVisible(true);
Dialog d = new LoginWin(this, " ");
d.setVisible(true);
}
public static void main(String[] args){
Frame f = new DialogTest(" -");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
System.exit(0);
}
});
}
}

281

282

III.

. 10.6.

FileDialog
FileDialog Frame, ( LOAD) (
SAVE). FileDialog
.
:
FileDialog(Frame owner) ;
FileDialog(Frame owner, String title)
title;

FileDialog(Frame owner, String title, int mode) -

; mode :
FileDialog.LOAD FileDialog.SAVE.
,
Dialog, Frame.
getDirectory() getFile()
String.
/, 23.
FileDialog.

setDirectory(String dir) setFile(String fileName).
fileName , *.java
( ), ,
java.
setFilenameFilter(FilenameFilter filter) filter
. , . Sun JDK MS Windows.

Component ComponentEvent, FocusEvent, KeyEvent, MouseEvent


, ,
WindowEvent.

10. AWT

283


,
AWT, Button, TextField -.
, , , Panel, .
, AWT : "" "" . "" AWT Canvas ,
peer- .

Canvas
Canvas . Canvas
Canvas() paint(Graphics g).
"" , Canvas, ,
paint().
, , Button
. .
"" .
10.7 FlowerButton.
paint(). paint(), ,
, , "" .
"".
"" .
, FlowerButton . 15, ,
isDown repaint().
mousePressed() mouseReleased().
Button . 10.7 .
drawFlower(),

10.7.
import java.awt.*;
import java.awt.event.*;
class FlowerButton extends Canvas implements MouseListener{
private boolean isDown=false;
public FlowerButton(){
super();
setBackground(Color.lightGray);

284

III.

addMouseListener(this);
}
public void drawFlower(Graphics g, int x, int y, int w, int h){
g.drawOval(x + 2*w/5 6, y, w/5, w/5);
g.drawLine(x + w/2 6, y + w/5, x + w/2 6, y + h 4);
g.drawOval(x + 3*w/10 6, y + h/3 4, w/5, w/5);
g.drawOval(x + w/2 6, y + h/3 4, w/5, w/5);
}
public void paint(Graphics g){
int w = getSize().width, h = getSize().height;
if (isDown){
g.drawLine(0, 0, w 1, 0);
g.drawLine(1, 1, w 1, 1);
g.drawLine(0, 0, 0, h 1);
g.drawLine(1, 1, 1, h 1);
drawFlower(g, 8, 10, w, h);
}else{
g.drawLine(0, h 2, w 2, h 2);
g.drawLine(1, h 1, w 1, h 1);
g.drawLine(w 2, h 2, w 2, 0);
g.drawLine(w 1, h 1, w 1, 1);
drawFlower(g, 6, 8, w, h);
}
}
public void mousePressed(MouseEvent e){
isDown=true;
repaint();
}
public void mouseReleased(MouseEvent e){
isDown=false;
repaint();
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e){}
}
class DrawButton extends Frame{
DrawButton(String s){
super(s);
setLayout(null);
Button b = new Button("OK");
b.setBounds(200, 50, 100, 60); add(b);
FlowerButton d = new FlowerButton();
d.setBounds(50, 50, 100, 60); add(d);
setSize(400, 150);
setVisible(true);
}

10. AWT

285

public static void main(String[] args){


Frame f = new DrawButton(" ");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
System.exit(0);
}
});
}
}

. 10.7.

""
"" , peer- , Component Container.
, "" peer-.
, 10.7 FlowerButton
class FlowerButton extends Component implements MouseListener{

, "" ,
, , setBackground(Color.lightGray)
.
,
peer- , "" ,
, Frame. ,
setBackground(), , paint().
setBackground()
paint(), 10.8.
"" "" , paint() "" paint()
:
super.paint(g);

"" -.
"" , "" .

paint() "" paint() .

III.

286

"" peer-,
"" , getPreferredSize(),
, FlowLayout(),
, .

getPreferredSize().

"" , .
. 10.8 , paint() 10.7 , . 10.8 .
10.8.
public void paint(Graphics g){
int w = getSize().width, h = getSize().height;
int d = Math.min(w, h);
//
Color c = g.getColor();
//
g.setColor(Color.lightGray);
//
g.fillArc(0, 0, d, d, 0, 360); //
g.setColor(c);
//
if (isDown){
g.drawArc(0, 0, d, d, 43, 180);
g.drawArc(1, 1, d 2, d 2, 43, 180);
drawFlower(g, 8, 10, d, d);
}else{
g.drawArc(0, 0, d, d, 229, 162);
g.drawArc(1, 1, d 2, d 2, 225, 170);
drawFlower(g, 6, 8, d, d);
}
}
public Dimension getPreferredSize(){
return new Dimension(30,30);
}
public Dimension getMinimumSize(){
return getPreferredSize();
}
public Dimension getMaximumSize(){
return getPreferredSize();
}

. 10.8.

10. AWT

287

. "" . "" enableEvents() . FlowerButton


enableEvents(AWTEvent.MOUSE_EVENT_MASK);

, "" . 15.

2. .


Frame
(menu bar), , . 10.9. MenuBar.

. 10.9.

, Frame,
MenuBar setMenuBar():
Frame f = new Frame(" ");
MenuBar mb = new MenuBar();
f.setMenuBar(mb);

mb , :
f.setMenuBar(new MenuBar());

, .
(drop-down menu )
Menu.
,
:
Menu mFile = new Menu("");
mb.add(mFile);

288

III.

Menu mEdit = new Menu("");


mb.add(mEdit);
Menu mView = new Menu("");
mb.add(mView);
Menu mHelp = new Menu("");
mb.setHelpMenu(mHelp);

. . add(),
. 10.9. (Help)
.
setHelpMenu(),
.
, . MenuItem.
, :
MenuItem create = new MenuItem("");
mFile.add(create);
MenuItem open = new MenuItem("...");
mFile.add(open);

. .
add().
. . . 10.9 . addSeparator() Menu
:
mFile.add(new MenuItem("-"));

, Menu MenuItem, . ,
, :
Menu send = new Menu("");
mFile.add(send);

send mFile . send , .


- ,
Checkbox. .
CheckboxMenuItem:
CheckboxMenuItem disk = new CheckboxMenuItem(" A:", true);
send.add(disk);
send.add(new CheckboxMenuItem(""));

. .
, , . 10.9.

10. AWT

289

, MS Windows, (tear-off) , .
Menu(String label, boolean tearOff);

tearOff == true ,
. .
, . MenuItem ActionEvent, , -
create.addActionListener(new SomeActionEventHandler());
open.addActionListener(new AnotherActionEventHandler());

CheckboxMenuItem ItemEvent, - :
disk.addItemListener(new SomeItemEventHandler());

, ,
, "" - (shortcut),
<Ctrl>. , "" , Ctrl+N, Ctrl+O. ""
MenuShortcut KeyEvent, :
MenuShortcut keyCreate = new MenuShortcut(KeyEvent.VK_N);

"" <Ctrl>+<N>. MenuItem:


MenuItem create = new MenuItem("", keyCreate);

<Ctrl>+<N> . ,
, , :
MenuItem open = new MenuItem("...", new MenuShortcut(KeyEvent.VK_O));

<Shift>. <Shift>+<Ctrl>+<X>, :
MenuShortcut(int key, boolean useShift);

useShift == true.
10.9 . 15. . 10.10.
10.9.
import java.awt.*;
import java.awt.event.*;
public class MenuScribble extends Frame{
public MenuScribble(String s){
super(s);

290

III.

ScrollPane pane = new ScrollPane();


pane.setSize(300, 300);
add(pane, BorderLayout.CENTER);
Scribble scr = new Scribble(this, 500, 500);
pane.add(scr);
MenuBar mb = new MenuBar();
setMenuBar(mb);
Menu f = new Menu("");
Menu v = new Menu("");
mb.add(f); mb.add(v);
MenuItem open = new MenuItem("...",
new MenuShortcut(KeyEvent.VK_O));
MenuItem save = new MenuItem("",
new MenuShortcut(KeyEvent.VK_S));
MenuItem saveAs = new MenuItem(" ...");
MenuItem exit = new MenuItem("",
new MenuShortcut(KeyEvent.VK_Q));
f.add(open); f.add(save); f.add(saveAs);
f.addSeparator(); f.add(exit);
open.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
FileDialog fd = new FileDialog(new Frame(),
" ", FileDialog.LOAD);
fd.setVisible(true);
}
});
saveAs.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
FileDialog fd = new FileDialog(new Frame(),
" ", FileDialog.SAVE);
fd.setVisible(true);
}
});
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
Menu c = new Menu("");
MenuItem clear = new MenuItem("",
new MenuShortcut(KeyEvent.VK_D));
v.add(c); v.add(clear);
MenuItem red = new MenuItem("");
MenuItem green = new MenuItem("");

10. AWT
MenuItem blue = new MenuItem("");
MenuItem black = new MenuItem("");
c.add(red); c.add(green); c.add(blue); c.add(black);
red.addActionListener(scr);
green.addActionListener(scr);
blue.addActionListener(scr);
black.addActionListener(scr);
clear.addActionListener(scr);
addWindowListener(new WinClose());
pack();
setVisible(true);
}
class WinClose extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
public static void main(String[] args){
new MenuScribble(" \"\" ");
}
}
class Scribble extends Component implements
ActionListener, MouseListener, MouseMotionListener{
protected int lastX, lastY, w, h;
protected Color currColor = Color.black;
protected Frame f;
public Scribble(Frame frame, int width, int height){
f = frame; w = width; h = height;
enableEvents(AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK);
addMouseListener(this);
addMouseMotionListener(this);
}
public Dimension getPreferredSize(){
return new Dimension(w, h);
}
public void actionPerformed(ActionEvent event){
String s = event.getActionCommand();
if (s.equals("")) repaint();
else if (s.equals("")) currColor = Color.red;
else if (s.equals("")) currColor = Color.green;
else if (s.equals(""))
currColor = Color.blue;
else if (s.equals("")) currColor = Color.black;
}
public void mousePressed(MouseEvent e){
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == 0) return;
lastX = e.getX(); lastY = e.getY();
}

291

292

III.

public void mouseDragged(MouseEvent e){


if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == 0) return;
Graphics g = getGraphics();
g.setColor(currColor);
g.drawLine(lastX, lastY, e.getX(), e.getY());
lastX = e.getX(); lastY = e.getY();
}
public void mouseReleased(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseMoved(MouseEvent e){}
}

. 10.10.


(popup menu) (context) .
, . Java PopupMenu. Menu, , MenuItem.
MenuBar Menu , . Component
add(PopupMenu menu).
, TextField TextArea, . .
. , ,
getComponent() MouseEvent, 10.10.

10. AWT

293

, PopupMenu
,
(x, y) comp. , ,
getComponent(). comp ,
, .
show(Component comp, int x, int y),

MS Windows ,
Motif ,
. , MouseEvent
isPopupTrigger(), ,
. ,
, , . .
show().
- . isPopupTrigger()
processMouseEvent().
10.9, Scribble
. , . 10.10, . 10.11 MS Windows.
10.10.
import java.awt.*;
import java.awt.event.*;
public class PopupMenuScribble extends Frame{
public PopupMenuScribble(String s){
super(s);
ScrollPane pane = new ScrollPane();
pane.setSize(300, 300);
add(pane, BorderLayout.CENTER);
Scribble scr = new Scribble(this, 500, 500);
pane.add(scr);
addWindowListener(new WinClose());
pack();
setVisible(true);
}
class WinClose extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
public static void main(String[] args){
new PopupMenuScribble(" \"\" ");
}
}

294

III.

class Scribble extends Component implements ActionListener{


protected int lastX, lastY, w, h;
protected Color currColor = Color.black;
protected Frame f;
protected PopupMenu c;
public Scribble(Frame frame, int width, int height){
f = frame; w = width; h = height;
enableEvents(AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK);
c = new PopupMenu("");
add(c);
MenuItem clear = new MenuItem("",
new MenuShortcut(KeyEvent.VK_D));
MenuItem red = new MenuItem("");
MenuItem green = new MenuItem("");
MenuItem blue = new MenuItem("");
MenuItem black = new MenuItem("");
c.add(red); c.add(green); c.add(blue); c.add(black);
c.addSeparator(); c.add(clear);
red.addActionListener(this);
green.addActionListener(this);
blue.addActionListener(this);
black.addActionListener(this);
clear.addActionListener(this);
}
public Dimension getPreferredSize(){
return new Dimension(w, h);
}
public void actionPerformed(ActionEvent event){
String s = event.getActionCommand();
if (s.equals("")) repaint();
else if (s.equals("")) currColor = Color.red;
else if (s.equals("")) currColor = Color.green;
else if (s.equals(""))
currColor = Color.blue;
else if (s.equals("")) currColor = Color.black;
}
public void processMouseEvent(MouseEvent e){
if (e.isPopupTrigger())
c.show(e.getComponent(), e.getX(), e.getY());
else if (e.getID() == MouseEvent.MOUSE_PRESSED){
lastX = e.getX(); lastY = e.getY();
}
else super.processMouseEvent(e);
}
public void processMouseMotionEvent(MouseEvent e){
if (e.getID() == MouseEvent.MOUSE_DRAGGED){
Graphics g = getGraphics();

10. AWT

295

g.setColor(currColor);
g.drawLine(lastX, lastY, e.getX(), e.getY());
lastX = e.getX(); lastY = e.getY();
}
else super.processMouseMotionEvent(e);
}
}

. 10.11.


1. Container Component, ?
2. ?
3. Component ?
4. Label, ?
5. ?
6. TextField TextArea?
7. Frame, Window?
8. "" "" ?

11


Swing
Java Platform, Standard Edition (Java SE), ,
GUI (Graphical User Interface). JFC (Java Foundation Classes). JFC :
AWT (Abstract Window Toolkit) "" (heavyweight) ,
java.awt . ;
Swing "" (lightweight) ,
AWT.
javax.swing;
Java 2D AWT, , , , . 9;
DnD (Drag and Drop) ,
(clipboard).
java.awt.datatransfer java.awt.dnd;
Input Method Framework /.
java.awt.im java.awt.im.spi;
Accessibility /: , .
javax.accessibility.

Java Swing. ,
Java Runtime Environment (JRE). , JRE, Oracle Java Plug-in,
http://www.oracle.com/technetwork/java/index-jsp-141438.html/ ,
Swing. Java Plug-in JRE
, , JRE.
, <OBJECT> <EMBED>,
.

11. Swing

297

Java SE
SwingSet2, $JAVA_HOME/demo/jfc/SwingSet2/. Swing.
. Swing,
SwingSet2.html. Swing
, Java Plug-in
SwingSet2Plugin.html.

Swing
Swing . ,
.
.
, Swing, , "" , .
, javax.swing. .
11.1 , Swing.
11.1. , Swing
import java.awt.*;
import javax.swing.*;

// AWT.
// Swing.

public class SwingApplicationTemplate extends JFrame{


public SwingApplicationTemplate(String title){
// .
super(title);
// .
// JDK 5.0 .
Container c = getContentPane();
// .
c.add(xxxx);
// ...
// .
setSize(500, 400);
// .
setDefaultCloseOperation(EXIT_ON_CLOSE);
// .
setVisible(true);
}

298

III.

public static void main(String[] args){


new SwingApplicationTemplate(" ");
}
}

( JColorChooser),
javax.swing.colorchooser.
( )
JFileChooser, javax.swing.filechooser.
JTable
javax.swing.table.
, JTree,
javax.swing.tree.

javax.swing.text. ,
, ,
.
(undo/redo) javax.swing.undo.
javax.swing.text.html javax.swing.text.rtf
HTML RTF,
javax.swing.text.html.parser HTML-.
, , javax.swing.border.
, javax.swing.plaf.*
(Look and Feel, L&F) .
.
. , , , : MS Windows, CDE/Motif, Macintosh,
""
. , (Pluggable Look and Feel, PL&F, PLAF plaf)
.
javax.swing.plaf.multi.
Java , "Java Look and Feel",
"Metal". ""
, , ,
. "" Java L&F
javax.swing.plaf.metal Java.
http://java.sun.com/products/jlf/ Java L&F "Java Look and Feel Design

11. Swing

299

Guidelines". , Swing, ,
, . Swing ,
"The Java Tutorial. A practical
guide for programmers", http://download.oracle.com/javase/
tutorial/.
Swing.

Swing
Swing :
, , , , , , , . javax.swing. .
JComponent.

JComponent
Swing
JComponent. JComponent Container, AWT. JComponent . Container, ,
Component, .
Container JComponent, . Swing
JComponent, .
JComponent , .
, "" , , .
, , .
JComponent Swing.
.
JComponent
setBorder(Border).


setOpaque(boolean).


setBackground(Color).

setFont(Font)

setForeground(Color).
Graphics,

,
paint(Graphics).

300

III.

setCursor(Cursor).

, .
, -

, . setToolTipText(String).
, -

setMinimumSize(Dimension), setMaximumSize(Dimension)
,

setPreferredSize(Dimension)
setLocale(Locale).

KeyEvent MouseEvent,
MouseWheelEvent,
ComponentEvent

FocusEvent,
ContainerEvent.

Swing MVC.

MVC Swing
-- (MVC, Model-View-Controller) 3. .
, Model, ,
, ,
, . setXXX()
.
, View. , ,
, : , , . , - . getXxx() isXxx() .
, Controller, . , setXxx()
, . .
. , ,
setXxx() , . ,
, , .
"-"
(subscribe-publish). , fireXxx(), , getXxx() isXxx() .
Swing , . , Swing . -

11. Swing

301

, .
, , . 11.1.
11.1. ,

BoundedRangeModel

DefaultBoundedRangeModel

ButtonModel

DefaultButtonModel
JToggleButton.ToggleButtonModel

ComboBoxModel

DefaultComboBoxModel

MutableComboBoxModel
ListModel

AbstractListModel
DefaultListModel

ListSelectionModel

DefaultListSelectionModel

SingleSelectionModel

DefaultSingleSelectionModel

ColorSelectionModel

DefaultColorSelectionModel

SpinnerModel

AbstractSpinnerModel
SpinnerDateModel
SpinnerListModel
SpinnerNumberModel

TableColumnModel

DefaultTableColumnModel

TableModel

DefaultTableModel

TreeModel

DefaultTreeModel

TreeSelectionModel

DefaultTreeSelectionModel
JTree.EmptySelectionModel


. , ,
, , .
MVC Swing (delegation)
, (delegate) xxxModel. , , model -,
getModel(), model.
, JTable -:
protected TableColumnModel columnModel;
protected TableModel dataModel;
protected ListSelectionModel selectionModel;

302

III.

, , :
TableColumnModel getColumnModel();
TableModel getModel();
ListSelectionModel getSelectionModel();

PL&F. JComponent ui - ComponentUI


javax.swing.plaf, . - paint() update(),
. ComponentUI. javax.swing.plaf . UI (User Interface), : ButtonUI, BasicButtonUI.
, getUI().
, , ,
JTable getXxx(), ,
:
public int getRowCount(){
return getModel().getRowCount();
}

.
. , , - , , xxxModel. setModel(xxxModel). , .

JLabel
JLabel. .
JLabel()

,
setText(String) setIcon(Icon).
JLabel(String) JLabel(Icon) -

String,
, Icon, ImageIcon.
, .
JLabel(String, int) JLabel(Icon, int)

LEFT, CENTER, RIGHT, LEADING TRAILING SwingConstants.

11. Swing

303

JLabel. LEADING TRAILING . ,


, , .
setHorizontalAlignment(int). setVerticalAlignment(int)
TOP, CENTER BOTTOM.
, JLabel(String, Icon, int), , ,

, .
setHorizontalTextPosition(int)
setVerticalTextPosition(int) . 4 .
setIconTextGap(int).
, :
JLabel l = new JLabel("- ", JLabel.RIGHT);
l.setVerticalAlignment(JLabel.TOP);

JLabel ,
, 10 ,
:
JLabel l = new JLabel("",
new ImageIcon("myimage.gif"), JLabel.CENTER);
l.setHorizontalTextPosition(JLabel.LEFT);
l.setIconTextGap(10);

, Swing "" HTML


, , , :
l.setText("<html> <font color=\"red\"><p>");

!
<html> , , .

, . , ,
<br> <p>.
. JLabel
setLabelFor(Component). - , ,

setDisplayedMnemonic('A');


setDisplayedMnemonic(KeyEvent.VK_A);

java.awt.event. A
. <Alt>+<A>

304

III.

( JLabel ). HTML , ,
, <u>.
, . setDisplayedMnemonicIndex(int)
. .
JLabel setEnabled(false)
. ,
, setDisabledIcon(Icon).
JLabel
, , JComponent, Container Component. setForeground(Color), setFont(Font),
setBackground(Color). , JLabel ,
,
setOpaque(true). setBorder(Border).
setToolTipText(String).
, .

Swing , . 11.1.
JMenuItem, JCheckBox,
JRadioButton.

. 11.1.

AbstractButton, ,
. , .
AbstractButton ActionEvent,
, ChangeEvent javax.swing.event, : ,
, . ., ItemEvent,
.
setText(String) setIcon(Icon).

11. Swing

305

JLabel, setDisabledIcon(Icon) , , . . ,
setEnabled(false).
setDisabledSelectedIcon(Icon).
, setRolloverIcon(Icon),
setRolloverEnabled(true). .

setSelectedIcon(Icon),
setRolloverSelectedIcon(Icon), setPressedIcon(Icon). .
, , , ,
,
. , .
setMnemonic(int)
java.awt.event.KeyEvent .
, .
JLabel, ,

setDisplayedMnemonicIndex(int) .
setToolTipText(String).
AbstractButton DefaultButtonModel,
ButtonModel. .
"" (rollover),
. setRollover(boolean) , isRollover().
"" (armed) . setArmed(boolean), isArmed().
"" (pressed) ""
. setPressed(boolean)
isPressed().
"" (selected),
setSelected(boolean) isSelected().
, "" (enabled) "" (disabled)
setEnabled(boolean) isEnabled().
AbstractButton setEnabled(boolean) isEnabled(), DefaultButtonModel, getModel().
, , AbstractButton,
, . , AbstractButton, JButton.

306

III.

JButton
JButton ,
Jlabel, / .
,
setHorizontalAlignment(int);
setVerticalAlignment(int);
setHorisontalTextPosition(int);
setVerticalTextPosition(int);
setIconTextGap(int);

, Jlabel, . , , .
JButton : JButton(), JButton(String)
Jbutton(Icon), JButton(String, Icon). , JButton(Action), , Action.
AbstractButton, JButton
. :
ImageIcon def = new ImageIcon("default.gif");
JButton b = new JButton("<html><u></u>", def);
b.setBackground(new Color(183, 220, 65));
b.setFont(new Font("Lucida", Font.ITALIC, 12));
b.setPreferredSize(new Dimension(100, 30));
b.setMnemonic(KeyEvent.VK_L);
b.setToolTipText(" ");
b.setRolloverEnabled(true);
b.setRolloverIcon(new ImageIcon("rollover.gif"));
b.setSelectedIcon(new ImageIcon("select.gif"));
b.setRolloverSelectedIcon(new ImageIcon("rollselect.gif"));
b.setPressedIcon(new ImageIcon("press.gif"));
b.setDisabledIcon(new ImageIcon("disable.gif"));
b.setDisabledSelectedIcon(new ImageIcon("disselect.gif"));
b.setActionCommand("next");
b.addActionListener(this);
b.addChangeListener(this);
b.addItemListener(this);

JButton ActionEvent,
, ChangeEvent,
, ItemEvent. ,
ComponentEvent ContainerEvent, .

JToggleButton
JToggleButton ,
, true/false,

11. Swing

307

"" . L&F ,
""
. isSelected(),
setSelected(boolean).
JToggleButton .
JToggleButton(String, Icon, boolean);

, true false.
- , false.
HTML. JToggleButton(Action)
, Action.
11.2 .
11.2.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class DummyToggleButton extends JFrame{
private JToggleButton tb;
public DummyToggleButton(){
tb = new JToggleButton("<html><u></u>?<p>?");
tb.setMnemonic(KeyEvent.VK_L);
tb.setToolTipText(" ");
add(tb);
// JDK 5.0
// getContentPane().add(tb);
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new DummyToggleButton();
}
}

JToggleButton
.
JCheckBox JRadioButton.

308

III.

JCheckBox
JCheckBox
, : true false.
L&F.
JCheckBox .
JCheckBox(String, Icon, boolean), , JToggleButton.
JCheckBox
, JToggleButton.

JRadioButton
,
JRadioButton(String, Icon, boolean), ,
JToggleButton.
JRadioButton
, JToggleButton.
,
. ButtonGroup,
add(AbstractButton).
, . , ,
, . 11.3 . . . 11.2 .
11.3.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
class RadioButtonTest extends JFrame{
public RadioButtonTest(){
setBackground(Color.white);
setLayout(new FlowLayout());
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.setBorder(BorderFactory.createEtchedBorder());
JRadioButton rb1 =
new JRadioButton("<html><u></u><p>");
rb1.setMnemonic(KeyEvent.VK_R);
rb1.setToolTipText("<html> <p> ");

11. Swing

309

rb1.addActionListener(this);
rb1.setActionCommand("red");
JRadioButton rb2 =
new JRadioButton("<html><u></u><p>");
rb2.setMnemonic(KeyEvent.VK_P);
rb2.setToolTipText("<html> <p> ");
rb2.addActionListener(this);
rb2.setActionCommand("green");
JRadioButton rb3 =
new JRadioButton("<html><u></u><p>");
rb3.setMnemonic(KeyEvent.VK_C);
rb3.setToolTipText("<html> <p> ");
rb3.addActionListener(this);
rb3.setActionCommand("blue");
ButtonGroup bg = new ButtonGroup();
bg.add(rb1); bg.add(rb2); bg.add(rb3);
p.add(rb1); p.add(rb2); p.add(rb3);
add(p);
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new RadioButtonTest();
}
}

. 11.2.

JRadioButton,
. ,
.
Swing : JList
JComboBox.

1. 10.1 Swing.

310

III.

JComboBox
JComboBox. , , . JPopupMenu.
JComboBox(), addItem(Object)
insertItemAt(Object, int).

JComboBox(Object[]) JComboBox(Vector),
, . :
String[] data = {"", "", ""};
JComboBox cb = new JComboBox(data);

, , , ,
JComboBox(ComboBoxModel) , .
, :
Object[] data = {new ImageIcon("apple.gif"),
new ImageIcon("grape.gif"),
new ImageIcon("pear.gif")};
JComboBox fruits = new JComboBox(data);

. . " " .
. - , setSelectedItem(Object)
setSelectedIndex(int). null 1 , . ,
.
setEditable(true). ,
ComboBoxEditor.
BasicComboBoxEditor,
JTextField.

, , getSelectedItem().
HTML ,
BasicComboBoxEditor
"" ASCII- getSelectedItem().
.
,
setMaximumRowCount(int);

11. Swing

311

, , .
( <Enter>)
ActionEvent ItemEvent,
PopupMenuEvent.
getSelectedItem(), getSelectedIndex().
JComboBox DefaultComboBoxModel,
: ListModel, ComboBoxModel MutableComboBoxModel,
AbstractListModel.
, JComboBox,
. DefaultComboBoxModel ListDataEvent, JComboBox. ActionEvent ItemEvent.
, JComboBox - ActionListener,
EventListener, ListDataListener, .
. JComboBox Item, getItemAt(int).
DefaultComboBoxModel getElementAt(int).
.
, JComboBox
. . "
" .

JList
JList. , ,
. JList(),
,
JList(Object[]), JList(Vector) JList(ListModel). ,
JComboBox.
JList .
, JScrollPane.
setVisibleRowCount(int). C :
JFrame f = new JFrame();
String[] data = {"", "<html><font color=red>", ""};
JList list = new JList(data);
list.setVisibleRowCount(2);
list.addListSelectionListener(this);
JScrollPane sp = new JScrollPane(list);
f.getContentPane().add(sp);

312

III.

, JComboBox, JList
, .
,
<Ctrl> .
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

.

SINGLE_INTERVAL_SELECTION.
ListSelectionModel DefaultListSelectionModel.
JList . -
, ListSelectionModel

setSelectionModel(ListSelectionModel).
() getSelectedValue(),
Object[] getSelectedValues(). getSelectedIndex(), getSelectedIndices().
ListSelectionModel JList . ListModel
AbstractListModel. JList DefaultListModel. DefaultListModel
delegate Vector
Vector, -, :
public Object getElementAt(int index){
return delegate.elementAt(index);
}

JList ListSelectionEvent, . , ,
ListDataEvent, .


JList JComboBox ,
String Icon.

. , -.
, . , design pattern, Flyweight.

-, , . -
ListCellRenderer,
public Component getListCellRendererComponent(
JList list,
// ,

11. Swing
Object value,
int index,
boolean isSelected,
boolean cellHasFocus
);

//
//
//
//

313

,

?
?

value, index.
, , isSelected (
) cellHasFocus
( ).
paint().
Swing ListCellRenderer BasicComboBoxRenderer
DefaultListCellRenderer, JLabel. ,
JLabel,
. ,
JComboBox , . BasicComboBoxRenderer
. JList, , . ListCellRenderer. :
public class DefaultListCellRenderer extends JLabel
implements ListCellRenderer, Serializable{
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus){
setComponentOrientation(list.getComponentOrientation());
if (isSelected){
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}else{
setBackground(list.getBackground());
setForeground(list.getForeground());
}
if (value instanceof Icon){
setIcon((Icon)value);
setText("");
}else{
setIcon(null);
setText((value == null) ? "" : value.toString());
}
setEnabled(list.isEnabled());
setFont(list.getFont());
setBorder((cellHasFocus) ?
UIManager.getBorder("List.focusCellHighlightBorder") :
noFocusBorder);

314

III.

return this;
}
. . . . .
}

,
JList Icon,
String. toString(),
JLabel. , if(value
instanceof Icon)
JLabel
setText(((JLabel)value).getText());
setIcon(((JLabel)value).getIcon());

JLabel.
. getSelectedValue() - , JLabel.toString(), . ,
JLabel, toString().
, , ,
String Icon, ,
. ,
getXxx()/setXxx(), toString(), paint().
JList(Object[])
getListCellRendererComponent() value.
ListCellRenderer.
JLabel JPanel.

2. 10.2 Swing.

JSpinner

,
.
JSpinner().
0, 1, 1,
.
JSpinner(SpinnerModel)
. SpinnerModel,
AbstractSpinnerModel
. SpinnerDateModel , ,
SpinnerListModel , List, , Object[]. SpinnerNumberModel Number.

11. Swing

315

, :
JSpinner sp = new JSpinner(new SpinnerNumberModel(50, 0, 100, 5));

50, 0 100
5. ,
47, 42, 52.
SpinnerNumberModel
SpinnerNumberModel(double current, double min, double max, double step);


SpinnerNumberModel(Number current, Comparable min, Comparable max, Number step);

min max null, .


, JSpinner getValue(), getPreviousValue() getNextValue() . Object. , null.
, <Enter>,
ChangeEvent. :
sp.addChangeListener(this);
// . . . .
public void stateChanged(ChangeEvent e){
comp.setValue((int)sp.getValue());
}

, SpinnerDateModel,
. SpinnerDateModel()
, ,
, .

SpinnerDateModel(Date value, Comparable first,


Comparable last, Date step);

value, first last


step. null,
. step : ERA, YEAR, MONTH, WEEK_OF_YEAR, WEEK_OF_MONTH,
DAY_OF_MONTH, DAY_OF_YEAR, DAY_OF_WEEK, DAY_OF_WEEK_IN_MONTH, AM_PM, HOUR, HOUR_OF_DAY, MINUTE,
SECOND, MILLISECOND Calendar.

SpinnerListModel. SpinnerListModel(Object[])
, :
String[] data = {"", "", "", ""};
SpinnerListModel model = new SpinnerListModel(data);
JSpinner emp = new JSpinner(model);

316

III.

, SpinnerListModel(List), , List, Vector.


, ,
toString() . , , JSpinner,
JFormattedTextField. JSpinner DefaultEditor DateEditor, ListEditor NumberEditor.

JScrollBar
Swing.
JScrollPane,
11.3, .
-, . minimum, maximum,
value extent.
, ,
. BoundedRangeModel.
ChangeEvent. JScrollBar
DefaultBoundedRangeModel .

JScrollBar(int orientation, int value, int extent, int min, int max);

JScrollBar(int orientation), min = 0,


max = 100, value = 0, extent = 10.
VERTICAL HORIZONTAL.
setMinimum(int), setMaximum(int),
setValue(int) setExtent(int).
getValue(). getUnitIncrement(int) ,
1, , 1. 1
setUnitIncrement(int).
getBlockIncrement(int)
. extent,
setBlockIncrement(int).
AdjustmentEvent, .

JSlider
, value minmax. , .
JSlider DefaultBoundedRangeModel
, , . ,

11. Swing

317

, JSlider(BoundedRangeModel)
setModel(BoundedRangeModel).
:
JSlider(int orientation, int min, int max, int value);

,
min = 0, max = 100, value = (min + max)/2.
,
, setMajorTickSpacing(int).
.
setPaintTicks(true).
setPaintLabels(true).
setMinorTickSpacing(int). setSnapToTicks(true),
.
setPaintTrack(false), .
.
createStandardLabels(int incr, int start) ,
incr start.
setLabelTable(Dictionary). ,
:
JSlider sl = new JSlider();
sl.setMajorTickSpacing(10);
sl.setMinorTickSpacing(5);
sl.setPaintTicks(true);
sl.setPaintLabels(true);
sl.setLabelTable(sl.createStandardLabels(20, 28));

28, 48, 68, 88, . 11.3.

. 11.3. JSlider

setLabelTable(Dictionary) , , -
Dictionary.
SliderUI. BasicSliderUI MultiSliderUI. . 11.3 BasicSliderUI MetalSliderUI.
-,
setUI(SliderUI).

318

III.

ChangeEvent. getValue().

3. 10.4, Swing.

JProgressBar
, "", , . - .
JProgressBar(int orientation, int min, int max);

min max . .
, min = 0, max = 100.
setValue(int). . setStringPainted(true) .
, , ,
(indeterminate mode). setIndeterminate(true). , ,
. , setMaximum(int),
setValue(int) setIndeterminate(false).
ProgressBarUI.
BasicProgressBarUI MultiProgressBarUI. Java
L&F MetalProgressBarUI.
setUI(ProgressBarUI).
,
ProgressMonitor.

JTree
JTree .
, . 0 (root) , 1, 2 . . (child) (node) ,
(parent). (leaf). , .
,
JTree. TreeNode MutableTreeNode. ,

11. Swing

319

, .
DefaultMutableTreeNode javax.swing.tree.
JTree DefaultMutableTreeNode(Object),
.
DefaultMutableTreeNode ,
getParent(). null, ,
, isRoot().
Vector, getXxx(). getLevel() , getDepth() , . insert(MutableTreeNode, int) ,
. setUserObject(Object) ,
.
setEditable(true). TreeCellEditor. DefaultTreeCellEditor, JTreeField.
JTree . JTree(TreeNode), ,
.
:
DefaultMutableTreeNode root = new DefaultMutableTreeNode("");
JTree tr = new JTree(root);
DefaultMutableTreeNode subtree1 = new DefaultMutableTreeNode(" 1");
root.add(subtree1);
subtree1.add(new DefaultMutableTreeNode(" 2a"));
DefaultMutableTreeNode subtree2 = new DefaultMutableTreeNode(" 2");
subtree1.add(subtree2);
subtree2.add(new DefaultMutableTreeNode(" 3a"));
subtree2.add(new DefaultMutableTreeNode(" 3b"));
subtree2.add(new DefaultMutableTreeNode(" 3c"));
subtree1.add(new DefaultMutableTreeNode(" 2b"));
root.add(new DefaultMutableTreeNode(" 1"));
// . ....

String.
. 11.4.
,
toString().

JTree(Vector). .
:

320

III.

Vector root = new Vector();


Vector subtree1 = new Vector();
root.add(subtree1);
subtree1.add(" 2a");
Vector subtree2 = new Vector();
subtree1.add(subtree2);
subtree2.add(" 3a");
subtree2.add(" 3b");
subtree2.add(" 3c");
subtree1.add(" 2b");

. 11.4. JTree

root.add(" 1");
JTree tr = new JTree(root);

, , ,
. , ,
.
JTree(Hashtable),
-.
:
Hashtable root = new Hashtable();
Hashtable subtree1 = new Hashtable();
root.put(" 1", subtree1);
Hashtable subtree2
subtree1.put("
subtree1.put("
subtree2.put("
subtree2.put("
subtree2.put("
subtree1.put("

= new Hashtable();
2a", new Integer(21));
2", subtree2);
3a", new Integer(31));
3b", new Integer(32));
3c", new Integer(33));
2b", new Integer(22));

root.put(" 1", new Integer(1));


JTree tr = new JTree(root);

" ", -,
. . ,
, -, . . ""
.
JScrollPane
, , setVisibleRowCount(int), :
JTree tr = new JTree(root);
JScrollPane sp = new JScrollPane(tr);
tr.setVisibleRowCount(8);

11. Swing

321

.
, , 0. getSelectionRows()
int[] . ,
RowMapper. javax.swing.tree AbstractLayoutCache, , :
FixedHeightLayoutCache VariableHeightLayoutCache.
,
, .
TreePath. getSelectionPath() ,
getSelectionPaths() .
TreePath .
TreePath, Object[] , , getPath().
, . TreePath .
, TreeSelectionModel DefaultTreeSelectionModel.
TreePath[] . :
SINGLE_TREE_SELECTION, CONTIGUOUS_TREE_SELECTION DISCONTIGUOUS_TREE_SELECTION.
. tr :
tr.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);

TreeSelectionEvent, . ,
TreeSelectionEvent , getPaths() TreePath[].
,
TreeModel. . . DefaultTreeModel, JTree , , TreeNode.
TreeModelEvent, .
, , getTreePath() TreePath
, , .
JList JTree , TreeCellRenderer.
:
Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf,
int row, boolean hasFocus);

III.

322

, value tree row ,


selected, expanded,
leaf hasFocus.
DefaultTreeCellRenderer,
JLabel. , .
Java SE JDK ,
$JAVA_HOME/demo/jfc/SampleTree/. ,
.

Swing
, Swing: , ,
, , MenuElement.
- , , getSubElements()
.

JFrame, JApplet, JDialog setJMenuBar(JMenuBar). .

JMenuBar
JMenuBar().
, add(JMenu) .
add(JMenu). (Help) . , JMenuBar
setHelpMenu(JMenu). ,
JDK.
:
JFrame f = new JFrame(" ");
JMenuBar mb = new JMenuBar());
f.setJMenuBar(mb);
JMenu
JMenu
JMenu
JMenu

file
edit
view
help

=
=
=
=

new
new
new
new

JMenu("<html><u></u>"));
JMenu("<html><u></u>"));
JMenu("<html><u></u>"));
JMenu("<html><u></u>"));

mb.add(file); mb.add(edit);
mb.add(view); mb.add(help);

11. Swing

323

JMenu
: ""
JPopupMenu,
"". . 11.1, JMenu ,
AbstractButton. , JMenu
JMenuItem. , JMenu -
, .
JMenu(String). JMenu(String,
boolean) (tear-off) , true. .
.
add(JMenuItem) add(String). ,
JMenuItem, . , add(Component), .
, ,
MenuElement. ,
JComboBox.
JMenuItem:
JMenu, JCheckBoxMenuItem
JRadioButtonMenuItem.
addSeparator().
, , ,
. insert(JMenuItem, int), insert(String, int) add(Component, int)
,
insertSeparator(int) .
remove(Component), remove(int), remove(JMenuItem) removeAll()
. add() insert() .
, ,
setMnemonic(int). - :
file.setMnemonic(KeyEvent.VK_A);
edit.setMnemonic(KeyEvent.VK_G);
view.setMnemonic(KeyEvent.VK_D);
help.setMnemonic(KeyEvent.VK_C);

MenuEvent, ,
.

JMenuItem
JMenuItem AbstractButton
.

324

III.

JMenuItem(String), JMenuItem(Icon)
JMenuItem(String, Icon). -

, .
.
, .
15.
JMenu nw = new JMenu("");
file.add(nw);
//
nw.add("");
//
nw.add("");
nw.add("");
JMenuItem open = file.add("...");
JMenuItem close = file.add("");
file.addSeparator();
// :
JMenuItem exit = new JMenuItem("");
file.add(exit);
// :
open.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JFileChooser fch = new JFileChooser();
fch.showOpenDialog(null);
}
});
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});

, ,
-, JMenuItem(String, int).
, setMnemonic(int) JMenuItem,
, , . setAccelerator(KeyStroke),
, Ctrl+O.
:
open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.CTRL_MASK));

JMenuItem , ChangeEvent, ActionEvent,


ItemEvent, MenuKeyEvent,
, MenuDragMouseEvent, .

11. Swing

325

JCheckBoxMenuItem

Swing JCheckBoxMenuItem.
JMenuItem getState(), . ,
isSelected().
:
JCheckBoxMenuItem cbm1 = new JCheckBoxMenuItem("");
JCheckBoxMenuItem cbm2 = new JCheckBoxMenuItem("");
JCheckBoxMenuItem cbm3 = new JCheckBoxMenuItem("");
view.add(cbm1); view.add(cbm2); view.add(cbm3);
view.addSeparator();
cbm1.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
if (e.getStateChange() == ItemEvent.SELECTED)
ch.setText(txt);
else ch.setText("");
}
});

JRadioButtonMenuItem

JRadioButtonMenuItem. JMenuItem
, .
:
JRadioButtonMenuItem rbm1 =
new JRadioButtonMenuItem("");
JRadioButtonMenuItem rbm2 =
new JRadioButtonMenuItem("");
JRadioButtonMenuItem rbm3 =
new JRadioButtonMenuItem("");
view.add(rbm1);view.add(rbm2); view.add(rbm3);
ButtonGroup bg = new ButtonGroup();
bg.add(rbm1); bg.add(rbm2); bg.add(rbm3);

JPopupMenu
(pop-up menu) .
MS Windows Java L&F .

326

III.

. , , ,
. , .
MouseEvent.
,
, MouseEvent
isPopupTrigger(). .
isPopupTrigger() true, ,
, show(Component, int, int).
, , .
, popup JPopupMenu:
public void processMouseEvent(MouseEvent e){
if (e.isPopupTrigger())
popup.show(e.getComponent(), e.getX(), e.getY());
else super.processMouseEvent(e);
}

, ,
processMouseEvent(),
, . . addMouseListener() enableEvents(AWTEvent.MOUSE_EVENT_MASK).
. JPopupMenu() JPopupMenu(String). , , ,
. setLabel(String). add(Action),
add(JMenuItem) add(String) . insert() remove()
.
, PopupMenuEvent.

JColorChooser
, , , . Swing
JColorChooser, RGB HSB.
.
,
showDialog(Component, String, Color). , . null , Frame, . ,
, null . :
Color c = JColorChooser.showDialog(null, "", null);

11. Swing

327

, ,
, OK, Cancel Reset. showDialog()
OK null, Cancel. , .
Reset.
Reset , .
createDialog(Component, String, boolean, JColorChooser, ActionListener,
ActionListener). , , . JColorChooser,
.
OK Cancel .
getColor(). :
JDialog d = JColorChooser.createDialog(
new JFrame(), " ", false,
cc = new JColorChooser(),
new OkColor(), new CancelColor());
d.setVisible(true);
class OkColor implements ActionListener{
public void actionPerformed(ActionEvent e){
comp.setColor(cc.getColor());
}
}
class CancelColor implements ActionListener{
public void actionPerformed(ActionEvent e){
comp.setColor(defColor);
}
}

,
, JColorChooser(Color), ,
JColorChooser(), .
.
JColorChooser PropertyChangeEvent
Java Bean, ,
JComponent
addPropertyChangeListener(PropertyChangeListener);

, , javax.swing.colorchooser.
,
ColorSelectionModel. JColorChooser -

328

III.

DefaultColorSelectionModel.
getSelectionModel(). ChangeEvent.
ColorSelectionModel
JColorChooser(ColorSelectionModel).

4. "" 10.9 10.10


Swing.

JFileChooser
.
Swing JFileChooser,
.
. JFileChooser(File) JFileChooser(String) ,
. JFileChooser() . JFileChooser(null). FileSystemView,
.
( FILES_ONLY).
DIRECTORIES_ONLY
FILES_AND_DIRECTORIES.
setFileSelectionMode(int).
(hidden) . ,
setFileHidingEnabled(false).
.
setMultiSelectionEnabled(true).

FileFilter
. ,
. FileFilter javax.swing.filechooser ( FileFilter java.io)
addChoosableFileFilter(FileFilter).
, .
FileFilter .
accept(File) true, .
getDescription() , (Files of type) .
, java. . 11.5.

11. Swing

329

class JavaFileFilter extends javax.swing.filechooser.FileFilter{


public boolean accept(File f){
if (f != null){
String name = f.getName();
int i = name.lastIndexOf('.');
if (i>0 && i < name.length() 1)
return name.substring(i + 1).equalsIgnoreCase("java");
}
return false;
}
public String getDescription(){
return " Java";
}
}

. 11.5.



showOpenDialog(Component),

showSaveDialog(Component)

showDialog(Component, String). (Open) (Save as).
, . Frame,
null.
, :
JFileChooser fch = new JFileChooser();
fch.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fch.setFileHidingEnabled(false);

330

III.

fch.setMultiSelectionEnabled(true);
fch.addChoosableFileFilter(new JavaFileFilter());
fch.addChoosableFileFilter(new AnotherFileFilter());
switch (fch.showDialog(null, "")){
case JFileChooser.APPROVE_OPTION:
File selectedFile = fch.getSelectedFile();
File directory = fch.getCurrentDirectory();
break;
case JFileChooser.CANCEL_OPTION:
break;
case JFileChooser.ERROR_OPTION:
System.err.println("Error"); break;
}


, showXxxDialog()
,
(Open) (Save) APPROVE_OPTION,
(Cancel) CANCEL_OPTION ERROR_OPTION.
,
getSelectedFile() File, . , FILES_AND_DIRECTORIES,
null. DIRECTORIES_ONLY, . ,
File[] getSelectedFiles(). ,
, File
getCurrentDirectory(), .
, :
JFileChooser fch = new JFileChooser();
int state = fch.showOpenDialog(null);
File f = fch.getSelectedFile();
if (f != null && state == JFileChooser.APPROVE_OPTION)
JOptionPane.showMessageDialog(null, f.getPath());
else if (state == JFileChooser.CANCEL_OPTION)
JOptionPane.showMessageDialog(null, "Canceled");

, ,
.


, setAccessory(JComponent).
, , -

11. Swing

331

. , , , :
class ImagePreviewer extends Jlabel implements PropertyChangeListener{
public ImagePreviewer(JFileChooser fch){
if (fch == null)
throw new IllegalArgumentException("fileChooser must be non-null");
fch.addPropertyChangeListener(this);
}
public void loadImageFromFile(File f){
Icon icon = null;
if (f != null){
ImageIcon im = new ImageIcon(f.getPath());
Dimension size = getSize();
if (im.getIconWidth() != size.width)
icon = new ImageIcon(im.getImage().getScaledInstance(
size.width, size.height, Image.SCALE_DEFAULT));
else icon = im;
}
setIcon(icon);
}
public void propertyChange(PropertyChangeEvent e){
String prop = e.getPropertyName();
if (prop.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)){
File f = (File)e.getNewValue();
if (isShowing()){
loadImageFromFile(f);
repaint();
}
}
}
}

JFileChooser, , :
JFileChooser fch = new JFileChooser();
ImagePreviewer ip = new ImagePreviewer(fch);
ip.setPreferredSize(new Dimension(200, 200));
fch.setAccessory(ip);

. 11.5.


.
- . FileView, , -

332

III.

setFileView(FileView). ,
Java :
class JavaFileView extends FileView{
public String getName(File f){
return null;
//
}
public String getDescription(File f){
String ext = getExtension(f);
if (ext != null && ext.equals("java"))
return " Java";
else return null;
}
public String getTypeDescription(File f){
return getDescription(f);
}
Icon icon = new ImageIcon("javacup.gif");
public Icon getIcon(File f){
String ext = getExtension(f);
if (ext != null && ext.equals("java"))
return icon;
return null;
}
public Boolean isTraversable(File f){
return null;
//
}
protected String getExtension(File f){
if (f != null){
String name = f.getName();
int i = name.lastIndexOf('.');
if (i > 0 && i < name.length() 1)
return name.substring(i + 1).toLowerCase();
}
return null;
}
}

fch JFileChooser
fch.setFileView(new JavaFileView());

Java java javacup.gif, . 11.5.



J2SE JDK $JAVA_HOME/demo/jfc/FileChooserDemo/.

11. Swing

333

, Swing, .
setControlButtonsAreShown(boolean).

Swing
, Swing , 5. , . 11.6. (properties), , , - .
swing_ru.jar, , , http://lib.juga.ru/article/articleprint/125/-1/53/. swing_ru.jar, , $JAVA_HOME/lib/ext/, -, . 11.6.

. 11.6.

: http://lib.juga.ru/article/archive/19/, " ...", Java. ,


, , .


1. Swing AWT?
2. Swing?
3. ?
4. ?
5. Swing ?
6. Swing ?
7. Swing ?
8. Swing ?

12



. , .
, , . Swing ,
javax.swing.text, javax.swing.text.html,
javax.swing.text.html.parser javax.swing.text.rtf.
JTextComponent JComponent. , . : JTextField, JTextArea ,
JEditorPane, JTextPane, - .
JTextField JPasswordField, ,
,
JFormattedTextField, Date, , .
.

JTextComponent
JTextComponent
.
"Model-View-Controller",
JTextComponent. .
.


MVC Document
. , "", ,

12.

335

. Document (content), , Unicode.


getLength(). ,
. ,
(position, location offset) . , , , ,
.
, , , , , Position. ,
Position, createPosition(int). getStartPosition()
getEndPosition() ,
Position. Position
getOffset(), int. ,
Position Bias, Bias: Forward Backward. ,
: . , ,

String getText(int offset, int length);
void getText(int offset, int length, Segment text);

length , offset. text


Segment. , .

Segment
Segment , .
Segment ,
current(). getIndex(), setIndex(int). Segment previous() next(), , first() last(),
. :
!
, Segment
(public) array char[], offset, count . ,
,
Segment . getBeginIndex() array, . . offset, getEndIndex() , .
Segment, , getText(int, int, Segment) Segment setPartialReturn(boolean).
true, getText() Segment , , . false. ,
Segment :

336

III.

Segment seg = new Segment();


seg.setPartialReturn(true);
doc.getText(0, doc.getLength(), seg);
// seg...


, .
void insertString(int offset, String text, AttributeSet attr);

text offset, .


insertString(), , : , , . ,
null.
" " , AttributeSet. ,
.
MutableAttributeSet. Swing
SimpleAttributeSet. " ",
StyleConstants
, : CharacterConstants, ColorConstants,
FontConstants ParagraphConstants.
, AttributeSet, , "" . ,
ResolveAttribute. ,
. - " "
getAttribute(Object), , getResolveParent(), .
MutableAttributeSet Style. getName(),
(style),
ChangeEvent
void addChangeListener(ChangeListener chl);

,
.
StyleContext.
:
StyleContext stc = StyleContext.getDefaultStyleContext();

stc
addAttribute(), removeAttribute(), .

12.

337



remove(int offset, int length);

length , , offset.


insertString()
, , . , Document, insertString() remove(). , .

remove()

DocumentFilter, .
:

DocumentFilter

void insertString(DocumentFilter.FilterBypass fb, int offset,


String text, AttributeSet attr);
void remove(DocumentFilter.FilterBypass fb, int offset, int length);
void replace(DocumentFilter.FilterBypass fb, int offset, int length,
String text, AttributeSet attr);

FilterBypass, .
DocumentFilter, ,
void setDocumentFilter(DocumentFilter filter);

AbstractDocument. insertString() remove() .


, , 12.1.


, , , . Element.
- , getStartOffset(), getEndOffset(). , getParentElement(). ,
,
. ,
. getElement(int).
getElementCount(),
getElementIndex(int). ,
getName().

338

III.

Element AbstractElement, AbstractDocument,


AbstractDocument BranchElement LeafElement,
AbstractElement. , BranchElement
, LeafElement .
BranchElement, , SectionElement,
DefaultStyledElement, BlockElement, HTMLDocument.
LeafElement RunElement, HTMLDocument.

Element createLeafElement(Element parent, AttributeSet attr,
int pos1, int pos2);
Element createBranchElement(Element parent, AttributeSet attr);


addAttribute(Object name, Object value) addAttributes(AttributeSet).
. getRootElements(),
Element[]. getDefaultRootElement(),
, Element.
, , getElement(int) Element
children(), .


,
DocumentEvent. getDocument(), ,
, getOffset() getLength(),
. ElementChange
getElement(), , , , .
DocumentEvent DefaultDocumentEvent,
AbstractDocument, undo(), , redo(), ,
.
(undo/redo),
UndoableEditEvent.


Document AbstractDocument.
. -"" -"".
readLock() writeLock().
readUnlock() writeUnlock().

12.

339

AbstractDocument ,
PlainDocument DefaultStyledDocument.
PlainDocument "" ,
JTextField, JPasswordField, JTextArea.
: . getDefaultRootElement(). getParagraphElement(int
offset) Element, offset. , , . .
DefaultStyledDocument, JTextPane. , .
, DefaultStyledDocument HTMLDocument. HTML. (style sheets).


, setDocument(Document) JTextComponent.

MVC ,
, , .
View. , .

, getElement(). , , getDocument(). , getParent() setParent(), . getViewCount(),
getView(int).
create(Element), ViewFactory. , , getViewFactory().
.

, , ,
.
Shape modelToView(int startPos, Position.Bias b0,
int endPos, Position.Bias b1, Shape fig);

Shape. startPos endPos , b0 b1 -

340

III.

, :
Position.Bias.Backward Position.Bias.Forward, fig.

int viewToModel(float x, float y, Shape fig, Position.Bias[] b);

, (x, y) fig.
, b,
.

Graphics.
paint(Graphics) . paint(Graphics), , getGraphics().
setSize(float width, float height),
, .
View Component. ,
, Component ,
, View -, . . 12.1.

. 12.1. -

. 12.1, .
HTML, ImageView
<IMG>, FormView <FORM> <INPUT>, <SELECT>, <TEXTAREA>,
ObjectView <OBJECT>.
PlainView
JTextArea, FieldView
JTextField, PasswordView JPasswordView.
BoxView .
,
.

12.

341


MVC
. EditorKit,

, , ,
void read(InputStream in, Document doc, int pos);
void read(Reader in, Document doc, int pos);


void write(OutputStream out, Document doc, int pos, int length);
void write(Writer out, Document doc, int pos, int length);


Document createDefaultDocument();

""
ViewFactory getViewFactory();

,

Caret createCaret();

Caret DefaultCaret , .
(dot). (mark). , . moveDot(int)
.
setDot(int) .
. setSelectionVisible(boolean),
isSelectionVisible().
getDot() getMark(), MVC.
Point getMagicCaretPosition();


void setMagicCaretPosition(Point);

null.
paint(Graphics). DefaultCaret
Rectangle, ,
.

342

III.

setBlinkRate(int), .
setVisible(true),
isVisible().
ChangeEvent,
. ,
, paint(Graphics) .
, Swing .


, DocumentFilter , NavigationFilter
, , -
.
, NavigationFilter,
:
void setDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias) -

dot ;
void moveDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias) -

dot, ;
int getNextVisualPositionFrom(JTextComponent tc, int pos, Position.Bias bias, int
direction, Position.Bias[] biasRet)
pos direction. View .
NavigationFilter, ,
setNavigationFilter(NavigationFilter) JTextComponent.
,
.
class CursorFilter extends NavigationFilter{
public void setDot(NavigationFilter.FilterBypass fb,
int dot, Position.Bias bias){
super.setDot(fb, (dot < 30)? dot:30, bias);
}
public void moveDot(NavigationFilter.FilterBypass fb,
int dot, Position.Bias bias){
super.moveDot(fb, (dot < 30)? dot:30, bias);
}
}

, :
JTextArea ta = new JTextArea(5, 60);
ta.setNavigationFilter(new CursorFilter());

12.

343


EditorKit DefaultEditorKit
, . JTextComponent.
DefaultEditorKit StyledEditorKit. , : , , ,
. JTextPane.
StyledEditorKit : HTMLEditorKit RTFEditorKit, HTML RTF.
, HTMLEditorKit : javax.swing.text.html
javax.swing.text.html.parser. HTML, DTD
CSS, (parser) HTML.
, MVC JTextComponent . . , . insertString(), -
. .
Swing, JTextComponent
MVC.
, .


, JtextComponent, .

KeyStroke. -
<Shift>, <Alt>, <Ctrl> <Meta>.
KeyStroke ""
:
KeyStroke getKeyStroke(char keyChar) keyChar, -

;
KeyStroke getKeyStroke(int keyCode, int modifiers) keyCode

VK_* KeyEvent <Shift>, <Alt>,


<Ctrl> <Meta> SHIFT_MASK, ALT_MASK,
CTRL_MASK META_MASK InputEvent. ;
KeyStroke getKeyStroke(Character keyChar, int modifiers)

Character;
KeyStroke getKeyStroke(int keyCode, int modifiers, boolean onRelease)

, (false) (true);

344

III.

KeyStroke getKeyStroke(String keyString)


keyString.

KeyStroke
, Keymap. , Action,
" " "KeyStroke Action". Action
14.
.
" "
void addActionForKeyStroke(KeyStroke key, Action a);

Action[]
getBoundActions(), KeyStroke[] getBoundKeyStrokes(). Action getAction(KeyStroke).
Keymap ,
setResolveParent(Keymap). "


"
, .

Swing Keymap . JTextComponent. DEFAULT_KEYMAP.


getKeymap(),
setKeymap(Keymap).
addKeymap(String name, Keymap parent);


print() JTextComponent
, . false,
, Cancel , true .
print() .
print(MessageFormat header, MessageFormat footer)
header footer ,
MessageFormat java.text.

, ,
.

JTextField
,
.

12.

345

:
JTextField(int columns) ,

columns . ,
;
JTextField(String text) text;
JTextField(String text, int columns) text -

columns ;
JTextField(Document doc, String text, int columns) doc.

setDocument(Document).
, setFont(Font).
, JTextComponent, setText(String), getText(),
getText(int offset, int length)
getSelectedText().
content
replaceSelection(String content).
.
setHorizontalAlignment(int), : LEFT, CENTER, RIGHT, LEADING,
TRAILING JTextField.
, setEditable(false).
setCaret(Caret).
setCaretColor(Color). getCaretPosition(),
setCaretPosition(int). , , moveCaretPosition(int).
getSelectionStart() getSelectionEnd(),
setSelectionStart(int) setSelectionEnd(int).
setSelectedTextColor(Color),
setSelectionColor(Color).
(clipboard) cut(), copy(),
, paste(),
.
,
, .
getDocument().
12.1 .
12.1.
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

III.

346

public class NumberText extends JFrame{


JTextField tf = new JTextField(5);
JLabel l = new JLabel(" :");
NumberText(){
super("text");
setLayout(new FlowLayout());
//
((PlainDocument)tf.getDocument()).
setDocumentFilter(new NumberFilter());
//
tf.setSelectedTextColor(Color.red);
//
tf.setSelectionColor(Color.white);
//
tf.setCaretColor(Color.red);
l.setLabelFor(tf);
add(l);
add(tf);
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new NumberText();
}
//
class NumberFilter extends DocumentFilter{
//
public void insertString(FilterBypass fb, int pos,
String text, AttributeSet attr)
throws BadLocationException{
try{
Integer.parseInt(text); // ?
}catch(Exception e){
// ,
super.insertString(fb, 0, "", attr);
return;
}
// ,
super.insertString(fb, pos, text, attr);
}
}
}

12.

347

JPasswordField
JPasswordField JTextField, , . ,
, .
setEchoChar(char).
, getText()
getPassword(),
char[], .

JFormattedTextField
JTextField JFormattedTextField
, , Date, Number. , JFormattedTextField(Object) setValue(Object) , .
:
JFormattedTextField ftf = new JFormattedTextField(new Date());
ftf.addActionListener(this);
// . . . . . . . .
// ... <Enter>
// . . . . . . . .
public void actionPerformed(ActionEvent e){
newDate = (Date)ftf.getValue();
}

getValue() Object,
.

JFormattedTextField AbstractFormatter.
valueToString(Object) stringToValue(String). . "" install(JFormattedTextField) AbstractFormatter
JFormattedTextField(JFormattedTextField.AbstractFormatter);

setFormatter(AbstractFormatter) JFormattedTextField.
, AbstractFormatter
DocumentFilter NavigationFilter,
getDocumentFilter() getNavigationFilter().
, .
Swing AbstractFormatter
DefaultFormatter. valueToString(Object)

III.

348

DefaultFormatter : toString()
. stringToValue(String) String. , .
DefaultFormatter , . Swing.
DefaultFormatter . MaskFormatter
, Format
java.text. ,
MaskFormatter mf = new MaskFormatter("###.##");

.
InternationalFormatter Format ,
InternationalFormatter(Format);

: NumberFormatter DecimalFormat
, DateFormatter DateFormat .

-,
AbstractFormatterFactory, DefaultFormatterFactory.
getXxxFormatter(), -.
JFormattedTextField

JTextArea
JTextArea "" , .
JTextEditor JTextPane.
JTextArea .
, JScrollPane:
JTextArea ta = new JTextArea(5, 50);
JScrollPane sp = new JScrollPane(ta);
container.add(sp);


, JScrollPane.
, , .
setWrapStyleWord(true).
, ,
. JScrollPane,
.
, setLineWrap(true).

12.

349

setText(String),
append(String) insert(String, int).
setTabSize(int).
JTextField.

JEditorPane
JEditorPane MIME- : text/plain, text/html text/rtf, DefaultEditorKit,
HTMLEditorKit RTFEditorKit . MIME- ,

JEditorPane(String type, String text);

setContentType(type), MIME- ,
setText(text). :
JEditorPane ep= new JEditorPane("text/html;Content-Type=windows-1251",
"<html> HTML");
JScrollPane sp = new JScrollPane(ep);
container.add(sp);

setText(String) . MIME- . ,
setEditor(EditorKit). ,
!
MIME-
setEditorKitForContentType(String type, EditorKit editor);

, .
,
URL. URL :
JEditorPane(URL url);
JEditorPane(String url);

URL
setPage(URL) setPage(String url). , MIME- . HTML, HTMLDocument HTMLEditorKit.

read(InputStream in, Object obj). HTMLEditorKit obj
HTMLDocument, HTML .
"" .
, HTML- <IMG>.
JTextPane.

350

III.

JTextPane
JTextPane JEditorPane
.
,
DefaultStyledDocument .

addStyle(String name, Style parent);

, ,
setCharacterAttributes(AttributeSet attr, boolean replace);

, ,
setParagraphAttributes(AttributeSet attr, boolean replace);

true, .

setStyledDocument(StyledDocument);


insertIcon(Icon). ,
.
,
insertComponent(Component). .


1. MVC ?
2. Swing AWT?
3. Swing ?
4. Swing ?
5. Swing?
6. Swing Swing?
7. Swing ?

13

. ,
.
.
.
, , , .
Swing JTable,
JTableHeader, TableColumn ,
javax.swing.table. , , , , . .

JTable
JTable . . -. JTable
DefaultTableModel , JTableHeader , TableCellEditor ,
TableCellRenderer , TableColumn .
.
"Model-View-Controller". : ,
TableModel, ,
TableColumnModel, ,
ListSelectionModel ( 11).
.
JTable()

352

III.

JTable(int rows, int columns) -

rows columns , Object


Vector, . .
JTable(Object[][] data, Object[] colNames) , -

data. colNames .
data ,
colNames. 13.1.
JTable(Vector data, Vector colNames) ,

. 13.3.
, ,
JScrollPane. , A, B, C . ., .
.
JTable(TableModel) -

. .
JTable(TableModel, TableColumnModel) -

.
JTable(TableModel, TableColumnModel, ListSelectionModel)

.
13.1
, .
13.1.
import java.awt.*;
import javax.swing.*;
public class SimpTable extends JFrame{
SimpTable(){
super(" My Table");
setLayout(new FlowLayout());
String[][] data = {{"-27", "32"}, {"-45", "55"}};
String[] colNames = {"", ""};
JTable t1 = new JTable(data, colNames);
add(new JScrollPane(t1));
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}

13.

353

public static void main(String[] args){


new SimpTable();
}
}


setValueAt(Object data, int row, int column);

(row, column) data.


, column , .
, .
setModel(TableModel)
setColumnModel(TableColumnModel). .


JTable . , TableModel TableColumnModel,
, ListSelectionModel JList.
11.


TableModel, AbstractTableModel DefaultTableModel.
,
.
, .
ind getColumnClass(int ind). getRowCount(),
getColumnCount(). ,
getColumnName(int), String.

Object getValueAt(int rowInd, int colInd), ,
, setValueAt(Object data, int rowInd, int colInd).
, ,
isCellEditable(int rowInd, int colInd).
, AbstractTableModel.
:
int getRowCount();
int getColumnCount();
Object getValueAt(int, int);

354

III.

.
, ,
isEditable() AbstractTableModel false, setValueAt() .
, .
13.2 AbstractTableModel
, .
13.2.
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class SimpTable extends JFrame{
SimpTable(){
super(" ");
setLayout(new FlowLayout());
JTable t1 = new JTable(new FirstColumnTableModel());
add(new JScrollPane(t1));
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new SimpTable();
}
}
class FirstColumnTableModel extends AbstractTableModel{
protected Object[][] data = {
{"", Color.black, new Boolean(true)},
{"", new Color(130, 56, 187), new Boolean(true)},
{"", new Color(200, 45, 125), new Boolean(false)},
};
protected String[] colNames = {"", "", ""};
public FirstColumnTableModel(){ super(); }
//
public int getRowCount(){ return data.length; }
public int getColumnCount(){ return data[0].length; }
public Object getValueAt(int row, int col){ return data[row][col]; }
//
public void setValueAt(Object value, int row, int col){
if (col != 0) data[row][col] = value;
}

13.

355

// ,
public boolean isCellEditable(int row, int col){
return col != 0;
}
//
//
public Class getColumnClass(int col){
return data[0][col].getClass();
}
//
public String getColumnName(int col){
return colNames[col];
}
}

. 13.1, Boolean JCheckBox.


getColumnClass(). . 13.2
. Color -
toString().

. 13.1.

DefaultTableModel TableModel . .
Vector, - . (protected) dataVector.
DefaultTableModel()
.
DefaultTableModel(int rowCount, int colCount) . null.

DefaultTableModel(Vector data, Vector colNames);


DefaultTableModel(Object[][] data, Object[] colNames);

III.

356


DefaultTableModel(Vector colNames, int rowCount);
DefaultTableModel(Object[] colNames, int rowNames);

.
DefaultTableModel, ,
addRow() addColumn(),
insertRow(). Object
Vector.

setValueAt(Object value, int row, int column);

getXxx() .

moveRow(int start, int end, int to);

start end , to , start.


, setDataVector() ,
. . dataVector.

DefaultTableModel, AbstractTableModel. 13.3
,
, .
13.3.
import
import
import
import

javax.swing.*;
javax.swing.table.*;
java.io.*;
java.util.*;

public class FileTable extends JFrame{


public FileTable(File dir){
super(" ");
JTable table = new JTable(new FileTableModel(dir));
add(new JScrollPane(table));
setSize(600, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
File dir = args.length > 0 ? new File(args[0]) :
new File(System.getProperty("user.home"));

13.

357

new FileTable(dir);
}
}
class FileTableModel extends DefaultTableModel{
protected File dir;
protected String[] fName;
protected String[] colName = new String[]{
"", "", " ",
"", " ", " "
};
protected Class[] colClass = new Class[]{
String.class, Long.class, Date.class,
Boolean.class, Boolean.class, Boolean.class
};
public FileTableModel(File dir){
super(dir.list().length, 6);
this.dir = dir;
fName = dir.list();
}
public String getColumnName(int col){ return colName[col]; }
public Class getColumnClass(int col){ return colClass[col]; }
public Object getValueAt(int row, int col){
File f = new File(dir, fName[row]);
switch(col){
case 0: return fName[row];
case 1: return new Long(f.length());
case 2: return new Date(f.lastModified());
case 3: return f.isDirectory() ?
Boolean.TRUE : Boolean.FALSE;
case 4: return f.canRead() ?
Boolean.TRUE : Boolean.FALSE;
case 5: return f.canWrite() ?
Boolean.TRUE : Boolean.FALSE;
default: return null;
}
}
}


TableModelEvent. : INSERT, DELETE UPDATE
getType(). ,
, , . getFirstRow(), getLastRow() getColumn().
ALL_COLUMNS, , . -

III.

358

addTableModelListener(TableModelEvent).

TableModelEvent. UPDATE, ALL_COLUMNS


MAX_VALUE getLastRow() ,
.
UPDATE, ALL_COLUMNS HEADER_ROW getFirstRow() , , . , TableColumnModelEvent.

setModel(TableModel) , 13.2.

TableColumn
TableColumn : , , , ,
, TableCellEditor
TableCellRenderer.
getXxx()/setXxx().
setMinWidth(int), setMaxWidth(int)
setPreferredWidth(int), ,
, .


TableColumnModel,
DefaultTableColumnModel.
TableColumn. , . ListSelectionModel,
.

. moveColumn(int oldInd, int
newInd), .
, , TableColumnModelEvent,

addColumnModelListener(ColumnModelListener);

JTableHeader
.
.
,
JScrollPane, . -

13.

359

A, B, C . .,
DefaultTableModel.
JTableHeader javax.swing.table.
TableColumnModel.
JTableHeader(). , JTableHeader(TableColumnModel),
.
setTable(JTable).

getTableHeader() JTable.
, . , 13.4 "",
"" BorderLayout.
, "" . BorderLayout .
13.4.
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class HeadTable extends JFrame{
HeadTable(){
super(" ");
Vector data = new Vector();
Vector row = new Vector();
row.addElement("");
row.addElement(new Integer(1970));
row.addElement(new Boolean(false));
data.addElement(r);
row = new Vector();
row.addElement("");
row.addElement(new Integer(1980));
row.addElement(new Boolean(true));
data.addElement(r);
Vector col = new Vector();
col.addElement("");
col.addElement(" ");
col.addElement(" ");
JTable t2 = new JTable(data, col);
JTableHeader th = t2.getTableHeader();
add(th, BorderLayout.NORTH);
add(t2, BorderLayout.CENTER);

360

III.
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);

}
public static void main(String[] args){
new HeadTable();
}
}

. 13.2 , 13.4. , Boolean


toString().

. 13.2.

. .
setAutoResizeMode(int) JTable. :
AUTO_RESIZE_OFF ;
AUTO_RESIZE_NEXT_COLUMN ;
AUTO_RESIZE_SUBSEQUENT_COLUMNS

( );
AUTO_RESIZE_LAST_COLUMN ;
AUTO_RESIZE_ALL_COLUMNS .


ListSelectionModel.
JTable DefaultListSelectionModel
. 11 JList.
: SINGLE_SELECTION, SINGLE_INTERVAL_SELECTION,
MULTIPLE_INTERVAL_SELECTION.

setSelectionMode(int) JTable, .
. setSelectionModel(ListSelectionModel) JTable.

13.

361

, TableColumnModel, . :
table.getColumnModel().setSelectionModel(new SomeSelectionModel());

setSelectionForeground(Color) setSelectionBackground(Color).

,
getSelectionModel() JTable.


JTable, TableCellRenderer.
TableCellRenderer :
Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int col);

, (row, col)
. value , , isSelected,
hasFocus, , table .
, value, .
, , . . this. paint(). - , paint().
JList, 11.

Swing

TableCellRenderer

JLabel. DefaultTableCellRenderer
JLabel, Icon. setText(String) JLabel :
DefaultTableCellRenderer,

protected void setValue(Object value){


setText((value == null) ? "" : value.toString());
}

, , , , toString() .
, , , setValue(Object)
DefaultTableCellRenderer. , 13.2 Color
, . 13.1. ,
DefaultTableCellRenderer, setValue():
class ColorRenderer extends DefaultTableCellRenderer{
public void setValue(Object value){

III.

362

setBackground((Color)value);
}
}

Color,
setDefaultRenderer(Class, TableCellRenderer) JTable.
13.2 SimpTable
t1.setDefaultRenderer(Color.class, new ColorRenderer());

,
- . ,
, , :
class IconRenderer extends DefaultTableCellRenderer{
public void setValue(Object value){ setIcon((Icon)value); }
}


t1.setDefaultRenderer(Icon.class, new IconRenderer());

JLabel,
DefaultTableCellRenderer, .
TableCellRenderer. 13.5
, , JTextArea, 12.
13.5.
import
import
import
import
import

java.awt.*;
javax.swing.*;
javax.swing.table.*;
javax.swing.border.*;
java.util.*;

public class MultiLineTable extends JFrame{


MultiLineTable(int lineCount){
super(" ");
// , ,
//
DefaultTableModel tm = new DefaultTableModel(){
public Class getColumnClass(int col){
return getValueAt(0, col).getClass();
}
};
//
tm.setDataVector(
new Object[][]{
{"\n","\n","\n"},

13.
{"\n","\n","\n"}
},
new Object[]{"","1","2"}
);
//
JTable t = new JTable(tm);
// ,
//
t.setRowHeight( t.getRowHeight() * lineCount);
// -
t.setDefaultRenderer(String.class, new MultiLineCellRenderer());
add(new JScrollPane(t));
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new MultiLineTable(2);
}
}
// -
class MultiLineCellRenderer extends JTextArea
implements TableCellRenderer{
public MultiLineCellRenderer(){
setLineWrap(true);
setWrapStyleWord(true);
setOpaque(true);
}
public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int col){
if (isSelected){
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
}else{
setForeground(table.getForeground());
setBackground(table.getBackground());
}
if (hasFocus){
setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
if (table.isCellEditable(row, col)){
setForeground(UIManager.getColor("Table.focusCellForeground"));

363

364

III.

setBackground( UIManager.getColor("Table.focusCellBackground"));
}
}else setBorder(new EmptyBorder(1, 2, 1, 2));
setFont(table.getFont());
setText((value == null) ? "" : value.toString());
return this;
}
}

.
13.5,
getTableCellRendererComponent() :
public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int col){
if (table != null){
JTableHeader header = table.getTableHeader();
if (header != null){
setForeground(header.getForeground());
setBackground(header.getBackground());
setFont(header.getFont());
}
}
setText((value == null) ? "" : value.toString());
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
return this;
}

( MultiLineHeader)
, :
MultiLineHeader mlh = new MultiLineHeader();
Enumeration e = t.getColumnModel().getColumns();
while (e.hasMoreElements())
((TableColumn)e.nextElement()).setHeaderRenderer(mlh);


. , .
-. , TableCellEditor.
TableCellEditor CellEditor

public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column);

13.

365

.
, , JTextField,
(row, column) value. table, . isSelected, , .
CellEditor , . stopCellEditing() true,
. false, . . cancelCellEditing() .
ChangeEvent,
,
addCellEditorListener(CellEditorListener).
TableCellEditor DefaultCellEditor.
JCheckBox, JComboBox
JTextField.
JTextField.
,
, toString() .
JCheckBox boolean, . 13.1. .
JomboBox ,
.
13.6 , .
JComboBox.
. 13.3.
13.6.
import
import
import
import
import
import

java.util.*;
java.awt.*;
java.awt.event.*;
javax.swing.*;
javax.swing.table.*;
javax.swing.event.*;

public class RowEd extends JFrame{


public RowEd(){
super(" ");
DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(
new Object[][]{{"", ""},

366

III.
{"", ""},
{"", ""}},
new Object[]{"", ""});
JTable table = new JTable(dm);
JComboBox cb = new JComboBox();
cb.addItem("");
cb.addItem("");
RowEditor rowEd = new RowEditor(table);
rowEd.setEditorAt(2, new DefaultCellEditor(cb));
table.getColumn("").setCellEditor(rowEd);
add(new JScrollPane(table));
setSize(400, 100);
setVisible(true);

}
public static void main(String[] args){
new RowEd();
}
}
class RowEditor implements TableCellEditor{
protected Hashtable editors;
protected TableCellEditor editor, defEditor;
JTable table;
public RowEditor(JTable table){
this.table = table;
editors = new Hashtable();
defEditor = new DefaultCellEditor(new JTextField());
}
public void setEditorAt(int row, TableCellEditor editor){
editors.put(new Integer(row), editor);
}
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column){
return editor.getTableCellEditorComponent(table,
value, isSelected, row, column);
}
public Object getCellEditorValue(){
return editor.getCellEditorValue();
}
public boolean stopCellEditing(){
return editor.stopCellEditing();
}

13.

367

public void cancelCellEditing(){


editor.cancelCellEditing();
}
public boolean isCellEditable(EventObject anEvent){
selectEditor((MouseEvent)anEvent);
return editor.isCellEditable(anEvent);
}
public void addCellEditorListener(CellEditorListener l){
editor.addCellEditorListener(l);
}
public void removeCellEditorListener(CellEditorListener l){
editor.removeCellEditorListener(l);
}
public boolean shouldSelectCell(EventObject anEvent){
selectEditor((MouseEvent)anEvent);
return editor.shouldSelectCell(anEvent);
}
protected void selectEditor(MouseEvent e){
int row = (e == null) ?
table.getSelectionModel().getAnchorSelectionIndex() :
table.rowAtPoint(e.getPoint());
editor = (TableCellEditor)editors.get(new Integer(row));
if (editor == null) editor = defEditor;
}
}

. 13.3. JComboBox


, , , MS Excel, - ,
. .
JTable.
setAutoCreateRowSorter(true):
JTable table = new JTable();
table.setAutoCreateRowSorter(true);

368

III.

!
, .
RowSorter<M>.
, , MVC
(. 3), .
View, Model .
RowSorter<M> DefaultRowSorter<M, I>,
, .
TableRowSorter<M extends
TableModel>. View Model ,
:
FileTableModel model = new FileTableModel();
JTable table = new JTable(model);
table.setRowSorter(new TableRowSorter(model));

, , ,
, Comparator (. 6).
isSortable(int column) DefaultRowSorter.
,
setComparator(int column, Comparator comparator);

. , , toString().
, ,
. List, RowSorter.SortKey. . ,
, ASCENDING DESCENDING SortOrder.
.
:
List<RowSorter.SortKey> keys = new ArrayList<RowSorter.SortKey>();
keys.add(new RowSorter.SortKey(1, SortOrder.ASCENDING));
keys.add(new RowSorter.SortKey(0, SortOrder.ASCENDING));
TableRowSorter sorter = new TableRowSorter(model));
sorter.setSortKeys(keys);

,
Model , , View.
int modelRowIndex = table.convertRowIndexToModel(viewRowIndex);
int viewRowIndex = table.convertRowIndexToView(modelRowIndex);

viewRowIndex View
modelRowIndex Model.

13.

369


, RowSorter Model - View. , RowFilter<M, I >, setRowFilter() DefaultRowSorter.
:
TableRowSorter sorter = new TableRowSorter(model));
RowFilter filter = RowFilter.regexFilter("java", 0);
sorter.setRowFilter(filter);

,
, "java".
RowFilter .

public static <M, I > RowFilter<M, I > regexFilter(String regex, int... indices);

regex, :
public static <M, I > RowFilter<M, I >
numberFilter(RowFilter.ComparisionType type, Number number, int... indices);
public static <M, I > RowFilter<M, I >
dateFilter(RowFilter.ComparisionType type, Date date, int... indices);

type AFTER, BEFORE, EQUAL NOT_EQUAL RowFilter.ComparisionType. ,


View , , number date, . indices ,
. indices .
, , ,
public static <M, I > RowFilter<M, I > notFilter(RowFilter<M, I > filter);
public static <M, I > RowFilter<M, I >
andFilter(Iterable<? extends RowFilter<? super M, ? super I >> filters);
public static <M, I > RowFilter<M, I >
orFilter(Iterable<? extends RowFilter<? super M, ? super I >> filters);

, notFilter(), ,
, . ,
andFilter(), , ,
filters. , orFilter(), , filters.
RowFilter.

public boolean include(RowFilter.Entry<? extends M, ? extends I > row);

370

III.

DefaultRowSorter Model, . true,


View.
,
RowFilter.Entry. RowFilter.Entry
:
I getIdentifier() ;
M getModel() ;
String getStringValue(int index) index

;
Object getValue(int index) index

;
int getValueCount() .

include(),
. ,
,
class SumRowFilter extends RowFilter{
private String text;
private int limit;
public SumRowFilter(String text, int limit){
this.text = text;
this.limit = limit;
}
public boolean include(Entry entry){
int sum = 0;
if (entry.getStringValue(0).equals(text)){
for (int i = 1; i < entry.getValueCount() 1; i++){
sum += ((Number)entry.getValue(i)).intValue();
}
if ( sum > limit) return true;
}
return false;
}
}


print() , .
false, ,
Cancel , true .
print(JTable.PrintMode mode) .

, -

13.

371

FIT_WIDTH JTable JTable.PrintMode,


NORMAL.
print()

JTable.PrintMode.FIT_WIDTH.
print(JTable.PrintMode mode, MessageFormat header, MessageFormat footer)

header footer ,
MessageFormat java.text.
, ,
.
Java SE
$JAVA_HOME/demo/jfc/TableExample/.


1. MVC ?
2. JTable ?
3. ?
4. -?
5. ?
6. JTable, ?
7. JTable?
8. JTable?

14


Swing
"",

. setBounds().
, .
. ,
, , .
,
, , :
int w = getSize().width;
int h = getSize().height;
Button b = new Button("OK");
b.setBounds(9*w/20, 4*h/5, w/10, h/10);

//
// .
// .

.
, AWT : LayoutManager LayoutManager2,
: BorlerLayout, CardLayout, FlowLayout,
GridLayout GridBagLayout. (layout
manager) .
. Swing , Swing.
,
LayoutManager LayoutManager2.
, .

FlowLayout
FlowLayout. ,
. "" ,

14. Swing

373

. 14.1. ,
add().
,
align FlowLayout.LEFT, ,
FlowLayout.RIGHT, , FlowLayout.CENTER.
(gap) hgap vgap. :
FlowLayout(int align, int hgap, int vgap);

5 :
FlowLayout(int align);

5 :
FlowLayout();

:
setHgap(int hgap);
setVgap(int vgap);
setAlignment(int align);

14.1 JButton, JLabel, JCheckBox, JComboBox, JtextField JFrame. 14.1 .


14.1. FlowLayout
import java.awt.*;
import javax.swing.*;
class FlowTest extends JFrame{
FlowTest(String s){
super(s);
setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
add(new JButton(""));
add(new JLabel(""));
add(new JCheckBox(""));
add(new JComboBox());
add(new JTextField("", 10));
setSize(300, 100);
setVisible(true);
}
public static void main(String[] args){
JFrame f= new FlowTest(" FlowLayout");
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

374

III.

. 14.1. FlowLayout

BorderLayout
BorderLayout , , . 14.2. NORTH, SOUTH, WEST, EAST CENTER.
add() BorderLayout : comp region,
: add(Component comp, String region).
add(Component comp)
CENTER.
, ,
getLayoutComponent(Object region);

.
:
BorderLayout() ;
BorderLayout(int hgap int vgap) hgap

vgap , .
, , . 14.3.
CENTER, .
14.2 , . setLayout()
BorderLayout JFrame . . 14.2.
14.2. BorderLayout
import java.awt.*;
import javax.swing.*;

14. Swing

375

class BorderTest extends JFrame{


BorderTest(String s){
super(s);
add(new JButton("North"), BorderLayout.NORTH);
add(new JButton("South"), BorderLayout.SOUTH);
add(new JButton("West"), BorderLayout.WEST);
add(new JButton("East"), BorderLayout.EAST);
add(new JButton("Center"));
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args){
JFrame f= new BorderTest(" BorderLayout");
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

. 14.2. BorderLayout

. 14.3. FlowLayout
BorderLayout

BorderLayout :
, , .
, , , , 14.3 . 14.3. , Panel JPanel
FlowLayout.
14.3.
import java.awt.*;
import javax.swing.*;
class BorderPanelTest extends JFrame{
BorderPanelTest(String s){
super(s);
// p2
JPanel p2 = new JPanel();

376

III.

p2.add(new JButton(""));
p2.add(new JButton(""));
p2.add(new JButton(""));
JPanel p1 = new JPanel();
p1.setLayout(new BorderLayout());
// p2 "" p1
p1.add(p2, BorderLayout.SOUTH);
// ""
p1.add(new JTextField(" ", 20), BorderLayout.NORTH);
//
JScrollPane sp = new JscrollPane(
new JTextArea(" ", 5, 20));
// p1
p1.add(sp), BorderLayout.CENTER);
// p1 ""
add(p1, BorderLayout.CENTER);
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args){
JFrame f= new BorderPanelTest(" ");
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

GridLayout
GridLayout
rows columns:
GridLayout(int rows, int columns);

.
.

hgap vgap:
GridLayout(int rows, int columns, int hgap, int vgap);

GridLayout() 0 0
. .
GridLayout
, add().
,
.
14.4 , . 14.4 ,
.

14. Swing

377

14.4. GridLayout
import java.awt.*;
import javax.swing.*;
import java.util.*;
class GridTest extends JFrame{
GridTest(String s){
super(s);
setLayout(new GridLayout(4, 4, 5, 5));
StringTokenizer st = new StringTokenizer("7 8 9 / 4 5 6 * 1 2 3 0 . = +");
while(st.hasMoreTokens())
add(new JButton(st.nextToken()));
setSize(200, 200);
setVisible(true);
}
public static void main(String[] args){
JFrame f= new GridTest(" GridLayout");
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

. 14.4. GridLayout

CardLayout
CardLayout
, (first), . . , add().
next(Container c), previous(Container c),
last(Container c), first(Container c).
, , this.
:
CardLayout() ;
CardLayout(int hgap, int vgap) hgap vgap

378

III.

CardLayout .
add() CardLayout :
add(Component comp, Object constraints);

constraints String .
name
show(Container parent, String name);

14.5 cl p, ""
JFrame. p parent next() show().
"" JFrame p2
ch. 14.5 .
14.5. CardLayout
import java.awt.*;
import javax.swing.*;
class CardTest extends JFrame{
CardTest(String s){
super(s);
JPanel p = new JPanel();
CardLayout cl = new CardLayout();
p.setLayout(cl);
p.add(new JButton(" "),"page1");
p.add(new JButton("English page"),
"page2");
p.add(new JButton("Deutsche Seite"), "page3");
add(p);
cl.next(p);
cl.show(p, "page1");
JPanel p2 = new JPanel();
p2.add(new JLabel(" :"));
JComboBox ch = new JComboBox();
ch.addItem("");
ch.addItem("");
ch.addItem("");
p2.add(ch);
add(p2, BorderLayout.NORTH);
setSize(400, 300);
setVisible(true);
}
public static void main(String[] args){
JFrame f= new CardTest(" CardLayout");
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

14. Swing

379

. 14.5. CardLayout

GridBagLayout
GridBagLayout ,
.
GridBagLayout , ,
. GridBagLayout, , . . ,
. , GridBagConstraints.

. ,
, , .
GridBagConstraints , , ,
. . 14.1.
, . ,
.
14.1. GridBagConstraints

anchor

. :
CENTER, NORTH, EAST, NORTHEAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST; PAGE_START, PAGE_END, LINE_START, LINE_END, FIRST_LINE_START,
FIRST_LINE_END, LAST_LINE_START, LAST_LINE_END,
BASELINE, BASELINE_LEADING, BASELINE_TRAILING, ABOVE_BASELINE,
ABOVE_BASELINE_LEADING, ABOVE_BASELINE_TRAILING, BELOW_BASELINE,
BELOW_BASELINE_LEADING, BELOW_BASELINE_TRAILING; CENTER

fill

. : NONE, HORIZONTAL,
VERTICAL, BOTH; NONE

gridheight

, . int, 1. REMAINDER , ,
RELATIVE

380

III.
14.1 ()

gridwidth

, . int, 1. REMAINDER , ,
RELATIVE

gridx

. 0. RELATIVE, :

gridy

. 0.
RELATIVE, :

insets

. Insets;

ipadx,
ipady

; 0, 0

weightx,
weighty

;
0, 0

, GridBagConstraints ,
, :
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 2;

gbc GridBagConstraints , comp , gbc.



add(Component comp, GridBagConstraints gbc);

, GridBagLayout :
GridBagLayout gbl = new GridBagLayout(); // .
setLayout(gbl);
// .
//
GridBagConstraints c = new GridBagConstraints();
JButton b1 = new JButton();
// .
c.gridwidth = 2;
// .
add(b1, c);
// b1
// .
JButton b2 = new JButton();
// .
c.gridwidth = 1;
// .
add(b2, c);
// .

. .
GridBagLayout
.

14. Swing

381

Swing
JComponent Swing AWT
Container, Swing JComponent, . ,
. Swing , . . . , Swing ,
.

JPanel
JPanel .
Panel AWT.
JPanel() FlowLayout. , ,
add(), ,
getPreferredSize() .
, .
getPreferredSize() , . setPreferredSize(Dimension)
.
JPanel(LayoutManager) .
setLayout(LayoutManager),
Container.
JPanel (double buffering) . 20. ,
JPanel(false).
, , JPanel(LayoutManager, boolean), .
, Container :
add(Component comp) comp , -

;
add(Component comp, Object constraints) comp

, ,
;

constraints,

add(Component comp, int ind) comp ind

;
add(Component comp, Object constraints, int ind) .

382

III.

JScrollPane
JScrollPane ,
.
JTextArea, JTable, , , .
, , , Scrollable,
.

setViewportView(Component). , . :
JScrollPane(Component)

void setVerticalScrollBarPolicy(int);
void setHorizontalScrollBarPolicy(int);

JScrollPane:
VERTICAL_SCROLLBAR_ALWAYS;
VERTICAL_SCROLLBAR_AS_NEEDED;
VERTICAL_SCROLLBAR_NEVER,

:
HORIZONTAL_SCROLLBAR_ALWAYS;
HORIZONTAL_SCROLLBAR_AS_NEEDED;
HORIZONTAL_SCROLLBAR_NEVER.

, ScrollPaneConstants, JScrollPane.
.
: , setColumnHeaderView(Component), , setRowHeaderView(Component), ,
setCorner(String, Component), 14.6.
. 14.6, 14.6. ScrollPaneLayout.
. , , setLayout(LayoutManager),

ScrollPaneLayout.
14.6.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

14. Swing
public class ScrollComps extends JFrame{
ScrollComps(){
super(" ");
setLayout(new FlowLayout());
JScrollPane sp = new JScrollPane(new JTextArea(5,30));
sp.setPreferredSize(new Dimension(200, 200));
sp.setCorner(JScrollPane.LOWER_LEFT_CORNER, new JLabel(" LL"));
sp.setCorner(JScrollPane.LOWER_RIGHT_CORNER, new JLabel("LR"));
sp.setCorner(JScrollPane.UPPER_LEFT_CORNER, new JLabel(" UL"));
sp.setCorner(JScrollPane.UPPER_RIGHT_CORNER, new JLabel("UR"));
JLabel lh = new JLabel(" Header");
lh.setBorder(BorderFactory.createEtchedBorder());
sp.setColumnHeaderView(lh);
JLabel lr = new JLabel("Row");
lr.setBorder(BorderFactory.createEtchedBorder());
sp.setRowHeaderView(lr);
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
sp.setViewportBorder(BorderFactory.createEtchedBorder());
add(sp);
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new ScrollComps();
}
}

. 14.6.

383

384

III.

, ,
JViewport. " " (viewport),
.
JViewport , ViewportLayout.
"" .
,
.
,
setWheelScrollingEnabled(false);

, ,
public boolean isWheelScrollingEnabled();

JSplitPane
JSplitPane , , ,
. , HORIZONTAL_SPLIT JSplitPane, VERTICAL_SPLIT. JSplitPane(int orientation). JSplitPane() .
JSplitPane . JSplitPane(int
orientation, boolean continuous).
.
JButton , UIManager.getString("SplitPane.leftButtonText")
UIManager.getString("SplitPane.rightButtonText"). "left button" "right
button", . 14.7.
, JSplitPane(int orientation, Component left, Component right),
orientation ,
() left, , () right.

. 14.7.

14. Swing

385

, ,
JScrollPane, , , .
, :
JSplitPane(int orientation, boolean continuous, Component left, Component right).

()
. getDividerLocation(), setDividerLocation(int). .
setDividerLocation(double),
() 0.0 1.0.
.
getLastDividerLocation(),
setLastDividerLocation(int).
setDividerSize(int), . Java L&F 8 .
,
, getMinimumSize(). getMinimumDividerLocation() getMaximumDividerLocation().
setOneTouchExpandable(true). . 14.7.

, .
setLeftComponent(Component), setRightComponent(Component),
setTopComponent(Component), setBottomComponent(Component),
.

JTabbedPane
JTabbedPane . ,
(tabs). .
JTabbedPane() . JTabbedPane(int pos) . pos JtabbedPane: TOP, BOTTOM, LEFT, RIGHT. ,
(TOP), , , ,
.
,
, , . 14.8. WRAP_TAB_LAYOUT, SCROLL_TAB_LAYOUT
JTabbedPane. , JTabbedPane(int pos, int tab),
.

386

III.

. 14.8.

, . JTabbedPane
:
Component add(Component)

Component add(String, Component) void addTab(String, Component)

, ;
void add(Component, Object) ,

. Icon;
Component add(Component, int) ;
void add(Component, Object, int) ;
void addTab(String, Icon, Component) / -

void addTab(String title, Icon image, Component comp, String tip) -

tip .

void insertTab(String title, Icon image, Component comp, String tip. int ind);

.
setXxx()
. , setBackgroundAt(Color), . 14.8 14.7. ,
.
14.7.
import java.awt.*;
import javax.swing.*;
public class Tabbed extends JFrame{
Tabbed(){
super(" ");
setLayout(new FlowLayout());
String[] day = {"", "", "",
"", "", "", ""};

14. Swing

387

JTabbedPane sp = new JTabbedPane(JTabbedPane.TOP,


JTabbedPane.SCROLL_TAB_LAYOUT);
sp.setPreferredSize(new Dimension(300, 100));
for (int i = 0; i < 7; i++){
sp.add(day[i], new JLabel(" " + i));
sp.setBackgroundAt(i, new Color(16*i, 0, 16*(7-i)));
}
add(sp);
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new Tabbed();
}
}

Box
Box ,
.
JToolBar,
. Box(int), BoxLayout: X_AXIS
, Y_AXIS .

createVerticalBox().
.
createHorizontalBox()

Box Container add(Component), add(Component, int).


Box BoxLayout. ,
setLayout(LayoutManager) , BoxLayout
. .

BoxLayout
BoxLayout BoxLayout(Container, int). ,
. X_AXIS ,
Y_AXIS , LINE_AXIS PAGE_AXIS . :
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.add(new JLabel(" : ", JLabel.RIGHT));
p.add(new JTextField(30));

388

III.

,
, .

. , ,
,
. , , getAlignmentX() getAlignmentY() .
0.0f (), 1.0f () .

-
, Box , ,
- .
(rigid area),
.
static Component Box.createRigidArea(Dimension);

,
.
"" (strut) . ,
static Component Box.createHorizontalStrut(int width);

. , .
,
static Component Box.createVerticalStrut(int height);

. .
" " (glue), "", ,
, . :
static Component Box.createGlue() "" ;
static Component Box.createHorizontalGlue() "" ;
static Component Box.createVerticalGlue() "" .

- , .
Filler, Box,
Box.Filler(Dimension min, Dimension pref, Dimension max);

,
void changeShape(Dimension min, Dimension pref, Dimension max);

14. Swing

389

14.8 Box. , "".


14.8. Box
import java.awt.*;
import javax.swing.*;
public class MyBox extends JFrame{
JButton b1 = new JButton("");
JButton b2 = new JButton("");
JTextArea ta = new JTextArea(5, 30);
MyBox(){
super(" ");
setLayout(new FlowLayout());
Box out = Box.createVerticalBox();
Box in1 = Box.createHorizontalBox();
Box in2 = Box.createHorizontalBox();
out.add(in1);
out.add(in2);
in1.add(ta);
in2.add(Box.createHorizontalGlue());
in2.add(b1);
in2.add(b2);
add(outer);
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new MyBox();
}
}

, Box, , . ,
, Box .
Box , .

SpringLayout
Box, BoxLayout,
,

390

III.

Box .
-.
.
,
AWT Swing .
, (x, y), width height
.
setBounds(int x, int y, int width, int height);


setLocation(int x, int y);
setSize(int width, int height);

,
.
, :
JPanel p = new JPanel();
p.setLayout(null);
int w = p.getSize().width, h = p.getSize().height;
JButton b = new JButton("");
b.setBounds(w/10, h/10, w/5, h/8);
p.add(b);

.
FlowLayout, , GridLayout, .
Java SE, JDK 1.4,
SpringLayout, .
(x, y) width, height, , Spring. .

Spring
Spring , . , .
.
Spring , ,
public static Spring constant(int min, int pref, int max);

, constant(int size), Spring


, size.
height width ,
comp:

14. Swing

391

public static Spring height(Component comp);


public static Spring width(Component comp);

, Spring
(min, pref, max).
, value, setValue(int value). value
. value
.
, getMinimumValue(),
getMaximumValue(), getPreferredValue(), getValue().
SpringLayout Spring.
, , . , , .
Spring :
public static Spring max(Spring s1, Spring s2) ,

s1 s2;
public static Spring minus(Spring s) ,

s ;
public static Spring sum(Spring s1, Spring s2) ,

s1 s2.
s1 s2 ,
:
Spring sp = Spring.minus(Spring.max(Spring.minus(s1), Spring.minus(s2)));

Constraints
Spring . ,
SpringLayout.Constraints.
Constraints, , (x, y), width height, , Spring. x y , . , , , SpringLayout.
x y .
WEST NORTH SpringLayout.
width height , , , SpringLayout.
. x + width y + height
EAST SOUTH .
Constraints "" "": setX(Spring), getX(), setY(Spring), getY(), setWidth(Spring),

392

III.

getWidth(), setHeight(Spring), getHeight(). setConstraint(String, Spring)


getConstraint(String) Spring
NORTH, WEST, SOUTH EAST.



SpringLayout .
, comp[0], comp[1], comp[2]
. .
6 . , 10
. 14.9 , ,
. 14.9 .
14.9. SpringLayout
import java.awt.*;
import javax.swing.*;
public class SpringWin extends JFrame{
JComponent[] comp = {
new JButton(" "),
new JButton("<html> <p> "),
new JButton("OK")
};
public SpringWin(){
super(" SpringLayout");
SpringLayout sl = new SpringLayout();
setLayout(sl);
//
Spring xPad = Spring.constant(6);
//
Spring yPad = Spring.constant(10);
//
Spring currX = yPad;
// , 0
Spring maxHeight = Spring.constant(0);
for (int i = 0; i < comp.length; i++){
add(comp[i]);
// i-
SpringLayout.Constraints cons = sl.getConstraints(comp[i]);
// i-
cons.setX(currX);
cons.setY(yPad);
//
currX = Spring.sum(xPad, cons.getConstraint("East"));

14. Swing

393

//
maxHeight = Spring.max(maxHeight, cons.getConstraint("South"));
}
//
SpringLayout.Constraints pCons = sl.getConstraints(c);
//
pCons.setConstraint(SpringLayout.EAST, Spring.sum(currX, yPad));
pCons.setConstraint(SpringLayout.SOUTH, Spring.sum(maxHeight, yPad));
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String args[]){
new SpringWin();
}
}

. 14.9. SpringLayout

JToolBar
JToolBar . . .
JToolBar().
JToolBar(int) :
HORIZONTAL, VERTICAL.
JToolBar(String) .
, JToolBar(String, int) .
Java SE , , BorderLayout . "". () "".
. 14.10. , . "", "" "", ,
. "" ,
JFrame. ,

394

III.

. "" ,
.
.
setFloatable(false). "" , .
, 2 . 14.10, setRollover(true)
.

. 14.10.

JToolBar
DefaultToolBarLayout, BoxLayout, ,
. 14.10 .
14.10.
import java.awt.*;
import javax.swing.*;
public class MyTool extends JFrame{
MyTool(){
super(" ");
JToolBar tb1 = new JToolBar(" 1"),
tb2 = new JToolBar(" 2");
tb1.setRollover(true);
tb1.add(new JButton(new ImageIcon("Add24.gif")));
tb1.add(new JButton(new ImageIcon("AlignTop24.gif")));
tb1.add(new JButton(new ImageIcon("About24.gif")));
tb2.add(new JButton(""));
tb2.add(new JButton(""));
tb2.add(new JButton(""));
add(tb1, BorderLayout.NORTH);
add(tb2, BorderLayout.WEST);
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);

14. Swing

395

setVisible(true);
}
public static void main(String[] args){
new MyTool();
}
}

Java SE $JAVA_HOME/demo/jfc/Notepad/
JToolBar. ,

java jar Notepad.jar

add(Component), ,
, . , , .
, Swing Action.

Action
Action , ,
- : , -, -,
, .
ActionListener,
String putValue(String
key, Object value), getValue(String key).
actionPerformed(ActionEvent)

:
ACCELERATOR_KEY -, KeyStroke;
ACTION_COMMAND_KEY KeyMap;
DEFAULT ;
DISPLAYED_MNEMONIC_INDEX_KEY , ;
LARGE_ICON_KEY ;
LONG_DESCRIPTION ;
MNEMONIC_KEY int;
NAME , ;
SELECTED_KEY ;
SHORT_DESCRIPTION ;
SMALL_ICON .

, , :
act.putValue(Action.SMALL_ICON, new ImageIcon("save.gif"));

:
ImageIcon ic = (ImageIcon)act.getValue(Action.SMALL_ICON);

396

III.

, Action, (enabled)
(disabled). setEnabled(boolean). , , ,
.
Action AbstractAction,
actionPerformed(ActionEvent).
AbstractAction, , .
, JMenu, JPopupMenu JToolBar, , Action.
add(Action act) , , act.
, tb.add(act) tb JToolBar JButton , , ,
act. m.add(act) m JMenu act
JMenuItem , , , act.

ActionEvent, actionPerformed(ActionEvent). ,
Action
.
, Action, , . , ,
. Action, add(Action).

JLayeredPane
(layered pane) JLayeredPane.
, . , , ,
. , Integer. , , . z .
add(Component comp, Object constraints) Container
JLayeredPane , , .
, comp 50 add(comp, new
Integer(50)).
Integer. Swing.
FRAME_CONTENT_LAYER Integer(30000). , .
JRootPane .

14. Swing

397

DEFAULT_LAYER Integer(0).

.
PALETTE_LAYER Integer(100). -

.
MODAL_LAYER Integer(200). -

.
POPUP_LAYER Integer(300). ,

.
DRAG_LAYER Integer(400).

.
.
,
setBounds(int x, int y, int width, int height);


setLocation(int x, int y);
setSize(int width, int height);

JLayeredPane JComponent Swing.


Container,
,
, 1 .
:
moveToFront(Component comp) comp 0;
moveToBack(Component comp) comp 1;
setPosition(Component comp, int ind) comp ind.

, :
setLayer(Component comp, int layer) comp layer

1 ;
setLayer(Component comp, int layer, int pos) comp layer

pos .
add().
.
JRootPane .

JRootPane
JRootPane (root pane),
JWindow, JDialog, JFrame, JInternalFrame, JApplet, , RootPaneContainer.

398

III.

,
. . , .
(content pane),
getContentPane(). Container, . BorderLayout. , :
getContentPane().setLayout(new FlowLayout());

, :
Container c = getContentPane();
c.add(new JLabel(" ", JLabel.CENTER), BorderLayout.NORTH);
c.add(new JTextArea(5, 50));

Java SE, .
c,

add(new JLabel(" ", JLabel.CENTER), BorderLayout.NORTH);
add(new JTextArea(5, 50));

FRAME_CONTENT_LAYER
JLayeredPane. , ,
JMenuBar.
, JRootPane .
JLayeredPane,
.
,
:
getLayeredPane().add(toolBar, JLayeredPane.PALETTE_LAYER);

, , "
" (glass pane). , Component, , . , , .
, ,
, , MouseEvent, .
, , . , ,
:
getGlassPane().addMouseInputListener(this);

, . ,
, , .
. , ,
, setVisible(true).

14. Swing

399

. , .
, setContentPane(Container), setLayeredPane(JLayeredPane)
setGlassPane(Component) .
,
AWT, Container. , :
JFrame fr = new JFrame(" ");
JPanel c = new JPanel();
c.add(new JTextField(50));
c.add(new JButton("OK"));
fr.setContentPane(c);

, , .
setWindowDecorationStyle(int) . NONE ( ), FRAME, PLAIN_DIALOG,
INFORMATION_DIALOG, ERROR_DIALOG, COLOR_CHOOSER_DIALOG, FILE_CHOOSER_DIALOG, QUESTION_DIALOG,
WARNING_DIALOG. Look and Feel 17.

JWindow
JWindow , . JWindow Window,
AWT. "" Swing.
JWindow . , . , , . JWindow (splash window), .
JWindow , "" (parent) .
JWindow(Frame), JWindow(Window)
JWindow(Window, GraphicsConfiguration). ,
, , ,
. .
JWindow() JWindow(GraphicsConfiguration),
. , ,
. .
JWindow
JRootPane. ,
.
getRootPane(), JWindow
getContentPane(), getLayeredPane() getGlassPane().
, .
, , :

400

III.

public Container getContentPane(){


return getRootPane().getContentPane();
}

, , setLayout(LayoutManager), .
setLayout() , rootPaneCheckingEnabled false,
. true,
setRootPaneCheckingEnabled(boolean). (protected),
JWindow.
add(), addImpl() JWindow,
JRootPane.
setRootPane(JRootPane)
setContentPane(Container), setLayeredPane(JLayeredPane)
setGlassPane(Component).
Window dispose() , .

JDialog
JDialog Dialog AWT (. 10) "" . (modal) .
,
.
Window, Dialog
Frame. JDialog()
.
JDialog(Frame), JDialog(Frame, String), JDialog(Dialog), JDialog(Dialog, String)
JDialog(Window), JDialog(Window, String) .
JDialog(Frame, boolean), JDialog(Frame, String, boolean), JDialog(Dialog,
boolean), JDialog(Dialog, String, boolean) DEFAULT_MODALITY_TYPE, true,
.

JDialog(Window,
Dialog.ModalityType),
JDialog(Window, String,
Dialog.ModalityType) .


setModalityType(Dialog.ModalityType) setTitle(String).
, JWindow, JRootPane
getContentPane(), getLayeredPane(), getGlassPane()
getRootPane().

14. Swing

401

, .
, JWindow.
JWindow, JDialog setRootPane(JRootPane),
setContentPane(Container), setLayeredPane(JLayeredPane) setGlassPane(Component).
, ,
. , , <Alt>+<F4>,
setDefaultCloseOperation(int);

:
DO_NOTHING_ON_CLOSE ;
HIDE_ON_CLOSE ( );
DISPOSE_ON_CLOSE , .

- , , :
setDefaultCloseOperation(JDialog.DO_NOTHUNG_ON_CLOSE);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
ta.setText(tf.getText()); dispose();
}
});

,
setResizable(boolean).
, , .
setUndecorated(true), .
Look and Feel
setWindowDecorationStyle(int) JRootPane. Look and Feel
17.
, ,
- . Swing JOptionPane
. .

JFrame
JFrame Frame AWT.
,
, , .

402

III.

JFrame(), JFrame(String)
. ,
setVisible(true).
JFrame
JRootPane. , , .
setDefaultCloseOperation(int), , : EXIT_ON_CLOSE System.exit(0). .
, JFrame Frame setIconImage(Image).
, ,
,
setUndecorated(true), Look and Feel
getRootPane().setWindowDecorationStyle(JRootPane.FRAME);

17.

JInternalFrame
JInternalFrame , JFrame, , JDesktopPane. , , , , .
, Java, Java L&F.
JFrame JInternalFrame:
, , .
. ,
JInternalFrame(), , , ,
, . , .

setClosable(boolean), setTitle(String), setIconifiable(boolean), setMaximizable(boolean),
setResizable(boolean), setVisible(boolean).
:
JInternalFrame(String title, boolean resizable, boolean closable,
boolean maximizable, boolean iconifiable)

, false. . 14.11 ,
. ,

14. Swing

403

. 14.11 ,
.
14.11.
import java.awt.*;
import javax.swing.*;
public class IntFrame extends JFrame{
IntFrame(){
super(" ");
setLayout(new FlowLayout());
JInternalFrame ifr1 =
new JInternalFrame(" ", true, true, true, true);
ifr1.getContentPane().add(new JLabel(" "));
ifr1.setPreferredSize(new Dimension(200, 200));
ifr1.setVisible(true);
add(ifr1);
JInternalFrame ifr2 = new JInternalFrame(" ");
ifr2.getContentPane().add(new JButton(" "));
ifr2.setPreferredSize(new Dimension(200, 200));
ifr2.setVisible(true);
add(ifr2);
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new IntFrame();
}
}

. 14.11.

III.

404

Swing, JInternalFrame JRootPane , .


JFrame, JVM setDefaultCloseOperation(int) EXIT_ON_CLOSE.

JDesktopPane
, " " JDesktopPane.
,
.
JDesktopPane JLayeredPane, , , ,
.
setBounds(), 14.12. . 14.12
14.12.
14.12.
import java.awt.*;
import javax.swing.*;
public class Desk extends JFrame{
Desk(){
super(" ");
JDesktopPane dp = new JDesktopPane();
setContentPane(dp);
JInternalFrame ifr1 =
new JInternalFrame(" ", true, true, true, true);
ifr1.getContentPane().add(new JLabel(" "));
ifr1.setBounds(10,10, 200,200);
ifr1.setVisible(true);
dp.add(ifr1);
JInternalFrame ifr2 = new JInternalFrame(" ");
ifr2.getContentPane().add(new JButton(" "));
ifr2.setBounds(150, 200, 200, 100);
ifr2.setVisible(true);
dp.add(ifr2);
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

14. Swing

405

public static void main(String[] args){


new Desk();
}
}

. 14.12.

setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);

JOptionPane
JDialog , (message), - (confirm) (input).
JOptionPane . showMessageDialog() ,
, showConfirmDialog(),
, showInputDialog(), , ,
showOptionDialog().
JDialog.
showInternalXxxDialog()
JInternalFrame.
, , , :
INFORMATION_MESSAGE , Java L&F "i"

, . 14.20 ( );

406

III.

WARNING_MESSAGE ,

, . 14.15;
ERROR_MESSAGE , "" -

, . 14.13;
QUESTION_MESSAGE , ,

. 14.14;
PLAIN_MESSAGE .

Icon,
. 14.16.

static void showMessageDialog(Component parent, Object message,


String title, int type, Icon icon);

parent,
title, message, type , , icon.
, message Object.
Component,
Icon. toString(), JLabel, . message Object[]. .
. 14.13 ,
JOptionPane.showMessageDialog(this,
" \"\" .",
" ", JOptionPane.ERROR_MESSAGE);

. 14.13. ""

. 14.14. ""

: Yes (),
No (), Cancel (). YES_NO_OPTION
YES_NO_CANCEL_OPTION optType showConfirmDialog().
:
static int showConfirmDialog(Component parent, Object message,
String title, int optType, int messType, Icon icon);

YES_OPTION, NO_OPTION, CANCEL_OPTION


, .
CLOSED_OPTION. . 14.14 , , , :

14. Swing

407

int n = JOptionPane.showConfirmDialog(this,
" / (Yes/No)?",
" ", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
switch(n){
case JOptionPane.YES_OPTION: saveDoc(); break;
case JOptionPane.NO_OPTION: restore(); saveDoc(); break;
case JOptionPane.CANCEL_OPTION:
case JOptionPane.CLOSED_OPTION: break;
default:
}

, , , OK Cancel (). . 14.15


,
String s = (String)JOptionPane.showInputDialog(this,
" : ", " ", JOptionPane.WARNING_MESSAGE);

. 14.15.
""

. 14.16.

. 14.16 ,
String[] vars = {"", "", ""};
String s = (String)JOptionPane.showInputDialog(this,
" :", " ",
JOptionPane.QUESTION_MESSAGE, new ImageIcon("bird.gif"),
vars, "");

, ,
,
static int showOptionDialog(Component parent, Object message,
String title, int optType, int messType, Icon icon,
Object[] options, Object init);

options
, . init
.

408

III.

, , . 14.14, ,
String[] vars = {"", "", " "};
int n = JOptionPane.showOptionDialog(this,
" ?",
" ", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, vars, "");

. 14.17.

. 14.17.

. 14.18.

, : L&F , , ,
, . ,
JDialog,
JOptionPane. .
JOptionPane() OK
. . 14.18.
JOptionPane op = new JOptionPane();
JDialog d = op.createDialog(this, " ");
d.setVisible(true);

:
JOptionPane(Object message, int messType, int optType,
Icon icon, Object[] options, Object init);

.
. 14.19 ,
String[] opts = {"", "", "", ""};
JOptionPane op = new JOptionPane(
"<html><font size=+2 > ?",
JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_CANCEL_OPTION,
null, opts, opts[2]);
JDialog d = op.createDialog(this, " ");
d.setVisible(true);

14. Swing

409

. 14.19.

ProgressMonitor
, , ProgressMonitor.
, -"" JProgressBar OK
Cancel.

ProgressMonitor(Component parent, Object message, String note, int min, int max);

parent , message, min max "" note. , setNote(String).



setProgress(int pos), pos, min
max. JProgressBar, 11.
14.13 .
. 14.20 14.13.
14.13.
import java.awt.*;
import javax.swing.*;
public class Progress extends JFrame{
Progress(){
super(" Progress...");
final ProgressMonitor mon = new ProgressMonitor(this,
" .", " ", 0, 100);
Runnable runnable = new Runnable(){
public void run(){
for (int i = 1; i < 100; i++){
try{
mon.setNote( " " + (100 i) + " %");
mon.setProgress(i);

III.

410

if (mon.isCanceled()){
mon.setProgress(100);
break;
}
Thread.sleep(100);
}catch(InterruptedException e){}
}
mon.close();
}
};
Thread thread = new Thread(runnable);
thread.start();
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new Progress();
}
}

. 14.20.

, InputStream ProgressMonitorInputStream, FilterInputStream.

Java, Sun Java SE


. ,
LayoutManager LayoutManager2,
.

14. Swing


1. ?
2. ?
3. ?
4. ?
5. BorderLayout ?
6. JFrame?
7. JPanel?
8. JScrollPane?
9. JWindow?
10. JDialog?
11. ?

411

15


,
, , , , . . ,
. , "" , .
, .
- , , . . .
(event) AWT , , , .
, , (source) .
AWT .
Java .
, .
- EventObject java.util Object. AWTEvent
java.awt , AWT.
- AWT . 15.1. ,
, AWTEvent, java.awt.event.
ComponentEvent, FocusEvent, KeyEvent, MouseEvent -

.
ContainerEvent Container, ,

Swing.
WindowEvent Window .
TextEvent TextComponent, TextArea,
TextField.

ActionEvent Button, List, TextField,


JComboBox, JTextField,

AbstractButton .

ItemEvent Checkbox, JCheckbox, Choice,


JComboBox, List

AbstractButton .

15.

413

, AdjustmentEvent
Scrollbar JScrollBar.

, , getSource()
Object.

EventObject.

- paramString(), String. ,
, . ,
getID() (identifier) ,
. - .
Swing -,
javax.swing.event.
EventObject.
.
, Java .
- (listener).
. 15.1 , InputEvent ( ),
. "Listener",
: ActionListener, MouseListener. "",
. , -
, .

. 15.1. , AWT

, . , , -
(handlers) (listeners): "",
, .
, -
eventHandler -
addXxxListener(XxxEvent eventHandler), Xxx .
, " " ,
(callback). , , , : " - ".
, removeXxxListener().

414

III.

, -, ,
. -,
, (delegate) .
(delegation). ,
- - . , -
.
, . ,
. , , : , , , . ,
, .
, - , . -
, . . , ,
addXxxListener(). - "", , .
, , , . ""
, .
. JFrame tf
JTextField, ta JTextArea b JButton.
tf , <Enter>
b ta.
tf . .
<Enter>,
ActionEvent, -:
tf b.
tf (, tf.getText()) ta (,
ta.append()). , ActionEvent,
, ActionListener.
actionPerformed(), .
, :
class TextMove implements ActionListener{
private JTextField tf;
private JTextArea ta;
TextMove(JTextField tf, JTextArea ta){
this.tf = tf; this.ta = ta;
}
public void actionPerformed(ActionEvent ae){
ta.append(tf.getText()+"\n");
}
}

. ActionEvent
- TextMove,

15.

415

-, actionPerformed(), , .
-, tf b
ActionEvent, TextMove,
addActionListener(), 15.1.
15.1. ActionEvent
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyNotebook extends JFrame{
MyNotebook(String title){
super(title);
JTextField tf = new JTextField(" ", 50);
add(tf, BorderLayout.NORTH);
JTextArea ta = new JTextArea();
ta.setEditable(false);
add(ta);
JPanel p = new JPanel();
add(p, BorderLayout.SOUTH);
JButton b = new JButton("");
p.add(b);
tf.addActionListener(new TextMove(tf, ta));
b.addActionListener(new TextMove(tf, ta));
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args){
JFrame f = new MyNotebook(" ActionEvent");
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
// TextMove
// ...

. 15.2 .
15.1 addActionListener()
tf b.
TextMove, :
TextMove

416

III.

TextMove tml = new TextMove(tf, ta);


tf.addActionListener(tml);
b.addActionListener(tml);

, , ,
, . ,
.

. 15.2. ActionEvent


, , .
, , ,
.
-, 15.2.
15.2. ActionEvent
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyNotebook extends JFrame implements ActionListener{
private JTextField tf;
private JTextArea ta;
MyNotebook(String title){
super(title);
tf = new JTextField(" ", 50);
add(tf, BorderLayout.NORTH);
ta = new JTextArea();
ta.setEditable(false);
add(ta);

15.

417

JPanel p = new JPanel();


add(p, BorderLayout.SOUTH);
JButton b = new JButton("");
p.add(b);
tf.addActionListener(this);
b.addActionListener(this);
setSize(300, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent ae){
ta.append(tf.getText()+"\n");
}
public static void main(String[] args){
JFrame f = new MyNotebook(" ActionEvent");
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

tf ta , ,
, actionPerformed().
MyNotebook. MyNotebook - ActionEvent ActionListener. addActionListener()
this .
, , , . , ta
, MyNotebook.


.
- TextMove,
15.3.
15.3.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyNotebook extends JFrame{
private JTextField tf;
private JTextArea ta;
MyNotebook(String title){
super(title);
tf = new JTextField(" ", 50);

418

III.

add(tf, BorderLayout.NORTH);
ta = new JTextArea();
ta.setEditable(false);
add(ta);
JPanel p = new JPanel();
add(p, BorderLayout.SOUTH);
JButton b = new JButton("");
p.add(b);
tf.addActionListener(new TextMove());
b.addActionListener(new TextMove());
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args){
JFrame f = new MyNotebook(" ActionEvent");
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//
class TextMove implements ActionListener{
public void actionPerformed(ActionEvent ae){
ta.append(tf.getText()+"\n");
}
}
}

, , , <Alt>+<F4>
AWT.
WindowEvent, windowClosing(),
System.exit(0).
, WindowAdapter.
-, .
.

1. .

ActionEvent
, - . , : , - .
ActionEvent :
getActionCommand() String JButton,

, , setActionCommand(String s) JButton, JList, - , ;

15.

419

getModifiers() <Alt>, <Ctrl>, <Meta> <Shift>,

- , int. , , ALT_MASK, CTRL_MASK, META_MASK, SHIFT_MASK.



<Meta> PC- , <Esc>
<Alt>.

, , <Alt>
Open:
public void actionPerformed(ActionEvent ae){
if (ae.getActionCommand() == "Open" &&
(ae.getModifiers() | ActionEvent.ALT_MASK) != 0){
// -
}
}


MouseEvent :
MOUSE_PRESSED;
MOUSE_RELEASED;
MOUSE_CLICKED (

);
MOUSE_MOVED;
MOUSE_DRAGGED;
MOUSE_ENTERED;
MOUSE_EXITED.

:
public interface MouseListener extends EventListener{
public void mouseClicked(MouseEvent e);
public void mousePressed(MouseEvent e);
public void mouseReleased(MouseEvent e);
public void mouseEntered(MouseEvent e);
public void mouseExited(MouseEvent e);
}
public interface MouseMotionListener extends EventListener{
public void mouseDragged(MouseEvent e);
public void mouseMoved(MouseEvent e);
}

e e.getX(), e.getY() e.getPoint(), -

420

III.

Point. , GraphicsConfiguration,
e.getXOnScreen(), e.getYOnScreen() e.getLocationOnScreen().
e.getClickCount(), . 0.
, , e.getModifiers()
InputEvent InputEvent:
BUTTON1_MASK , ;
BUTTON2_MASK , ,

;
BUTTON3_MASK , .

, . 15.4 "" Scribble. mousePressed() .



mouseDragged(). . 15.3 .
15.4.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ScribbleTest extends JFrame{
public ScribbleTest(String s){
super(s);
Scribble scr = new Scribble(this, 500, 500);
JScrollPane pane = new JScrollPane(scr);
pane.setSize(300, 300);
add(pane, BorderLayout.CENTER);
JPanel p = new JPanel();
add(p, BorderLayout.SOUTH);
JButton b1 = new JButton("");
b1.addActionListener(scr);
JButton b2 = new JButton("");
b2.addActionListener(scr);
JButton b3 = new JButton("");
b3.addActionListener(scr);
JButton b4 = new JButton("");
b4.addActionListener(scr);
JButton b5 = new JButton("");
b5.addActionListener(scr);

p.add(b1);
p.add(b2);
p.add(b3);
p.add(b4);
p.add(b5);

setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();

15.

421

setVisible(true);
}
public static void main(String[] args){
new ScribbleTest(" \"\"");
}}
class Scribble extends JPanel implements
ActionListener, MouseListener, MouseMotionListener{
protected int lastX, lastY, w, h;
protected Color currColor = Color.black;
protected JFrame f;
public Scribble(JFrame frame, int width, int height){
f = frame; w = width; h = height;
enableEvents(AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK);
addMouseListener(this);
addMouseMotionListener(this);
}
public Dimension getPreferredSize(){
return new Dimension(w, h);
}
public void actionPerformed(ActionEvent event){
String s = event.getActionCommand();
if (s.equals("")) repaint();
else if (s.equals("")) currColor = Color.red;
else if (s.equals("")) currColor = Color.green;
else if (s.equals(""))
currColor = Color.blue;
else if (s.equals("")) currColor = Color.black;
}
public void mousePressed(MouseEvent e){
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == 0) return;
lastX = e.getX(); lastY = e.getY();
}
public void mouseDragged(MouseEvent e){
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == 0) return;
Graphics g = getGraphics();
g.setColor(currColor);
g.drawLine(lastX, lastY, e.getX(), e.getY());
lastX = e.getX(); lastY = e.getY();
}
public void mouseReleased(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseMoved(MouseEvent e){}
}

- Scribble MouseListener
MouseMotionListener , -

422

III.

,
mousePressed() mouseDragged(). .
, , -.

. 15.3.

2. - .

-
- -,
.
"Adapter". , -.
:
public abstract
public void
public void
public void
public void
public void
public void
public void
public void
}
public abstract
public void
public void
}

class MouseAdapter implements MouseListener{


mouseClicked(MouseEvent e){}
mousePressed(MouseEvent e){}
mouseReleased(MouseEvent e){}
mouseEntered(MouseEvent e){}
mouseExited(MouseEvent e){}
mouseMoved(MouseEvent e){}
mouseDragged(MouseEvent e){}
mouseWheelMoved(MouseEvent e){}
class MouseMotionAdapter implements MouseMotionListener{
mouseDragged(MouseEvent e){}
mouseMoved(MouseEvent e){}

15.

423

, .
, ,
. - WindowAdapter.
- . ,
ComponentAdapter, ContainerAdapter, FocusAdapter KeyAdapter.


, , . Java SE, JDK 1.4, , ,
JScrollPane. , , MouseWheelEvent.
MouseWheelEvent MouseEvent, ,
. : , WHEEL_BLOCK_SCROLL,
WHEEL_UNIT_SCROLL. , "" ""
getScrollType(). , , .
WHEEL_UNIT_SCROLL, getUnitsToScroll() : , . getScrollAmount()
. .
"",
getWheelRotation() "",
.
, ,
.
MouseWheelListener
public void mouseWheelMoved(MouseWheelEvent e);

-,
. 15.5 .
15.5.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WheelEv extends JFrame
implements MouseWheelListener{
JTextArea ta = new JTextArea(5, 30);
WheelEv(){
super(" ");
getContentPane().add(ta);

424

III.

ta.addMouseWheelListener(this);
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void mouseWheelMoved(MouseWheelEvent e){
if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL)
ta.append(" = " + e.getUnitsToScroll() +
" = "+ e.getScrollAmount() +
" = " + e.getWheelRotation() + "\n");
}
public static void main(String[] args){
new WheelEv();
}
}

15.4 , Windows XP.

. 15.4. ,


KeyEvent :
KEY_PRESSED;
KEY_RELEASED;
KEY_TYPED.

- ,
,
<Shift>+<>. <Alt>- MS Windows.
, <F1>, KEY_TYPED.
, :
public interface KeyListener extends EventListener{
public void keyTyped(KeyEvent e);

15.

425

public void keyPressed(KeyEvent e);


public void keyReleased(KeyEvent e);
}

e .
e.getKeyChar() Unicode char, .
, CHAR_UNDEFINED.
int.
,
(virtual key codes), : VK_F1, VK_SHIFT, VK_A, VK_B, VK_PLUS. KeyEvent.
. , ,
getKeyCode() .
, KEY_TYPED,
VK_UNDEFINED.
e.getKeyCode()
KeyEvent

, - <Alt>, <Ctrl>,
<Meta>, <Shift>, InputEvent
getModifiers() ALT_MASK, CTRL_MASK, META_MASK,
SHIFT_MASK. isAltDown(), isControlDown(),
isMetaDown(), isShiftDown().
15.3 tf
<Esc>. - TextMove:
class TextMove implements ActionListener, KeyListener{
public void actionPerformed(ActionEvent ae){
ta.append(tf.getText()+"\n");
}
public void keyPressed(KeyEvent ke){
if (ke.getKeyCode() == KeyEvent.VK_ESCAPE) tf.setText("");
}
public void keyReleased(KeyEvent ke){}
public void keyTyped(KeyEvent ke){}
}

3. .

TextEvent
TextEvent
TEXT_VALUE_CHANGED.
:
public interface TextListener extends EventListener{
public void textValueChanged(TextEvent e);
}

426

III.

e -
getSource(), EventObject, , :
JTextComponent tc = (JTextComponent)e.getSource();
String s = tc.getText();
//

ChangeEvent
ChangeEvent
Swing: Swing , , "", .
,
, JColorChooser JSlider .
hangeEvent ,
, getSource().
ChangeListener :
public void stateChanged(ChangeEvent);


, :
import javax.swing.event.*;
class SliderHandler implements ChangeListener{
private int threshold;
private JLabel l;
public SliderHandler(int threshold, JLabel l){
this.threshold = threshold; this.l = l;
}
public void stateChanged(ChangeEvent e){
JSlider sl = (JSlider)e.getSource();
if (!sl.getValueIsAdjusting())
if (threshold <= (int)sl.getValue())
l.setText(" ");
}
}


WindowEvent :
WINDOW_OPENED;
WINDOW_CLOSED;
WINDOW_CLOSING;

15.

427

WINDOW_ACTIVATED;
WINDOW_GAINED_FOCUS;
WINDOW_DEACTIVATED;
WINDOW_LOST_FOCUS;
WINDOW_ICONIFIED;
WINDOW_DEICONIFIED;
WINDOW_STATE_CHANGED;
WINDOW_FIRST;
WINDOW_LAST.

:
public interface WindowListener extends EventListener {
public void windowOpened(WindowEvent e);
public void windowClosing(WindowEvent e);
public void windowClosed(WindowEvent e);
public void windowIconified(WindowEvent e);
public void windowDeiconified(WindowEvent e);
public void windowActivated(WindowEvent e);
public void windowDeactivated(WindowEvent e);
}

e Window -
e.getWindow().
repaint() .

ComponentEvent
:
COMPONENT_MOVED;
COMPONENT_RESIZED;
COMPONENT_HIDDEN;
COMPONENT_SHOWN.

:
public interface ComponentListener extends EventListener{
public void componentMoved(ComponentEvent e);
public void componentResized(ComponentEvent e);
public void componentHidden(ComponentEvent e);
public void componentShown(ComponentEvent e);
}

e -
e.getComponent().

428

III.

ContainerEvent
:
COMPONENT_ADDED;
COMPONENT_REMOVED.

:
public interface ContainerListener extends EventListener{
public void componentAdded(ContainerEvent e);
public void componentRemoved(ContainerEvent e);
}

e , , e.getChild() e.getContainer().
.

C FocusEvent
,
FOCUS_GAINED FOCUS_LOST.
:
public interface FocusListener extends EventListener{
public void focusGained(FocusEvent e);
public void focusLost(FocusEvent e);
}

,
brighter() Color, ,
darker().
.

ItemEvent
List,
Choice, JComboBox, Checkbox, Swing,
AbstractButton, ITEM_STATE_CHANGED.
:
public interface ItemListener extends EventListener{
void itemStateChanged(ItemEvent e);
}

e e.getItemSelectable(),
e.getItem() Object.

15.

429

e.getStateChange() , : SELECTED , , DESELECTED .


10 .

AdjustmentEvent
Scrollbar JScrollBar ADJUSTMENT_VALUE_CHANGED.
:
public interface AdjustmentListener extends EventListener{
public void adjustmentValueChanged(AdjustmentEvent e);
}

e
e.getAdjustable(),
e.getValue() e.getAdjustmentType(), :
UNIT_INCREMENT ;
UNIT_DECREMENT ;
BLOCK_INCREMENT ;
BLOCK_DECREMENT ;
TRACK .

"" , 10.4, . 15.6.


15.6.
import java.awt.*;
import java.awt.event.*;
class ScrollTest1 extends Frame{
private Scrollbar
sbRed = new Scrollbar(Scrollbar.VERTICAL, 127, 16, 0, 271),
sbGreen = new Scrollbar(Scrollbar.VERTICAL, 127, 16, 0, 271),
sbBlue = new Scrollbar(Scrollbar.VERTICAL, 127, 16, 0, 271);
private Color c = new Color(127, 127, 127);
private Label lm = new Label();
private Button
b1 = new Button(""),
b2 = new Button("");
ScrollTest1(String s){
super(s);

430

III.

setLayout(null);
setFont(new Font("Serif", Font.BOLD, 15));
Panel p = new Panel();
p.setLayout(null);
p.setBounds(10,50, 150, 260); add(p);
Label lc = new Label(" ");
lc.setBounds(20, 0, 120, 30); p.add(lc);
Label lmin = new Label("0", Label.RIGHT);
lmin.setBounds(0, 30, 30, 30); p.add(lmin);
Label lmiddle = new Label("127", Label.RIGHT);
lmiddle.setBounds(0, 120, 30, 30); p.add(lmiddle);
Label lmax = new Label("255", Label.RIGHT);
lmax.setBounds(0, 200, 30, 30); p.add(lmax);
sbRed.setBackground(Color.red);
sbRed.setBounds(40, 30, 20, 200); p.add(sbRed);
sbRed.addAdjustmentListener(new ChColor());
sbGreen.setBackground(Color.green);
sbGreen.setBounds(70, 30, 20, 200); p.add(sbGreen);
sbGreen.addAdjustmentListener(new ChColor());
sbBlue.setBackground(Color.blue);
sbBlue.setBounds(100, 30, 20, 200); p.add(sbBlue);
sbBlue.addAdjustmentListener(new ChColor());
Label lp = new Label(":");
lp.setBounds(250, 50, 120, 30); add(lp);
lm.setBackground(new Color(127, 127, 127));
lm.setBounds(220, 80, 120, 80); add(lm);
b1.setBounds(240, 200, 100, 30); add(b1);
b1.addActionListener(new ApplyColor());
b2.setBounds(240, 240, 100, 30); add(b2);
b2.addActionListener(new CancelColor());
setSize(400, 300);
setVisible(true);
}
class ChColor implements AdjustmentListener{
public void adjustmentValueChanged(AdjustmentEvent e){
int red = c.getRed(), green = c.getGreen(), blue = c.getBlue();
if (e.getAdjustable() == sbRed)
red = e.getValue();
else if (e.getAdjustable() == sbGreen) green = e.getValue();
else if (e.getAdjustable() == sbBlue) blue = e.getValue();
c = new Color(red, green, blue);
lm.setBackground(c);
}
}

15.

431

class ApplyColor implements ActionListener{


public void actionPerformed(ActionEvent ae){
setBackground(c);
}
}
class CancelColor implements ActionListener{
public void actionPerformed(ActionEvent ae){
c = new Color(127, 127, 127);
sbRed.setValue(127);
sbGreen.setValue(127);
sbBlue.setValue(127);
lm.setBackground(c);
setBackground(Color.white);
}
}
public static void main(String[] args){
Frame f = new ScrollTest1(" ");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
System.exit(0);
}
});
}
}


, 15.115.3, TextMove, : tf JTextField b JButton.
. b
"",
"". Button peer-.
FlowerButton 10.7 paint()
.
design pattern Observer.

. -
,
addXxxListener().
,
, .
addXxxListener() -, Vector, java.awt

432

III.

AWTEventMulticaster.
XxxListener, , . add(), ,
:
add(ActionListener a, ActionListener b);

: ,
ActionListener, a b, .
a += b.
Button, , addActionListener()
:
public synchronized void addActionListener(ActionListener l){
if (l == null){ return; }
actionListener = AWTEventMulticaster.add(actionListener, l);
newEventsOnly = true;
}

actionListener l.
InputEvent, KeyEvent MouseEvent, consume(). -, peer-, . ,
, "" .


, , , -,
- .
, , . , ,
.
AWT,
:
enableEvents().

AWTEvent, , , :
enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK |
AWTEvent.MOUSE_EVENT_MASK | AWTEvent.KEY_EVENT_MASK)

XxxEvent.
dispatchEvent() ,
, - processEvent() .

15.

433

processEvent()
processXxxEvent(). :
protected void processEvent(AWTEvent e){
if (e instanceof FocusEvent){
processFocusEvent((FocusEvent)e);
}else if (e instanceof MouseEvent){
switch(e.getID()){
case MouseEvent.MOUSE_PRESSED:
case MouseEvent.MOUSE_RELEASED:
case MouseEvent.MOUSE_CLICKED:
case MouseEvent.MOUSE_ENTERED:
case MouseEvent.MOUSE_EXITED:
processMouseEvent((MouseEvent)e);
break;
case MouseEvent.MOUSE_MOVED:
case MouseEvent.MOUSE_DRAGGED:
processMouseMotionEvent((MouseEvent)e);
break;
}
}else if (e instanceof KeyEvent){
processKeyEvent((KeyEvent)e);
}
// ...

, processKeyEvent(). -
- . :
protected void processKeyEvent(KeyEvent e){
KeyListener listener = keyListener;
if (listener != null){
int id = e.getID();
switch(id){
case KeyEvent.KEY_TYPED: listener.keyTyped(e);
break;
case KeyEvent.KEY_PRESSED: listener.keyPressed(e);
break;
case KeyEvent.KEY_RELEASED: listener.keyReleased(e);
break;
}
}
}

, AWTEvent,
processEvent(), ,
,
processKeyEvent(). ,
, :
super.processKeyEvent(e);

434

III.


processXxxEvent() .

10 10.10
.


.
15.7 MyEvent,
.
MyEvent (START)
(STOP).
15.7.
// 1. :
public class MyEvent extends java.util.EventObject{
protected int id;
public static final int START = 0, STOP = 1;
public MyEvent(Object source, int id){
super(source);
this.id = id;
}
public int getID(){ return id; }
}
// 2. Listener:
public interface MyListener extends java.util.EventListener{
public void start(MyEvent e);
public void stop(MyEvent e);
}
// 3. fireEvent():
protected Vector listeners = new Vector();
public void fireEvent( MyEvent e){
Vector list = (Vector) listeners.clone();
for(int i = 0; i < list.size(); i++){
MyListener listener = (MyListener)list.elementAt(i);
switch(e.getID()){
case MyEvent.START: listener.start(e); break;
case MyEvent.STOP: listener.stop(e); break;
}
}
}

,
fireEvent(this, MyEvent.START);

15.


fireEvent(this, MyEvent.STOP);


1. AWT?
2. Swing?
3. ?
4. ?
5. ?
6. ?
7. ?
8. ?
9. AWT ?

435

16



, .
- . , JButton ,
.
, "".
, JLabel, .
Swing
, , ,
.
Border
javax.swing.border.
public void paintBorder(Component c, Graphics g,
int x, int y, int width, int height);

c, , g Graphics,
, , , .
.
isBorderOpaque().
, getBorderInsets(Component c), ,
c, Insets. ,
Insets top, left,
right bottom. Insets
, :
int d = b.getBorderInsets(this).top;

Border AbstractBorder,
paintBorder(), isBorderOpaque()
false, getBorderInsets() .
public static Rectangle getInteriorRectangle(Component c, Border b,
int x, int y, int width, int height);

16.

437

AbstractBorder , . javax.swing
BorderFactory, createXxxBorder() . ,
setBorder(Border) JComponent. , . 16.1
:
JLabel l2 = new JLabel(" LineBorder(Color.blue, 3) ");
l2.setBorder(BorderFactory.createLineBorder(Color.blue, 3));

.
. 16.1, 16.1.
16.1.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class SimpBorders extends JFrame{
SimpBorders(){
super(" ");
setLayout(new FlowLayout());
JButton l1 = new JButton(" EmptyBorder() ");
l1.setBackground(Color.white);
l1.setBorder(BorderFactory.createEmptyBorder());
JLabel l2 = new JLabel(" LineBorder(Color.blue, 3) ");
l2.setBorder(BorderFactory.createLineBorder(Color.blue, 3));
JLabel l3 = new JLabel(" BevelBorder(BevelBorder.RAISED) ");
l3.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
JLabel l4 = new JLabel(" BevelBorder(BevelBorder.LOWERED) ");
l4.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
JLabel l5 = new JLabel(" ");
l5.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED,
Color.black, Color.white, Color.black, Color.white));
JLabel l6 = new JLabel(" EtchedBorder() ");
l6.setBorder(BorderFactory.createEtchedBorder());
add(l1); add(l2); add(l3);
add(l4); add(l5); add(l6);
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}

438

III.

public static void main(String[] args){


new SimpBorders();
}
}

. 16.1.

EmptyBorder
EmptyBorder . , , . 16.1, .
EmptyBorder(Insets);
EmptyBorder(int top, int left, int bottom, int right);

.
createEmptyBorder() BorderFactory ,
createEmptyBorder(int top, int left, int bottom, int right);

.
isBorderOpaque() false, paintBorder() . getBorderInsets()
Insets.

EmptyBorder setBorder(Border) JComponent.

LineBorder
LineBorder ,
. . 16.1, .
LineBorder(Color).
LineBorder(Color, int) .
LineBorder(Color, int, boolean), true, .
, createBlackLineBorder() createGrayLineBorder(),
.

16.

439

BorderFactory ,
LineBorder: createLineBorder(Color) createLineBorder(Color, int).

BevelBorder
BevelBorder : .
, ,
. RAISED,
. 16.1 . ,
. LOWERED,
. 16.1 . JButton.
BevelBorder(int type) type .

createBevelBorder(int type);
createRaisedBevelBorder();
createLoweredBevelBorder();

BorderFactory.

BevelBorder(int type, Color highlight, Color shadow);


createBevelBorder(int type, Color highlight, Color shadow);

BorderFactory highlight shadow .


.
BevelBorder(int type, Color highlightOuter, Color highlightInner,
Color shadowOuter, Color shadowInner);


createBevelBorder(int type, Color highlightOuter, Color highlightInner,
Color shadowOuter, Color shadowInner);

. highlightInner
shadowInner, highlightOuter shadowOuter.

SoftBevelBorder
SoftBevelBorder BevelBorder, , . , BevelBorder:
SoftBevelBorder(int type);
SoftBevelBorder(int type, Color highlight, Color shadow);
SoftBevelBorder(int type, Color highlightOuter, Color highlightInner,
Color shadowOuter, Color shadowInner);

440

III.

EtchedBorder
EtchedBorder , ,
, - ,
RAISED, - , LOWERED.
. 16.1 . "" Java L&F, "Metal".
EtchedBorder()
createEtchedBorder() BorderFactory.
RAISED LOWERED EtchedBorder(int)
createEtchedBorder(int).

EtchedBorder(Color highlight, Color shadow);


createEtchedBorder(Color highlight, Color shadow);

, ,
EtchedBorder(int type, Color highlight, Color shadow);


createEtchedBorder(int type, Color highlight, Color shadow);

MatteBorder
MatteBorder ,
. 16.2, , , , .
MatteBorder(Icon).
.
c
MatteBorder(Insets, Icon);
MatteBorder(Insets, Color);
MatteBorder(int top, int left, int bottom, int right, Icon);
MatteBorder(int top, int left, int bottom, int right, Color);


createMatteBorder(int top, int left, int bottom, int right, Icon);
createMatteBorder(int top, int left, int bottom, int right, Color);

BorderFactory.
, ,
. 16.2 , . 16.2.

16.

441

. 16.2.

16.2.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class MatBorders extends JFrame{
MatBorders(){
super(" ");
setLayout(new FlowLayout());
JLabel l1 = new JLabel(" MatteBorder(Icon) ");
l1.setBorder(new MatteBorder(new ImageIcon("about16.gif")));
JLabel l2 = new JLabel(" MatteBorder(3,6,3,6, Color.red) ");
l2.setBorder(BorderFactory.createMatteBorder(3,6,3,6, Color.red));
add(l1);
add(l2);
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new MatBorders();
}
}

TitledBorder
TitledBorder . TitledBorder(String) createTitledBorder(String)
BorderFactory ,
. . 16.3, .
.
TitledBorder(Border, String);

442

III.


createTitledBorder(Border, String);

. 16.3 EtchedBorder.
, TOP, , ABOVE_TOP, , BELOW_TOP. :
BOTTOM, ABOVE_BOTTOM, BELOW_BOTTOM. pos , .
, LEFT, ,
CENTER, , RIGHT. just ,
.
, , 16.5.

TitledBorder(Border, String, int just, int pos);


createTitledBorder(Border, String, int just, int pos);

. 16.3.
,
TitledBorder(Border, String, int just, int pos, Font);


createTitledBorder(Border, String, int just, int pos, Font);

,
TitledBorder(Border, String, int just, int pos, Font, Color);

BorderFactory
createTitledBorder(Border, String, int just, int pos, Font, Color);

. 16.3.

16.

443

16.3 , . 16.3. .
16.3.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class TitBorders extends JFrame{
TitBorders(){
super(" ");
setLayout(new FlowLayout());
JLabel l1 = new JLabel(" TitledBorder(String) ");
l1.setBorder(new TitledBorder(""));
JLabel l2 = new JLabel(
" TitledBorder(new EtchedBorder(),\"\") ");
l2.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), ""));
JLabel l3 = new JLabel(
"<html> CENTER," +
" ABOVE_TOP<p> ITALIC, 18 ");
l3.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "",
TitledBorder.CENTER, TitledBorder.ABOVE_TOP,
new Font("Times New Roman", Font.ITALIC, 18)));
JLabel l4 =
new JLabel(" RIGHT, BELOW_TOP ");
l4.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "",
TitledBorder.RIGHT, TitledBorder.BELOW_TOP,
new Font("Times New Roman", Font.ITALIC, 18),
Color.red ));
JLabel l5 =
new JLabel(" CENTER, BOTTOM ");
l5.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "",
TitledBorder.CENTER, TitledBorder.BOTTOM,
new Font("Times New Roman", Font.ITALIC, 18),
Color.red ));
add(l1); add(l2); add(l3); add(l4); add(l5);
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}

444

III.

public static void main(String[] args){


new TitBorders();
}
}

CompoundBorder
CompoundBorder , .
CompoundBorder(Border out, Border in)
createCompoundBorder(Border out, Border in) BorderFactory.

. 16.4.

. . 16.4 , 16.4 , .
16.4.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class CompBorders extends JFrame{
CompBorders(){
super(" ");
setLayout(new FlowLayout());
JLabel l1 = new JLabel(
" CompoundBorder(TitledBorder, TitledBorder) ");
l1.setBorder(new CompoundBorder(
BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "",
TitledBorder.CENTER, TitledBorder.ABOVE_TOP,
new Font("Times New Roman", Font.ITALIC|Font.BOLD, 20)),
BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "",
TitledBorder.RIGHT, TitledBorder.BOTTOM,

16.

445

new Font("Times New Roman", Font.ITALIC, 12),


Color.red)
));
JLabel l2 = new JLabel(
" CompoundBorder(BevelBorder.RAISED, BevelBorder.RAISED) ");
l2.setBorder(new CompoundBorder(
BorderFactory.createBevelBorder(BevelBorder.RAISED),
BorderFactory.createBevelBorder(BevelBorder.RAISED)
));
JLabel l3 = new JLabel(
" CompoundBorder(BevelBorder.RAISED, BevelBorder.LOWERED) ");
l3.setBorder(new CompoundBorder(
BorderFactory.createBevelBorder(BevelBorder.RAISED),
BorderFactory.createBevelBorder(BevelBorder.LOWERED)
));
add(l1); add(l2); add(l3);
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new CompBorders();
}
}


Swing
BorderFactory , .
AbstractBorder,
paintBorder() getBorderInsets().
, isBorderOpaque() ,
true.
, - . 16.5 , TitledBorder, , JComponent.
TitledBorder , PlaceBorder
.
PlaceBorder
PlaceBorderPane, JPanel. , PlaceBorder. 16.5
. 16.5.

III.

446

16.5. ,
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
interface BorderConstants{
static public final int DEFAULT_POSITION
static public final int ABOVE_TOP
static public final int TOP
static public final int BELOW_TOP
static public final int ABOVE_BOTTOM
static public final int BOTTOM
static public final int BELOW_BOTTOM
static
static
static
static
static
static

public
public
public
public
public
public

final
final
final
final
final
final

int
int
int
int
int
int

=
=
=
=
=
=
=

0;
1;
2;
3;
4;
5;
6;

DEFAULT_JUSTIFICATION = 0;
LEFT
= 1;
CENTER
= 2;
RIGHT
= 3;
LEADING = 4;
TRAILING = 5;

static public final int EDGE_SPACING = 2;


static public final int TEXT_SPACING = 2;
static public final int TEXT_INSET_H = 5;}
public class CompTitledTest extends JFrame
implements BorderConstants{
public CompTitledTest(){
super(" ");
JLabel lab = new JLabel(" PlaceBorder(JLabel) ",
new ImageIcon("middle.gif"), JLabel.LEFT);
PlaceBorderPane pbp =
new PlaceBorderPane(new EtchedBorder(), lab, CENTER, TOP);
add(pbp);
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new CompTitledTest();
}
}
class PlaceBorderPane extends JPanel implements BorderConstants{
protected JComponent comp;
protected JPanel p;
protected PlaceBorder border;

16.
public PlaceBorderPane(){
this(new JLabel(""));
}
public PlaceBorderPane(JComponent c){
this(null, c, LEFT, TOP);
}
public PlaceBorderPane(Border b, JComponent c, int just, int pos){
super(); comp = c;
border = new PlaceBorder(b, c, just, pos);
setBorder(border);
setLayout(null);
add(comp);
p = new JPanel();
add(p);
}
public JPanel getContentPane(){
return p;
}
public void doLayout(){
Insets insets = getInsets();
Rectangle r = getBounds();
r.x = 0; r.y = 0;
comp.setBounds(border.getComponentRect(r,insets));
r.x += insets.left;
r.y += insets.top;
r.width -= insets.left + insets.right;
r.height -= insets.top + insets.bottom;
p.setBounds(r);
}
class PlaceBorder extends TitledBorder{
public PlaceBorder(JComponent c){
this(null, c, LEFT, TOP);
}
public PlaceBorder(Border b){
this(b, null, LEFT, TOP);
}
public PlaceBorder(Border b, JComponent c){
this(b, c, LEFT, TOP);
}
public PlaceBorder(Border b, JComponent c, int just, int pos){
super(b, null, just, pos, null, null);
if (b == null)
border = super.getBorder();
}

447

448

III.

public void paintBorder(Component c, Graphics g,


int x, int y, int width, int height){
Rectangle r = new Rectangle(
x + EDGE_SPACING, y + EDGE_SPACING,
width (EDGE_SPACING * 2), height (EDGE_SPACING * 2));
Insets bIns = (border != null) ?
border.getBorderInsets(c) : new Insets(0, 0, 0, 0);
Rectangle rect = new Rectangle(x, y, width, height);
Insets insets = getBorderInsets(c);
Rectangle compR = getComponentRect(rect, insets);
int diff;
switch (titlePosition){
case ABOVE_TOP:
diff = compR.height + TEXT_SPACING;
r.y += diff;
r.height -= diff;
break;
case TOP:
case DEFAULT_POSITION:
diff = insets.top/2 bIns.top EDGE_SPACING;
r.y += diff;
r.height -= diff;
break;
case BELOW_TOP:
case ABOVE_BOTTOM:
break;
case BOTTOM:
diff = insets.bottom/2 bIns.bottom EDGE_SPACING;
r.height -= diff;
break;
case BELOW_BOTTOM:
diff = compR.height + TEXT_SPACING;
r.height -= diff;
}
border.paintBorder(c, g, r.x, r.y, r.width, r.height);
Color col = g.getColor();
g.setColor(c.getBackground());
g.fillRect(compR.x, compR.y, compR.width, compR.height);
g.setColor(col);
comp.repaint();
}
public Insets getBorderInsets(Component c, Insets insets){
Insets bIns = (border != null) ?
border.getBorderInsets(c) : new Insets(0, 0, 0, 0);
insets.top
= EDGE_SPACING + TEXT_SPACING + bIns.top;
insets.right = EDGE_SPACING + TEXT_SPACING + bIns.right;

16.
insets.bottom = EDGE_SPACING + TEXT_SPACING + bIns.bottom;
insets.left
= EDGE_SPACING + TEXT_SPACING + bIns.left;
if (c == null || comp == null) return insets;
int h = (comp != null) ? comp.getPreferredSize().height : 0;
switch (titlePosition){
case ABOVE_TOP:
insets.top += h + TEXT_SPACING;
break;
case TOP:
case DEFAULT_POSITION:
insets.top += Math.max(h, bIns.top) bIns.top;
break;
case BELOW_TOP:
insets.top += h + TEXT_SPACING;
break;
case ABOVE_BOTTOM:
insets.bottom += h + TEXT_SPACING;
break;
case BOTTOM:
insets.bottom += Math.max(h, bIns.bottom) bIns.bottom;
break;
case BELOW_BOTTOM:
insets.bottom += h + TEXT_SPACING;
}
return insets;
}
public Rectangle getComponentRect(Rectangle rect, Insets bIns){
Dimension d = comp.getPreferredSize();
Rectangle r = new Rectangle(0, 0, d.width, d.height);
switch (titlePosition){
case ABOVE_TOP:
r.y = EDGE_SPACING;
break;
case TOP:
case DEFAULT_POSITION:
r.y = EDGE_SPACING +
(bIns.top EDGE_SPACING TEXT_SPACING d.height)/2;
break;
case BELOW_TOP:
r.y = bIns.top d.height TEXT_SPACING;
break;
case ABOVE_BOTTOM:
r.y = rect.height bIns.bottom + TEXT_SPACING;
break;
case BOTTOM:
r.y = rect.height bIns.bottom + TEXT_SPACING +
(bIns.bottom EDGE_SPACING TEXT_SPACING d.height)/2;
break;

449

450

III.
case BELOW_BOTTOM:
r.y = rect.height d.height EDGE_SPACING;
}
switch (titleJustification) {
case LEFT:
case DEFAULT_JUSTIFICATION:
r.x = TEXT_INSET_H + bIns.left;
break;
case RIGHT:
r.x = rect.width bIns.right -TEXT_INSET_H r.width;
break;
case CENTER:
r.x = (rect.width r.width) / 2;
}
return r;

}
}}

. 16.5. JLabel


1. Swing ?
2. ?
3. ?
4. - ?
5. - ?
6. , ?
7. ?
8. ?

17


Swing .
(look) , ,
, , , . (feel)
, ,
. . , Look and Feel, L&F. , L&F .

Swing LookAndFeel javax.swing. - L&F , L&F.
Swing
. , , (system defaults).
BasicLookAndFeel, LookAndFeel. BasicLookAndFeel javax.swing.plaf.basic.
, ,
, BasicLookAndFeel:
MotifLookAndFeel , CDE

(Common Desktop Environment),


Motif. ""
Solaris.
CDE/Motif;
WindowsLookAndFeel Win32, MS Win-

dows;
MacLookAndFeel , Apple Macintosh.

CDE/Motif ,
Windows Macintosh, - , .

452

III.

Java , , Java
Look and Feel, Java L&F, JLF. "Metal" L&F .
""
. , JLF
, . Swing.
- SwingSet2. Java SE "Ocean", "Steel". "Steel"
, swing.metalTheme=steel.
, JLF, .
, .
Java L&F
BasicLookAndFeel MetalLookAndFeel.
, Java L&F Nimbus L&F,
JDK 1.6.0_10. Nimbus Java 2D ,
9. , ,
Nimbus .
Nimbus NimbusLookAndFeel
javax.swing.plaf.nimbus.
, ,
(look and feel defaults).
(user
defaults), .
. ,
Swing . ,
.
, L&F: ""
, CDE/Motif, Nimbus Java L&F. . 17.1.
JFrame JDialog, ,
.
,
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame newLAFWin = new JFrame();

,
L&F ,
JFrame JDialog L&F, . 17.4.

17.

453

. 17.1.
L&F

L&F, , setWindowDecorationStyle(int) JRootPane:


JFrame fr = new JFrame();
fr.setUndecorated(true);
fr.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);

, , .
,
.
Swing Pluggable
Look and Feel, PL&F, PLAF plaf.

L&F
L&F L&F
UIManager javax.swing.
, L&F, L&F.
UIManager L&F
swing.defaultlaf, , ,
D:
XxxLookAndFeel

java -Dswing.defaultlaf=com.sun.java.swing.plaf.motif.MotifLookAndFeel
SomeSwingApplication

, swing.properties,
$JAVA_HOME/lib. , swing.defaultlaf, :
swing.defaultlaf=com.sun.java.swing.plaf.motif.MotifLookAndFeel

454

III.

swing.properties, Java L&F.


swing.properties,
L&F, :
swing.defaultlaf=javax.swing.plaf.nimbus.NimbusLookAndFeel

Nimbus.
L&F UIManager UIDefaults. UIDefaults Hashtable, , -, " " (key value). - get(Object key), value key,
put(Object key, Object value), value key,
UIDefaults , . , get(Object).
, getBoolean(Object key) key,
boolean. getBorder(Object), getColor(Object),
getDimension(Object), getFont(Object), getIcon(Object), getInsets(Object), getInt(Object),
getString(Object). getXxx(Object, Locale), .
UIDefaults, UIManager, (private)
. UIDefaults
UIManager .
, , Jlabel,
:
Font labelFont = UIManager.getFont("Label.font");

, getDefaults()
UIDefaults, UIManager.
, UIDefaults,
:
UIDefaults defs = UIManager.getDefaults();
Enumeration keys = defs.keys();
Enumeration elem = defs.elements();
while (keys.hasMoreElements() && elem.hasMoreElements())
System.out.println(
keys.nextElement() + ": " + elem.nextElement());


put(Object key, Object value);

,
L&F . L&F
geLookAndFeelDefaults(), UIDefaults.

17.

455

, UIManager
L&F UIManager.LookAndFeelInfo.

installLookAndFeel(String name, String className);

UIManager.LookAndFeelInfo,
installLookAndFeel(UIManager.LookAndFeelInfo);

L&F, CDE/Motif, Nimbus Java L&F.


L&F :
UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels();
for (int i = 0; i < info.length; i++)
System.out.println(info[i].getName());

L&F
PL&F, setLookAndFeel(LookAndFeel) setLookAndFeel(String) UIManager. ,
XxxLookAndFeel . , "javax.swing.plaf.metal.
MetalLookAndFeel" , Java L&F. Java SE, Java L&F
getCrossPlatformLookAndFeelClassName()
UIManager. , Java L&F ,
, .
getSystemLookAndFeelClassName() UIManager ,
L&F .
L&F :
public static void main(String[] args){
try{
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}catch(Exception e){}
new SomeSwingApplication();
}

,
Java L&F.
CDE/Motif UIManager
, :
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.motif.MotifLookAndFeel");

17.1 , . 17.1.
L&F.

456

III.

17.1. L&F
import java.awt.*;
import javax.swing.*;
public class DiffLAF extends JFrame{
DiffLAF(){
super(" L&F");
setLayout(new FlowLayout());
JInternalFrame ifr1 =
new JInternalFrame(" O Metal", true, true, true, true);
ifr1.getContentPane().add(new JLabel(" Java L&F"));
ifr1.setPreferredSize(new Dimension(200, 100));
ifr1.setVisible(true);
add(ifr1);
try{
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
JInternalFrame ifr2 =
new JInternalFrame(" O Windows", true, true, true, true);
ifr2.getContentPane().add(
new JLabel("<html> Windows L&F<p> Classic"));
ifr2.setPreferredSize(new Dimension(200, 100));
ifr2.setVisible(true);
add(ifr2);
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.motif.MotifLookAndFeel");
}catch(Exception e){}
JInternalFrame ifr3 =
new JInternalFrame(" O CDE/Motif", true, true, true, true);
ifr3.getContentPane().add(
new JLabel(" Solaris CDE L&F"));
ifr3.setPreferredSize(new Dimension(200, 100));
ifr3.setVisible(true);
add(ifr3);
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new DiffLAF();
}
}

17.

457

L&F
L&F Swing (auxiliary) L&F. MultiLookAndFeel
javax.swing.plaf.multi. XxxLookAndFeel
$JAVA_HOME/lib/swing.properties, swing.auxiliarylaf, .
L&F Java
L&F, L&F
swing.auxiliarylaf swing.properties.
L&F /:
, / .
L&F ,
L&F. L&F , BasicLookAndFeel,
MultiLookAndFeel.

L&F
GUI L&F . L&F L&F:
UIManager.setLookAndFeel(new MyCoolLookAndFeel());

L&F.
- , L&F, L&F ,
PropertyChangeEvent. UIManager addPropertyChangeListener(PropertyChangeListener).
L&F.
updateComponentTreeUI(Component)
SwingUtilities. , .
, L&F :
JFrame frame = JFrame(" ");
UIManager.addPropertyChangeListener(
new PropertyChangeListener(){
public void propertyChange(PropertyChangeEvent e){
SwingUtilities.updateComponentTreeUI(frame);
}
});

, frame.pack().
updateComponentTreeUI(frame) . updateUI()
JComponent, , , setUI(ComponentUI)
, L&F .

III.

458

17.2 , L&F , . . 17.2 .


17.2. L&F
import
import
import
import
import

java.awt.*;
java.awt.event.*;
java.beans.*;
java.util.*;
javax.swing.*;

public class ChLAF extends JFrame{


ChLAF(){
super(" L&F");
setLayout(new FlowLayout());
JMenuBar mb = new JMenuBar();
setJMenuBar(mb);
JMenu serv = new JMenu("");
mb.add(serv);
JMenu laf = new JMenu("");
serv.add(laf);
ButtonGroup bg = new ButtonGroup();
UIManager.LookAndFeelInfo[] info =
UIManager.getInstalledLookAndFeels();
for (int i = 0; i < info.length; i++){
JRadioButtonMenuItem item =
new JRadioButtonMenuItem(info[i].getName());
item.addItemListener(new LAFChange(info[i].getClassName()));
bg.add(item);
laf.add(item);
}
JButton b = new JButton("");
add(b);
UIManager.addPropertyChangeListener(
new PropertyChangeListener(){
public void propertyChange(PropertyChangeEvent e){
SwingUtilities.updateComponentTreeUI(c);
}
});

17.

459

setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new ChLAF();
}
class LAFChange implements ItemListener{
private String className;
public LAFChange(String className){
this.className = className;
}
public void itemStateChanged(ItemEvent e){
if(e.getStateChange() == ItemEvent.SELECTED)
try{
UIManager.setLookAndFeel(className);
}catch(Exception ex){}
}
}
}

. 17.2. L&F

Java SE, $JAVA_HOME/demo/jfc/SwingSet2/, ,


L&F .
java jar SwingSet2.jar

L&F
L&F, .
put(Object key, Object value) UIManager.
UIDefaults
, getDefaults().
updateComponentTreeUI(Component) .

III.

460

17.3 , . , .
17.3.
import
import
import
import
import
import

java.awt.*;
java.awt.event.*;
java.beans.*;
java.util.*;
javax.swing.*;
javax.swing.plaf.*;

public class PropCh extends JFrame{


PropCh(){
super(" ");
setLayout(new FlowLayout());
JMenuBar mb = new JMenuBar();
setJMenuBar(mb);
JMenu serv = new JMenu("");
mb.add(serv);
JMenu laf = new JMenu(" ");
serv.add(laf);
ButtonGroup bg = new ButtonGroup();
FontChange fch = new FontChange();
for (int i = 10; i < 22; i += 2){
JRadioButtonMenuItem item = new JRadioButtonMenuItem(""+ i);
item.addItemListener(fch);
bg.add(item);
laf.add(item);
}
JTextArea
ta = new JTextArea(5, 20);
JTextField
tf = new JTextField(20);
JPasswordField pf = new JPasswordField(20);
add(ta); add(tf); add(pf);
PropertyChangeListener pcl =
new PropertyChangeListener(){
public void propertyChange(PropertyChangeEvent e){
SwingUtilities.updateComponentTreeUI(c);
}
};
UIManager.addPropertyChangeListener(pcl);
UIManager.getDefaults().addPropertyChangeListener(pcl);

17.

461

setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new PropCh();
}
class FontChange implements ItemListener{
public FontChange(){}
public void itemStateChanged(ItemEvent e){
if (e.getStateChange() == ItemEvent.SELECTED){
JMenuItem mi = (JMenuItem)e.getSource();
int n = Integer.parseInt(mi.getText());
Font f = UIManager.getFont("TextArea.font");
String name = f.getName();
int style = f.getStyle();
FontUIResource fr = new FontUIResource(name, style, n);
UIManager.put("TextArea.font", fr);
UIManager.put("TextField.font", fr);
UIManager.put("PasswordField.font", fr);
UIManager.put("EditorPane.font", fr);
UIManager.put("TextPane.font", fr);
UIManager.put("FormattedTextField.font", fr);

//
//

}
}
}
}

. 17.3 17.3.
20 . , .

. 17.3.

462

III.

Java L&F
Java L&F (primary) (secondary) ,
. , .
- ,
, , (theme)
.
, , MetalTheme javax.swing.plaf.metal. ,
, DefaultMetalTheme. -, , , primary1 RGB (102,
102, 153), primary2 (153, 153, 204), primary3 (204, 204, 255). -, -, , secondary1
(102, 102, 102), secondary2 (153, 153, 153), secondary3 (204, 204, 204).
primary1 , .
primary2 , primary3 .
secondary1 "" , secondary2 , secondary3 .
DefaultMetalModel ,
, .
OceanTheme, DefaultMetalModel,
-, -, , RGB
(99, 130, 191), (163, 184, 204) (184, 207, 229). -,
- -, , (122, 138, 153), (184, 207, 229) (238, 238, 238).
MetalTheme, , : getPrimary1(), getPrimary2(),
getPrimary3(), getSecondary1(), getSecondary2(), getSecondary3(), ,
: getControlTextFont(), getMenuTextFont(), getSubTextFont(),
getSystemTextFont(), getUserTextFont(), getWindowTitleFont().
, DefaultMetalTheme
OceanTheme.
, , ColorUIResource. :
ColorUIResource(Color);
ColorUIResource(int red, int green, int blue);
ColorUIResource(float red, float green, float blue);
ColorUIResource(int rgb);

, , :
public ColorUIResource getPrimary1(){
return new ColorUIResource(36, 124, 225);
}

, , FontUIResource,
:

17.

463

FontUIResource(Font);
FontUIResource(String name, int style, int size);

, , :
public FontUIResource getSystemTextFont(){
return FontUIResource("Times New Roman", Font.PLAIN, 10);
}

, ,
Java L&F. MetalTheme
addCustomEntriesToTable(UIDefaults), UIDefaults
, - . MetalTheme, .
17.4 ,
.
, MetalTheme,
DefaultMetalTheme OceanTheme, setCurrentTheme(MetalTheme) MetalLookAndFeel, 17.4.
, . . 17.4.
17.4. , ""
import
import
import
import
import

java.awt.*;
javax.swing.*;
javax.swing.border.*;
javax.swing.plaf.*;
javax.swing.plaf.metal.*;

public class ContTheme extends JFrame{


ContTheme(){
super(" ");
JDesktopPane dp = new JDesktopPane();
setLayout(new FlowLayout());
setContentPane(dp);
JInternalFrame ifr1 = new JInternalFrame(
" O GrayMetalTheme", true, true, true, true);
ifr1.getContentPane().setLayout(new FlowLayout());
ifr1.getContentPane().add(
new JLabel("<html> Java L&F<p> " ));
ifr1.setBounds(0,0, 200,200);
ifr1.setVisible(true);
dp.add(ifr1);
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}

464

III.

public static void main(String[] args){


JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
MetalLookAndFeel.setCurrentTheme(new GrayMetalTheme());
new ContTheme();
}
}
class GrayMetalTheme extends DefaultMetalTheme{
public ColorUIResource getPrimary1(){
return getSecondary1();
}
public ColorUIResource getPrimary2(){
return getSecondary2();
}
public ColorUIResource getPrimary3(){
return getSecondary3();
}
public void addCustomEntriesToTable(UIDefaults table){
super.addCustomEntriesToTable(table);
BorderUIResource b = new BorderUIResource(
new CompoundBorder(
new LineBorder(Color.gray),
new LineBorder(Color.white)));
table.put("TextField.border", b);
table.put("PasswordField.border", b);
table.put("TextArea.border", b);
table.put("TextPane.font", b);
}
}

. 17.4. , ""

Java SE, $JAVA_HOME/demo/jfc/MetalWorks/,


MetalWorks Java L&F.
,
java jar MetalWorks.jar

, , Java L&F.

17.

465


1. (Look and Feel) ?
2. (theme) ?
3. L&F Swing?
4. Swing L&F?
5. Java L&F?
6. Java L&F?

18

(applications),
(standalone) JVM .
Frame, (window manager) .
Java (applets). ,
.
. JVM , JVM . .
AWT,
Applet, , , Panel. ,
, . ,
Panel, FlowLayout. Applet java.applet, , . ,
.
Swing JApplet, Applet. Swing AWT
setJMenuBar(JMenuBar)
, JFrame. ,
getContentPane(), BorderLayout.
, ,
JVM, , main(),
.
. , .
, .
, main(),
init() Applet. Java . Applet:
public void init(){}

18.

467

! init() , Applet.
,
destroy(), . Applet .
init() destroy() Applet ,
. start() stop(),
. stop() ,
, start() . ,
.
.
, , , init() . , , start(), , stop(). ,
, , destroy().
. 18.1
AWT, HelloWorld.
18.1. HelloWorld
import java.awt.*;
import java.applet.*;
public class HelloWorld extends Applet{
public void paint(Graphics g){
g.drawString("Hello, XXI century World!", 10, 30);
}
}

HelloWorld.java :
javac HelloWorld.java

HelloWorld.class, java main().


.
, (tags), HTML (HyperText
Markup Language). , <applet>.
code,
width height . HTML
18.2.

468

III.

18.2. HTML HelloWorld


<html>
<head><title> Applet</title></head>
<body>
.<br>
<applet code = "HelloWorld.class" width = "200" height = "100">
</applet>
</body>
</html>

html htm, HelloWorld.html.


, .
HelloWorld.html HelloWorld.class , HelloWorld.html , . , HTML-, <applet> . ,
. 18.1.

. 18.1. HelloWorld
Internet Explorer

. -,
, <applet>. ,
, . ,
, . , , :
<applet code = "HelloWorld.class" width = "100%" height = "100%">

-, . 18.1, . , . ,
setBackground(Color.white), init().
JDK appletviewer. ,
. -

18.

469

, . appletviewer
:
appletviewer HelloWorld.html

. 18.2 appletviewer HelloWorld.

. 18.2. HelloWorld
appletviewer

.
(status bar) .
str showStatus(String str). 18.3 ,
" ", 18.4
HTML-.
18.3.
// RunningString.java
import java.awt.*;
import java.applet.*;
public class RunningString extends Applet{
private boolean go;
public void start(){
go = true;
sendMessage(" ");
}
public void sendMessage(String s){
String s1 = s + " ";
while (go){
showStatus(s);
try{
Thread.sleep(200);
}catch(Exception e){}
s = s1.substring(1) + s.charAt(0);
s1 =s;
}
}

470

III.

public void stop(){


go = false;
}
}
18.4. RunningString.html
<html>
<head><title> Applet</title></head>
<body>
.<br>
<applet code = "RunningString.class" width = "1" height = "1">
</applet>
</body>
</html>

, , -. appletviewer ,
. , .
. ShowWindow SomeWindow Frame,
TextField. , <Enter> . . SomeWindow ,
. , stop() start(),
? 18.5 18.6, . 18.3.
18.5. ,
// ShowWindow.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ShowWindow extends Applet{
private SomeWindow sw = new SomeWindow();
private TextField tf = new TextField(30);
private Button b = new Button("");
public void init(){
add(tf); add(b); sw.pack();
b.addActionListener(new ActShow());
sw.tf.addActionListener(new ActShow());
}
public void start(){ sw.setVisible(true); }
public void stop(){ sw.setVisible(false); }
public void destroy(){ sw.dispose(); sw = tf = b = null; }

18.

471

public class ActShow implements ActionListener{


public void actionPerformed(ActionEvent ae){
if (ae.getSource() == sw.tf)
tf.setText(sw.tf.getText());
else if (b.getActionCommand() == ""){
sw.setVisible(true);
b.setLabel("");
}else{
sw.setVisible(false);
b.setLabel("");
}
}
}
}
class SomeWindow extends Frame{
public TextField tf = new TextField(50);
SomeWindow(){
super(" ");
add(new Label(", , "), "North");
add(tf, "Center");
}
}

18.6. ShowWindow.html
<html>
<head><title> ShowWindow Applet</title></head>
<body>
.<br>
<applet code = "ShowWindow.class" width = "400" height = "50">
</applet>
</body>
</html>

. 18.3. ,

III.

472

,
Refresh Reload .
Refresh Internet Explorer (IE) <Ctrl>,
Reload Firefox <Shift>. .
. : ,
. IE Delete Files ,
Tools | Internet Options. Firefox Network Tools |
Options | Advanced Clear Now.

1. " ", 15.


2. "" 15.
3. "-" .


java main(String[] args).
, .
<param>,
<applet> </applet> HTML-.
<param> name value.
, , HelloWorld . 18.7 HelloWorld.html.
18.7.
<html>
<head><title> Applet</title></head>
<body>
.<br>
<applet code = "HelloWorld.class"
<param name = "fontName" value
<param name = "fontStyle" value
<param name = "fontSize" value
</applet>
</body>
</html>

width = "400" height = "50">


= "Serif">
= "2">
= "30">


getParameter(String name) Applet, String.
name ,
, value
.

18.

473

System.out.println(), ,
Java Console. . Internet Explorer Java Console enabled Tools | Internet Options | Advanced. IE View Java Console.

18.8 HelloWorld. ,
, HTML-.
18.8. ,
import java.awt.*;
import java.applet.*;
public class HelloWorld extends Applet{
public void init(){
setBackground(Color.white);
String font = "Serif";
int style = Font.PLAIN, size = 10;
font = getParameter("fontName");
style = Integer.parseInt(getParameter("fontStyle"));
size = Integer.parseInt(getParameter("fontSize"));
setFont(new Font(font, style, size));
}
public void paint(Graphics g){
g.drawString("Hello, XXI century World!", 10, 30);
}
}


, HTML-, -
, 18.8.

. 18.4 .

. 18.4.

III.

474

, ,
, ,
. "", "", "".
:
String[][] pinfo = {
{"fontName", "String", "font name"},
{"fontStyle", "int", "font style"},
{"fontSize", "int", "font size"}
};

getParameterInfo(), .
Applet. , , , . :
public String[][] getParameterInfo(){
return pinfo;
}


, ,
, . :
getAppletInfo(),

public String getAppletInfo(){


return "MyApplet v.1.5 P.S.Ivanov";
}

. ,
JVM. -, java_arguments
JVM, ,
<applet name = "AnApplet" code = "AnApplet.class" width = "300" height = "200">
<param name="java_arguments" value="-Xmx128m Dsun.java2d.nodraw=true">
</applet>

-, , JVM, separate_jvm true (


false):
<applet name = "AnApplet" code = "AnApplet.class" width = "300" height = "200">
<param name="separate_jvm" value="true">
</applet>

-, java_version JRE, , ,
<applet name = "AnApplet" code = "AnApplet.class" width = "300" height = "200">
<param name="java_version" value="1.6.0_10+">
</applet>

, .

18.

475

-, , , , - Lava, ,
"". ,
:
<applet name
<param
<param
<param
<param
<param
<param
</applet>

= "AnApplet" code = "AnApplet.class" width = "300" height = "200">


name="image" value="my_animated.gif">
name="boxborder" value="false">
name="centerimage" value="true">
name="boxmessage" value="My text">
name="boxbgcolor" value="#99CDFF">
name="boxfgcolor" value="black">

, <applet>.

<applet>
<applet>.
:
ode URL- ;
width height .

:
odebase URL- , .

, ,
HTML-;
archive , , -

ZIP JAR, 25,


. URL-
;
align . -

: ABSBOTTOM, ABSMIDDLE, BASELINE, BOTTOM, CENTER, LEFT, MIDDLE, RIGHT,


TEXTTOP, TOP;
hspace vspace , -

;
download . -

;
name . , -

code codebase;
style CSS (Cascading Style Sheet, );
title , ;
alt , , ;

III.

476

mayscript . , -

JavaScript.
<applet> </applet> , ,
<applet>. <applet>:
<applet name = "AnApplet" code = "AnApplet.class"
archive = "anapplet.zip, myclasses.zip"
codebase = "http://www.some.com/public/applets"
width = "300" height = "200" align = "TOP"
vspace = "5" hspace = "5" mayscript
alt = "If you have a java-enabled browser,
you would see an applet here.">
<hr>If your browser recognized the applet tag,
you would see an applet here.<hr>
</applet>


zip- jar- archive HTML-. .

, , 4.0, HTML <object>, , , ActiveX.


, <embed>.
, , , .
.


getCodeBase() URL- , .
getDocumentBase() URL- , HTML-,
.
AppletContext, java.applet.
getAppletContext().
getApplet(String name) getApplets() AppletContext
name , .
showDocument(URL address) HTML- address.
showDocument(URL address, String target) ,
target. :
_self , ;
_parent ;
_top ;

18.

477

_blank ;
name name. , .

4. , .


Java Image, . drawImage()
Graphics.
20, :
drawImage(Image img, int x, int y, ImageObserver obs);
drawImage(Image img, int x, int y, int width, int height,
ImageObserver obs);

, img. , , drawImage().
false, .
(x, y) img; width
height ; obs , ImageObserver, . this.
,
Image, . getWidth(), getHeight()
Image.
ImageObserver, Component, , Applet,
imageUpdate(),
.
. ,
.


, , ,
. ,
awt.image.incrementalDraw true.

imageUpdate() ImageObserver.
img. :
imageUpdate(Image img, int status, int x, int y, int width, int height);

478

III.

status ,
ImageObserver:
WIDTH -

width;
HEIGHT -

height;
PROPERTIES ,
getProperties() Image;

SOMEBITS , -

; x, y, width, height ;
FRAMEBITS , ;

x, y, width, height ;
ALLBITS , x, y, width, height -

;
ERROR , , ABORT;
ABORT , -

.

.

MediaTracker. , ,
. MediaTracker .

MediaTracker
MediaTracker(Component comp) . this.
addImage(Image img, int id) img id.
.
checkID(int id), checkID(int id, boolean load)
checkAll() , id
. true,
, false . load true,
.
statusID(int id), statusID(int id, boolean load) statusAll()
, COMPLETE, ABORTED, ERRORED.
, waitForID(int id) waitForAll() .
20 20.5 .

18.

479

, Image,
, GIF JPEG, Applet:
getImage(URL address) URL- ;
getImage(URL address, String fileName) address -

filename.
, ,
AudioClip, AU, AIFF, WAVE MIDI
Applet :
getAudioClip(URL address);
getAudioClip(URL address, String fileName);
newAudioClip(URL address);

, ,
.
AudioClip java.applet . . play() . loop() . stop() .
. , .
18.9 ,
, HTML-. . 18.5 , , .
18.9.
import java.applet.*;
import java.awt.*;
import java.awt.image.*;
public class SimpleAudioImage extends Applet{
private Image img;
private AudioClip ac;
public void init(){
img = getImage(getDocumentBase(), "javalogo52x88.gif");
ac = getAudioClip(getDocumentBase(), "yesterday.au");
}
public void start(){ ac.loop(); }
public void paint(Graphics g){
int w = img.getWidth(this), h = img.getHeight(this);
g.drawImage(img, 0, 0, 2 * w, 2 * h, this);
}
public void stop(){ ac.stop(); }
}

480

III.

. 18.5.

,
20.

5. , , .
6. , 3 .


, .
. , - , . ,
, , ,
, , , .
: "Applet started...", , , : "Warning: Applet Window".
.
. Firefox Disable , Tools | Add-ons, Internet
Explorer Tools | Internet Options | Security.
.
, ,
(sandbox), "" , .
, , :
, , -

18.

481

, ;
, , ,

6.4;
, ,

;
(clipboard);
exec();
"" load();
JVM exit();
java.*, sun.*

.
, , , ,
. (trusted) ,
java.security.*.
, ,
. SecurityManager. JVM

setSecurityManager(SecurityManager sm);

System. .
SecurityManager -,
. JVM .

Swing
, ,
Swing, JApplet, Applet.
JFrame. , Swing
. 18.10 .
18.10. , Swing
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingAppletTemplate extends JApplet{
public void init(){
Container c = getContentPane();

482

III.

c.setLayout(new XxxLayout()); // BorderLayout


c.add(new MainFrame());
}
public void start(){
}
public void stop(){
}
public void destroy(){
}

//

}
class MainFrame extends JFrame{
// ,
}

JApplet
, , Swing,
JApplet, Applet. ,
, : init(), start(), stop(),
destroy(). Swing, Swing
JRootPane. JFrame.
,
BorderLayout.
, , Swing,
JApplet <APPLET> . Swing ,
Java Plug-in. JRE
JRE. Java Plug-in
,
. Java Plug-in http://java.sun.com/
http://www.microsoft.com/java/ .
JDK 1.6.0_10 Java Plug-in JRE .
Java Plug-in <applet> <object> Internet Explorer <embed> Netscape Communicator.
JRE ,
, , :
<html>
<body>
<!--"CONVERTED_APPLET"-->
<!-- HTML CONVERTER -->
<object classid = "clsid:CAFEEFAC-0014-0000-0000-ABCDEFFEDCBA"
width = 100 height = 100
codebase="http://java.sun.com/products/plugin/1.4/
jinstall-140-win32.cab#Version=1,4,0,0">

18.

483

<param name = CODE value = some.class >


<param name = ARCHIVE value = some.jar >
<param name="type" value="application/x-java-applet;jpi-version=1.4">
<param name="scriptable" value="false">
<comment>
<embed type="application/x-java-applet;jpi-version=1.4"
code = some.class archive = some.jar
width = 100 height = 100
scriptable = false
pluginspage="http://java.sun.com/products/plugin/1.4/
plugin-install.html">
<noembed></noembed></embed>
</comment>
</object>
<!-<applet code = some.class archive = some.jar width = 100 height = 100>
</applet>
-->
<!--"END_CONVERTED_APPLET"-->
</body>
</html>

codebase <object> pluginspage <embed>


java.sun.com/products/, Java Plug-in. Web-, .
Java SE JDK $JAVA_HOME/lib/htmlconverter.jar. HTML-, <APPLET>, <OBJECT> <EMBED>. HTML- dummy.html,
:
<html>
<body>
<APPLET CODE = some.class ARCHIVE = some.jar WIDTH = 100 HEIGHT = 100>
</APPLET>
</body>
</html>

,
java jar htmlconverter.jar dummy.html

Java JRE, JDK 1.4, <OBJECT>.


<APPLET>, , htmlconverter.
Java SE, $JAVA_HOME/docs/technotes/guides/plugin/,
, Java Plug-in.

7. Swing.

484

III.

Java.
Java ,
WWW. , JDK demo/applets.
JDK java.applet, Sun
, .
. , , , ,
" ".
, , Java, . .
,
, , .
Oracle java.applet.
.
2007 JavaFX,
, , , Rich Internet Applications. JavaFX http://
www.oracle.com/technetwork/java/javafx/overview/index.html.


1. ?
2. ?
3. , , , . .
?
4. ?
5. ?
6. ?
7. ?
8. , ?
9. ?

19

Swing
Swing, .


Swing -, JComponent. , .
putClientProperty(Object key,
Object value). , value key getClientProperty(Object key),
value Object. , getClientProperty(Object)
, null.
JToolBar , (. . 14.10).
setRollover(boolean) JToolBar.isRollover.
:
public void setRollover(boolean rollover){
putClientProperty("JToolBar.isRollover",
rollover ? Boolean.TRUE : Boolean.FALSE);
}

isRollover() . :
public boolean isRollover(){
Boolean rollover =
(Boolean)getClientProperty("JToolBar.isRollover");
if (rollover != null)
return rollover.booleanValue();
return false;
}

comp JComponent:
- , :
comp.putClientProperty("Number", new Integer(k++));

486

III.

, , :
Integer numb = (Integer)comp.getClientProperty("Number");

19.1.


Swing, JScrollPane, . , Scrollable. Swing.


(drag), .
,
, scrollRectToVisible(Rectangle rect). :

setAutoscrolls(true).

JPanel p = new JPanel();


p.setAutoscrolls(true);
p.addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1);
((JPanel)e.getSource()).scrollRectToVisible(r);
}
});

scrollRectToVisible(r) . , JViewport, , rect.


Swing .
. <Tab>, <Ctrl>+<Tab>.
, ,
, , .
. <Shift>+<Tab>, <Ctrl>+<Shift>+<Tab>.
,
. ,
, .

19. Swing

487

Component
requestFocus(boolean) requestFocusInWindow(boolean).
true , false .
, , . ,
, . false,
, true, .
. , Swing
AWT. java.awt KeyEventDispatcher,
dispatchKeyEvent(KeyEvent). false,
KeyEvent ,
, true, .
- KeyListener, ,
dispatchKeyEvent(KeyEvent) , .
, KeyEventPostProcessor,
postProcessKeyEvent(KeyEvent),
.
KeyboardFocusManager, DefaultKeyboardFocusManager.
KeyEvent .
:
FORWARD_TRAVERSAL_KEY <Tab> <Ctrl>+<Tab>;
BACKWARD_TRAVERSAL_KEY <Shift>+<Tab>;
UP_CYCLE_TRAVERSAL_KEY ,

DOWN_CYCLE_TRAVERSAL_KEY , -

.

setDefaultFocusTraversalKeys(int, Set), <Tab> <Shift>.
Set AWTKeyStroke.
setFocusTraversalKeys(int, Set) Component.
,
, FocusTraversalPolicy. , :
getComponentAfter(Container, Component) ;

getComponentBefore(Container, Component) ;
getFirstComponent(Container) ;
getLastComponent(Container) ;
getDefaultComponent(Container) , -

III.

488

getInitialComponent(Window) , -

.

FocusTraversalPolicy.
ContainerOrderFocusTraversalPolicy , , getComponents() Container.
accept(Component),
. :
protected boolean accept(Component comp){
if (!(comp.isVisible() && comp.isDisplayable() &&
comp.isEnabled() && comp.isFocusable())) return false;
// ...
}

, ,
.
ContainerOrderFocusTraversalPolicy DefaultFocusTraversalPolicy,
accept(Component) , ,
isFocusable(), , .
, InternalFrameFocusTraversalPolicy, Swing.
, javax.swing. getInitialComponent(JInternalFrame). Component.
InternalFrameFocusTraversalPolicy SortingFocusTraversalPolicy.
, Comparator, .
6. SortingFocusTraversalPolicy(Comparator).

SortingFocusTraversalPolicy,

,
LayoutFocusTraversalPolicy.

, . L&F BasicLookAndFeel .

setDefaultFocusTraversalPolicy(FocusTraversalPolicy)
LayoutFocusTraversalPolicy

KeyboardFocusManager.
setFocusTraversalPolicy(FocusTraversalPolicy)
Container.

focusNextComponent() focusPreviousComponent()
.

transferFocus(), transferFocusBackward() Component.
KeyboardFocusManager

19.1
. 19.1 .

19. Swing

. 19.1.

19.1.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimpFocus extends JFrame implements FocusListener{
DefaultKeyboardFocusManager myFocusmgr =
new DefaultKeyboardFocusManager();
JButton
bt;
JTextField tf;
JTextArea ta;
SimpFocus(){
super(" ");
JPanel p = new JPanel();
add(p, BorderLayout.NORTH);
bt = new JButton(" myButton ");
bt.putClientProperty("Focus", "JButton bt");
tf = new JTextField(" myTextField ");
tf.putClientProperty("Focus", "JTextField tf");
tf.addFocusListener(this);
ta = new JTextArea(6, 40);
ta.putClientProperty("Focus", "JTextArea ta");
add(ta);
p.add(tf);
p.add(bt);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);

489

490

III.
printDefaultSettings(myFocusmgr);
changeFocusOwner(myFocusmgr);

}
public void focusLost(FocusEvent e){
ta.append("\n myTextField: .");
ta.append("\n " +
((JComponent)e.getOppositeComponent()).
getClientProperty("Focus")+".");
}
public void focusGained(FocusEvent e){
ta.append("\n myTextField: .");
}
public void printDefaultSettings(
DefaultKeyboardFocusManager fm){
ta.append("\n : ");
ta.append("\n FORWARD_TRAVERSAL_KEYS: " +
fm.getDefaultFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
ta.append("\n BACKWARD_TRAVERSAL_KEYS: " +
fm.getDefaultFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS));
ta.append("\n UP_CYCLE_TRAVERSAL_KEYS: " +
fm.getDefaultFocusTraversalKeys(
KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS));
ta.append("\n DOWN_CYCLE_TRAVERSAL_KEYS: " +
fm.getDefaultFocusTraversalKeys(
KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS));
}
public void changeFocusOwner(DefaultKeyboardFocusManager fm){
ta.append("\n " +
((JComponent)fm.getFocusOwner()).getClientProperty("Focus"));
ta.append("\n : " +
(fm.getCurrentFocusCycleRoot()));
ta.append("\n .");
fm.focusNextComponent();
ta.append("\n " +
((JComponent)fm.getFocusOwner()).getClientProperty("Focus"));
ta.append("\n .");
fm.focusPreviousComponent();
ta.append("\n " +
((JComponent)fm.getFocusOwner()).getClientProperty("Focus"));
}
public static void main(String[] args){
new SimpFocus();
}
}

19. Swing

491

Drag and Drop


Swing JColorChooser, JFileChooser, JList, JTable, JTree,
JTextComponent (Drag and Drop) (Cut-Copy-Paste)
(clipboard). .
setDragEnabled(true).
Clipboard
java.awt.datatransfer. , ,
Transferable, , DataFlavor.
setContents(Transferable, ClipBoardOwner);

getContents(Object) ,
Transferable. , ClipBoardOwner.
TransferHandler.
Swing. TransferHandler(String),
JavaBean.
setTransferHandler(TransferHandler) JComponent.

exportAsDrag(JComponent comp, InputEvent evt, int action);

comp
evt. action COPY MOVE.

<Ctrl>, L&F.
,
AWT. : java.awt.dnd java.awt.datatransfer.
TransferHandler.
19.2
JTextField JLabel .
19.2.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LabelDnD extends JFrame{
public LabelDnD(){
super(" JLabel");
JTextField tf = new JTextField(100);
tf.setDragEnabled(true);

492

III.

JLabel tl = new JLabel(" ", JLabel.LEFT);


tl.setTransferHandler(new TransferHandler("text"));
tl.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
JComponent c = (JComponent)e.getSource();
TransferHandler th = c.getTransferHandler();
th.exportAsDrag(c, e, TransferHandler.COPY);
}
});
getContentPane().add(tf, BorderLayout.NORTH);
getContentPane().add(tl);
tl.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(200, 100);
setVisible(true);
}
public static void main(String[] args){
new LabelDnD();
}
}

Timer
Timer ,
ActionEvent.

Timer(int millisec, ActionListener al);

"" start().
, millisec
ActionEvent. al.
, stop().
,
setRepeats(false).
setDelay(int). setInitialDelay(int).
setLogTimers(true),
System.out , "Timer ringing:"
Timer.
19.3 Timer.
. "".

19. Swing

493

19.3. Timer
import
import
import
import

java.awt.*;
java.util.*;
java.awt.event.*;
javax.swing.*;

public class SimpTimer extends JFrame implements ActionListener{


JButton bt;
JTextArea ta;
javax.swing.Timer t;
SimpTimer(){
super(" ");
JPanel p = new JPanel();
add(p, BorderLayout.NORTH);
bt = new JButton("");
bt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
t.stop(); ta.append("\nStop");
}
});
ta = new JTextArea(6, 30);
add(ta);
p.add(bt);
t = new javax.swing.Timer(500, this);
t.setInitialDelay(1000);
t.setLogTimers(true);
t.start();
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
ta.append("\n : " + new Date());
}
public static void main(String[] args){
new SimpTimer();
}
}

19.3 Timer javax.swing.


java.util. ,
Timer javax.swing Swing. Swing Timer,
java.util.

20


, Java
Image. 18 , getImage()
.
getImage() Toolkit
String URL. getToolkit() Component :
java.awt

Image img = getToolkit().getImage("C:\\images\\Ivanov.gif");

getDefaultToolkit()
Toolkit:
Image img = Toolkit.getDefaultToolkit().getImage("C:\\images\\Ivanov.gif");

Toolkit createImage(), Image:


createImage(String fileName)

filename;
createImage(URL address) -

, URL address;
createImage(byte[] imageData) imageData,

GIF JPEG;
createImage(byte[] imageData, int offset, int length)

imageData, offset length ;


createImage(ImageProducer producer) , -

producer.
Component. "", .

"-"
:
, - .

20.

495

AWT .
"" (Producer-Consumer). , "",
,
, . , "", .
Image .
, . ,
.
AWT : ImageProducer
ImageConsumer java.awt.image.
ImageProducer :
addConsumer(ImageConsumer ic) ic;
removeConsumer(ImageConsumer ic) ;
isConsumer(ImageConsumer ic) ; ,

ic;
startProduction(ImageConsumer ic) ic -

;
requestTopDownLeftRightResend(ImageConsumer ic)

, " , " , .
Image ,
ImageProducer. getSource() Image.
ImageProducer MemoryImageSource . pix, .
MemoryImageSource.
Image createImage().
20.1 ,
100 100 . , ,
, .
20.1. ,
import
import
import
import

java.awt.*;
java.awt.event.*;
java.awt.image.*;
javax.swing.*;

public class InMemory extends JFrame{


private int w = 100, h = 100;
private int[] pix = new int[w * h];
private Image img;

496

III.

InMemory(String s){
super(s);
int i = 0;
for (int y = 0; y < h; y++){
int red = 255 * y / (h 1);
for (int x = 0; x < w; x++){
int green = 255 * x / (w 1);
pix[i++] = (255 << 24)|(red << 16)|(green << 8)| 128;
}
}
setSize(250, 200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics gr){
if (img == null)
img = createImage(new MemoryImageSource(w, h, pix, 0, w));
gr.drawImage(img, 50, 50, this);
}
public static void main(String[] args){
new InMemory(" ");
}
}

20.1 - MemoryImageSource(w, h, pix, 0, w)


w h , pix, 0
w. img,
createImage() drawImage(img, 50, 50, this).
img (50, 50) ,
this , ImageObserver InMemory. paint() if (img == null), . imageUpdate(),
18, return true.
20.1 . , -
.
ImageConsumer , setPixels(). :
setPixels(int x, int y, int width, int height, ColorModel model,
byte[] pix, int offset, int scansize);

, pix int,
byte.
. width height c
(x, y), pix, offset.
scansize pix. model ( RGB).

20.

. 20.1. ,

497

. 20.2. ,
"-"

. 20.2 , "-".

-
ImageConsumer ,
ImageFilter. , , . , setPixels().
,
(protected) consumer .
java.awt.image ImageFilter:
CropImageFilter(int x, int y, int w, int h) , -

;
RGBImageFilter ; ,

filterRGB();
ReplicateScaleFilter(int w, int h)

, / ;
AreaAveragingScaleFilter(int w, int h) ; -

, .
-,
ImageProducer FilteredImageSource. , producer, filter - ImageFilter .
FilteredImageSource(ImageProducer producer, ImageFilter filter);

, .
20.220.4.

498

III.


20.2 . , ,
ReplicateScaleFilter AreaAveragingScaleFilter.
20.2.
import
import
import
import

java.awt.*;
java.awt.event.*;
java.awt.image.*;
javax.swing.*;

public class CropTest extends JFrame{


private Image img, cropimg, replimg, averimg;
CropTest(String s){
super(s);
// 1. Image.
img = getToolkit().getImage("javalogo52x88.gif");
// 2. -:
//
) 30x30,
CropImageFilter crp =
new CropImageFilter(0, 0, 30, 30);
//
) ,
ReplicateScaleFilter rsf =
new ReplicateScaleFilter(104, 176);
//
) .
AreaAveragingScaleFilter asf =
new AreaAveragingScaleFilter(104, 176);
// 3. .
cropimg = createImage(new FilteredImageSource(img.getSource(), crp));
replimg = createImage(new FilteredImageSource(img.getSource(), rsf));
averimg = createImage(new FilteredImageSource(img.getSource(), asf));
setSize(400, 350);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g){
g.drawImage(img, 10, 40, this);
g.drawImage(cropimg, 150, 40, 100, 100, this);
g.drawImage(replimg, 10, 150, this);
g.drawImage(averimg, 150, 150, this);
}
public static void main(String[] args){
new CropTest(" ");
}
}

. 20.3, , ,
, , .

20.

499

. 20.3.


20.3 .
rgb >> 1 filterRGB().
. filterRGB()
ColorFilter RGBImageFilter.
20.3.
import
import
import
import

java.awt.*;
java.awt.event.*;
java.awt.image.*;
javax.swing.*;

public class RGBTest extends JFrame{


private Image img, newimg;
RGBTest(String s){
super(s);
img = getToolkit().getImage("javalogo52x88.gif");
RGBImageFilter rgb = new ColorFilter();
newimg = createImage(new FilteredImageSource(img.getSource(), rgb));
setSize(400, 350);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g){
g.drawImage(img, 10, 40, this);

500

III.

g.drawImage(newimg, 150, 40, this);


}
public static void main(String[] args){
new RGBTest(" ");
}
}
class ColorFilter extends RGBImageFilter{
ColorFilter(){
canFilterIndexColorModel = true;
}
public int filterRGB(int x, int y, int rgb){
return rgb >> 1;
}
}


20.4 .
ShiftFilter ImageFilter, . , ,
setPixels().
20.4.
import
import
import
import

java.awt.*;
java.awt.event.*;
java.awt.image.*;
javax.swing.*;

public class ShiftImage extends JFrame{


private Image img, newimg;
ShiftImage(String s){
super(s);
// 1. .
img = getToolkit().getImage("javalogo52x88.gif");
// 2. .
ImageFilter imf = new ShiftFilter(26);
// 26 .
// 3. .
ImageProducer ip = new FilteredImageSource(img.getSource(), imf);
// 4. .
newimg = createImage(ip);
setSize(300, 200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics gr){
gr.drawImage(img,
20, 40, this);
gr.drawImage(newimg, 100, 40, this);
}

20.

501

public static void main(String[] args){


new ShiftImage(" ");
}
}
// -
class ShiftFilter extends ImageFilter{
private int sh;
// sh .
public ShiftFilter(int shift){ sh = shift; }
public void setPixels(int x, int y, int w, int h,
ColorModel m, byte[] pix, int off, int size){
for (int k = x; k < x+w; k++){
if (k+sh <= w)
consumer.setPixels(k, y, 1, h, m, pix, off+sh+k, size);
else
consumer.setPixels(k, y, 1, h, m, pix, off+sh+k-w, size);
}
}
}

20.4, setPixels() ,
, ,
consumer ImageFilter setPixels() .
. 20.4 .

. 20.4.

1. "", .
2. , .
3. 20.4 setPixels() , ,
.


Java 2D. (immediate mode model).

502

III.

Graphics Java 2D
Graphics2D, 9, Image Java 2D BufferedImage.
BufferedImage(int width, int height, int imageType);

:
TYPE_INT_RGB

TYPE_4BYTE_ABRG

TYPE_USHORT_565_RGB

TYPE_INT_ARGB

TYPE_4BYTE_ABRG_PRE

TYPE_USHORT_555_RGB

TYPE_INT_ARGB_PRE

TYPE_BYTE_GRAY

TYPE_USHORT_GRAY

TYPE_INT_BRG

TYPE_BYTE_BINARY

TYPE_3BYTE_BRG

TYPE_BYTE_INDEXED

, 4 INT, 4BYTE, 2 USHORT,


1 BYTE. RGB, ARGB, BRG, GRAY. , 5 6 .
BufferedImage .
createImage() Component
:
BufferedImage bi = (BufferedImage)createImage(width, height);

bi : , .
Raster
, getPixel(), getPixels(). WritableRaster setPixel() setPixels() setRect().
WritableRaster.


(minX, minY), .
BufferedImage
WritableRaster.
, .
DataBufferByte, DataBufferInt, DataBufferShort, DataBufferUShort
.
DataBuffer. , : TYPE_BYTE, TYPE_USHORT,
TYPE_INT, TYPE_UNDEFINED.
DataBuffer ,
Raster WritableRaster.
Raster WritableRaster
DataBuffer.

20.

503

, Raster
DataBuffer, SampleModel,
, (samples) . RGB
, .
java.awt.image SampleModel:
ComponentSampleModel

DataBuffer;
BandedSampleModel ,

, DataBuffer :
;
ComponentSampleModel;
PixelInterleavedSampleModel

DataBuffer;
ComponentSampleModel;
MultiPixelPackedSampleModel -

, DataBuffer;
SinglePixelPackedSampleModel

DataBuffer.
. 20.5 Java 2D, .
, Java 2D DataBuffer
SampleModel Raster BufferedImage. , Raster
SampleModel. , DataBuffer.

. 20.5. ,

504

III.

, .
.

Java 2D
source, BufferedImage,
destination
filter(BufferedImage source, BufferedImage destination);

BufferedImageOp. , destination BufferedImage,


.

filter(Raster source, WritableRaster destination);

WritableRaster.
RasterOp.
, , .
java.awt.image , BufferedImageOp
RasterOp:
AffineTransformOp : , -

, , ;
RescaleOp ;
LookupOp ;
BandCombineOp Raster;
ColorConvertOp ;
ConvolveOp , /

, "" .
, .


AffineTransform 9,
.
AffineTransformOp at interp / hints:
AffineTransformOp(AffineTransform at, int interp);
AffineTransformOp(AffineTransform at, RenderingHints hints);

: TYPE_NEAREST_NEIGHBOR ( ) TYPE_BILINEAR.

20.

505

AffineTransformOp filter().
BufferedImage,
. 20.6, . .

drawImage(BufferedImage img, BufferedImageOp op, int x, int y);

Graphics2D. img,
. 20.6, .

. 20.6.

20.5 , , . 20.6.
BufferedImage.
. ,
,
, Swing .
20.5.
import
import
import
import
import

java.awt.*;
java.awt.geom.*;
java.awt.image.*;
java.awt.event.*;
javax.swing.*;

public class AffOp extends JFrame{


private BufferedImage bi;
public AffOp(String s){
super(s);
// img.
Image img = getToolkit().getImage("javalogo52x88.gif");
// .
try{
MediaTracker mt = new MediaTracker(this);
mt.addImage(img, 0);
mt.waitForID(0);
// .
}catch(Exception e){}

506

III.
// bi
// img.
bi = new BufferedImage(img.getWidth(this), img.getHeight(this),
BufferedImage.TYPE_INT_RGB);
// big bi.
Graphics2D big = bi.createGraphics();
// img big.
big.drawImage(img, 0, 0, this);

}
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D)g;
int w = getSize().width;
int h = getSize().height;
int bw = bi.getWidth(this);
int bh = bi.getHeight(this);
// at.
AffineTransform at = new AffineTransform();
at.rotate(Math.PI/4);
// 45
// .
// bw.
at.preConcatenate(new AffineTransform(1, 0, 0, 1, bw, 0));
// bimg
// . .
BufferedImage bimg =
new BufferedImage(2*bw, 2*bw, BufferedImage.TYPE_INT_RGB);
// biop, at.
BufferedImageOp biop = new AffineTransformOp(at,
AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
// , bimg.
biop.filter(bi, bimg);
// .
g2.drawImage(bi, null, 10, 30);
// biop bi.
g2.drawImage(bi, biop, w/4+3, 30);
// bimg .
g2.drawImage(bimg, null, w/2+3, 30);
}
public static void main(String[] args){
JFrame f = new AffOp(" ");
f.setSize(400, 200);
f.setVisible(true);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

. 20.6 , .

20.

507


factor
offset. . .
factor offset
hints:
RescaleOp(float factor, float offset, RenderingHints hints);

filter().
. 20.7 ,
, . 70 .
20.6 , .

. 20.7.

20.6.
import
import
import
import

java.awt.*;
java.awt.image.*;
java.awt.event.*;
javax.swing.*;

public class Rescale extends JFrame{


private BufferedImage bi;
public Rescale(String s){
super(s);
Image img = getToolkit().getImage("javalogo52x88.gif");
try{
MediaTracker mt = new MediaTracker(this);
mt.addImage(img, 0);
mt.waitForID(0);
}catch(Exception e){}
bi = new BufferedImage(img.getWidth(this), img.getHeight(this),
BufferedImage.TYPE_INT_RGB);
Graphics2D big = bi.createGraphics();
big.drawImage(img, 0, 0, this);
}

508

III.

public void paint(Graphics g){


Graphics2D g2 = (Graphics2D)g;
int w = getSize().width;
int bw = bi.getWidth(this);
int bh = bi.getHeight(this);
BufferedImage bimg =
new BufferedImage(bw, bh, BufferedImage.TYPE_INT_RGB);
//---------- -----------RescaleOp rop = new RescaleOp(0.5f, 70.0f, null);
rop.filter(bi, bimg);
//---------- ------------g2.drawImage(bi, null, 10, 30);
g2.drawImage(bimg, null, w/2+3, 30);
}
public static void main(String[] args){
JFrame f = new Rescale(" ");
f.setSize(300, 200);
f.setVisible(true);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}


,
BufferedImage, TYPE_INT_RGB. , . ,
int.
. 20.7 samples.
.
20.7 - . ByteLookupTable,
. LookupOp. , filter() .
20.7 . 20.6 . Java - .
20.7.
//---------------- 20.6 --------------byte samples[][] = new byte[3][256];
for (int j = 0; j < 255; j++){
samples[0][j] = (byte)(255);
// .
samples[1][j] = (byte)(0);
// .
samples[2][j] = (byte)(0);
// .
}

20.

509

samples[0][255] = (byte)(255);
// .
samples[1][255] = (byte)(255);
samples[2][255] = (byte)(255);
ByteLookupTable blut=new ByteLookupTable(0, samples);
LookupOp lop = new LookupOp(blut, null);
lop.filter(bi, bimg);
//------------------ ------------------------


.
(convolution)
. (x, y) ,
A(x, y). w(0),
w(1) ... w(8). (x, y) :
w(0)*A(x-1, y-1) + w(1)*A(x, y-1) + w(2)*A(x+1, y-1)+
w(3)*A(x-1, y) + w(4)*A(x, y)
+ w(5)*A(x+1, y) +
w(6)*A(x-1, y+1) + w(7)*A(x, y+1) + w(8)*A(x+1, y+1)

w(i),
, .
w(i) 1.0f, . , . . 0.1111111f, , , . w(4) 1.0f, , ,
.
, ,
15 (3 5, 5 3), 25 (5 5) .
Java 2D . , :
float[] w = {0, -1, 0, -1, 5, -1, 0, -1, 0};

Kernel :
Kernel kern = new Kernel(3, 3, w);

ConvolveOp :
ConvolveOp conv = new ConvolveOp(kern);

, filter():
conv.filter(bi, bimg);

20.8 , "".
20.8.
//-------------- 20.6 -----------------------float[] w1 = { 0.11111111f, 0.11111111f, 0.11111111f,
0.11111111f, 0.11111111f, 0.11111111f,
0.11111111f, 0.11111111f, 0.11111111f };

510

III.

Kernel kern = new Kernel(3, 3, w1);


ConvolveOp cop = new ConvolveOp(kern, ConvolveOp.EDGE_NO_OP, null);
cop1.filter(bi, bimg);
//------------- ------------------------------------

. 20.8 , , , w1, w2 w3, w1 20.8,


w2 w3 :
float[] w2 = { 0, -1, 0,-1, 4, -1, 0, -1, 0 };
float[] w3 = { -1, -1, -1,-1, 9, -1, -1, -1, -1 };

. 20.8.

4. , .
5. ,
.
6. 20.8 9 15 25 .
?

.
,
Image BufferedImage .
20.9. run1.gif,
run2.gif, ..., run10.gif. img[]
100 , 0,1 .
20.9.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

20.

511

class SimpleAnim extends JFrame{


private Image[] img = new Image[10];
private int count;
SimpleAnim(String s){
super(s);
MediaTracker tr = new MediaTracker(this);
for (int k = 0; k < 10; k++){
img[k] = getToolkit().getImage("run"+(k+1)+".gif");
tr.addImage(img[k], 0);
}
try{
tr.waitForAll();
// .
}catch(InterruptedException e){}
setSize(400, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g){
g.clearRect(0, 0, getSize().width, getSize().height);
g.drawImage(img[count % 10], 0, 0, this);
}
public void go(){
while(count < 100){
repaint();
// .
try{
// 0,1 .
Thread.sleep(100);
}catch(InterruptedException e){}
count++;
}
}
public static void main(String[] args){
SimpleAnim f = new SimpleAnim(" ");
f.go();
}
}

.
paint() , paint() , .
Component repaint().
repaint() , ,
paint(). ""
update(Graphics g). repaint()
Java .

512

III.

update() Component paint(g),


Component. "" . repaint() repaint() "" , "" ,
Container. update(), .
update() "" .
, "" update() "" ,
super.update(g) super.paint(g).
, ,
clearRect() , ,
"". , , (double buffering).


,
Image BufferedImage ,
. , . .
update(), paint() update().
20.10 20.11 .
20.10. Image
public void update(Graphics g){
int w = getSize().width, h = getSize().height;
// - .
Image offImg = createImage(w, h);
// .
Graphics offGr = offImg.getGraphics();
//
offGr.setColor(getBackground());
// , .
offGr.fillRect(0, 0, w, h);
// .
offGr.setColor(getForeground());
// 20.9 .
offGr.drawImage(img[count % 10], 0, 0, this);
//
// ( ).
paint(offGr);
// -
// ( paint()).

20.

513

g.drawImage(offImg, 0, 0, this);
}
// paint() .
public void paint(Graphics g){ update(g); }
20.11. BufferedImage
public void update(Graphics g){
Graphics2D g2 = (Graphics2D)g;
int w = getSize().width, h = getSize().height;
// - .
BufferedImage bi = (BufferedImage)createImage(w, h);
// .
Graphics2D big = bi.createGraphics();
// .
big.setColor(getBackground());
// .
big.clearRect(0, 0, w, h);
// .
big.setColor(getForeground());
// - big
// ...
// .
g2.drawImage(bi, 0, 0, this);
}

, Swing .
.
- , paint()
, .
20.12
, update(), . .
20.12.
import
import
import
import
import

java.awt.*;
java.awt.event.*;
java.awt.geom.*;
java.awt.image.*;
javax.swing.*;

class DrawAnim1 extends JFrame{


private Image img;
private int count;
DrawAnim1(String s){
super(s);

514

III.
MediaTracker tr = new MediaTracker(this);
img = getToolkit().getImage("back2.jpg");
tr.addImage(img, 0);
try{
tr.waitForID(0);
}catch(InterruptedException e){}
setSize(400, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

}
public void update(Graphics g){
Graphics2D g2 = (Graphics2D)g;
int w = getSize().width, h = getSize().height;
BufferedImage bi = (BufferedImage)createImage(w, h);
Graphics2D big = bi.createGraphics();
// img.
big.drawImage(img, 0, 0, this);
// .
big.setColor(Color.red);
// ,
// .
big.fill(new Arc2D.Double(4*count, 50+30*Math.sin(count),
50, 50, 0, 360, Arc2D.OPEN));
// .
big.setColor(getForeground());
//
big.draw(new Line2D.Double(0, 125, w, 125));
// - .
g2.drawImage(bi, 0, 0, this);
}
public void go(){
while(count < 100){
repaint();
try{
Thread.sleep(10);
}catch(InterruptedException e){}
count++;
}
}
public static void main(String[] args){
DrawAnim1 f = new DrawAnim1(" ");
f.go();
}
}

, , ,
,

20.

515

MemoryImageSource.

newPixels()
repaint(),
setAnimated(true). :
newPixels(int x, int y, int width, int height)

;
newPixels() .

20.13 . , ,
.
20.13. MemoryImageSource
import
import
import
import

java.awt.*;
java.awt.event.*;
java.awt.image.*;
javax.swing.*;

class InMemory extends JFrame{


private int w = 100, h = 100, count;
private int[] pix = new int[w * h];
private Image img;
MemoryImageSource mis;
InMemory(String s){
super(s);
int i = 0;
for(int y = 0; y < h; y++){
int red = 255 * y / (h 1);
for(int x = 0; x < w; x++){
int green = 255 * x / (w 1);
pix[i++] = (255 << 24)|(red << 16)|(green << 8)| 128;
}
}
mis = new MemoryImageSource(w, h, pix, 0, w);
// .
mis.setAnimated(true);
img = createImage(mis);
setSize(350, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics gr){
gr.drawImage(img, 10, 30, this);
}
public void go(){
while(count < 100){
int i = 0;

III.

516

// .
for(int y = 0; y < h; y++)
for(int x = 0; x < w; x++)
pix[i++] = (255 << 24)|(255 + 8 * count << 16)|
(8*count << 8)| 255 + 8 * count;
// .
mis.newPixels();
try{
Thread.sleep(100);
}catch(InterruptedException e){}
count++;
}
}
public static void main(String[] args){
InMemory f= new InMemory(" ");
f.go();
}
}

, .
, . ,
Java SE, $JAVA_HOME/demo/applets/ $JAVA_HOME/
demo/jfc/Java2D/src/, .

7. - run1.gif,
run2.gif . . 20.9.
8. Java 2D .

18, AudioClip.
, , getAudioClip(), , , , play(), loop()
stop() .
Applet newAudioClip(URL address), ,
address, , AudioClip. , , , , .
20.14 , doom.mid, .
, <Ctrl>+<C>.

20.

517

20.14.
import java.applet.*;
import java.net.*;
class SimpleAudio{
SimpleAudio(){
try{
AudioClip ac = Applet.newAudioClip(new URL("file:doom.mid"));
ac.loop();
}catch(Exception e){}
}
public static void main(String[] args){
new SimpleAudio();
}
}

AU, WAVE, AIFF, MIDI,


.
Java, Java SE 1.3, , , : AU, WAVE,
AIFF, MIDI, , .
, javax.sound.sampled,
javax.sound.midi.spi.
Java Sound API.
javax.sound.midi, javax.sound.sampled.spi

Java
, JVM, : (digital audio) (sample rate) 8000
48 000 (quantization) 8 16 MIDI-
(sequences) 0 1.
AU, WAV AIFF.
.
Clip.
,
, .
SourceDataLine.
, .
AudioFormat.
:
AudioFormat(float sampleRate, int sampleSize, int channels,
boolean signed, boolean bigEndian);

sampleRate ( 44 100 ), sampleSize, ( 16 ), channels

518

III.

(1 , 2 ); ,
(signed == true) , bigEndian.
, .
.
getAudioFileFormat() AudioSystem, getFormat()
AudioFileFormat. 20.15.
AudioFormat, DataLine.Info (line) : Clip SourceDataLine.
, .
getLine()
AudioSystem. AudioInputStream.
AudioFormat getFormat(). 20.16. open().
-! , start(), stop(), "" setFramePosition(0)
setMillisecondPosition(0).
n loop(n)
loop(Clip.LOOP_CONTINUOUSLY). n
m setLoopPoints(n, m).
close().
20.15.
20.15.
import javax.sound.sampled.*;
import java.io.*;
class PlayAudio{
PlayAudio(String s){
play(s);
}
public void play(String file){
Clip line = null;
try{
// , .
File f = new File(file);
// .
AudioFileFormat aff = AudioSystem.getAudioFileFormat(f);
// .
AudioFormat af = aff.getFormat();
// ,
// Class.
DataLine.Info info = new DataLine.Info(Clip.class, af);

20.

519

// , .
if (!AudioSystem.isLineSupported(info)){
System.err.println("Line is not supported");
System.exit(0);
}
// .
line = (Clip)AudioSystem.getLine(info);
// .
AudioInputStream ais = AudioSystem.getAudioInputStream(f);
// .
line.open(ais);
}catch(Exception e){
System.err.println(e);
}
// .
line.start();
//
// :
line.stop();
// .
line.close();
}
public static void main(String[] args){
if (args.length != 1)
System.out.println("Usage: java PlayAudio filename");
new PlayAudio(args[0]);
}
}

, Java Sound API ,


. , " " (low
level).
( SourceDataLine) .
20.16.
import javax.sound.sampled.*;
import java.io.*;
class PlayAudioLine{
PlayAudioLine(String s){
play(s);
}
public void play(String file){
SourceDataLine line = null;
AudioInputStream ais = null;
byte[] b = new byte[2048];

// .

520

III.
try{
File f = new File(file);
// f.
ais = AudioSystem.getAudioInputStream(f);
// .
AudioFormat af = ais.getFormat();
// info.
DataLine.Info info = new DataLine.Info(SourceDataLine.class, af);
// , .
if (!AudioSystem.isLineSupported(info)){
System.err.println("Line is not supported");
System.exit(0);
}
// .
line = (SourceDataLine)AudioSystem.getLine(info);
// .
line.open(af);
// .
line.start();
// .
int num = 0;
// .
while(( num = ais.read(b)) != -1)
line.write(b, 0, num);
// "" , .
line.drain();
// .
ais.close();
}catch(Exception e){
System.err.println(e);
}
// .
line.stop();
// .
line.close();

}
public static void main(String[] args){
String s = "mamba.aif";
if (args.length > 0) s = args[0];
new PlayAudioLine(s);
}
}

. LineEvent
, OPEN, , CLOSE, , , START, , STOP, . . LineListener update().
MIDI- (sequence)
(sequencer) , MIDI--

20.

521

, . (tracks), MIDI (events). (channel).



,
(synthesizer).
MIDI- , , , 20.17. start(). stop(), ""
setMicrosecondPosition(long mcs) setTickPosition(long tick).
20.17. MIDI-
import javax.sound.midi.*;
import java.io.*;
class PlayMIDI{
PlayMIDI(String s){
play(s);
}
public void play(String file){
try{
File f = new File(file);
// .
Sequencer sequencer = MidiSystem.getSequencer();
// , .
if (sequencer == null) {
System.err.println("Sequencer is not supported");
System.exit(0);
}
// .
sequencer.open();
// MIDI- .
Sequence seq = MidiSystem.getSequence(f);
// .
sequencer.setSequence(seq);
// .
sequencer.start();
// ,
// :
sequencer.stop();
}catch(Exception e){
System.err.println(e);
}
}

522

III.

public static void main(String[] args){


String s = "doom.mid";
if (args.length > 0) s = args[0];
new PlayMIDI(s);
}
}

Java
MIDI-
Sequence - : , , ,
, 20.18.
:
Sequence(float divisionType, int resolution);
Sequence(float divisionType, int resolution, int numTracks);

, divisionType, (ticks) MIDI :


PPQ (Pulses Per Quarter note)

;
SMPTE_24, SMPTE_25, SMPTE_30, SMPTE_30DROP (Society of Motion Picture and Television

Engineers) , .
, resolution, , :
Sequence seq = new Sequence(Sequence.PPQ, 10);

10 .
, numTracks, MIDI-.
, , :
Track tr = seq.createTrack();

,
:
Track[] trs = seq.getTracks();

MIDI- MIDI-. . ShortMessage,


setMessage():
ShortMessage msg = new ShortMessage();
msg.setMessage(ShortMessage.NOTE_ON, 60, 93);

: NOTE_ON , NOTE_OFF
. . NOTE_ON ,

20.

523

MIDI 0 127, 60 ""


. "" MIDI-
- .
MIDI-:
MidiEvent me = new MidiEvent(msg, ticks);

, msg , , ticks
( "") seq ( ).
.
, :
tr.add(me);

, . 20.18 , MIDI-
MIDI-.
MIDI .
, 20.17, . start()
startRecording(), ,
. :
write(Sequence in, int type, File out);
write(Sequence in, int type, OutputStream out);

, type, MIDI-,
seq
getMidiFileTypes(seq). . . 20.18.
20.18. MIDI-
import javax.sound.midi.*;
import java.io.*;
class SynMIDI{
SynMIDI(){
play(synth());
}
public Sequence synth(){
Sequence seq = null;
try{
// 10
// MIDI- .
seq = new Sequence(Sequence.PPQ, 10);

524

III.
// .
Track tr = seq.createTrack();
for (int k = 0; k < 100; k++){
ShortMessage msg = new ShortMessage();
// MIDI- 10 109.
msg.setMessage(ShortMessage.NOTE_ON, 10+k, 93);
// 5 .
tr.add(new MidiEvent(msg, 5*k));
msg = null;
}
}catch(Exception e){
System.err.println("From synth(): "+e);
System.exit(0);
}
return seq;

}
public void play(Sequence seq){
try{
Sequencer sequencer = MidiSystem.getSequencer();
if (sequencer == null){
System.err.println("Sequencer is not supported");
System.exit(0);
}
sequencer.open();
sequencer.setSequence(seq);
sequencer.startRecording();
int[] type = MidiSystem.getMidiFileTypes(seq);
MidiSystem.write(seq, type[0], new File("gammas.mid"));
}catch(Exception e){
System.err.println("From play(): " + e);
}
}
public static void main(String[] args){
new SynMIDI();
}
}

,
(synthesizer), ,
Java Sound API. Java SE, $JAVA_
HOME/docs/technotes/guides/sound/programmer_guide/, .

9. Java 2D Java Sound API .

20.


01. Java?
02. Image?
03. "-"?
04. ?
05. Java?
06. ?
07. Java 2D ?
08. Java?
09. Java?
10. Java?

525

IV


Java
21.

22.

23.

24.

Java

21


(exceptions)
(runtime) , . , ,
, , .
, -
:
if (something == wrong){
//
}else{
//
}

,
. , Pascal, , 2/3 .
, , ,
. , .
- .

, .
, , . ,
. , .
: .
. 21.1 ,
0. . . 21.1,
Java.

IV. Java

530

. 21.1.

21.1.
class SimpleExt{
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
System.out.println("10 / n = " + (10 / n));
System.out.println("After all actions");
}
}

SimpleExt . args[0] 5 : "10 / n = 2". :


"After all actions".
0, ,
"main" ArithmeticException : "/ by zero". ,
main SimpleExt, , ,
, SimpleExt.java.
, .
. args[] ,
, args[0]. ArrayIndexOutOfBoundsException , SimpleExt.java. , println() .


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

21.

531

, , . (try) "" (catch) . , , , .


, ,
. ! - .
(try) (catch) -,
, , try{}catch(){}. catch(){} . catch(){} .
, , 21.1
. , 21.2.
21.2.
class SimpleExt1{
public static void main(String[] args){
try{
int n = Integer.parseInt(args[0]);
System.out.println("After parseInt()");
System.out.println(" 10 / n = " + (10 / n));
System.out.println("After results output");
}catch(ArithmeticException ae){
System.out.println("From Arithm.Exc. catch: " + ae);
}catch(ArrayIndexOutOfBoundsException arre){
System.out.println("From Array.Exc. catch: " + arre);
}finally{
System.out.println("From finally");
}
System.out.println("After all actions");
}
}

21.2 try{} catch(){}


.
-,
toString() -.
, finally{}. , , . , , , , try{}

532

IV. Java

return. return finally{}.

catch(){}

finally{}, catch(){}
, . . ,
- - .
21.2 , .
: 5, 0 .
. 21.2.

. 21.2.

, , .
, , catch(ArithmeticException ae){}, ,
finally{}.
parseInt()
catch(ArrayIndexOutOfBoundsException arre){}, finally{}.
, ,
"After all actions".
, , 21.1, finally{}.
,
.
. 21.2.

21.

533

, catch(){},
, , ,
. ""
.
, "" . ? 21.2, f(). 21.3.
21.3.
class SimpleExt2{
private static void f(int n){
System.out.println(" 10 / n = " + (10 / n));
}
public static void main(String[] args){
try{
int n = Integer.parseInt(args[0]);
System.out.println("After parseInt()");
f(n);
System.out.println("After results output");
}catch(ArithmeticException ae){
System.out.println("From Arithm.Exc. catch: " + ae);
}catch(ArrayIndexOutOfBoundsException arre){
System.out.println("From Array.Exc. catch: " + arre);
}finally{
System.out.println("From finally");
}
System.out.println("After all actions");
}
}

21.3, ,
, , . 21.2. ,
f(), "" , "" main(), .

1. , .
2. .

throws
, , (throws) , throws
:

534

IV. Java

private static void f(int n) throws ArithmeticException{


System.out.println(" 10 / n = " + (10 / n));
}

21.3? , JLS
(checked), , , (unchecked).

throws.
.
, RuntimeException , ArithmeticException, , throws .
Error .
? , RuntimeException ,
. Error,
.
, , , .
, .
, throws. main() 21.1,
, ,
RuntimeException, :
public static void main(String[] args)
throws ArithmeticException, ArrayIndexOutOfBoundsException{
//
}

f()
, 21.4. . 21.3.
21.4.
class SimpleExt3{
private static void f(int n){ // throws ArithmeticException{
try{
System.out.println(" 10 / n = " + (10 / n));
System.out.println("From f() after results output");
}catch(ArithmeticException ae){
System.out.println("From f() catch: " + ae);
//
throw ae;
}finally{
System.out.println("From f() finally");
}
}

21.

535

public static void main(String[] args){


try{
int n = Integer.parseInt(args[0]);
System.out.println("After parseInt()");
f(n);
System.out.println("After results output");
}catch(ArithmeticException ae){
System.out.println("From Arithm.Exc. catch: " + ae);
}catch(ArrayIndexOutOfBoundsException arre){
System.out.println("From Array.Exc. catch: " + arre);
}finally{
System.out.println("From finally");
}
System.out.println("After all actions");
}
}

,
ArithmeticException main().
try{}catch(){} f()
, main().
throw ae. 21.4 . //,
, .
, , throws, . , .

. 21.3.

536

IV. Java

throw
: throw . throw, :
throw new ArithmeticException();

. -
, ,
ArithmeticException.



catch(){} , , . , catch ( multicatch) , - .
. 21.2, 21.5.
21.5.

class SimpleExt4{
public static void main(String[] args){
try{
int n = Integer.parseInt(args[0]);
System.out.println("After parseInt()");
System.out.println(" 10 / n = " + (10 / n));
System.out.println("After results output");
}catch(RuntimeException ae){
System.out.println("From Run.Exc. catch: " + ae);
}finally{
System.out.println("From finally");
}
System.out.println("After all actions");
}
}

21.5 catch(){} ,
RuntimeException. . 21.4, . ?
RuntimeException.
, -, .
-.

21.

537

. 21.4.

-
- Throwable
Object.
Throwable :
Throwable() ;
Throwable(String message) -

message.
getMessage().
, null.
toString() , .
, "" :
printStackTrace() , , -

;
printStackTrace(PrintStream stream) stream;
printStackTrace(PrintWriter stream) stream.

Throwable Error Exception.


, -
- (error) - (exception).
-, Error,
Java.
JVM. . -

538

IV. Java

throw. Error - .
-, , Error.
-, Exception,
, .
throw. - , . Java SE API.
- . -,
Exception .
- RuntimeException
Exception. , JVM, , . ,
, JVM,
, . , throws.
-, , Exception.


catch(){} .
.
21.2 catch(){},
. , - ArithmeticException ArrayIndexOutOfBoundsException . , catch(){} , . 21.5 , RuntimeException, ,
:
try{
// ,
}catch(RuntimeException re){
// -
}catch(ArrayIndexOutOfBoundsException ae){
// !
}

,
RuntimeException catch(){}. , ,
ArrayOutOfBoundsException , RuntimeException.

3. , .

21.

539



21.5 RuntimeException. ArithmeticException ArrayIndexOutOfBoundsException . RuntimeException
, catch(){}.
Java SE 7 , multi-catch.
ArithmeticException ArrayIndexOutOfBoundsException,
catch ( ). 21.6.
21.6.
class SimpleExt5{
public static void main(String[] args){
try{
int n = Integer.parseInt(args[0]);
System.out.println("After parseInt()");
System.out.println(" 10 / n = " + (10 / n));
System.out.println("After results output");
}catch(ArithmeticException | ArrayIndexOutOfBoundsException ae){
System.out.println("From two Exceptions catch: " + ae);
}finally{
System.out.println("From finally");
}
System.out.println("After all actions");
}
}

, , , , :
.


, , , , , .
-.
Exception .
-. , , Exception. , toString() getMessage().
. handle(int cipher)
09, cipher int.
, cipher 09.

IV. Java

540

, , Exception.
,
- . ,
CipherException, Exception. CipherException, 21.7, ExceptDemo. . 21.5 .
21.7. -
class CipherException extends Exception{
private String msg;
CipherException(){ msg = null; }
CipherException(String s){ msg = s; }
public String toString(){
return "CipherException (" + msg + ")";
}
}
public class ExceptDemo{
static public void handle(int cipher) throws CipherException{
System.out.println("handle()'s beginning");
if (cipher < 0 || cipher > 9)
throw new CipherException("" + cipher);
System.out.println("handle()'s ending");
}
public static void main(String[] args){
try{
handle(1);
handle(10);
}catch(CipherException ce){
System.out.println("caught " + ce);
ce.printStackTrace();
}
}
}

. 21.5.

21.

541

. Java SE , , , .
, ,
. , KISS.
, finally{}
. , ,
try{}? .


1. -
, , ?
2. ?
3. return?
4. ?
5. catch(){}?
6. finally{}?
7. , ,
throws?
8. ?
9. -?

22

(process).
, , .
(runnable) ,
, .
, "" (sleep) , . .
.
(multitasking), . , , , , .
, .
,
, . "" (ticks). 0,01 .
(priority).
,
, , " ". , (scheduler), . ,
, .
.
, (context).
, .
- . MS Windows , . , . .

22.

543

UNIX ,
.
: , .
.
, .
threads.
. "", . thread "", /. "", "-".
" ", ,
Solaris, thread lightweight process. "".
,
, .
,
Java . , Java, ,
.
Java
, . (main)
- , main() . , ,
, . . , .
, .
,
- (enum) Thread.State,
Thread:
NEW , ;
RUNNABLE ;
BLOCKED ;
WAITING ;
TIMED_WAITING ;
TERMINATED .

Thread.State.
Java Thread.
start().

544

IV. Java


Thread.currentThread();

getState(),
Thread.State.
Thread Runnable, run().
, . ,
Thread run(), Thread , . run() .
run() , .
, . run() ,
,
.
Java start().
. JDK java.util.concurrent,
java.util.concurrent.atomic, java.util.concurrent.locks, , .
Callable, call().
run() call() Exception. call()
Future, get()
call() . isDone(). call() cancel(),
isCancelled().
Future ForkJoinTask, ,
adapt(), .
Runnable, Runnable Future RunnableFuture.
RunnableFuture FutureTask, Runnable Callable.
,
Runnable, Executor. execute(Runnable), , execute(Runnable) .
.
Executor
ExecutorService. submit() Runnable
Callable Future, .

22.

545

ExecutorService . AbstractExecutorService,
newTaskFor(),
submit().
AbstractExecutorService ThreadPoolExecutor, , ForkJoinPool,
ForkJoinTask, Runnable Callable execute(), invoke() submit().
, ,
, .
Executor 26.8.
,
,
. ,
.
, , . java.util.concurrent RecursiveTask
RecursiveAction. compute(),
.
ForkJoinPool, ForkJoinTask RecursiveAction
Java SE, $JAVA_HOME/sample/forkjoin/mergesort.
, java.util.concurrent Executors,
, ExecutorService .
, : Thread, Runnable, Executor
. Thread . , run() , , - . .
, Thread.

Thread
Thread . ,
Thread(ThreadGroup group, Runnable target, String name, long stackSize);

name, group
run() target. , stackSize, .
,
null:
Thread() run();
Thread(Runnable target);

546

IV. Java

Thread(Runnable target, String name);


Thread(String name);
Thread(ThreadGroup group, Runnable target, String name);
Thread(ThreadGroup group, Runnable target);
Thread(ThreadGroup group, String name).

name ,
Java .
start().
Java run() -.
run(). - null.

sleep(long ms);

ms . . ,

sleep(long ms, int nanosec);

22.1 . Thread 1 Thread 2, run().


20 , .
22.1. ,
class OutThread extends Thread{
private String msg;
OutThread(String s, String name){
super(name); msg = s;
}
public void run(){
for(int i = 0; i < 20; i++){
//
try{
//
Thread.sleep(100);
//
}catch(InterruptedException ie){}
System.out.print(msg + " ");
}
System.out.println("End of " + getName());
}
}
class TwoThreads{
public static void main(String[] args){
new OutThread("HIP", "Thread 1").start();

22.

547

new OutThread("hop", "Thread 2").start();


System.out.println();
}
}

. 22.1 22.1. ,
Thread 1
.
Thread 1 , Thread 2,
, Thread 1 .
22.1 , 0,1 . InterruptedException ,
. . 22.2 . , ,
.

. 22.1.

. 22.2.

, , (synchronization) ? ,
.

548

IV. Java

22.2 : TwoThreads2
Thread, run() .
22.2. Thread
class TwoThreads2 extends Thread{
private String msg;
TwoThreads2(String s, String name){
super(name); msg = s;
}
public void run(){
for(int i = 0; i < 20; i++){
try{
Thread.sleep(100);
}catch(InterruptedException ie){}
System.out.print(msg + " ");
}
System.out.println("End of " + getName());
}
public static void main(String[] args){
new TwoThreads2("HIP", "Thread 1").start();
new TwoThreads2("hop", "Thread 2").start();
System.out.println();
}
}

: TwoThreads3 Runnable.
22.3. Thread,
TwoThreads3 . , , Applet JApplet.
22.3. Runnable
class TwoThreads3 implements Runnable{
private String msg;
TwoThreads3(String s){ msg = s; }
public void run(){
for(int i = 0; i < 20; i++){
try{
Thread.sleep(100);
}catch(InterruptedException ie){}
System.out.print(msg + " ");
}
System.out.println("End of thread.");
}

22.

549

public static void main(String[] args){


new Thread(new TwoThreads3("HIP"), "Thread 1").start();
new Thread(new TwoThreads3("hop"), "Thread 2").start();
System.out.println();
}
}

,
: ,
, . run()
, , - null.
22.4 ,
run() , - th go, . stop(), .
, Java SE JDK. -, 1 .
22.4.
class TwoThreads5 implements Runnable{
private String msg;
private Thread go;
TwoThreads5(String s){
msg = s;
go = new Thread(this);
go.start();
}
public void run(){
Thread th = Thread.currentThread();
while(go == th){
try{
Thread.sleep(100);
}catch(InterruptedException ie){}
System.out.print(msg + " ");
}
System.out.println("End of thread.");
}
public void stop(){ go = null; }
public static void main(String[] args){
TwoThreads5 th1 = new TwoThreads5("HIP");
TwoThreads5 th2 = new TwoThreads5("hop");
try{
Thread.sleep(1000);
}catch(InterruptedException ie){}

IV. Java

550
th1.stop(); th2.stop();
System.out.println();
}
}


, ,
.
,
numDep. ,
:
Deposit myDep = getDeposit(numDep); // numDep
int rest = myDep.getRest();
// myDep
rest += sum;
// sum
myDep.setRest(rest); // myDep

1000 . 500 ,
1500 .
, myDep numDep.
. 22.1 22.2, , . 1000 500,
1000 + 1500 = 2500 ,
setRest()
500 . .
Java ,
(monitor). , ,
, , . myDep,
. ,
, myDep.
synchronized(){}, :
Deposit myDep = getDeposit(numDep);
synchronized(myDep){
int rest = myDep.getRest();
rest += sum;
myDep.setRest(rest);
}

synchronized ,
.
, . .

22.

551

- , synchronized
, synchronized,
(synchronized):
synchronized int getRest(){
//
}
synchronized void setRest(int rest){
//
}

, , . . this. , , synchronized, synchronized(){} . ,


.
. run() 22.5 "Hello,
World!" 1 . , th. .
run() , , 22.5 . . 22.3.

. 22.3.

22.5.
class TwoThreads4 implements Runnable{
public void run(){
//
synchronized public void run(){
System.out.print("Hello, ");
try{
Thread.sleep(1000);
}catch(InterruptedException ie){}

552

IV. Java

System.out.println("World!");
}
public static void main(String[] args){
TwoThreads4 th = new TwoThreads4();
new Thread(th).start();
new Thread(th).start();
}
}

, ,
(critical section) . , , . , , .
Java 2 JDK . ,
. 22.1 , .
, print() PrintStream , System.out , print()
.
, synchronized(){}. (mutually exclusive) .
, ?
Java (wait-notify).



Java
. wait() notify(), , , (notify) . Object .
,
(wait set). " " .
wait(long millisec) this, , millisec " ", .
, ,
. millisec ,
notify(), . millisec 0,
,
notify().

22.

553

sleep() , wait()
. " ", , , Java
Language Specification.
, wait(), wait(0). , wait(long millisec,
int nanosec), nanosec , .
notify() " " , . notifyAll() . .
? ,
.
"-", 20.
, , , , ,
. st Store.
. ,
st, ,
.
Store ,
.
22.6 Store . . 22.4.
22.6.
class Store{
private int inform;
synchronized public int getInform(){ return inform; }
synchronized public void setInform(int n){ inform = n; }
}
class Producer implements Runnable{
private Store st;
private Thread go;
Producer(Store st){
this.st = st;
go = new Thread(this);
go.start();
}
public void run(){
int n = 0;
Thread th = Thread.currentThread();

IV. Java

554
Wwile (go == th){
st.setInform(n);
System.out.print("Put: " + n + " ");
n++;
}
}
public void stop(){ go = null; }
}
class Consumer implements Runnable{
private Store st;
private Thread go;

Consumer(Store st){
this.st = st;
go = new Thread(this);
go.start();
}
public void run(){
Thread th = Thread.currentThread();
while (go == th) System.out.println("Got: " + st.getInform());
}
public void stop(){ go = null; }
}
class ProdCons{
public static void main(String[] args){
Store st = new Store();
Producer p = new Producer(st);
Consumer c = new Consumer(st);
try{
Thread.sleep(30);
}catch(InterruptedException ie){}
p.stop(); c.stop();
}
}

. 22.4.

22.

555

22.7 Store ready, .


Producer, ready true, Consumer
. ready
false.
. , , , . setInform() notify(). ready ,
" " wait().
Store . 22.5.
22.7.
class Store{
private int inform = -1;
private boolean ready;
synchronized public int getInform(){
try{
if (!ready) wait();
ready = false;
return inform;
}catch(InterruptedException ie){
}finally{
notify();
}
return -1;
}
synchronized public void setInform(int n){
if (ready)
try{
wait();
}catch(InterruptedException ie){}
inform = n;
ready = true;
notify();
}
}

. 22.5.

556

IV. Java

getInform() return inform, finally{}.


: "Got: 0" .
"-" ,
java.util.concurrent -, , .
BlockingQueue BlockingDeque, 6,
ArrayBlockingQueue ArrayBlockingDeque; ConcurrentLinkedQueue ConcurrentLinkedDeque; ,
SynchronousQueue.
"-"
SynchronousQueue. Store:
class Store<T>{
private SynchronousQueue<T> st = new SynchronousQueue<>();
public T getInform(){
try{
return st.take();
}catch(InterruptedException e){}
return null;
}
public void setInform(T t){
try{
st.put(t);
}catch(InterruptedException e){}
}
}

SynchronousQueue , Store, Store.


22.8 , "-"
SynchronousQueue.
22.8. SynchronousQueue
import java.util.concurrent.SynchronousQueue;
public class ProdCons{
public static void main(String[] args){
SynchronousQueue<Integer> st = new SynchronousQueue<>();
Consumer c = new Consumer(st);
Producer p = new Producer(st);
try{
Thread.sleep(30);
}catch(InterruptedException ie){}
p.stop(); c.stop();
}
}

22.

557

class Producer implements Runnable{


private SynchronousQueue<Integer> st;
private Thread go;
Producer(SynchronousQueue<Integer> st){
this.st = st;
go = new Thread(this);
go.start();
}
public void run(){
int t = 0;
Thread th = Thread.currentThread();
while (go == th){
try{
st.put(t);
}catch(InterruptedException ie){}
System.out.print("Put: " + t + " ");
t++;
}
}
public void stop(){ go = null; }
}
class Consumer implements Runnable{
private SynchronousQueue<Integer> st;
private Thread go;
Consumer(SynchronousQueue<Integer> st){
this.st = st;
go = new Thread(this);
go.start();
}
public void run(){
Thread th = Thread.currentThread();
try{
while (go == th) System.out.println("Got: " + st.take());
}catch(InterruptedException ie){}
}
public void stop(){ go = null; }
}


Java , . - . .
Thread , :
NORM_PRIORITY , , 5;

IV. Java

558

MIN_PRIORITY , 1;
MAX_PRIORITY , 10.

1 10,
, , , .

sleep() .


. checkAccess(), SecurityException,
.
setPriority(int newPriority) ,

, -.
, , , NORM_PRIORITY. , - ,
, MAX_PRIORITY. , , , MIN_PRIORITY.

-
main() .
,
.
. , . ,
, .
. , - , , . ,
, ,
.
, (daemons).
UNIX.
(user) ,
.
Java.
, .
setDaemon(true). checkAccess()
SecurityException.
.
, , . setDaemon(false).

22.

559


. Java main.
.
,
. ThreadGroup

ThreadGroup(String name);

, name. Thread. , .
.

ThreadGroup(ThreadGroup parent, String name);

.
. , setMaxPriority(int maxPri) ThreadGroup.
maxPri, , maxPri, .

Java , threads.
, Java, ,
. , , , .
, , , , .


1. ?
2. , , ?
3. Java ?
4. ?
5. ?
6. ?
7. "" ?
8. Java?

23

/

, , , .
, , . , .
/,
Java (stream). , (input stream) Unicode ,
read(). write() print(), println()
(output stream) . ,
: , , , write()
print() .
, "" , . read(), write(), print(),
println() , ,
.
, / . Java - /,
, .
System in, out err.
,
. (stdin), (stdout) (stderr).
.
out err PrintStream,
. print(), println()
write(), PrintStream
.
err : ,
- .
, log-, -

23. /

561

. Java . , ,
.
in InputStream.
, read(). InputStream ,
- .
/, Java ,
, , . . . , ,
String, - . , (pipe) .
, Java. , . (serialization) .
java.io.
, , java.io , ,
, .
, java.io,
.
, Java , . ,
Object:
Reader ,

;
Writer ,

;
InputStream ;
OutputStream .

Reader InputStream :
read() , , -

int; , 1;
read(char[] buf) buf -

; InputStream byte[] ; 1,
;
read(char[] buf, int offset, int len)

buf, offset, len;


1.
IOException, /.

562

IV. Java

, skip(long n), "" n


. read(). , n, .
mark(int n), reset(), n . ,
markSupported(), true, .
Writer OutputStream
:
write(char[] buf) , OutputStream

byte[];
write(char[] buf, int offset, int len) len buf,

offset;
write(int elem) Writer 16, OutputStream 8 -

elem .
Writer :
write(String s) s ;
write(String s, int offset, int len) len s,

offset;
Writer append(char c) ,

;
Writer append(CharSequence seq) -

;
Writer append(CharSequence seq, int offset, int len) len -

seq, offset.
Writer OutputStream .
, , , . ,
. flush(),
.
, close().
, , close(), Closeable. Java
try{}catch(){}
close() , .
, Autoloseable.
Closeable Autoloseable, Closeable .
try(){}catch(){} 23.4.

23. /

563

. 23.1.

. 23.2.

, /, . 23.1 23.2.
java.io : ,
(data sink), , (data processing).
, , , :
, , :
FileReader
FileWriter

FileInputStream
FileOutputStream

, , :
CharArrayReader
CharArrayWriter

ByteArrayInputStream
ByteArrayOutputStream

, :
PipedReader
PipedWriter

PipedInputStream
PipedOutputStream

, , :
StringReader
StringWriter

, Java:
ObjectInputStream
ObjectOutputStream

, .

IV. Java

564

, , , . " ", .
:
FilterReader
FilterWriter

FilterInputStream
FilterOutputStream

. , /.
,
. .
/:
BufferedReader
BufferedWriter

BufferedInputStream
BufferedOutputStream

, Java,
:
DataInputStream
DataOutputStream

,
:
PushbackReader

PushbackInputStream

, :
PrintWriter

PrintStream

:
InputStreamReader ;
OutputStreamWriter .

StreamTokenizer
(tokens) , StringTokenizer,
5, .
SequenceInputStream,
, , , LineNumberReader, ""
.
'\n' / '\r'.
RandomAccessFile, .
,
.
Console, , /, .
/ , ,
. .

23. /

565

/
println() PrintStream, . out System, PrintStream. Java .
, System.out.println(),
System.out, :
PrintStream pr = System.out;

pr.println().
, Unicode . Latin 1 '\u0000'
'\u00FF'
'0x00''0xFF'. , '\u0400''\u04FF'
Unicode,
, .
5.
, , . MS Windows. CP1251,
CP866.
PrintStream, , PrintWriter " " Unicode
System.out, ,
OutputStreamWriter. ,
CP866. :
PrintWriter pw = new PrintWriter(
new OutputStreamWriter(System.out, "Cp866"), true);

PrintWriter . true

println(). print() ! print()
flush().

PrintWriter , print()
. flush().

PrintWriter,
PrintStream, , ,
pw.println(" ");

23.1 . 23.3.

IV. Java

566

, PrintWriter, ,
OutputStreamWriter
.
read() InputStream in System. C , scan-
. Unicode
, .

BufferedReader, " "
InputStreamReader:
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in, "Cp866"));

BufferedReader read() Reader.


, readLine().
readLine() String, , '\n' / '\r'. -
. , null.
23.1 , /. . 23.3 .
23.1. /
import java.io.*;
class PrWr{
public static void main(String[] args){
try{
BufferedReader br =
new BufferedReader(
new InputStreamReader(System.in, "Cp866"));
PrintWriter pw = new PrintWriter(
new OutputStreamWriter(System.out, "Cp866"), true);
String s = " ";
System.out.println("System.out puts: " + s);
pw.println("PrintWriter puts: " + s);
int c = 0;
pw.println(" :");
while ((c = br.read()) != -1)
pw.println((char)c);
pw.println(" :");
do{
s = br.readLine();

23. /

567

pw.println(s);
}while(!s.equals("q"));
}catch(Exception e){
System.out.println(e);
}
}
}

. 23.3. System.out. ,
.
, CP866.
" :" "" <Enter>. "". <Enter>,
.
. . '\n' '\r',
<Enter>. (glyph).
<Ctrl>+<Z>. "^Z"
, .
.
" :" " " ,
<Enter>, s. s
.
q <Enter>.

. 23.3. /

IV. Java

568


Java , . printf(),
- :
, .
JDK 1.5 printf(), ,
PrintStream PrintWriter. ,
format(), .
Formatter, java.util .
/ PrintStream :
PrintStream
PrintStream
PrintStream
PrintStream

format(Local l, String format, Object ... args);


format(String format, Object ... args);
printf(Local l, String format, Object ... args);
printf(String format, Object ... args);

PrintWriter
PrintWriter.
, ,
, , Locale.
, .
format , , ,
. , ,

System.out.println("x = " + x + ", y = " + y);


System.out.printf("x = %d, y = %d\n", x, y);

"x = , y = \n",
. "%d".
,
. , . . x, , y, . . ,
, , :
System.out.printf(" %d%% \n", x);

, , MissingFormatArgumentException, , ,
" " , .
, , : %1$d, %2$d, %3$d.
,
System.out.printf("x = %2$d, y = %1$d\n", x, y);

23. /

569

y, x.
, :
System.out.printf("x = %2$d, y = %2$d\n", x, y);

,
a, A, b, B, c, C, d, e, E, f, g, G, h, H, n, o, s, S, t, T, x, X, . d, , ,

.
, ,
. , , , .


d ,
, %10d %2$10d. ,
10 , .
, 10 , ,
.
: %-10d, %2$-10d,
, .
,
: %010d, %2$010d.
: , , . %,10d, %2$,10d,
, ,
.
.
, %+10d, %2$+10d, , - . , , . .
d . o , x X
. x, , d2cf10,
X , D2CF10.
o, x, X
BigInteger, . "" (#). ,
0x 0X,
Java.

570

IV. Java


a, A, e, E, f, g, G. f , e E . E. g, G ,
.
, .
. ,
%.8f, %2$.6e, %+10.5E, %2$-10.4g, %2.5G. 6 .
a, A . .


Unicode.

. : %c, %2$6c, %-10C, %2$-3.


s, S .
, toString().
, null.
. S, .
: %s, %2$6S, %-10s, %2$-50S.


b, B true false.
. B, : TRUE, FALSE. : %b, %2$6B, %-10b, %2$-3b.

-
h, H - .
h, ,
H, .
. : %h, %2$6H,
%-10h, %2$-3h.


t, T .

23. /

571

long Long,
Calendar Date.
t T , : , , , . . ,
System.out.printf(" : %tT\n", Calendar.getInstance());

, , .
12:36:14.

System.out.printf(" %tH \n", Calendar.getInstance());

, 12. %tM , %tS .


-, , ,
System.out.printf(" : %1$tH , %1$tM \n",
Calendar.getInstance());

, %ts ,
1 1970 (Epoch), %tQ ,
.
10/24/11 %tD, 2011-10-24
%tF. , .
24.10.11
System.out.printf(" %1$td.%1$tm.%1$ty\n", Calendar.getInstance());

%td , : 01.
, %te.
%ty .
%tY.
, , %tB,
%tb %th.
%tA,
%ta.
, , %tc.

Console
, -
. Java SE 6 java.io Console, .
,
Java, Console
console() System, :
Console cons = System.console();

572

IV. Java

null, Java , - . cons


:
Console cons;
if ((cons = System.console()) != null){
// ...
}


public String readLine();
public String readLine(String format, Object... args);


public char[] readPassword();
public char[] readPassword(String format, Object... args);

null, , , <Ctrl>+<D>
UNIX <Ctrl>+<Z> MS Windows.
,
Reader reader();

Reader, .

Console printf(String format, Object... args);

, PrintWriter:
PrintWriter writer();

,
void flush();

1. "" , . .
2. "25 2011 ",
.

/

, /
FileInputStream FileOutputStream. , -, , , .
, .
Unicode,

23. /

573

.
.
.
, java.io FileReader
FileWriter. :
, . ,
InputStreamReader OutputStreamWriter , , " " .
, /
.

String File. ,
. :
FileInputStream fis = new FileInputStream("PrWr.java");
FileReader fr = new FileReader("D:\\jdk1.7.0\\src\\PrWr.java");

FileNotFoundException,
FileWriter IOException.
FileWriter FileOutputStream
, , . , .
true, , false,
. :
FileWriter fw = new FileWriter("ch23.txt", true);
FileOutputStream fos = new FileOutputStream("D:\\samples\\newfile.txt");

!
, , .

:
fis.read(); fr.read();

:
fos.write((char)c); fw.write((char)c);

close().
FileReader FileWriter .
FileReader, FileInputStream.
, ,
" " , , :
InputStreamReader isr = new InputStreamReader(fis, "KOI8_R"));

fis .

574

IV. Java


/, ,
. ,
, , .
File,
. Java
NIO2.
.
File,
File(String filename);

, . UNIX /, MS Windows \, Apple Macintosh :. file.separator (. . 6.2). . UNIX , MS Windows :


, . ,
,
user.dir.
, , File exists().
File ,
.
, isFile(), isDirectory() ,
, , .
list(), String[].
File[] listFiles().
, FileNameFilter
list(FileNameFilter filter) listFiles(FileNameFilter filter).
, mkdir(). true, .
mkdirs() ,
.
delete().
length(), 1 1970 lastModified(). , .
setLastModified(long time).
canRead(), canWrite(), canExecute()
, setReadable(), setWritable(), setExecutable()
.

23. /

575

renameTo(File newName)
delete(). true,
.
, createNewFile(), true, ,
, false, .

createTempFile(String prefix, String suffix, File tmpDir);
createTempFile(String prefix, String suffix);

prefix suffix tmpDir


, java.io.tmpdir (. . 6.2). prefix
. suffix == null, .tmp.
File . deleteOnExit(), JVM
.
getXxx() ,
. , File
.
getTotalSpace(), getFreeSpace(), getUsableSpace() long.
, toURI() URI.
23.2 File, . 23.4 .

. 23.4.

23.2.
import java.io.*;
class FileTest{

IV. Java

576

public static void main(String[] args) throws IOException{


PrintWriter pw = new PrintWriter(
new OutputStreamWriter(System.out, "Cp866"), true);
File f = new File("FileTest.java");
pw.println();
pw.println(" \"" + f.getName() + "\" " +
(f.exists()?"":" ") + "");
pw.println(" " + (f.canRead()?"":" ") + " ");
pw.println(" " + (f.canWrite()?"":" ") + " ");
pw.println(" " + f.length() + " ");
pw.println();
File d = new File("D:\\jdk1.3\\MyProgs");
pw.println(" :");
if (d.exists() && d.isDirectory()){
String[] s = d.list();
for (int i = 0; i < s.length; i++)
pw.println(s[i]);
}
}
}

NIO2
, Java , java.nio.file, java.nio.file.attribute
java.nio.file.spi.
, .
FileSystem, .

FileSystems.
, getDefault()
FileSystems.
Path, get()
Paths, ,
getPath() FileSystem, .
, . get()
, URI.
, :
Path path = Paths.get("pub/file.txt");
Path path = Paths.get("C:\\docs\\pub\\file.txt");

Path , .

23. /

577

getName(), getParent(),
getRoot(). , iterator() . Path.
Path. ,
for (Path name: path) System.out.println(name);

path docs, pub, file.txt.



resolve()
relativize().

startsWith(), endsWith(), compareTo().

Files.
, .
Files File,
Path.
File, , , exists() notExists().
, , , , ,
isRegularFile(Path), isDirectory(Path), isSymbolicLink(Path), isHidden(Path).
isReadable(Path), isWritable(Path),
isExecutable(Path).
createFile() createDirectory(), copy(), move(), delete(Path) deleteIfExists(Path).
, , , ,
, BasicFileAttributes,
DosFileAttributes PosixFileAttributes.
readAttributes(Path, Class) Files. BasicFileAttributes ,
. size(), creationTime(),
lastAccessTime(), lastModifiedTime(), isRegularFile(), isDirectory(), isSymbolicLink().

setLastModifiedTime() Files.
setAttribute().
UserPrincipal
getOwner(Path) Files. setOwner(Path,
UserPrincipal).
, , . Files DirectoryStream<Path> newDirectoryStream().
:
DirectoryStream<Path> dir = Files.newDirectoryStream(path);
for (Path p: dir) System.out.println(p);

578

IV. Java

newDirectoryStream() NotDirectoryException,
path , . , .
,
newDirectoryStream() ,
DirectoryStream.Filter. , newInputStream() newOutputStream()
Files .
, readAllBytes(Path), .
, readAllLines(), List<String>.

write().
NIO2 23.4.
Java SE,
$JAVA_HOME/sample/nio.

/
/ . , .
, ,
.
, .
, . , . , ,
.
/ . BufferedXxx, .
/ " ", :
BufferedReader br = new BufferedReader(isr);
BufferedWriter bw = new BufferedWriter(fw);

isr fw .
23.3 , CP866,
KOI8-R. .
args[0], args[1].
23.3. /
import java.io.*;
class DOStoUNIX{

23. /

579

public static void main(String[] args) throws IOException{


if (args.length != 2){
System.err.println("Usage: DOStoUNIX Cp866file KOI8_Rfile");
System.exit(0);
}
BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(args[0]), "Cp866"));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(args[1]), "KOI8_R"));
int c = 0;
while ((c = br.read()) != -1)
bw.write((char)c);
br.close(); bw.close();
System.out.println(" .");
}
}

/
.
. Java
java.nio.* (New Input-Output, NIO), /. , , . Java NIO ,
NIO2.
, NIO, Buffer. :
capacity(), position(),
reset() rewind() .
Buffer ByteBuffer, CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer
DoubleBuffer. get()
put() . ,
, .
,
java.nio.channels java.nio.channels.spi. Channel. . : isOpen() close(). ,
.
ReadableByteChannel,
WritableByteChannel, GatheringByteChannel, ScatteringByteChannel Channel. , read(ByteBuffer), , write(ByteBuffer),
. , ByteChannel,
ReadableByteChannel WritableByteChannel. SeekableByteChannel,
position(), size() trancate(),

IV. Java

580

/ AsynchronousChannel AsynchronousByteChannel.
java.nio.channels AsynchronousFileChannel,
AsynchronousSocketChannel, AsynchronousServerSocketChannel.
Java SE, SJAVA_HOME/sample/nio/chatserver, chat-,
/.
(final) Channels.
InputStream, OutputStream, Reader Writer,
ReadableByteChannel WritableByteChannel.
, Files newByteChannel(),
SeekableByteChannel.
Channels , . . / FileChannel. FileInputStream FileOutputStream,
getChannel() FileChannel
FileChannel.
23.4 /.
23.4. NIO2
import
import
import
import
import
import

java.nio.*;
java.nio.channels.*;
java.nio.file.*;
java.nio.file.attribute.*;
java.util.*;
java.io.*;

public class PathTest{


public static void main(String[] args){
try{
Path path = Paths.get("C:\\code\\PathTest.java");
if (Files.exists(path)){
System.out.println("File is readable: " +
Files.isReadable(path));
BasicFileAttributes attrs = Files.readAttributes(path,
BasicFileAttributes.class);
System.out.println("Basic attrs: " +
attrs.creationTime() + ", " +
attrs.isDirectory());
UserPrincipal owner = Files.getOwner(path);
System.out.println("File owner: " + owner.getName());
for (Path d: path) System.out.println("File: " + d);
if (attrs.isDirectory()){
try(DirectoryStream<Path> dir =
Files.newDirectoryStream(path)){
for (Path p: dir)
System.out.println("Path: " + p);

23. /

581

}catch(IOException ie){
ie.printStackTrace();
}
}
try(FileChannel fc = (FileChannel)Files.newByteChannel(
path, StandardOpenOption.READ,
StandardOpenOption.WRITE)){
ByteBuffer buf = ByteBuffer.allocate((int)fc.size());
int n = fc.read(buf);
System.out.println("n = " + n);
byte[] arr = new byte[n];
buf.position(0);
buf.get(arr);
for(byte b: arr)
System.out.print((char)b);
}catch(IOException ie){
ie.printStackTrace();
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}

, / Java NIO2
,
.
1. Files.readAllBytes(Path), Files.readAllLines(Path, Charset),
Files.write(Path, byte[]) .
2. Files.newBufferedReader(Path, Charset), Files.newBufferedWriter(Path, Charset)
/ BufferedReader
BufferedWriter.
3. Files.newInputStream(Path), Files.newOutputStream(Path)
/ InputStream OutputStream.
4. Files.newByteChannel()
SeekableByteChannel.
5. , , . " ", FileChannel,
.

3. , , .
4. , .

582

IV. Java

Java
DataOutputStream Java
writeBoolean(boolean b), writeByte(int b), writeShort(int h), writeChar(int c),
writeInt(int n), writeLong(long l), writeFloat(float f), writeDouble(double d).
, writeBytes(String s) s ,
Unicode,
writeChars(String s) s ,
Unicode, , writeChar().
writeUTF(String s) s
UTF-8. .

UTF-8
, Unicode . UTF-8 (Universal Transfer Format) .
, .
Unicode '\u0000''\u007F', , , .
Unicode '\u0080''\u07FF', , : Unicode 00000xxxxxyyyyyy
110xxxxx10yyyyyy.
Unicode '\u0800''\uFFFF' : Unicode xxxxyyyyyyzzzzzz 1110xxxx10yyyyyy10zzzzzz.
,
, .
, writeUTF(String s) , , , s UTF-8, . readUTF() DataInputStream.

DataOutputStream
DataInputStream InputStream, Java, . , , DataOutputStream.
readBoolean(), readByte(), readShort(), readChar(), readInt(), readLong(), readFloat(),
readDouble(), .
, readUnsignedByte() readUnsignedShort() int,
, .

23. /

583

readUTF(), writeUTF(), String, , writeUTF().


, , readUTF(DataInput in) in, UTF-8. ,
DataInputStream.
23.5 fib.txt ,
.
. . 23.5 .
23.5. /
import java.io.*;
class DataPrWr{
public static void main(String[] args) throws IOException{
DataOutputStream dos = new DataOutputStream(
new FileOutputStream("fib.txt"));
int a = 1, b = 1, c = 1;
for (int k = 0; k < 40; k++){
System.out.print(b + " ");
dos.writeInt(b);
a = b; b = c; c = a + b;
}
dos.close();
System.out.println("\n");
DataInputStream dis = new DataInputStream(
new FileInputStream("fib.txt"));
while (true)
try{
a = dis.readInt();
System.out.print(a + " ");
}catch(IOException e){
dis.close();
System.out.println("End of file");
System.exit(0);
}
}
}

. 23.5.

IV. Java

584

, IOException, 23.5
.


, Java, , , FileChannel java.nio.channels
RandomAccessFile java.io. .
, , .
FileChannel ,
NIO, , Path
:
Path path = Paths.get("pub/file.txt");
FileChannel fc = (FileChannel)Files.newByteChannel(path,
StandardOpenOption.READ,
StandardOpenOption.WRITE);

, StandardOpenOption
, .
APPEND, CREATE, CREATE_NEW, TRANCATE_EXISTING, DELETE_ON_CLOSE,
SPARSE, SYNC, DSYNC.
Path
open(), ,

FileChannel

FileChannel fc = FileChannel.open(path, StandardOpenOption.CREATE,


StandardOpenOption.APPEND);

FileChannel
FileInputStream FileOutputStream, RandomAccessFile
getChannel():
RandomAccessFile ras = new RandomAccessFile("pub/file.txt", "rw");
FileChannel fc = ras.getChannel();

, RandomAccessFile .

RandomAccessFile(File file, String mode);
RandomAccessFile(String fileName, String mode);

, mode, .
"r" , "rw" ,
"rwd" "rws" , .
.
DataInputStream DataOutputStream, ,
readLine() .

23. /

585

0, . (file pointer) .
. ,
0.
. pos
seek(long pos). seek(0) .
getFilePointer().
RandomAccessFile
, .
FileChannel position(), position(long pos).
FileChannel read() write().
, ByteBuffer,
.
:
ByteBuffer buf = ByteBuffer.allocate((int)fc.size());
int n = fc.read(buf);
byte[] arr = new byte[n];
buf.position(0);
buf.get(arr);
for (byte b: arr) System.out.print((char)b);
fc.close();

5. 4 .


,
. java.io PipedXxx, .

PipedWriter+ PipedOutputstream,
write() .

PipedReader PipedInputStream. -
connect()
read().
.
(pipe) . ,
. , .

IV. Java

586

, .
23.6 run() Source , k, pw.write(k). run() Target
pr.read(). Target. . 23.6
.

. 23.6. ,

23.6.
import java.io.*;
class Target extends Thread{
private PipedReader pr;
Target(PipedWriter pw){
try{
pr = new PipedReader(pw);
}catch(IOException e){
System.err.println("From Target(): " + e);
}
}
PipedReader getStream(){ return pr;}
public void run(){
while(true)
try{
System.out.println("Reading: " + pr.read());
}catch(IOException e){
System.out.println("The job's finished.");

23. /

587

System.exit(0);
}
}
}
class Source extends Thread{
private PipedWriter pw;
Source(){
pw = new PipedWriter();
}
PipedWriter getStream(){ return pw;}
public void run(){
for (int k = 0; k < 10; k++)
try{
pw.write(k);
System.out.println("Writing: " + k);
}catch(Exception e){
System.err.println("From Source.run(): " + e);
}
}
}
class PipedPrWr{
public static void main(String[] args){
Source s = new Source();
Target t = new Target(s.getStream());
s.start(); t.start();
}
}


ObjectInputStream ObjectOutputStream

, , , DataInputStream
DataOutputStream .
, ObjectXxx ,
. ,
, / .

(serialization),
(deserialization).
, , , private- , , , -

588

IV. Java

, .
, ,
Serializable. , .
.
class A implements Serializable{...}

, .
Java, .
ObjectOutputStream, ,
writeObject():
MyClass mc = new MyClass("abc", -12, 5.67e-5);
int[] arr = {10, 20, 30};
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("myobjects.ser"));
oos.writeObject(mc);
oos.writeObject(arr);
oos.writeObject("Some string");
oos.writeObject(new Date());
oos.flush();

, , ,
. - .
, ,
, - , . writeObject() . , , ,
.
, , Serializable,
NotSerializableException . J2SE JDK . , . , java.awt.Component Serializable, , .
, , java.awt.Toolkit.
. Serializable , Java " ".
, :
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("myobjects.ser"));

23. /
MyClass mc1
int[] a
String s
Date d

=
=
=
=

589

(MyClass)ois.readObject();
(int[])ois.readObject();
(String)ois.readObject();
(Date)ois.readObject();

.
23.7 GregorianCalendar , date.ser, . . 23.7.
23.7.
import java.io.*;
import java.util.*;
class SerDate{
public static void main(String[] args) throws Exception{
GregorianCalendar d = new GregorianCalendar();
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("date.ser"));
oos.writeObject(d);
oos.flush();
oos.close();
Thread.sleep(3000);
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("date.ser"));
GregorianCalendar oldDate = (GregorianCalendar)ois.readObject();
ois.close();
GregorianCalendar newDate = new GregorianCalendar();
System.out.println("Old time = " +
oldDate.get(Calendar.HOUR) + ":" +
oldDate.get(Calendar.MINUTE) + ":" +
oldDate.get(Calendar.SECOND) + "\nNew time = " +
newDate.get(Calendar.HOUR) + ":" +
newDate.get(Calendar.MINUTE) + ":" +
newDate.get(Calendar.SECOND));
}
}

. 23.7.

590

IV. Java

- ,
transient, :
transient MyClass mc = new MyClass("abc", -12, 5.67e-5);

writeObject() , static
transient. , , writeObject()
.
, / .
, Serializable,
Externalizable, readExternal() writeExternal(),
/.
. , Java Object Serialization Specification,
Java SE docs/platform/serialization/spec/.
docs/technotes/guides/serialization/examples/ ,
.

Java
,
. Java
AWT Java 2D. , javax.print.*
, .

Graphics " ". Graphics,
PrintGraphics
PrintJob, java.awt.
Toolkit java.awt.
:
PrintJob pj = getToolkit().getPrintJob(this, "Job Title", null);
Graphics pg = pj.getGraphics();

getPrintJob() (Print) .
K, pj.
(Cancel), null.
Toolkit getPrintJob():
getPrintJob(Frame frame, String jobTitle, JobAttributes jobAttr,
PageAttributes pageAttr);
getPrintJob(Frame frame, String jobTitle, Properties prop);

frame , . null. jobTitle ,


, null. prop

23. /

591

, null, .
jobAttr . JobAttributes,
, . , , .
, , .
pageAttr . PageProperties
,
. , .
, . Java 2D , .
" " pg Graphics ,
print(pg) printAll(pg) Component.
paint(pg).
, .
, ,
paint(pg) pg.drawString() ,
9. , " "
, pg.setFont().
print() pg.dispose(),
, pj.end(), .
23.8 , paint(). : , , .
simplePrint().
23.8. AWT
import java.awt.*;
import java.awt.event.*;
class PrintTest extends Frame{
PrintTest(String s){
super(s);
setSize(400, 400);
setVisible(true);
}
public void simplePrint(){
PrintJob pj =
getToolkit().getPrintJob(this, "Job Title", null);
if (pj != null){
Graphics pg = pj.getGraphics();
if (pg != null){
print(pg);

IV. Java

592

pg.dispose();
}else System.err.println("Graphics's null");
pj.end();
}else System.err.println("Job's null");
}
public void paint(Graphics g){
g.setFont(new Font("Serif", Font.ITALIC, 30));
g.setColor(Color.black);
g.drawArc(100, 100, 200, 200, 0, 360);
g.drawString(" 1", 100, 100);
}
public static void main(String[] args){
PrintTest pt = new PrintTest(" ");
pt.simplePrint();
pt.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
System.exit(0);
}
});
}
}

Java 2D
Java 2D
, java.awt.print.
AWT. ,
. , , , ,
AWT.
AWT, Java 2D , Graphics
Graphics2D.
Java 2D, ,
, , (page painter).
Printable.
print(). , , .
print() int :
print(Graphics g, PageFormat pf, int ind);

g , ,
pf PageFormat, , ind , .
print() , , paint(), AWT. , , Frame paint(). Graphics Graphics2D
print().

23. /

593

, print() , PAGE_EXISTS.
print() . ind 1.
ind , print()
NO_SUCH_PAGE, .
, paint()
. ind ,
print() .
PageFormat . 1/72 ,
:
PORTRAIT , Ox

, Oy ;
LANDSCAPE , Ox , Oy
;

REVERSE_LANDSCAPE , Ox ,

Oy .
, ,
(imageable area), getImageableX() getImageableY(),
getImageableWidth() getImageableHeight().
,
drawString(), 23.10.
PageFormat(),
, .
, , Java,
: " ?" :
" ".
pageDialog(PageDialog pd)
(Page Setup) , , pd.
(Cancel), pd; K, . pd .
.
, Paper :
Paper p = new Paper();


p.setSize(double width, double height);
p.setImageableArea(double x, double y, double width, double height);

594

IV. Java

PageFormat :
PageFormat pf = new PageFormat();


pf.setPaper(p);

pageDialog()
, (silent) . , " " .
, , print() . (print job) , ,
, . PrinterJob.
Java 2D .
Printable Job , ,
, , .
, Pageable Job
, ,
. , , , , . Book ,
Pageable.
Book, -, , :
Book b = new Book();

, .
Book :
append(Printable p, PageFormat pf) p ;
append(Printable p, PageFormat pf, int numPages) numPages p

; ,
UNKNOWN_NUMBER_OF_PAGES.

, . . PrinterJob,

setPrintable(Printable pr), setPrintable(Printable pr, PageFormat pf) setPageble(Pageable pg).
pr, .

(Print) ,
printDialog(). .
true, K, false
(Cancel).
, 1, setCopies(int n),
.
defaultPage() PrinterJob
PageFormat .
PageFormat.

23. /

595

, PrinterJob. , ,
getPrinterJob(), PrinterJob.
print() PrinterJob. . print(g, pf, ind) ,
, .
23.9. Java 2D
, 23.8. . 6.
, System.exit(0).
23.9. Java 2D
import java.awt.*;
import java.awt.geom.*;
import java.awt.print.*;
class Print2Test implements Printable{
public int print(Graphics g, PageFormat pf, int ind)
throws PrinterException{
// 5 .
if (ind > 4) return Printable.NO_SUCH_PAGE;
Graphics2D g2 = (Graphics2D)g;
g2.setFont(new Font("Serif", Font.ITALIC, 30));
g2.setColor(Color.black);
g2.drawString("Page " + (ind + 1), 100, 100);
g2.draw(new Ellipse2D.Double(100, 100, 200, 200));
return Printable.PAGE_EXISTS;
}
public static void main(String[] args){
// 1. .
PrinterJob pj = PrinterJob.getPrinterJob();
// 2. " ".
PageFormat pf = pj.pageDialog(pj.defaultPage());
// 3. , , ,
//
.
pj.setPrintable(new Print2Test(), pf);
// 4. , :
pj.setCopies(2);
// .
// 5. "" ()
if (pj.printDialog()){
// ...
try{
pj.print();
// print(g, pf, ind).
}catch(Exception e){
System.err.println(e);
}
}

IV. Java

596
// 6. .
System.exit(0);
}
}



drawString().
.
23.10 ,
. , , .
.
23.10.
import java.awt.*;
import java.awt.print.*;
import java.io.*;
public class Print2File{
public static void main(String[] args){
if (args.length < 1){
System.err.println("Usage: Print2File path");
System.exit(0);
}
PrinterJob pj = PrinterJob.getPrinterJob();
PageFormat pf = pj.pageDialog(pj.defaultPage());
pj.setPrintable(new FilePagePainter(args[0]), pf);
if (pj.printDialog()){
try{
pj.print();
}catch(PrinterException e){}
}
System.exit(0);
}
}
class FilePagePainter implements Printable{
private BufferedReader br;
private String file;
private int page = -1;
private boolean eof;
private String[] line;
private int numLines;

23. /
public FilePagePainter(String file){
this.file = file;
try{
br = new BufferedReader(new FileReader(file));
}catch(IOException e){ eof = true; }
}
public int print(Graphics g, PageFormat pf, int ind)
throws PrinterException{
g.setColor(Color.black);
g.setFont(new Font("Serif", Font.PLAIN, 10));
int h = (int)pf.getImageableHeight();
int x = (int)pf.getImageableX() + 10;
int y = (int)pf.getImageableY() + 12;
try{
// :
if (ind != page){
if (eof) return Printable.NO_SUCH_PAGE;
page = ind;
line = new String[h/12];
// .
numLines = 0;
// .
// .
while (y + 48 < pf.getImageableY() + h){
line[numLines] = br.readLine();
if (line[numLines] == null){
eof = true;
break;
}
numLines++;
y += 12;
}
}
// .
y = (int)pf.getImageableY() + 12;
g.drawString(": " + file + ", " + (ind + 1), x, y);
// .
y += 36;
// .
for (int i = 0; i < numLines; i++){
g.drawString(line[i], x, y);
y += 12;
}
return Printable.PAGE_EXISTS;
}catch(IOException e){
return Printable.NO_SUCH_PAGE;
}
}
}

597

598

IV. Java


Printable Job
, , , .
Pageable Job Book.
, Book, , .
PageFormat, , .
,
UNKNOWN_NUMBER_OF_PAGES. , print() NO_SUCH_PAGE.

setPage(int pageIndex, Printable p, PageFormat pf);

pageIndex p.
23.11 , : Cover Content.
print(). Cover
.
. Content
.
pf1,
pf2.
bk Book : ,
, print() Content.
23.11.
import java.awt.*;
import java.awt.print.*;
public class Print2Book{
public static void main(String[] args){
PrinterJob pj = PrinterJob.getPrinterJob();
// .
PageFormat pfl = pj.defaultPage();
pfl.setOrientation(PageFormat.LANDSCAPE);
// .
PageFormat pf2 = pj.pageDialog(new PageFormat());
Book bk = new Book();
// .
bk.append(new Cover(), pfl);
// .
bk.append(new Content(), pf2, 2);
// Pageable Job.
pj.setPageable(bk);

23. /

599

if (pj.printDialog()){
try{
pj.print();
}catch(Exception e){}
}
System.exit(0);
}
}
class Cover implements Printable{
public int print(Graphics g, PageFormat pf, int ind)
throws PrinterException{
g.setFont(new Font("Helvetica-Bold", Font.PLAIN, 40));
g.setColor(Color.black);
int y = (int)(pf.getImageableY() +
pf.getImageableHeight()/2);
g.drawString(" .", 72, y);
g.drawString(" ", 72, y+60);
g.drawString(" .", 72, y+120);
return Printable.PAGE_EXISTS;
}
}
class Content implements Printable{
public int print(Graphics g, PageFormat pf, int ind)
throws PrinterException{
Graphics2D g2 = (Graphics2D)g;
g2.setFont(new Font("Serif", Font.PLAIN, 12));
g2.setColor(Color.black);
int x = (int)pf.getImageableX() + 30;
int y = (int)pf.getImageableY();
g2.drawString(" .",
x, y += 16);
g2.drawString(" ,", x, y += 16);
g2.drawString(" .", x, y += 16);
return Printable.PAGE_EXISTS;
}
}


1. (stream) ?
2. / Java
?

600

IV. Java

3. /?
4. ?
5. , ?
6. ?
7. / ?
8. ?
9. , , , /?

24

Java
, , . , (peer-to-peer) .
,
-, , , . . ,
, -, .
, , . . - (client-server).
, (listen) ,
.
(request) , . (response), , . ,
, (session).
,
(protocol) . , ,
.
, , . , , ,
. ,
. , , .
, , , , . , , , .
, : ,
. . , . , -
- , .

602

IV. Java

: , , ,
, . , . , , , .
,
, , . , , .
- -.
,
, Web-. , - (port).
, , -. , , ,
, , . , 25,
21, Web- 80.
1023. , 1024 65 535, .
. -
- . , " ", "" . . , -"".
, . , ,
.
, - . Web-
80 81, 8080, 8001 -
.
. , : " !" : " ...".
. : ", !" : ", ".
. , . , , . , . , ,
, , . , .
, :
, , .
(stack) : " ".

24. Java

603

, TCP/IP.
, ,
(application) : HTTP (80), SMTP (25), Telnet (23), FTP (21), POP3 (100) . .
(transport) . , , ,
. TCP
(Transmission Control Protocol) UDP (User Datagram Protocol).
TCP TCP- (packet), UDP
(datagram).
, , .
. , , .
,
.
, . , UDP . , , , , .
TCP- , ,
TCP . . . , . . , , ,
TCP . TCP
, .
, (network) .
IP (Internet Protocol). , . IP-.
, IP- , (link)
ENET, SLIP, PPP, , .
, , ,
.
IP-? , , (host), , IP- (IP-address).
0 255,
(octet), , : 138.2.45.12
17.056.215.38.
IP- , .
: " 154.223.145.26!" IP-
(domain name).

604

IV. Java

: ru , su , ua , de . ., :
com , org , edu . : msc.ru , spb.ru , kcn.ru , : bhv.ru "-", ksu.ru , sun.com Sun Microsystems. :
www.bhv.ru, java.sun.com.
.
Java IP- InetAddress java.net.
getByName(String host)
, host IP-.

WWW
WWW (World Wide Web),
HTTP (Hypertext Transfer Protocol). , URL (Uniform Resource Locator). :
protocol://authority@host:port/path/file#ref
protocol://authority@host:port/path/file/query?user_info
authority : ,
host IP- . :
http://www.bhv.ru/
https://132.192.5.10:448/public/some.html
ftp://guest:password@lenta.ru/users/local/pub
file:///C:/text/html/index.htm
- URL , . , HTTP 80,
HTTPS 443, FTP 21. path/file,
, , "welcome file".
index.html, index.htm index.jsp.
Java URL URL java.net.
.
URL(String url);

url . getProtocol(),
getAuthority(), getHost(), getPort(), getPath(), getFile(), getQuery(), getUserInfo(), URL, :
openConnection() URL URLConnection;
openStream() URL -

InputStream.
24.1 , , openStream().

24. Java

605

24.1. Web-
import java.net.*;
import java.io.*;
public class SimpleURL{
public static void main(String[] args){
try{
URL bhv = new URL("http://www.bhv.ru/");
BufferedReader br = new BufferedReader(
new InputStreamReader(bhv.openStream()));
String line = null;
while ((line = br.readLine()) != null)
System.out.println(line);
br.close();
}catch(MalformedURLException me){
System.err.println("Unknown host: " + me);
System.exit(0);
}catch(IOException ioe){
System.err.println("Input error: " + ioe);
}
}
}

, : , , , , , ,
, openConnection()
URLConnection HttpURLConnection.
,
. :
setDoOutput(boolean out) out true, -

; false;
setDoInput(boolean in) in true,

; true, setDoOutput(true),
false;
setUseCaches(boolean cache) cache false,

, true, ;
setDefaultUseCaches(boolean default) default true, -

, ;
setRequestProperty(String name, String value) name -

value .
connect(). . ,
getXxx(), ,
, connect() .

606

IV. Java

Web- , , ,
getXxx(). :
getContentType() String, MIME- -

, "text/html", null, ;
getContentLength() 1,

;
getContent() Object;
getContentEncoding() String -

null, .
/, :
getInputStream() InputStream;
getOutputStream() OutputStream.

, , .
bhv.openStream(), 24.1,

bhv.openConnection().getInputStream();

24.2 , URL.
Web-, , , . ? , ?
? ?
CGI (Common Gateway Interface), , , . URL
, -. , Web
. - , .
. Web- , .
CGI- : C, C++, Pascal, Perl, ASP, PHP,
. Java,
Java
(servlets) JSP, 26 27. CGI-
cgi-bin.
24.2. URL
import java.net.*;
import java.io.*;
public class PostURL{
public static void main(String[] args){
String req = "This text is posting to URL";

24. Java

607

try{
// URL CGI-.
URL url = new URL("http://www.bhv.ru/cgi-bin/some.pl");
// uc.
URLConnection uc = url.openConnection();
//
uc.setDoOutput(true);
//
uc.setDoInput(true);
// .
uc.setUseCaches(false);
//
uc.setRequestProperty("content-type", "application/octet-stream");
// .
uc.setRequestProperty("content-length", "" + req.length());
// .
uc.connect();
//
DataOutputStream dos = new DataOutputStream(uc.getOutputStream());
// , URL.
dos.writeBytes(req);
// .
dos.close();
// .
BufferedReader br = new BufferedReader(new InputStreamReader(
uc.getInputStream()));
String res = null;
// .
while ((res = br.readLine()) != null)
System.out.println(res);
br.close();
}catch(MalformedURLException me){
System.err.println(me);
}catch(UnknownHostException he){
System.err.println(he);
}catch(UnknownServiceException se){
System.err.println(se);
}catch(IOException ioe){
System.err.println(ioe);
}
}
}

1. , .
2. , CGI-
.

608

IV. Java

TCP
-, , . - ,
-.
,
, (socket).
"socket" , . ,
220 50 , , , .
(bind) ; , (listen) . .
1. , .
2. , ,
(accept) .
3. , , ,
, .
4. .
,
, .
Java Socket java.net. , .

Socket(String host, int port);

.
. ,
/:
getInputStream() InputStream;
getOutputStream() OutputStream.


HTTP. :
1. "POST filename
HTTP/1.1\n\n", filename .
2. , filename
. filename /, index.html, .
3. "HTTP/1.1 code \n\n",
code , : 200 , ;
400 ; 404 .
4. , .

24. Java

609

5. System.out
System.err.
6. , .
24.3 24.4.
24.3. HTTP-
import java.net.*;
import java.io.*;
import java.util.*;
public class Client{
public static void main(String[] args){
if (args.length != 3){
System.err.println("Usage: Client host port file");
System.exit(0);
}
String host = args[0];
int
port = Integer.parseInt(args[1]);
String file = args[2];
try{
Socket sock = new Socket(host, port);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(
sock.getOutputStream()), true);
pw.println("POST " + file + " HTTP/1.1\n");
BufferedReader br = new BufferedReader(new InputStreamReader(
sock.getInputStream()));
String line = null;
line = br.readLine();
StringTokenizer st = new StringTokenizer(line);
String code = null;
if ((st.countTokens() >= 2) && st.nextToken().equals("POST")){
if ((code = st.nextToken()) != "200"){
System.err.println("File not found, code = " + code);
System.exit(0);
}
}
while ((line = br.readLine()) != null)
System.out.println(line);
sock.close();
}catch(Exception e){
System.err.println(e);
}
}
}

IV. Java

610

/ . , .
java.net ServerSocket.
:
ServerSocket(int port);

, accept(), ,
. , Socket, .
24.4. HTTP-
import java.net.*;
import java.io.*;
import java.util.*;
public class Server{
public static void main(String[] args){
try{
ServerSocket ss = new ServerSocket(Integer.parseInt(args[0]));
while (true)
new HttpConnect(ss.accept());
}catch(ArrayIndexOutOfBoundsException ae){
System.err.println("Usage: Server port");
System.exit(0);
}catch(IOException e){
System.out.println(e);
}
}
}
class HttpConnect extends Thread{
private Socket sock;
HttpConnect(Socket s){
sock = s;
setPriority(NORM_PRIORITY 1);
start();
}
public void run(){
try{
PrintWriter pw = new PrintWriter(new OutputStreamWriter(
sock.getOutputStream()), true);
BufferedReader br = new BufferedReader(new InputStreamReader(
sock.getInputStream()));
String req = br.readLine();
System.out.println("Request: " + req);

24. Java

611

StringTokenizer st = new StringTokenizer(req);


if ((st.countTokens() >= 2) && st.nextToken().equals("POST")){
if ((req = st.nextToken()).endsWith("/") || req.equals(""))
req += "index.html";
try{
File f = new File(req);
BufferedReader bfr = new BufferedReader(new FileReader(f));
char[] data = new char[(int)f.length()];
bfr.read(data);
pw.println("HTTP/1.1 200 OK\n");
pw.write(data);
pw.flush();
}catch(FileNotFoundException fe){
pw.println("HTTP/1.1 404 Not Found\n");
}catch(IOException ioe){
System.out.println(ioe);
}
}else pw.println("HTTP/1.1 400 Bad Request\n");
sock.close();
}catch(IOException e){
System.out.println(e);
}
}
}

, , :
java Server 8080

, IP- ,
:
java Client localhost 8080 Server.java

Server.java .
.
, .

, TCP/IP, ""
127.0.0.1 localhost. . - . , .

Java SE, $JAVA_HOME/sample/nio/server,


HTTP/HTTPS-, NIO.

proxy-
proxy-, -

612

IV. Java

IP-. ,
proxy-, JDK 5.0 Socket
Socket(Proxy proxy);

Proxy, proxy-.
Proxy(Proxy.Type type, SocketAddress address);

proxy- :
DIRECT proxy-;
HTTP proxy-, HTTP FTP;
SOCKS proxy-, SOCKS4

SOCKS5.
SocketAddress, , .
InetSocketAddress.
. , proxy, :
Socket sock = new Socket(new Proxy(Proxy.Type.SOCKS,
new InetSocketAddress("socks.domain.com", 1080)));

3. , FTP.
4. proxy- .

UDP

. Java DatagramSocket. :
DatagramSocket()

;
DatagramSocket(int port) port -

;
DatagramSocket(int port, InetAddress addr) -

port; addr .
, , :
send(DatagramPacket pack) , pack;
receive(DatagramPacket pack)

pack.

24. Java

613

, , , .

connect(InetAddress addr, int port);

addr
port , .
disconnect().
UDP , :
String mes = "This is the sending message.";
byte[] data = mes.getBytes();

InetAddress, :
InetAddress addr = InetAddress.getByName(host);

DatagramPacket. , , :
DatagramPacket pack = new DatagramPacket(data, data.length, addr, port);

:
DatagramSocket ds = new DatagramSocket();

:
ds.send(pack);

, -
:
ds.close();

,
send() receive(DatagramPacket pack).
24.5 Sender, ,
, localhost, 1050. Recipient, 24.6, .
24.5. UDP
import java.net.*;
import java.io.*;
public class Sender{
private String host;
private int port;
Sender(String host, int port){
this.host = host;
this.port = port;
}

614

IV. Java

private void sendMessage(String mes){


try{
byte[] data = mes.getBytes();
InetAddress addr = InetAddress.getByName(host);
DatagramPacket pack =
new DatagramPacket(data, data.length, addr, port);
DatagramSocket ds = new DatagramSocket();
ds.send(pack);
ds.close();
}catch(IOException e){
System.err.println(e);
}
}
public static void main(String[] args){
Sender sndr = new Sender("localhost", 1050);
for (int k = 0; k < args.length; k++)
sndr.sendMessage(args[k]);
}
}
24.6. UDP
import java.net.*;
import java.io.*;
public class Recipient{
public static void main(String[] args){
try{
DatagramSocket ds = new DatagramSocket(1050);
while (true){
DatagramPacket pack = new DatagramPacket(new byte[1024], 1024);
ds.receive(pack);
System.out.println(new String(pack.getData()));
}
}catch(Exception e){
System.out.println(e);
}
}
}

5. .


1. "-"?
2. ?

24. Java

615

3. ?
4. ?
5. ?
6. TCP/IP?
7. IP-?
8. ?
9. ?
10. DNS-?
11. URL?
12. -?

Web- Java
25.

Web- Java

26.

27.

JSP

28.

Java XML

25

Web- Java
Java,
, .

jar
, ,
Java JAR. jar-
, jar. ZIP. JAR (Java ARchive)
TAR (Tape ARchive), UNIX.
jar- zip- , jar- META-INF, .
, 18, , .
-, ,
. <applet>
archive, :
<applet code = "MillAnim.class" archive = "first.jar, second.jar"
width = "100%" height = "100%"></applet>

MillAnim.class -
first.jar second.jar. ,
, , , HTML-. , jar-, zip- .
(applications). , appl.jar.
, jar, :
java jar appl.jar

, main(),
MANIFEST.MF, .

V. Web- Java

620

JDK MS Windows
jar javaw, , :
"C:\jre1.6.0_02\bin\javaw.exe" -jar "%1" %*

, Windows.

.
, , java.util.jar.


Jar- java.util.jar jar.
jar tar.
jar <Enter>,
, , . 25.1.

. 25.1. jar

jar ,
:
jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files...

. , jar : c, t, x, u i.
:
c (create) ;
t (table of contents) ;

25. Web- Java

621

x (extract) ;
u (update) , .

, , ,
. :
v (verbose) -

;
f (file) jar-file ;
m (manifest) manifest-file -

;
0 () , ;
M (manifest) ;
e (entry) . entrypoint , main(), .
MANIFEST.MF (. ).

-i (index) INDEX.LIST.
.
-
jar-file, , , manifest-file, , ,
entry-point, ,
. , .
. -C dir ,
jar dir.
.
,
. f,
jar-. m, (manifest-file).
, ,
f m.
f , .
m ,
MANIFEST.MF, META-INF ,
.
. 25.2 Base.jar ch3.
ch3. , Base.class classes. ch3. Base.jar. .
, META-INF, MANIFEST.MF.

V. Web- Java

622

. 25.2. jar

MANIFEST.MF
MANIFEST.MF, META-INF , :
, ;
JavaBeans, ;
;
, ;
.
,
manif. jar,
m, :
jar cmf manif Base.jar classes Base.class

25. Web- Java

623

manif
MANIFEST.MF, .
manif , JAR File Specification. Java SE,
docs/technotes/guides/jar/jar.html.
, Base.class
Base.jar, manif :
Main-Class: Base

, , . .
class. , .
, , '\n'.
, name.gif, (splash screen)

SplashScreen-Image: name.gif

Base.jar, :
java jar Base.jar

INDEX.LIST

INDEX.LIST. . jar
i, :
jar i Base.jar

META-INF INDEX.LIST. . 25.3


,
.

. 25.3.

624

V. Web- Java

JavaBeans
IDE (Integrated
Development Environment), NetBeans, IntelliJ IDEA, Eclipse, JBuilder .
, .
, . , .
, ,
.
(properties) : , ,
, .
, .
Properties ,
. , .
,
.
, Eclipse, .
, .
(properties), .
getXxx()/setXxx()/isXxx() . IDE, .
, ,
Java JavaBean.
. , jar-
MANIFEST.MF Java-Bean: True.
AWT Swing JavaBeans.
, III, JavaBean. -
JavaBeans, ,
IDE, , NetBeans.
JavaBeans
Java SE, technotes/guides/beans.
JavaBeans JavaBeans API
Specification, :
http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html.
JavaBeans.
, JavaBeans, ,
. ,
JavaBeans , .

25. Web- Java

625

.
, JavaBeans

.

JDBC
, .
. , (
) -
.
, .
, ,
?
Microsoft, ODBC (Open
Database Connectivity) , C. , . , ,
ODBC.
ODBC, . , , , .
, ODBC
.
Sun , JDBC, . java.sql, javax.sql ,
Java SE.
"JDBC" , , "Java Database Connectivity".
JDBC , JDBC
. JDBC . JDBC
.
http://developers.sun.com/product/jdbc/drivers http://www.sqlsummit.com/
JDBCVend.htm.
JDBC:
, JDBC ODBC.
(bridge) JDBCODBC.
ODBC, ,
;
, JDBC API .
;

626

V. Web- Java

, JDBC , -

, HTTP. , ,
;
, JDBC .

,
JDBCODBC:
try{
Class dr = sun.jdbc.odbc.JdbcOdbcDriver.class;
}catch(ClassNotFoundException e){
System.err.println("JDBC-ODBC bridge not found " + e);
}

dr , .
25.1.
, .
Connection. , ,
getConnection() DriverManager, :
String url = "jdbc:odbc:mydb";
String login = "admin";
String password = "1nF4vb";
Connection con = DriverManager.getConnection(url, login, password);

, url.
"jdbc:", (subprotocol), JDBCODBC, "odbc:".
(subname) , "mydb".
.
, . , Statement. createStatement(), Connection. :
Statement st = con.createStatement();

(query) execute()
getResultSet().
executeQuery(), :
ResultSet rs = st.executeQuery("SELECT name, code FROM tbl1");

tbl1 name code


rs , ResultSet.
SQL- INSERT, UPDATE, DELETE, CREATE TABLE .
executeUpdate().
next() rs getXxx() ResultSet, :

25. Web- Java

627

while (rs.next()){
emp[i] = rs.getString("name");
num[i] = rs.getInt("code");
i++;
}

ResultSetMetaData , , , rs .
st
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);

previous(),
first(), last(). rs updateXxx() , . ,
rs rs.getType()
rs.getConcurrency().
Statement PreparedStatement,
, setXxx().
PreparedStatement, , CallableStatement,
.
25.1 Oracle Oracle
Thin. , , .
Oracle, .
.
25.1. , Oracle
import
import
import
import
import

java.awt.*;
java.awt.event.*;
java.applet.*;
java.util.*;
java.sql.*;

public class JdbcApplet extends Applet implements ActionListener, Runnable{


private TextField tf1, tf2, tf3;
private TextArea ta;
private Button b1, b2;
private String url = "jdbc:oracle:thin:@localhost:1521:ORCL",
login = "scott",
password = "tiger",
query = "SELECT * FROM dept";
private Thread th;
private Vector results;

628

V. Web- Java

public void init(){


setBackground(Color.white);
try{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
}catch(SQLException e){
System.err.println(e);
}
setLayout(null);
setFont(new Font("Serif", Font.PLAIN, 14));
Label l1 = new Label("URL :", Label.RIGHT);
l1.setBounds(20, 30, 70, 25); add(l1);
Label l2 = new Label(":", Label.RIGHT);
l2.setBounds(20, 60, 70, 25); add(l2);
Label l3 = new Label(":", Label.RIGHT);
l3.setBounds(20, 90, 70, 25); add(l3);
tf1 = new TextField(url, 30);
tf1.setBounds(100, 30, 280, 25); add(tf1);
tf2 = new TextField(login, 30);
tf2.setBounds(100, 60, 280, 25); add(tf2);
tf3 = new TextField(password, 30);
tf3.setBounds(100, 90, 280, 25); add(tf3);
tf3.setEchoChar('*');
Label l4 = new Label(":", Label.LEFT);
l4.setBounds(10, 120, 70, 25); add(l4);
ta = new TextArea(query, 5, 50, TextArea.SCROLLBARS_NONE);
ta.setBounds(10, 150, 370, 100); add(ta);
Button b1 = new Button("");
b1.setBounds(280, 260, 100, 30); add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae){
url
= tf1.getText();
login
= tf2.getText();
password = tf3.getText();
query
= ta.getText();
if (th == null){
th = new Thread(this);
th.start();
}
}
public void run(){
try{
Connection con = DriverManager.getConnection(url, login, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
//
int n = rsmd.getColumnCount();
results = new Vector();

25. Web- Java

629

while (rs.next()){
String s = " ";
// 1!
for (int i = 1; i <= n; i++)
s += " " + rs.getObject(i);
results.addElement(s);
}
rs.close();
st.close();
con.close();
repaint();
}catch(Exception e){
System.err.println(e);
}
repaint();
}
public void paint(Graphics g){
if (results == null){
g.drawString("Can't execute the query", 5, 30);
return;
}
int y = 30, n = results.size();
for (int i = 0; i < n; i++)
g.drawString((String)results.elementAt(i), 5, y += 20);
}
}

24 , , ,
127.0.0.1 localhost. ,
, . , Web-. Web- 8080, HTML , URL http://localhost:8080/public/
JdbcApplet.html. , Web- , public usr/local/http/public .

, JDBC .
JDBC , JDBC,
: http://java.sun.com/products/jdbc/.
Java SE, technotes/guides/jdbc/,
JDBC.


1. Java JAR?
2. jar- , ?
3. jar-?

630

V. Web- Java

4. jar- ?
5. JavaBeans: , , , ?
6. , JavaBean?
7. JavaBeans?
8. JDBC?
9. JDBC?
10. JDBC?

26

HTTP- : , .
HTTP URL.
- . SSI (Server
Side Include) HTML. HTTP Web-.
. URL , CGI
(Common Gateway Interface), .
URL , , " ", :
http://some.firm.com/cgi-bin/mycgiprog.pl?name=Ivanov&age=27
HTML <form>.
Web-, , CGI- (
mycgiprog.pl), cgi-bin,
"Ivanov" "27" name age.
HTML, Web- .
CGI , . Perl. , CGI. : PHP, ASP, JavaScript.
Java
JSP (JavaServer Pages).
(servlets) Web- , , .

, (servlet container). ""
, , , , , . ,

632

V. Web- Java

. " ", "servlet engine", , " ".


Web-, , (application server, AS).
, , "Java Servlet Specification" (deploy) . (deployment) , , .
.
, autodeploy/ webapps/, , . Java EE SDK deploytool.
.
Java, Web-.
Java .
Web-
. Tomcat, Apache Software Foundition Jakarta, Resin
Caucho, JRun Macromedia. Web .
Tomcat http://tomcat.apache.org/
. zip-, - .
Tomcat 7, "" Servlet 3.0 JSP 2.2.

Web-
, . Web-.
Web- (web application) , : , JSP, HTML, XML, , , . "Java
Servlet Specification" , .
. 26.1.
, , Web-,
, Web-.
InfoAppl. WEB-INF
. , WEB-INF ,
. " " Web-. ,
WEB-INF, .
WEB-INF XML- web.xml,
Web-: , .

26.

633

Web- ,
WEB-INF, web.xml. ,
web.xml .
WEBINF/classes .

. 26.1. Web-

Web- JAR.
war (Web ARchive). Web- ,
Web- , . Tomcat WAR-
webapps. "" , , .
Tomcat server.xml.

Servlet
Java, "" Servlet.
.
, ,
. , init() , , , , init(), Servlet,
ServletConfig:
public void init(ServletConfig conf);

, ServletConfig, Web- . ,
, Web-.

634

V. Web- Java


(deployment descriptor) ,
Web-: , , JSP, HTML
XML, . Web .
XML web.xml. WEB-INF, Web-, , IDE, NetBeans
Eclipse. -
make-, . ,
make Java , Java: ant, Apache Software Foundation
Jakarta, Maven Apache Software
Foundation, Ivy - Apache.
Tomcat ,
/manager/html. ,
: http://localhost:8080/manager/.
26.1 web.xml,
Tomcat. XML 28, XML .
26.1. web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<web-app>
<!- , .
"default" .
-->
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>
org.apache.tomcat.servlets.DefaultServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!- , ,
"invoker".
-->
<servlet>
<servlet-name>invoker</servlet-name>

26.
<servlet-class>
org.apache.tomcat.servlets.InvokerServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<!- JSP
JspServlet. "jsp".
-->
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>
org.apache.jasper.runtime.JspServlet
</servlet-class>
<!-- uncomment the following to use Jikes for JSP compilation
, jikes.
<init-param>
<param-name>jspCompilerPlugin</param-name>
<param-value>
org.apache.jasper.compiler.JikesJavaCompiler
</param-value>
</init-param>
-->
<load-on-startup>
-2147483646
</load-on-startup>
</servlet>
<!- - ,
URL .
,
public_html webapps.
URL servlet,
"invoker", . . InvokerServlet.
-->
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
<!- JSP,
"jsp", . . JspServlet.
-->
<servlet-mapping>
<servlet-name>jsp</servlet-name>

635

V. Web- Java

636
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>

<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-
MIME- .
-->
<mime-mapping>
<extension>txt</extension>
<mime-type>text/plain</mime-type>
</mime-mapping>
<mime-mapping>
<extension>html</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>htm</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>gif</extension>
<mime-type>image/gif</mime-type>
</mime-mapping>
<!- .
, ,
.
-->
<welcome-file-list>
<welcome-file>index.jsp </welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
</web-app>

, web.xml . Web . Servlet 3.0,


, . ,
web.xml, XML- <web-fragment>, <web-app>. web-fragment.xml META-INF. XML web.xml.

26.

637

ServletConfig
ServletConfig ,
<servlet-name> , , <init-param>, ServletContext.
public
public
public
public

String getServletName();
Enumeration getInitParameterNames();
String getInitParameter(String name);
ServletContext getServletContext();

ServletConfig.
web.xml
.
, <param> getParameter() .
26.2 , .
26.2.
package myservlets;
import java.io.*;
import java.util.*;import javax.servlet.*;
public class InfoServlet extends GenericServlet{
private ServletConfig sc;
@Override
public void init(ServletConfig conf)
throws ServletException{
super.init(conf);
sc = conf; }
@Override
public void service(ServletRequest req, ServletResponse resp)
throws ServletException, IOException{
resp.setContentType("text/html; charset=windows-1251");
PrintWriter pw = resp.getWriter();
pw.println("<html><head>");
pw.println("<title> </title>");
pw.println("</head><body><h2> </h2>");
pw.println(" " + sc.getServletName() + "<br>");
pw.println(" : <br>");
Enumeration names = sc.getInitParameterNames();

V. Web- Java

638
while (names.hasMoreElements()){
String name = (String)names.nextElement();
pw.print(name + ": ");
pw.println(sc.getInitParameter(name) + "<br>");
}
pw.println("</body></html>");
pw.flush();
pw.close();
}
public void destroy(){
sc = null;
}
}

26.2 ,
:
init(ServletConfig), init(ServletConfig) -

;
setContentType() -

getWriter(). .
26.2 , InfoServlet.class . ,
, make- ant-.
, webapps, autodeploy, -
. ,
:
http://<servlethost>:8000/InfoAppl/servlet/InfoServlet
HTML, . , , .


, .
.

, Tomcat,
, Web-. Web- ,
. Web- :
http://<servlethost>:8000/InfoAppl/InfoServlet
getServletContext(),
ServletContext, .

26.

639


, Web-, . (context) , Web. , , , , , web.xml , , .
ServletContext. ,
.
getServerInfo() Java EE SDK,
getMajorVersion() getMinorVersion() Servlet API.
, Web-. Web- web.xml
<context-param>.
public Enumeration getInitParameterNames();
public String getInitParameter(String name);

,
Java.
public Enumeration getAttributeNames();
public Object getAttribute(String name);


public void setAttribute(String name, Object value);
public void removeAttribute(String name);

, Web-, , Web-, .

Service

public void service(ServletRequest req, ServletResponse resp);

init()
req ServletRequest, , . req . , service()
resp ServletResponse.
service() , req, resp. resp , Web- . , ServletRequest ServletResponse.

V. Web- Java

640

ServletRequest
ServletRequest, , getXxx(), null,
.
getRemoteAddr(), getRemoteHost() getRemotePort() IP-,
DNS- proxy- ,
getServerName() getServerPort() ,
.
getLocalAddr(), getLocalName() getLocalPort() IP-,
DNS- , , .
getScheme()
getProtocol()

: http:, https:, ftp: . .,


, "HTTP/1.1".

getContentType() getCharacterEncoding() MIME-


, , getContentLength()
, , 1, .
setCharacterEncoding(String) ,
getCharacterEncoding(), , .
, , String.
26.5. .
, ,
public
public
public
public

Enumeration getParameterNames();
String getParameter(String name);
String[] getParameterValues(String name);
Map getParameterMap();

- ,
public Enumeration getAttributeNames();
public Object getAttr