Professional Documents
Culture Documents
by
Yakov
Fain
Java
and
all
Java-based
trademarks
and
logos
are
trademarks
or
registered
trademarks
of
Oracle
Corporation
in
the
United
States
and
other
countries.
Windows
7
and
Windows
XP
are
trademarks
of
Microsoft
Corporation.
All
other
product
names
and
company
names
are
the
property
of
their
respective
owners.
ISBN:
0-9718439-5-3
Java , , iii
,
,
.
,
(
)
.
2004
-,
,
.
.
,
.
,
http://yurifain.com.
. ?
,
-
.
,
.
mp3
,
.
http://americhka.us
.
,
,
,
-
3-4
,
,
Java
,
.
,
,
,
,
.
:
,
,
,
,
,
!
,
,
,
,
.
,
.
,
.
,
,
,
,
J.
,
.
,
.
.
Java , , iv
,
.
,
?
,
,
.
,
,
Java
,
,
.
,
,
,
.
-
,
,
-
,
.
,
(yakovfain@gmail.com),
.
,
,
,
,
,
Java!
Java , , v
,
-
,
Java
.
,
.
Java
,
!
Amazon
(
-)
,
,
!
,
Google,
,
Java
,
,
Reader-Rabbit.
,
?
.
,
-
.
,
:
11
18
;
;
,
;
(
).
,
,
.
,
-
!
.
, !
.
-,
,
.
,
a.
-
-.
.
.
Java , , vi
Java
,
,
String.
Java.
,
.
a
,
-
.
,
.
,
.
,
.
,
,
.
,
.
,
.
,
,
,
,
.
Java , , vii
,
Eclipse,
.
New
Jersey
Transit
139.
.
,
Java
,
.
,
,
.
Java , , viii
......................................... III
...................................................................................... V
............................................................................... VII
..................................................................................... VIII
1. ....................................................... 13
Java ............................................................................................................. 14
........................................................................... 18
1 ............................................................................................. 18
2 ........................................................................................... 20
3 ..................................................................................................... 21
............................................................................ 22
Eclipse ................................................................................................ 28
Eclipse IDE........................................................................................... 32
HelloWorld..................................................................................... 36
............................................................................ 38
...................................................................................................... 38
............................................................. 39
3. JAVA .... 40
..................................................................................................................... 40
............................................................................................................................. 42
................................................................................................. 46
............................................................ 52
........................................................................................................ 56
........................................................................................................... 57
Java , , ix
..................................................................................................... 57
............................................................. 58
4. JAVA .................... 59
...................................................................................................... 59
if ....................................................................... 60
............................................................................................................. 62
. ............................................................................................................ 63
................................................................................................................... 63
else if............................................................................................................... 64
switch .............................................................................. 65
? ............................................................................................... 66
: ................................................................................... 67
this ............................................................................................................... 68
...................................................................................................................................... 69
............................................................................ 71
............................................................................ 74
...................................................................................................... 74
............................................................. 75
5. ....................... 76
AWT Swing ............................................................................................................................... 76
import ........................................................................................... 77
Swing ...................................................................................................... 78
................................................................................................................... 81
FlowLayout - ................................................................................ 82
GridLayout - ................................................................................. 82
BorderLayout - .............................................................................. 84
....................................................................................... 85
BoxLayout - .............................................. 88
CardLayout ........................................................................................................ 90
, ? ................................................................. 91
...................................................................................................................... 91
............................................................................ 95
...................................................................................................... 95
............................................................. 96
6. ............................................................... 97
................................................................................................................................ 98
........................................................................... 105
...................................................................................................... 106
.............................................................................. 112
.................................................................................................. 114
.......................................................................... 115
.................................................................................................... 115
........................................................... 115
7. - ........................................ 116
HTML
15
................................................................................................. 117
................................................................................................................ 121
- ............................................................................................. 123
.................................................................................................................................. 124
.................................................................................................................... 124
.......................................................................... 134
.................................................................................................... 135
........................................................... 136
8. .............. 137
Java , , xi
..................................................................................................... 138
.................................................................................. 139
................................................................................................. 148
.......................................................................... 150
.................................................................................................... 151
........................................................... 151
9. .......................................... 152
..................................................................................................................... 153
................................................................................................ 155
.............................................................................................. 157
..................................................................................................... 160
.......................................................................... 166
.................................................................................................... 166
........................................................... 167
................................................................................................................ 171
............................................................................................... 174
................................................................................................................................. 176
........................................................................................................................ 179
..................................................................................................... 183
.......................................................................... 190
.................................................................................................... 190
Java , , xii
........................................................... 191
.............................................................................................................................................. 193
...................................................................................................... 201
-............................................................................................... 206
.......................................................................... 216
........................................................................................................... 216
......................................................... 217
. - .......... 225
.......................................................................... 229
.................................................................................................... 229
............................................................................................... 230
Java , , 13
1.
.
,
,
,
,
.
,
.
,
.
C#
Java.
Java
?
-,
Java
()
-
,
PC,
Apple
.
,
Java
,
,
,
JVM
(Java
Virtual
Machine).
,
,
Java
-
,
JVM,
,
.
,
Java
(),
.
,
Java
Car
()
,
,
,
,
.
,
,
,
,
Ford,
Java , , 14
Car
,
Ford.
,
Java
( ),
, Java
ee
.
,
Java
!
e
Java,
!
Java
Java,
()
-
Oracle.
Java
Sun
Microsystems.
2009
Oracle
Sun
Microsystems.
Java
Development
Kit
(JDK).
(JDK
7)
-:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
Java
SE
7
.
Download
JDK
.
.
,
,
.
Windows,
Windows
x86
(32-
)
Windows
x64
(64-
).
Linux
Solaris,
.
Apple
JDK.
Apple,
,
Java
Enter.
Command
not
found,
Java
,
:
Java , , 15
http://support.apple.com/downloads/#Java
.
.
Windows
:
Java , , 16
.
,
Windows
:
C:\Program Files\Java\jdk1.7.0, : .
:,
.
Next,
Install
Finish
.
Java
.
.
,
Windows
,
.
,
Java , , 17
.
...
Windows
7.
,
,
:
Path,
Windows
(
Unix)
JDK
.
,
Java.
Path
,
Java
:
Java , , 18
CLASSPATH.
,
a
(.;).
Java
.
,
Java
.
,
.
,
JDK
!
Java
.
Java
.
,
Java
-,
JVM.
.
1
Java , , 19
Java,
,
,
.
,
,
.java.
,
HelloWorld,
(
)
HelloWorld.java. ,
Java-.
,
Hello
World:
public class HelloWorld {
System.out.println("Hello World");
}
}
,
Hello
World
.
Java , , 20
2
.
javac,
JDK.
,
C:\practice.
,
cmd
.
.
,
PATH
CLASSPATH,
set.
.
C:\practice
:
cd \practice
javac HelloWorld.java
practice
,
.
javac
Java.
-
,
HelloWorld
.
,
!
dir.
,
.
,
HelloWorld.class.
,
Java , , 21
.
HelloWorld.java
.
,
,
-
.
,
,
,
Java
.
.
,
,
HelloWorld.class.
,
.
:
java HelloWorld
,
java,
javac?
JRE
(Java
Run-time
Environment)
JVM,
HelloWorld.
,
Java
,
,
HelloWorld
H
W,
helloworld
helloWorld
JVM
, , , .
,
.
,
.
,
,
!
,
.
Java , , 22
,
,
J.
,
,
,
.
:
http://download.oracle.com/javase/tutorial/getStarted/c
upojava/win32.html
Java
Windows:
http://download.oracle.com/javase/7/docs/webnotes/in
stall/windows/jdk-installation-windows.html
Java , , 23
2. Eclipse IDE
IDE
(Integrated
Development
Environment).
,
.
IDE
,
,
,
.
IDE
,
IDE
Eclipse.
-
www.eclipse.org.
Eclipse
IDE
Hello World.
.
Eclipse
,
Java.
Eclipse IDE
-
www.eclipse.org
Download
Eclipse
(
Eclipse).
Java , , 24
Eclipse
Downloads,
.
Eclipse
IDE
for
Java
Developers.
,
,
.
Windows
,
32-
.
Java , , 25
,
,
.
,
,
.
,
(
).
Java , , 26
,
ZIP
.
C:.
.
.
.
Java , , 27
Eclipse
!
Eclipse.
.
>
>
C:\eclipse
eclipse.exe.
,
Eclipse.
Eclipse
(workspace)
,
.
Workspace
(
)
,
C:\workspace.
,
Eclipse
Java , , 28
,
Use
this
as
the
default
and
do
not
ask
again
(
).
OK.
Eclipse
Welcome.
Eclipse.
Workbench
(
),
Java.
,
Welcome.
Eclipse
,
Java
Eclipse.
Eclipse.
Help
(),
Help
Contents
(
),
Java , , 29
Location
().
,
.
Java , , 30
.
,
Eclipse.
,
-
.
.
Eclipse
,
(perspective).
,
Window
(),
Open
Perspective
(
)
.
,
.
,
Java
Java,
Debug
().
My
First
Project,
JRE System
Library (jdk 1.7.0).
.
-
,
.
Windows
(),
Preferences
().
Java,
Editor
(),
Installed
JREs
(
JRE).
Add
().
Java , , 31
Standard
VM
(
).
Next
().
Directory
,
Java,
,
C:\Program Files\Java\jdk1.7.0\.
Java , , 32
Finish.
JRE.
Eclipse IDE
HelloWorld
1
Eclipse.
Java
,
.
.
Eclipse,
File,
New,
Class.
HelloWorld
Name
().
Which
methods
stubs
you
would
like
to
create
(
?)
main():
public static void main(String[] args)
Java , , 33
Finish
Eclipse
HelloWorld,
main().
.
,
Java
,
,
main().
public class HelloWorld {
}
}
,
main,
Enter
:
Java , , 34
System.out.println("Hello World");
,
Ctrl-S.
,
,
.
,
,
.
Ctrl-S.
Problems
Eclipse
Syntax
error,
insert
"}"
to
complete
ClassBody
(
;
"}"
ClassBody).
,
,
.
,
.
,
,
.
.
Problems.
Ctrl-S
,
!
Java , , 35
HelloWorld Eclipse
,
.
,
Eclipse
,
.
,
,
Run
().
Console
()
Hello
World,
,
1.
o
Run
(),
Run
()
Ctrl-F11.
Java , , 36
HelloWorld
-
HelloWorld?
HelloWorld
main(),
Java.
,
main
,
main.
()
,
,
main(),
Hello World,
println().
,
:
public static void main(String[] args)
public.
public
,
main()
Java
JVM.
static.
static
,
()
HelloWorld
,
.
.
-
?
void
,
main()
,
.
Eclipse.
,
-
,
.
-
main.
,
String[] args.
main()
Java , , 37
String[] args ,
String,
.
,
,
.
,
,
main().
Java
.
,
Game
startGame(), stopGame(), readScore()
.
main()
:
System.out.println("Hello World");
(;).
println()
(
).
Java
.
,
,
.
System.out
,
out
System,
Java.
,
System
-
out?
Eclipse
.
,
System
,
Eclipse
,
.
Ctrl-Space,
,
.
Java , , 38
out.println()
,
,
out
-
out
println().
,
,
.
,
PingPongGame,
saveScore()
.
,
,
:
PingPongGame.saveScore("", 3);
,
.
,
,
,
.
saveScore()
,
3.
Eclipse
,
,
?
,
Java
IDE.
Eclipse IDE Tutorial by Lars Vogel:
http://www.vogella.de/articles/Eclipse/article.html
Java , , 39
HelloWorld,
println().
HelloWorld,
Hello
,
.
Java , , 40
3.
Java
Java
,
.
-,
,
,
-
.
,
,
Java
,
.
,
VideoGame
(
).
,
,
:
,
,
()
.
-
,
,
,
,
.
Java
.
,
.
.
Java , , 41
:
class VideoGame {
int color; //
String int price; //
void start () {
}
void stop () {
}
void saveScore(String playerName, int score) {
}
}
K
VideoGame
,
,
,
,
,
.
GameBoyAdvance
-
.
,
,
GameBoy
Advance,
.
GameBoyAdvance
cartridgeType
and
screenWidth
startGame()
stopGame().
-
,
.
class GameBoyAdvance {
Java , , 42
String cartridgeType; //
int screenWidth; //
void startGame() {
}
void stopGame() {
}
}
GameBoy
Advance
,
Java-
.
,
GameBoyAdvance
Java.
.
.
,
,
-
-
,
-
,
.
,
GameBoyAdvance.
Java , , 43
.
-
.
,
-
.
,
.
y=x+2?
Java
x
y,
-
,
(integer
int)
(double):
int x;
int y;
.
,
:
x=5;
y=x+2;
Java
.
,
:
int y=5;
y++;
,
Java
.
,
myScore
:
int myScore=5;
myScore=myScore+1;
,
,
:
int myScore=10;
Java , , 44
myScore--;
myScore=myScore*2;
myScore=myScore/3;
System.out.println("My score is " + myScore);
-
(,
My
score
is
)?
Eclipse,
,
(scrapbook)
.
File,
New,
Scrapbook
Page
Test
-.
,
:
,
Console
:
My
score
is
6
println()
My
score
is
myScore,
.
(concatenation).
,
myScore
,
:
Java
,
String
My
Score
is.
Java , , 45
,
:
myScore=myScore*2; // myScore*=2;
myScore=myScore+2; // myScore+=2;
myScore=myScore-2; // myScore-=2;
myScore=myScore/2; // myScore/=2;
Java
()
,
s
.
,
,
,
:
byte,
short,
int,
and
long.
float
double.
char.
,
boolean,
:
true
false
(
).
Java
.
:
f
float,
l
long.
-
,
Java
,
false
boolean,
\u0000
char.
final,
,
.
final-
Java , , 46
.
.
(-
Pet).
,
Pet
.
,
(eat,
sleep,
say)
?
Java , , 47
Pet.
:
(age),
(height),
(weight)
(color).
Pet
My
First
Project
,
,
main().
:
Pet.
.
:
class Pet{
}
.
int
,
float
,
String
.
class Pet{
Java , , 48
int age;
float weight;
float height;
String color;
}
.
-
:
sleep()
,
.
eat()
!
say()
,
,
,
.
,
,
.
Pet
:
() sleep():
,
sleep()
(public)
(void).
,
,
.
say()
:
?
-
,
.
,
Pet
!
,
PetMaster
().
main(),
Pet.
PetMaster,
Eclipse
-
main().
,
.
,
Eclipse,
:
PetMaster.
Run
,
:
, !
!! !! !!
,
PetMaster
Pet.
myPet
and
new:
Pet myPet = new Pet();
myPet
Pet
(
,
,
,
).
myPet
,
Pet,
,
Pet,
:
myPet.eat();
-
,
-.
-
,
,
,
:
String petReaction;
petReaction = myPet.say("!! !!");
petReaction
:
System.out.println(petReaction);
Java , , 52
Pet
Java,
(inheritance).
-
.
Java
.
Pet,
,
,
,
,
.
,
,
,
,
.
-,
,
,
.
Fish
()
,
Pet,
,
.
extends:
Fish
-
Pet,
Pet
-
Fish.
Pet,
Fish.
class Fish extends Pet{
Java , , 53
}
Fish
,
,
,
Pet.
:
Fish myLittleFish = new Fish();
myLittleFish.sleep();
Fish,
sleep(),
-!
Eclipse!
File,
New,
Class
Fish,
.
-
java.lang.Object
Pet.
Java , , 54
,
Pet,
,
,
,
-,
.
,
,
,
.
Fish
dive()
-
.
dive()
howDeep,
,
.
currentDepth,
dive().
currentDepth
.
,
,
FishMaster:
Java
-
Object,
extends.
,
Java-
.
Java
,
,
,
-
.
myFish.sleep();
}
}
FishMaster
:
2
2
3
5
,
,
FishMaster
Fish,
sleep()
-
Pet?
-!
Pet.
extends
Fish
Pet!
Java , , 56
,
,
dive()
currentDepth,
FishMaster
.
,
FishMaster
.
-
,
Fish,
.
,
,
FishTrafficDispatcher
(
),
,
-
.
,
,
,
(
).
Fish
Pet,
say().
,
-
:
myFish.say();
,
,
Fish
(override)
say(),
Pet.
:
-
-
,
-
-,
Java
-,
-.
Fish
say().
say()
main()
FishMaster:
myFish.say("");
:
, ?
,
say()
Pet
.
!
.
final,
,
:
Java , , 57
1.
Car
()
:
public void start()
public void stop()
public int drive(int howlong)
drive()
()
.
:
distance = howlong*60;
2.
CarOwner
(
),
Car
.
System.out.println().
Java , , 58
Car,
JamesBondCar
(
)
drive().
:
distance = howlong*180;
!
.
Java , , 59
4.
Java
, Java,
,
,
,
.
,
,
.
-
.
:
1.
,
:
//
2.
/*
*/,
:
/* 3
.
*/
3.
Java
javadoc,
.
.
Java , , 60
/**
*/.
,
,
.
/**
. $100,
= 20%, 10%.
*/
,
,
.
if
:
,
-
.
Java
if,
,
(true)
(false).
,
,
.
,
?
true,
,
.
,
JVM
,
,
else.
,
100
,
20%
,
10%.
// 20%
price=price*0.8;
System.out.println(" 20%);
else{
price=price*0.9;
System.out.println(" 10%);
dive()
Fish,
,
:
int currentDepth=0;
currentDepth=currentDepth + howDeep;
System.out.println(" "+
" 100 ");
currentDepth=currentDepth - howDeep;
}else{
return currentDepth;
}
}
}
FishMaster
100
:
public class FishMaster {
Java , , 62
// 100
myFish.dive(2);
myFish.dive(97);
myFish.dive(3);
myFish.sleep();
}
}
,
:
2
2
97
99
100
,
,
,
.
,
(Texas)
(California),
.
.
(true),
-
(true).
Java
.
String.
a
Java
equals()
,
state
()
:
if (state.equals("Texas") | state.equals("California"))
if:
if (state.equals("Texas") || state.equals("California"))
Java , , 63
,
,
(true),
.
, JVM
.
(&&).
,
.
,
,
(state)
-
(price)
110
.
:
if (state.equals("New York") && price >110)
if (state.equals("New York") & price >110)
(false),
,
..
,
.
.
(negation)
.
.
,
,
-
,
:
if (!state.equals("New York"))
if (!(price >=50))
if,
.
,
,
,
.
,
Java , , 64
,
-
:
,
discount
()
,
-
.
if:
discount = 10;
} else {
discount = 5;
else if
if
else if .
ReportCard
(
),
main(),
,
.
,
(A,
B,
C,
D).
convertGrades().
public class ReportCard {
/**
M convertGrades
- A, B, C or D
.
*/
public char convertGrades( int testResult){
char grade;
return grade;
Java , , 65
else if
,
char.
,
&&
,
.
" testResult
80
89",
Java
,
testResult
80, (&)
89,
:
testResult >= 80 && testResult < 89
,
||.
switch
switch
if.
switch ,
case ,
:
switch (yourGrade){
case 'A':
System.out.println(" !");
break;
case 'B':
System.out.println(" !");
break;
case 'C':
System.out.println(" !");
break;
Java , , 66
case 'D':
System.out.println(" !");
break;
}
}
break
case
,
,
switch.
break,
,
,
yourGrade
.
switch
,
,
:
char
int
byte
short
enum
convertGrades()
ReportCard
grade.
,
.
,
.
,
,
.
Java , , 67
(scope)
,
.
,
.
Fish,
currentDepth
(member
variable).
Fish,
(instance
variables).
,
,
,
.
,
System.out.println()
out,
System.
!
System,
?
,
static ().
static,
,
.
.
,
convertGrades()
ReportCard
,
,
.
sqrt()
Math
:
Java
new,
:
Fish
,
Fish().
,
,
(constructors)
,
:
Java , , 68
.
,
.
,
void
.
.
,
Java
(default
no-
argument
constructor).
new
Fish(),
Fish
.
,
,
,
Fish
,
currentDepth
.
int currentDepth;
Fish(int startingPosition){
currentDepth=startingPosition;
}
}
FishMaster
Fish
.
Fish,
20
:
,
,
.
-
.
this
this
,
.
:
Java , , 69
class Fish {
int currentDepth ;
Fish(int currentDepth){
this.currentDepth = currentDepth;
}
}
this
,
this.currentDepth
currentDepth,
currentDepth
.
,
Fish
this.
this,
6
.
,
o.
,
String,
,
String.
,
:
String [] players;
String players[];
Java,
players.
,
.
Java , , 70
,
String,
:
players[0] = "David";
players[1] = "Daniel";
players[2] = "Anna";
players[3] = "Gregory";
,
,
.
,
.
,
Java,
,
ArrayList,
.
length,
,
,
:
,
,
,
Java
:
,
.
,
:
, Daniel!
,
[1]?
,
,
[0].
(one-dimensional),
.
,
.
Java
(multi-dimensional
arrays).
,
,
10.
,
-
.
,
.
-
for:
int totalPlayers = players.length;
int counter;
JVM
,
,
counter
()
.
:
,
.
0
(counter=0),
counter
(counter++).
,
counter
totalPlayers
(counter<totalPlayers).
-
while.
,
Java , , 72
,
.
,
while,
,
counter
()
totalPlayers:
counter++;
9
,
.
,
,
,
.
,
while.
:
break
continue.
break
,
,
(true).
,
,
,
.
,
0,
1
2,
-
break
.
if.
counter
3.
,
3
counter.
==
=
if,
,
:
if (counter == 3){
break; //
}
Java , , 73
}
continue
,
.
,
,
continue
.
counter++;
String thePlayer = players[counter];
if (thePlayer.equals("David"){
continue;
while,
do,
:
do {
// , -
,
.
,
.
,
while
,
,
(false).
Java , , 74
Java:
http://download.oracle.com/javase/tutorial/java/index.h
tml
1.
TemperatureConverter.
,
:
public String convertTemp
(int temperature, char convertTo)
convertTo
F,
,
C,
.
,
char
.
2.
convertGrades()
ReportCard
main().
Java , , 75
,
continue
counter++;
?
,
,
break?
s
Java , , 76
5.
J ava ,
.
Java.
AWT Swing
Java
-
AWT.
,
,
Button
(),
TextField
(
),
Label
(
)
.
,
Swing.
,
.
J.
,
JButton,
JTextField
.
Swing
,
,
JVM,
Swing.
Java , , 77
import
Java
,
(packages).
,
.
,
String
java.lang
java.lang.String.
Java
,
,
java.lang,
String
,
,
,
.
,
Swing
:
javax.swing
javax.swing.event
,
,
.
,
import
,
:
import javax.swing.JFrame;
import javax.swing.JButton;
class Calculator{
import
,
JFrame
JButton
,
.
,
import,
*.
,
javax.swing
:
import javax.swing.*;
Java , , 78
,
import
.
,
.
10.
Swing
,
Swing-
:
(frame),
JFrame.
(panel)
,
,
pane
(
)
,
,
.
JPanel.
,
JButton,
JTextfield,
JList,
.
(layout
managers)
,
.
,
JPanel
.
.
Java , , 79
, .
.
,
.
,
,
(events),
.
,
.
Eclipse,
My
Calculator
SimpleCalculator
:
Java , , 80
import javax.swing.*;
import java.awt.FlowLayout;
//
//
//
//
windowContent.add(label1);
windowContent.add(field1);
windowContent.add(label2);
windowContent.add(field2);
windowContent.add(label3);
windowContent.add(result);
windowContent.add(go);
//
//
frame.setSize(400,100);
frame.setVisible(true);
}
}
.
:
Java , , 81
,
,
,
,
.
.
.
,
.
,
,
,
(users).
Java
(Layout
Managers),
,
.
,
,
,
.
Swing
:
FlowLayout
GridLayout
BoxLayout
BorderLayout
CardLayout
GridBagLayout
,
-
Java , , 82
(container),
,
SimpleCalculator.
FlowLayout -
e
(
)
.
,
,
,
,
.
,
.
,
.
,
.
java.awt.FlowLayout
.
,
this
SimpleCalculator.
FlowLayout fl = new FlowLayout();
this.setLayoutManager(fl);
,
FlowLayout
.
-
.
GridLayout -
java.awt.GridLayout
,
.
.
,
,
.
,
.
(
):
,
:
(
),
.
SimpleCalculatorGrid
My
Calculator.
import javax.swing.*;
import java.awt.GridLayout;
//
//
windowContent.setLayout(gl);
//
//
windowContent.add(label1);
windowContent.add(field1);
windowContent.add(label2);
windowContent.add(field2);
windowContent.add(label3);
windowContent.add(result);
windowContent.add(go);
Java , , 84
//
JFrame frame = new JFrame("My First Calculator");
frame.setContentPane(windowContent);
//
frame.setSize(400,100);
frame.setVisible(true);
}
}
SimpleCalculatorGrid, :
,
:
,
.
BorderLayout -
java.awt.BorderLayout
,
,
,
.
,
,
,
.
,
,
Java , , 85
,
,
,
.
BorderLayout
:
.
,
,
,
..
.
BorderLayout
,
,
Calculator.java.
,
GridLayout
,
,
Microsoft
Windows?
,
,
.
,
.
Java , , 86
.
:
BorderLayout
,
,
.
JTextField
,
.
p1
GridLayout,
20
.
p2
GridLayout,
p2
.
,
:
Calculator
.
,
,
,
.
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
public class Calculator {
// .
JPanel windowContent;
JTextField displayField;
JButton button0;
JButton button1;
JButton button2;
JButton button3;
JButton button4;
JButton button5;
JButton button6;
JButton button7;
Java , , 87
JButton button8;
JButton button9;
JButton buttonPoint;
JButton buttonEqual;
JPanel p1;
//
//
// Borderlayout Gridlayout
Calculator(){
//
BorderLayout bl = new BorderLayout();
windowContent.setLayout(bl);
//
//
// ,
// JButton,
//
button0=new JButton("0");
button1=new JButton("1");
button2=new JButton("2");
button3=new JButton("3");
button4=new JButton("4");
button5=new JButton("5");
button6=new JButton("6");
button7=new JButton("7");
button8=new JButton("8");
button9=new JButton("9");
buttonPoint = new JButton(".");
buttonEqual=new JButton("=");
// GridLayout
// 12 - 10
//
p1 = new JPanel();
GridLayout gl =new GridLayout(4,3);
p1.setLayout(gl);
// p1
p1.add(button1);
p1.add(button2);
p1.add(button3);
p1.add(button4);
p1.add(button5);
p1.add(button6);
p1.add(button7);
Java , , 88
p1.add(button8);
p1.add(button9);
p1.add(button0);
p1.add(buttonPoint);
p1.add(buttonEqual);
// p1
windowContent.add("Center",p1);
//
JFrame frame = new JFrame("Calculator");
frame.setContentPane(windowContent);
//
// ,
frame.pack();
// ,
frame.setVisible(true);
}
}
BoxLayout -
java.swing.BoxLayout
(
)
(
).
FlowLayout,
BoxLayout
,
.
BoxLayout
(
GridLayout).
box
layout
JPanel.
JPanel p1= new JPanel();
,
BoxLayout,
,
setLayout().
Java , , 89
GridBag Layout -
.
java.awt.GridBagLayout
.
,
GridLayout
.
,
,
.
GridBagLayout
-
.
,
.
GridBagLayout
,
GridBagConstraints
(
).
,
,
.
,
.
,
GridBagConstraints
gridWidth.
-
,
.
GridBagLayout
GridBagConstraints,
.
,
.
Java , , 90
,
,
,
GridBagLayout.
// GridBagLayout
GridBagLayout gb = new GridBagLayout();
this.setLayout(gb);
// GridBagConstraints
//
//
//
// x
constr.x=0;
// y
constr.y=0;
// ,
constr.gridheight =1;
// 6
constr.gridwidth= 6;
//
constr.fill= constr.BOTH;
// ,
constr.weightx = 1.0;
// ,
constr.weighty = 1.0;
//
constr.anchor=constr.CENTER;
//
gb.setConstraints(displayField,constr);
//
windowContent.add(displayField);
CardLayout
,
,
.
java.awt.CardLayout
a,
,
,
.
Java , , 91
.
,
,
,
.
,
"
"
.
,
,
Swing
.
JTabbedPane.
,
?
,
!
a
.
,
.
Java
null,
.
,
,
:
windowContent.setLayout(null);
,
,
,
.
,
40
,
20,
100
200
:
JButton myButton = new Button("New Game");
myButton.setBounds(100,200,40,20);
Swing
,
Swing,
.
Swing.
JButton,
JLabel
JTextField.
:
Java , , 92
JButton
JLabel
JCheckBox
JRadioButton
JToggleButton
JScrollPane
JSpinner
JTextField
JTextArea
JPasswordField
JFormattedTextField
JEditorPane
JScrollBar
JSlider
JProgressBar
JComboBox
JList
JTabbedPane
JTable
JToolTip
JTree
JViewPort
ImageIcon
(JMenu
JPopupMenu),
,
(JInternalFrame)
(JFileChooser,
JColorChooser
JOptionPane).
Java
,
Swing
.
,
Java
SDK,
C:\Program
Files\Java\jdk1.6.0_19\demo\jfc\SwingSet3.
:
https://swingset3.dev.java.net.
SwingSet3.html,
,
:
Java , , 93
,
,
Swing
.
,
,
Source
Code.
,
combobox
(
),
,
:
Java , , 94
Swing
,
.
Swing
,
,
.
,
.
Java
Swing.
,
Swing
,
Matisse.
Gigloo
GUI
Builder.
,
.
Java , , 95
1.
Swing:
http://download.oracle.com/javase/tutorial/uis
wing/index.html
2.
JFormattedTextField:
http://download.oracle.com/javase/7/docs/api
/javax/swing/JFormattedTextField.html
1.
Calculator.java
+,
-,
/,
*.
p2,
.
2.
JFormattedTextField
,
JTextField.
,
.
Java , , 96
Calculator.java
,
,
:
Buttons[] numButtons= new Buttons[10];
10
,
button0=new JButton("0"); ,
.
:
-
7.
Java , , 97
6.
:
,
-
,
.
,
5,
.
,
,
,
.
Java,
(listeners),
.
,
,
.
,
,
,
,
.
MouseMotionListener
.
,
.
ActionListener,
.
Java,
.
Java , , 98
,
,
,
,
,
.
.
,
,
,
,
:
interface MouseMotionListener {
,
mouseDragged()
mouseMoved()
,
MouseMotionListener.
,
.
implements
,
,
,
:
Java , , 99
import java.awt.event.MouseMotionListener;
// ,
//
mouseDragged(MouseEvent e){
// ,
// -
mouseMoved(MouseEvent e){
// ,
//
}
}
,
,
?
,
,
,
.
,
(
JVM)
,
MyDrawingPad
MouseMotionListener,
,
mouseDragged()
mouseMoved().
,
,
JVM
mouseMoved()
,
.
,
mouseMoved(),
movedMouse(),
mouseCrawling()?
JVM
,
,
.
Java
,
,
:
class myDrawingProgram implements MouseMotionListener,
ActionListener {
//
// o ax
,
,
Java,
,
,
,
.
Java , , 100
ActionListener
.
,
.
-,
-
,
.
-,
,
,
Calculator.java,
.
CalculatorEngine,
,
java.awt.ActionListener
-
actionPerformed(ActionEvent).
JVM
,
,
-
.
:
import java.awt.event.ActionListener;
(
Eclipse),
,
,
,
actionPerformed(ActionEvent e).
:
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
// ,
// , JVM
}
}
(a
message
box)
actionPerformed().
JOptionPane
showConfirmDialog()
.
,
CalculatorEngine
:
Java , , 101
showConfirmDialog(),
.
null
,
,
,
,
,
(PLAIN_MESSAGE
,
-
OK).
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
JOptionPane.showConfirmDialog(null,
"Something happened...", "Just a test",
JOptionPane.PLAIN_MESSAGE);
}
}
,
,
Something
happened.
ActionListener
,
actionPerformed()?
JVM
,
CalculatorEngine
(
)!
Calculator
,
:
Java , , 102
,
button0,
JVM
actionPerformed()
CalculatorEngine.
Calculator
Something
happened!
,
.
,
:
button1.addActionListener(calcEngine);
button2.addActionListener(calcEngine);
button3.addActionListener(calcEngine);
button4.addActionListener(calcEngine);
-
-?
,
,
.
,
JVM
-
actionPerformed(ActionEvent),
ActionEvent.
,
-.
- casting
,
,
,
getSource()
ActionEvent.
evt
-,
-
.
,
Java,
getSource()
Object,
Java,
.
,
,
.
-
,
!
(we
cast
the
type)
Object
JButton,
:
Java , , 103
JButton
,
getSource()
Object,
JVM:
,
,
JButton.
Object
JButton
getText(),
JButton.
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.JButton;
//
JButton clickedButton= (JButton)e.getSource();
//
String clickedButtonLabel = clickedButton.getText();
//
JOptionPane.showConfirmDialog(null,"You pressed " +
clickedButtonLabel,
"Just a test", JOptionPane.PLAIN_MESSAGE);
}
}
,
,
:
Java , , 104
,
,
-
?
JButton!
Java,
instanceof
,
.
,
,
JButton
JTextField:
public void actionPerformed(ActionEvent evt){
JTextField myDisplayField=null;
JButton clickedButton=null;
}
}
,
,
.
public void actionPerformed(ActionEvent e){
if (src == buttonPlus){
// ,
-,
,
,
.
displayField
Calculator
actionPerformed()
CalculatorEngine.
,
CalculatorEngine
,
Calculator.
CalculatorEngine
.
Calculator.
,
,
!
JVM
CalculatorEngine
.
Calculator
CalculatorEngine,
:
CalculatorEngine calcEngine = new CalculatorEngine(this);
,
Calculator.
CalculatorEngine
parent,
actionPerformed()
.
parent.displayField.getText();
parent.displayField.setText(dispFieldText + clickedButtonLabel);
:
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
//
// parent
CalculatorEngine(Calculator parent){
this.parent = parent;
Java , , 106
//
JButton clickedButton = (JButton) e.getSource();
// ()
//
String dispFieldText = parent.displayField.getText();
//
String clickedButtonLabel = clickedButton.getText();
parent.displayField.setText(dispFieldText +
clickedButtonLabel);
}
}
-
,
,
,
.
Java
Object,
,
,
Fish
Pet,
:
Fish myFish = new Fish();
Pet myFish = new Fish();
Object myFish = new Fish();
(
),
:
1.
.
2.
-
+,
-,
/
or
*
,
,
.
3.
.
Java , , 107
4.
double,
.
,
2.
5.
4
,
2.
CalculatorEngine.
,
,
actionPerformed()
selectedAction
currentResult.
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
Calculator parent; //
//
//
CalculatorEngine(Calculator parent){
this.parent = parent;
//
String dispFieldText=parent.displayField.getText();
double displayValue=0;
// ,
// .
//
if (!"".equals(dispFieldText)){
displayValue= Double.parseDouble(dispFieldText);
Java , , 108
//
// : +, -, /, *,
// currentResult,
//
if (src == parent.buttonPlus){
selectedAction = '+';
currentResult=displayValue;
parent.displayField.setText("");
selectedAction = '-';
currentResult=displayValue;
parent.displayField.setText("");
selectedAction = '/';
currentResult=displayValue;
parent.displayField.setText("");
selectedAction = '*';
currentResult=displayValue;
parent.displayField.setText("");
// ,
// selectedAction, currentResult
//
if (selectedAction=='+'){
currentResult+=displayValue;
// ,
//
parent.displayField.setText(""+currentResult);
}else if (selectedAction=='-'){
currentResult -=displayValue;
parent.displayField.setText(""+currentResult);
}else if (selectedAction=='/'){
currentResult /=displayValue;
parent.displayField.setText(""+currentResult);
}else if (selectedAction=='*'){
Java , , 109
currentResult*=displayValue;
parent.displayField.setText(""+currentResult);
} else{
//
//
-
:
Calculator
:
.
CalculatorEngine.
CalculatorEngine
.
,
.
Calculator:
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
//
//
Calculator(){
//
BorderLayout bl = new BorderLayout();
windowContent.setLayout(bl);
//
windowContent.add("North",displayField);
// GridLayout
// 12 - 10 ,
//
p1.setLayout(gl);
p1.add(button1);
p1.add(button2);
p1.add(button3);
p1.add(button4);
p1.add(button5);
p1.add(button6);
p1.add(button7);
p1.add(button8);
p1.add(button9);
p1.add(button0);
p1.add(buttonPoint);
p1.add(buttonEqual);
// p1
windowContent.add("Center",p1);
Java , , 111
// GridLayout
// 4 -
// , ,
p2.setLayout(gl2);
p2.add(buttonPlus);
p2.add(buttonMinus);
p2.add(buttonMultiply);
p2.add(buttonDivide);
// p2
windowContent.add("East",p2);
// frame JFrame
frame = new JFrame("Calculator");
frame.setContentPane(windowContent);
// ,
//
frame.pack();
//
frame.setVisible(true);
//
//
CalculatorEngine calcEngine = new CalculatorEngine(this);
button0.addActionListener(calcEngine);
button1.addActionListener(calcEngine);
button2.addActionListener(calcEngine);
button3.addActionListener(calcEngine);
button4.addActionListener(calcEngine);
button5.addActionListener(calcEngine);
button6.addActionListener(calcEngine);
button7.addActionListener(calcEngine);
button8.addActionListener(calcEngine);
button9.addActionListener(calcEngine);
buttonPoint.addActionListener(calcEngine);
buttonPlus.addActionListener(calcEngine);
buttonMinus.addActionListener(calcEngine);
buttonDivide.addActionListener(calcEngine);
buttonMultiply.addActionListener(calcEngine);
buttonEqual.addActionListener(calcEngine);
//
Calculator calc = new Calculator();
}
}
Java , , 112
Calculator.
,
.
!
,
.
,
,
,
.
,
Eclipse,
.
Java
java.awt,
:
(FocusListener)
,
.
,
,
,
.
(ItemListener)
.
(KeyListener)
.
(MouseListener)
,
,
.
(MouseMotionListener)
,
-
.
(drag)
.
(WindowListener)
,
,
,
.
,
,
.
Java , , 113
FocusListener
focusGained(FocusEvent)
focusLost(FocusEvent)
ItemListener
itemStateChanged(ItemEvent)
KeyListener
keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)
mouseClicked(MouseEvent)
MouseListener
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
MouseMotionListener
mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
WindowListener
windowActivated
(WindowEvent)
windowClosed(WindowEvent)
windowClosing(WindowEvent)
windowDeactivated
(WindowEvent)
windowDeiconified(WindowEvent)
windowIconified(WindowEvent)
windowOpened(WindowEvent)
Java , , 114
,
FocusListener
:
focusGained()
focusLost().
,
-
,
focusLost().
,
Java
-
,
.
,
-
,
.
,
,
WindowsListener
.
,
windowClosing()
.
java.awt
,
,
(,
).
WindowAdapter.
,
,
WindowAdapter
,
,
windowClosing().
class MyEventProcessor extends java.awt.WindowsAdapter {
// ,
//
,
:
MyEventProcessor myListener = new MyEventProcessor();
addWindowListener(myListener);
,
,
.
Java , , 115
:
http://download.oracle.com/javase/tutorial/uiswing/events/
-
Infinity.
CalculatorEngine,
,
,
.
CalculatorEngine
,
.
:
indexOf()
String,
,
.
Java , , 116
7. -
,
Java
.
-.
-
,
HTML,
()
,
.
,
HTML
<applet>,
,
Java.
Java-
,
-,
,
JVM
,
.
,
,
,
-
Java , , 117
,
.
,
,
-
Java
,
,
-
,
-
.
:
,
,
.
,
.
.
,
Java,
HTML,
<applet>,
,
-,
Java.
Eclipse
,
appletviewer.
,
15
,
HTML.
HTML
15
,
-
-
(TicTacToe).
HTML
.
TicTacToe.html
(,
Eclipse
).
HTML
.html
.htm.
(header)
(body).
HTML
,
(/),
<Head>
</Head>.
TicTacToe.html
:
<HTML>
<HEAD>
<TITLE>My First Web Page</TITLE>
Java , , 118
</HEAD>
<BODY>
My Tic-Tac-Toe game is coming soon
</BODY>
</HTML>
,
<Title>
</Title>,
.
HTML
-
Java,
,
.
-
.
My
First
Web
Page,
My
Tic-Tac-Toe
game
is
coming
soon:
,
-:
<HTML>
<BODY>
Here is my Tic-Tac-Toe game:
<APPLET code=TicTacToe.class width=300 height=250>
</APPLET>
</BODY>
</HTML>
-:
Java , , 119
:
-
TicTacToe,
.
.
HTML
,
.
<APPLET>
:
code
-
Java-.
width
,
.
,
.
height
-
,
.
Java-
,
jar,
JDK
(Java
Developer
Kit
Java).
,
(archive)
,
.
jar
.
Java , , 120
A
AWT
AWT
,
,
Swing
?
,
Swing?
,
.
-
JVM,
AWT,
Swing,
.
,
JVM,
HTML,
HTML
,
JVM,
?
,
,
,
.
-
,
,
.
,
-,
(
).
AWT,
,
.
,
.
Java
.
JVM,
JVM,
.
,
(
)
JVM
.
:
https://jdk6.dev.java.net/plugin2
.
Microsoft
Windows
Java
Control
Panel
-
Java
Start
|
Control
Panel.
Advanced
Java
Plug-in
,
Enable
the
next-generation
Java
Plug-
in.
:
http://blogs.sun.com/thejavatutorials/entry/enabling_the_next_generation_j
ava
.
Java , , 121
, Swing
. Java
. JavaFX , ,
: http://javafx.com/.
Java-
AWT
java.applet.Applet,
:
class TicTacToe extends java.applet.Applet {
Swing,
JApplet:
Java,
main(),
-
,
<applet>.
,
,
,
,
.
,
,
(callback
methods):
init(), start(), paint(), stop(),
destroy().
JVM
-
:
init()
,
.
,
,
Java.
start()
init().
,
.
Java , , 122
paint()
,
-
.
,
-
.
stop()
,
-
,
.
destroy()
,
.
,
,
,
,
.
,
:
init()
paint().
,
,
!.
paint()
,
Graphics
JVM
-.
.
drawString(),
,
!.
public class HelloApplet extends java.applet.Applet {
public void paint(java.awt.Graphics graphics) {
}
}
Eclipse.
Run
Java
Applet
,
New,
HelloApplet
Applet
Class.
-,
Hello.html
,
:
<HTML>
<BODY>
Here is my first applet:<P>
<APPLET code=HelloApplet.class width=200 height=100>
</APPLET>
</BODY>
</HTML>
Java , , 123
-
Hello.html
File
Open.
:
,
?
!
-
Java , , 124
-
,
.
.
,
,
.
,
.
-
,
:
3x3.
,
.
,
,
.
,
.
,
.
,
.
,
New
Game.
,
,
,
,
,
.
,
,
,
,
.
,
,
,
.
Java , , 125
,
,
,
.
BorderLayout,
New
Game.
,
,
:
init().
ActionListener
actionPerformed().
lookForWinner()
,
,
.
computerMove(),
.
Java
Math
random().
,
,
:
if(squares[0].getLabel().equals(squares[1].getLabel())){}
Java , , 126
,
,
:
String label0 = squares[0].getLabel();
String label1 = squares[1].getLabel();
if(label0.equals(label1)){}
Java
,
.
,
equals(),
getLabel().
,
.
.
/**
* - 3x3
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
Button squares[];
Button newGameButton;
Label score;
int emptySquaresLeft=9;
/**
* init
*/
// ,
this.setLayout(new BorderLayout());
this.setBackground(Color.CYAN);
// ,
// 20
// New Game
//
Java , , 127
newGameButton.addActionListener(this);
this.add(topPanel,"North");
// , 9
squares=new Button[9];
// ,
// ,
//
for(int i=0;i<9;i++){
squares[i]=new Button();
squares[i].addActionListener(this);
squares[i].setBackground(Color.ORANGE);
centerPanel.add(squares[i]);
}
}
/**
*
* @param ActionEvent
*/
// New Game ?
if (theButton ==newGameButton){
for(int i=0;i<9;i++){
squares[i].setEnabled(true);
squares[i].setLabel("");
squares[i].setBackground(Color.ORANGE);
emptySquaresLeft=9;
score.setText("Your turn!");
newGameButton.setEnabled(false);
Java , , 128
return; //
}
// ?
if ( theButton == squares[i] ) {
squares[i].setLabel("X");
winner = lookForWinner();
if(!"".equals(winner)){
endTheGame();
} else {
computerMove();
winner = lookForWinner();
if ( !"".equals(winner)){
endTheGame();
}
}
break;
}
} // for
if ( winner.equals("X") ) {
score.setText("You won!");
} else if (winner.equals("O")){
score.setText("You lost!");
} else if (winner.equals("T")){
score.setText("It's a tie!");
}
} // actionPerformed
/**
* , ,
* . ,
* ,
* ( )
* @return "X", "O", "T" , "" -
*/
String lookForWinner() {
if (emptySquaresLeft==0){
return "T"; // . T tie
// 1 0,1,2
if (!squares[0].getLabel().equals("") &&
squares[0].getLabel().equals(squares[1].getLabel()) &&
squares[0].getLabel().equals(squares[2].getLabel())) {
theWinner = squares[0].getLabel();
highlightWinner(0,1,2);
// 2 3,4,5
} else if (!squares[3].getLabel().equals("") &&
squares[3].getLabel().equals(squares[4].getLabel()) &&
squares[3].getLabel().equals(squares[5].getLabel())) {
theWinner = squares[3].getLabel();
highlightWinner(3,4,5);
// 3 6,7,8
} else if ( ! squares[6].getLabel().equals("") &&
squares[6].getLabel().equals(squares[7].getLabel()) &&
squares[6].getLabel().equals(squares[8].getLabel())) {
theWinner = squares[6].getLabel();
highlightWinner(6,7,8);
// 1 0,3,6
} else if ( ! squares[0].getLabel().equals("") &&
squares[0].getLabel().equals(squares[3].getLabel()) &&
squares[0].getLabel().equals(squares[6].getLabel())) {
theWinner = squares[0].getLabel();
highlightWinner(0,3,6);
// 2 1,4,7
} else if ( ! squares[1].getLabel().equals("") &&
squares[1].getLabel().equals(squares[4].getLabel()) &&
squares[1].getLabel().equals(squares[7].getLabel())) {
theWinner = squares[1].getLabel();
highlightWinner(1,4,7);
// 3 2,5,8
} else if ( ! squares[2].getLabel().equals("") &&
squares[2].getLabel().equals(squares[5].getLabel()) &&
squares[2].getLabel().equals(squares[8].getLabel())) {
Java , , 130
theWinner = squares[2].getLabel();
highlightWinner(2,5,8);
// 0,4,8
squares[0].getLabel().equals(squares[4].getLabel()) &&
squares[0].getLabel().equals(squares[8].getLabel())) {
theWinner = squares[0].getLabel();
highlightWinner(0,4,8);
// 2,4,6
} else if ( ! squares[2].getLabel().equals("") &&
squares[2].getLabel().equals(squares[4].getLabel()) &&
squares[2].getLabel().equals(squares[6].getLabel())) {
theWinner = squares[2].getLabel();
highlightWinner(2,4,6);
}
return theWinner;
/**
* ,
* .
* , .
*/
void computerMove() {
int selectedSquare;
//
// ,
selectedSquare = findEmptySquare("O");
// ,
// 3-
// ,
if ( selectedSquare == -1 )
selectedSquare = findEmptySquare("X");
// selectedSquare -1,
//
if ( (selectedSquare == -1)
&&(squares[4].getLabel().equals("")) ){
selectedSquare=4;
}
Java , , 131
// ...
//
if ( selectedSquare == -1 ){
selectedSquare = getRandomSquare();
squares[selectedSquare].setLabel("O");
}
/**
* ,
* ,
* .
* @param X O
* @return ,
* -1,
*
*/
int findEmptySquare(String player) {
if ( squares[i].getLabel().equals("O") )
weight[i] = -1;
else if ( squares[i].getLabel().equals("X") )
weight[i] = 1;
else
weight[i] = 0;
}
// , 1
// .
if ( weight[0] + weight[1] + weight[2] == twoWeights ) {
if ( weight[0] == 0 )
return 0;
else if ( weight[1] == 0 )
return 1;
else
return 2;
}
// , 2
// .
if (weight[3] +weight[4] + weight[5] == twoWeights) {
if ( weight[3] == 0 )
return 3;
else if ( weight[4] == 0 )
return 4;
else
return 5;
}
Java , , 132
// , 3
// .
if (weight[6] + weight[7] +weight[8] == twoWeights ) {
if ( weight[6] == 0 )
return 6;
else if ( weight[7] == 0 )
return 7;
else
return 8;
}
// , 1
// .
if (weight[0] + weight[3] + weight[6] == twoWeights) {
if ( weight[0] == 0 )
return 0;
else if ( weight[3] == 0 )
return 3;
else
return 6;
}
// , 2
// .
if (weight[1] +weight[4] + weight[7] == twoWeights ) {
if ( weight[1] == 0 )
return 1;
else if ( weight[4] == 0 )
return 4;
else
return 7;
}
// , 3
// .
if (weight[2] + weight[5] + weight[8] == twoWeights ){
if ( weight[2] == 0 )
return 2;
else if ( weight[5] == 0 )
return 5;
else
return 8;
// , 1
// .
if (weight[0] + weight[4] + weight[8] == twoWeights ){
Java , , 133
if ( weight[0] == 0 )
return 0;
else if ( weight[4] == 0 )
return 4;
else
return 8;
}
// , 2
// .
if (weight[2] + weight[4] + weight[6] == twoWeights ){
if ( weight[2] == 0 )
return 2;
else if ( weight[4] == 0 )
return 4;
else
return 6;
}
//
return -1;
} // findEmptySquare()
/**
*
* @return
*/
int getRandomSquare() {
do {
if (squares[selectedSquare].getLabel().equals("")){
gotEmptySquare = true; //
} while (!gotEmptySquare );
return selectedSquare;
} // getRandomSquare()
/**
* .
* @param ,
*/
void highlightWinner(int win1, int win2, int win3) {
Java , , 134
squares[win1].setBackground(Color.CYAN);
squares[win2].setBackground(Color.CYAN);
squares[win3].setBackground(Color.CYAN);
}
// New Game
void endTheGame(){
newGameButton.setEnabled(true);
for(int i=0;i<9;i++){
squares[i].setEnabled(false);
}
}
} //
!
Java!
Swing, Button
JButton, Panel JPanel, .. ,
-, :
http://download.oracle.com/javase/tutorial/deployment/applet.
Eclipse,
TicTacToe.html,
,
TicTacToe.html
TicTacToe.class
.
TicTacToe
,
,
,
,
.
TicTacToe
,
,
,
,
.
,
.
Java:
http://download.oracle.com/javase/tutorial/deployment/
applet/
Java , , 135
Math
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Math.
html
1.
TicTacToe
.
,
.
,
You
won
You
lost.
2.
,
.
!
,
.
,
.
3.
main()
TicTacToe,
,
Java-.
Java , , 136
1.
TicTacToe,
,
JButton squares[]
3x3:
JButton squares[][]
2.
.
Java , , 137
8.
, Java-.
,
.
(run-time
errors),
,
,
.
,
Java-
.
,
-
?
,
,
,
:
, - ,
scores.txt. , ,
?
,
.
.
Java
,
.
Java
(exceptions),
(exception
handling).
,
,
try/catch.
JVM
:
,
-
,
,
:
try{
fileScores.read();
System.out.println(
" ,
Java , , 138
scores.txt");
}
9,
I/O
/
(input/output).
(
)
/,
IOException
,
/.
(throws)
.
.
catch
,
catch.
,
,
.
,
,
.
,
,
.
(stack
trace).
,
,
,
.
TestStackTrace,
(
).
1 class TestStackTrace{
2 TestStackTrace()
3 {
4 divideByZero();
5 }
6
7 int divideByZero()
8 {
9 return 25/0;
10 }
11
12 static void main(String[]args)
13 {
14 new TestStackTrace();
15 }
16 }
Java , , 139
,
.
,
.
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at TestStackTrace.divideByZero(TestStackTrace.java:9)
at TestStackTrace.<init>(TestStackTrace.java:4)
at TestStackTrace.main(TestStackTrace.java:14)
,
main(),
init()
,
divideByZero().
14,
4
9
,
.
,
ArithmeticException,
9
.
Java
,
(
):
Java , , 140
Exception
(checked
exceptions),
.
..
-
,
,
.
Error
JVM,
.
TooManyBikesException (
)
,
.
,
Java-
,
Java , , 141
try/catch?
!
,
,
Java
,
:
"ScoreReader.java": unreported exception:
java.io.IOException; must be caught or declared to be
thrown at line 57
,
,
Java.
.
try/catch
Java
: try, catch, finally, throw throws.
try
catch,
,
.
,
,
,
FileNotFoundException.
,
,
,
EOFException.
,
.
.
public void getScores(){
try{
fileScores.read();
System.out.println(" ");
}catch(FileNotFoundException e){
System.out.println(" Scores");
}catch(EOFException e1){
System.out.println(" ");
}catch(IOException e2){
System.out.println(" " +
e2.getMessage());
}
}
Java , , 142
read()
,
println()
catch
.
,
println(),
catch
,
getScores()
,
.
catch,
,
,
.
,
EOFException
IOException,
catch
.
catch
IOException,
FileNotFound
EOFException,
catch
.
Java 7,
catch:
public void getScores(){
try{
fileScores.read();
System.out.println(" ");
}catch(FileNotFoundException | EOFException |
IOException e){
System.out.println(" " +
e.getMessage());
}
}
getScores()
:
public void getScores(){
try{
fileScores.read();
}catch(Exception e){
System.out.println((" " +
e.getMessage());
}
}
.
,
,
-
,
.
Java , , 143
catch
Exception,
,
getMessage()
.
,
,
toString():
catch(Exception e){
,
printStackTrace().
,
,
,
.
6.
Calculator
abc.
-
:
java.lang.NumberFormatException: For input string: "abc" at
java.lang.NumberFormatException.forInputString(NumberFormat
Exception.java:48)
at
java.lang.FloatingDecimal.readJavaFormatString(FloatingDeci
mal.java:1213)
at java.lang.Double.parseDouble(Double.java:202)
at
CalculatorEngine.actionPerformed(CalculatorEngine.java:27)
at
javax.swing.AbstractButton.fireActionPerformed(AbstractButt
on.java:1764)
.
actionPerformed()
CalculatorEngine
:
displayValue= Double.parseDouble(dispFieldText);
dispFieldTest
,
parseDouble()
double
NumberFormatException.
Java , , 144
,
. ,
parseDouble()
try/catch,
Eclipse
.
. Source
and
Surround
with
try/catch
block.
!
:
try {
displayValue= Double.parseDouble(dispFieldText);
e1.printStackTrace();
}
printStackTrace() :
javax.swing.JOptionPane.showConfirmDialog(null,
", ", " ",
javax.swing.JOptionPane.PLAIN_MESSAGE);
return;
, :
NumberFormatException
.
throws
,
,
,
,
e
.
Java , , 145
,
(),
.
throws.
.
read()
IOException,
,
.
,
getAllScores()
IOException:
class MySuperGame{
// try/catch,
//
file.read();
try{
// getAllScores() ,
//
msg.getAllScores();
}catch(IOException e){
System.out.println(
", ");
}
}
getAllScores(),
IOException
main().
.
finally
try/catch
:
Java , , 146
try
,
.
try
return
.
try
,
catch,
,
,
.
,
,
finally:
try{
file.read();
}catch(Exception e){
printStackTrace();
}finally{
// ,
// , file.close();
finally,
,
.
,
finally
,
-
,
,
.
,
.
,
finally
catch:
void myMethod () throws IOException{
try{
// ,
}
finally{
// ,
}
}
Java , , 147
throw
,
,
.
,
,
,
.
throw
()
()
Java-.
,
,
.
,
,
Throwable.
Java
.
getAllScores()
IOException,
Exception
main().
,
main()
,
getAllScores()
try/catch,
Exception,
,
,
.
main()
,
.
class ScoreList{
//
Java , , 148
try{
file.read();//
} catch (IOException e) {
}
}
System.out.println("Scores");
try{
getAllScores();
}catch(Exception e1){
System.out.println(e1.getMessage());
}
}
}
,
,
e1.getMessage()
,
,
,
Java.
Java , , 149
.
,
.
,
.
,
FireBird.
Exception
TooManyBikesException.
,
-
,
:
class TooManyBikesException extends Exception{
//
TooManyBikesException (){
//
// ,
super(
" .");
}
}
,
,
.
.
catch
,
,
,
getMessage().
,
OrderWindow
.
,
actionPerformed(),
,
.
,
checkOrder()
,
TooManyBikesException.
,
,
catch.
.
class OrderWindow implements ActionListener{
// .
//
try{
bikeOrder.checkOrder("FireBird", quantity);
//
txtFieldOrderConfirmation.setText(
" ");
} catch(TooManyBikesException e){
txtFieldOrderConfirmation.setText(e.getMessage());
}
}
throws TooManyBikesException{
// , ,
// .
// , :
}
}
.
.
,
Java
,
,
.
:
http://download.oracle.com/javase/tutorial/ess
ential/exceptions/index.html
Java , , 151
1.
Swing-
.
,
.
2.
OrderWindow
TooManyBikesException.
,
.
1.
,
,
,
,
.
2.
Swing-
JComboBox
ItemListener
,
.
Java , , 152
9.
, ,
.
,
,
,
.
,
,
,
,
.
,
,
(streams).
,
(
,
).
,
,
,
.
,
,
scores.txt,
.
,
,
..
,
,
String,
int,
double
,
Java,
,
,
,
.
java.io.
java.nio.
,
,
:
,
.
.
.
Java , , 153
,
,
,
,
.
,
,
,
,
-
,
.
,
,
Java
FileInputStream FileOutputStream.
,
FileInputStream
abc.gif
c:\practice.
Microsoft
Windows,
Java,
,
:
c:\\practice.
,
,
,
.
0
255.
ByteReader
,
.
,
ByteReader
finally.
close()
try/catch
,
finally.
,
close()
!
,
FileInputStream.read()
.
import java.io.FileInputStream;
import java.io.IOException;
try {
// ,
while (true) {
if (intValueOfByte == -1){
//
break;
}
} // while
// myFile.close();
} catch (IOException e) {
System.out.println(" : "
+ e.toString());
} finally{
try{
myFile.close();
e1.printStackTrace();
}
System.out.println(
" ");
}
}
,
,
xyz.dat,
FileOutputStream:
int somedata[]= {56,230,123,43,11,37};
try {
// xyz.dat,
//
file.write(data[i]);
Java , , 155
} catch (IOException e) {
System.out.println(" : "+
e.toString());
} finally{
try{
myFile.close();
e1.printStackTrace();
}
}
,
.
,
1000
,
ByteReader
1000
.
,
.
,
Java
,
"
".
BufferedInputStream
FileInputStream.
,
read()
.
,
,
.
,
.
,
FileInputStream
BufferedInputStream,
read():
FileInputStream myFile = null;
try {
// FileInputStream BufferedInputStream
while (true) {
if (byteValue == -1)
break;
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
buff.close();
myFile.close();
} catch(IOException e1){
e1.printStackTrace();
}
}
?
JVM,
600
,
.
,
5000
,
:
,
.
BufferedOutputStream
,
,
,
FileOutputStream.
int somedata[]= {56,230,123,43,11,37};
try {
//
buff = new BufferedOutputStream(myFile);
buff.write(somedata[i]);
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
buff.flush();
buff.close();
myFile.close();
} catch(IOException e1){
e1.printStackTrace();
}
}
,
,
BufferedOutputStream,
flush().
ByteReader
abc.gif
,
,
,
(
)
.
,
,
xyz.gif,
,
.
,
.
Java
,
:
java ByteReader xyz.gif
main()
xyz.gif.
,
main()
:
public static void main(String[] args) {}
,
String,
JVM
.
,
Java , , 158
.
,
,
.
,
,
:
public class TestArguments {
// ?
int numberOfArgs = args.length;
}
}
}
,
,
xyz.gif
250.
JVM
xyz.gif
args[0],
args[1].
(String).
,
:
int myScore = Integer.parseInt(args[1]);
,
.
main().
,
,
System.exit():
public static void main(String[] args) {
if (args.length != 2){
Java , , 159
System.out.println(
", , :");
//
System.exit(0);
}
}
.
,
,
.
Eclipse,
,
.
Run
Configurations,
(x)=Arguments
Program
Arguments.
Java , , 160
VM
arguments
JVM.
,
,
,
JVM,
..
.
Java
,
FileReader
FileWriter
.
,
read(),
,
readLine().
FileReader
FileWriter
Java , , 161
,
BufferedReader BufferedWriter,
.
ScoreReader
scores.txt
.
,
readLine()
null,
.
,
c:\scores.txt,
:
David 235
Brian 190
Anna 225
Zachary 160
ScoreReader,
.
.
,
,
.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
try {
myFile=new FileReader("c:\\scores.txt");
buff = new BufferedReader(myFile);
while (true) {
// scores.txt
String line = buff.readLine();
//
if (line == null) break;
System.out.println(line);
} // while
Java , , 162
e.printStackTrace();
} finally {
try{
buff.close();
myFile.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
} // main
}
,
write()
FileWriter.
,
String
.
FileWriter
(overloaded)
.
,
,
:
FileWriter fOut = new FileWriter("Scores.txt");
,
(true
,
):
FileWriter fOut = new FileWriter("Scores.txt", true);
,
ScoreWriter
scores
c:\scores.txt.
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
//
try {
// scores2.txt
buff.write(scores[i]);
System.out.println(" ");
e.printStackTrace();
} finally {
try{
buff.flush();
buff.close();
myFile.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
} // main
}
:
Mr. Smith 240
Ms. Lee 300
Mr. Dolittle 190
Java , , 164
File
java.io.File
,
,
,
..
,
,
.
,
File,
,
exists().
true,
abc.txt
,
:
File aFile = new File("abc.txt");
if (aFile.exists()){
// a JOptionPane
//
File,
,
,
.
,
createNewFile().
File.
createNewFile()
,
File.
,
.
delete()
renameTo()
length()
exists()
true,
list()
Java , , 165
/,
lastModified()
mkDir()
customers.txt
customers.txt.bak.
.bak
,
.
File file = new File("customers.txt");
File backup = new File("customers.txt.bak");
if (backup.exists()){
backup.delete();
file.renameTo(backup);
Java
7
Files,
,
.
File,
Files
,
.
Path
,
.
Customers.txt
Windows
:
Path pathCustomers=
FileSystems.getDefault().getPath(.,c\\Customers.txt);
Path pathCustomers=
FileSystems.getDefault().getPath(.,/Customers.txt);
:
List customers=
Files.readAllLines(pathCustomers,Charset.defaultCharset());
,
:
byte[] customers=Files.readAllBytes(pathCustomers);
:
Reader reader=
Files.newBufferedReader(pathCustomers, Charset.defaultCharset());
Java , , 166
Customers.txt
:
Path fileName= Paths.get(c:\\Customers.txt);
Path customers=Paths.createFile(fileName);
,
Java
,
.
.
,
NASA
Java
.
,
.
J
1.
JVM
http://download.oracle.com/javase/tutorial/essential/environm
ent/cmdLineArgs.html
2.
http://java.sun.com/docs/books/tutorial/essential/io/filestreams
.html
Java , , 167
FileCopy,
.
(
)
read()
write()
.
,
:
java FileCopy c:\\temp\\scores.txt
c:\\backup\\scores2.txt
Swing,
,
JFileChooser,
.
Browse.
.
,
Copy,
actionPerformed()
.
Java , , 168
,
/.
Java , , 169
10.
Java
.
-.
,
Java
.
.
Java
,
.
,
15.06.2011
15
2011.
Java
,
.
java.util.Date
java.text.SimpleDateFormat
.
,
:
Date today = new Date();
System.out.println( ": " + today );
:
: Sat Oct 08 20:41:44 MSD 2011
SimpleDateFormat
.
,
.
format(),
Java , , 170
Date.
.
import java.util.Date;
import java.text.SimpleDateFormat;
// Date
//
// , 10-08-11
SimpleDateFormat sdf= new SimpleDateFormat("MM-dd-yy");
String formattedDate=sdf.format(today);
// , 08-10-2011
sdf = new SimpleDateFormat("dd-MM-yyyy");
formattedDate=sdf.format(today);
// , , 27, 11
sdf = new SimpleDateFormat("EEE, MMM d, ''yy");
formattedDate=sdf.format(today);
System.out.println(
// , 07:18:51 AM
sdf = new SimpleDateFormat("hh:mm:ss a");
formattedDate=sdf.format(today);
}
}
MyDateFormat,
-
:
: Sat Oct 08 20:54:37 MSD 2011
(--): 10-08-11
(--): 08-10-2011
Java , , 171
( , , ') , 8, '11
(::) 08:54:37 PM
Java
SimpleDateFormat
.
,
,
Java
java.util.Calendar.
,
.
(method
overloading).
,
println()
System
:
String,
int,
char
.
System.out.println("!");
System.out.println(250);
System.out.println('A');
,
println(),
.
,
,
,
printString(),
printInt(),
printChar()?
,
,
.
,
,
.
(polymorfism)
.
,
Fish
4,
dive(),
:
public int dive(int howDeep)
,
.
5
,
100
.
Fish
final
DEFAULT_DIVING
(
),
.
Java , , 172
Fish dive().
int currentDepth=0;
final int DEFAULT_DIVING = 5;
currentDepth=currentDepth + DEFAULT_DIVING;
System.out.println(" " +
currentDepth=currentDepth - DEFAULT_DIVING;
}else{
System.out.println(" " +
" ");
return currentDepth;
}
currentDepth=currentDepth + howDeep;
System.out.println(" " +
currentDepth=currentDepth - howDeep;
}else{
" . ");
return currentDepth;
}
Java , , 173
// constructor
Fish(int startingPosition){
currentDepth=startingPosition;
}
}
FishMaster
dive():
public class FishMaster {
myFish.dive(2);
myFish.dive(); //
myFish.dive(97);
myFish.dive(3);
myFish.sleep();
}
}
,
.
JVM
.
,
Fish
(
),
FishMaster
:
Fish myFish = new Fish(20);
Fish myFish = new Fish();
Java , , 174
,
,
.
FishMaster
,
Fish.
:
?,
.
System.out.
,
out
java.io.OutputStream.
,
System.in.
,
,
,
in
java.io.InputStream.
FishMaster
.
,
Enter,
JVM
InputStream
.
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
int feet;
// InputStreamReader,
// System.in
// BufferedReader
//
// "Q"
while (true) {
System.out.println(" . ?");
Java , , 175
try {
feetString = stdin.readLine();
if (feetString.equals("Q")){
//
System.out.println("!");
System.exit(0);
}else {
// feetString
// , feet
feet = Integer.parseInt(feetString);
myFish.dive(feet);
} catch (IOException e) {
e.printStackTrace();
}
} // while
} // main
}
FishMaster
:
. ?
14
14 .
34 .
. ?
30
30 .
64 .
. ?
!
FishMaster
BufferedReader,
System.in.
Java , , 176
.
?
readLine()
,
Enter.
String,
FishMaster
int
dive()
Fish.
,
Q,
.
feetString.equals("Q")
feetString
String
Q.
,
,
readLine().
System.in.read(),
,
,
.
,
,
,
,
.
,
,
(),
.
Java
.
,
java.io
,
/.
javax.swing
Swing.
Eclipse
PingPong.
:
screens
engine.
PingPongTable
Package
screens:
Java , , 177
Finish
()
Eclipse
,
.
package screens;
}
}
Java , , 178
,
package,
.
,
Eclipse
screens
PingPongTable.java.
c:\eclipse\workspace\PingPong\screens
PingPongTable.java
PingPongTable.class.
PingPongEngine,
engine.
PingPong
:
Java , , 179
(,
,
),
PingPongTable
PingPongEngine,
import.
package screens;
import engine.PingPongEngine;
Java
.
,
.
Java,
: public, private, protected
package.
Java , , 180
PingPongEngine
public.
,
.
public
PingPongEngine.
PingPongTable
,
PingPongEngine
cannot
be
resolved
to
a
type
(
PingPongEngine)
The
type
engine.PingPongEngine
is
not
visible
(
engine.PingPongEngine
).
,
PingPongTable
PingPongEngine.
,
package.
,
,
().
,
PingPongEngine,
PingPongTable
,
,
.
-
,
.
private
.
.
,
,
,
,
.
.
Java
,
Car
public
brake(),
,
.
Java , , 181
,
,
.
,
Java
,
,
.
public class Car {
// private
//
private String brakesCondition;
boolean useRegularBrakes;
useRegularBrakes=checkForAntiLockBrakes (pedalPressure);
if (useRegularBrakes==true){
useRegularBrakes();
}else{
useAntiLockBrakes();
}
}
// private , -
//
private boolean checkForAntiLockBrakes(int pressure){
return true;
}else {
return false;
}
}
// private
//
private void useRegularBrakes(){
// ,
}
Java , , 182
// private
//
private void useAntiLockBrakes(){
// , }
Java
protected
.
,
-
,
,
.
,
.
-
.
.
,
.
,
,
.
Java , , 183
Score,
private.
9
ScoreWriter
String
.
,
.
.
,
,
.
Score.
(getter)
(setter)
,
private.
,
,
,
,
:
Score.score = 250;
Score.setScore(250);
,
,
,
500
?
Score
setScore(),
,
.
,
.
setScore()
.
,
.
?
.
,
setter-
,
.
import java.util.Date;
Java , , 184
return firstName;
this.firstName = firstName;
return lastName;
this.lastName = lastName;
return score;
this.score=score;
return playDate;
this.playDate=playDate;
// (String)
// .
// ,
Java , , 185
// ,
// System.out.println(myScore.toString());
return scoreString;
}
}
ScoreWriter2
Score
.
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.Date;
/** main :
1.
2. Score
3.
*/
// The player #1
scores[0]=new Score();
scores[0].setFirstName("");
scores[0].setLastName("");
scores[0].setScore(250);
scores[0].setPlayDate(today);
// The player #2
scores[1]=new Score();
scores[1].setFirstName("");
scores[1].setLastName("");
scores[1].setScore(300);
scores[1].setPlayDate(today);
// The player #3
scores[2]=new Score();
scores[2].setFirstName("");
Java , , 186
scores[2].setLastName("");
scores[2].setScore(190);
scores[2].setPlayDate(today);
try {
// String
// scores2.txt
buff.write(scores[i].toString());
System.out.println(" " +
scores[i].getLastName() );
}
System.out.println(" ");
e.printStackTrace();
} finally {
try{
buff.flush();
buff.close();
myFile.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
}
}
,
,
,
scores[5].getLastName(),
Java
ArrayIndexOutOfBoundsException.
ArrayList
java.util
,
,
()
.
:
ArrayList,
HashTable,
HashMap
List.
,
java.util.ArrayList.
Java , , 187
,
.
,
,
:
String[] myFriends = new String[5];
ArrayList
,
,
.
,
.
?
ArrayList!
,
.
ArrayList
,
.
,
,
int (
-
-
autoboxing).
ArrayList,
.
,
ArrayList,
add().
,
ArrayList
String
.
import java.util.ArrayList;
// ArrayList
ArrayList friends = new ArrayList();
friends.add("");
friends.add("");
friends.add("");
friends.add("");
// ?
int friendsCount = friends.size();
// ArrayList
for (int i=0; i<friendsCount; i++){
}
}
}
:
Java , , 188
0
1
2
3
get()
ArrayList
,
.
,
get()
Object.
.
,
friends
String.
Java
Object
String.
,
ArrayList
,
,
Fish,
Fish
,
FishTank,
.
Fish,
,
ArrayList
fishTank.
,
Fish
.
import java.util.ArrayList;
Fish theFish;
aFish.color = "";
aFish.weight = 2;
fishTank.add(aFish);
aFish.color = "";
aFish.weight = 5;
fishTank.add(aFish);
Java , , 189
FishTank:
2.0 . :20
5.0 . :10
,
Java,
Pet
Fish.
age,
color,
weight
height
protected,
,
-
.
currentDepth
private.
public
,
,
getAge(),
age,
setAge(),
.
.
,
.
Score
private ,
getter-
setter-
.
Java,
,
,
.
Java.
,
.
Java , , 190
1.
Java:
http://download.oracle.com/javase/tutorial/col
lections/intro/index.html
2.
ArrayList:
http://download.oracle.com/javase/7/docs/api
/java/util/ArrayList.html
3. :
http://www.vogella.de/articles/JavaDateTimeA
PI/article.html
4. Calendar:
http://download.oracle.com/javase/7/docs/api
/java/util/Calendar.html
1.
(
)
Fish.
10
.
FishMaster
Fish
,
:
2.
Score
.
ScoreWriter3,
Score
setter-,
,
:
Score aScore = new Score("",
Java , , 191
HashMap.
HashMapDemo,
ArrayListDemo,
.
Java , , 192
11. .
-
5, 6 7
AWT
Swing
.
,
,
,
.
,
,
.
,
-.
,
.
:
,
(
)
21
.
.
.
N
,
Q
S
.
.
,
,
,
.
Java , , 193
,
.
,
.
,
.
,
,
,
.
,
(
),
,
(
).
.
1.
?
(/)?
.
2.
,
,
.
(/)?
,
.
,
3.
(/)?
.
.
4.
(/)?
.
,
.
!
.
:
PingPongGreenTable
.
,
.
Java , , 194
PingPongGameEngine,
,
,
.
PingPongGreenTable,
.
GameConstants
,
,
,
..
-:
:
-.
,
.
.
PingPongGreenTable,
JPanel
Swing.
,
.
Java , , 195
,
PingPongGreenTable
-
PingPongGameEngine.
,
.
addPaneltoFrame()
,
.
,
paint(),
paintComponent().
JVM,
,
,
repaint().
,
,
repaint()
paintComponent()
Graphics,
.
.
,
,
fillRect().
X
Y
,
.
fillOval(),
,
.
,
.
X
,
Y
.
,
100
,
70:
X Y .
getPreferredSize().
,
,
Dimension
Swing.
Java
,
getPreferredSize()
Java , , 196
PingPongGreenTable.
Dimension,
.
PingPongGreenTable
PingPongGameEngine
,
.
,
PingPongGreenTable
,
PingPongGameEngine
,
,
.
(
final)
.
GameConstants.
,
implements
GameConstants
final
,
!
PingPongGreenTable
PingPongGameEngine
GameConstants.
,
,
,
GameConstants.
PingPongGreenTable
GameConstants.
package screens;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
import java.awt.Point;
import java.awt.Dimension;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Color;
import engine.PingPongGameEngine;
/**
-
,
*/
implements GameConstants{
JLabel label;
//
// Java
return preferredSize;
//. .
PingPongGreenTable(){
//
addMouseListener(gameEngine);
//
addMouseMotionListener(gameEngine);
// JLabel
void addPaneltoFrame(Container container) {
container.setLayout(new BoxLayout(container,
BoxLayout.Y_AXIS));
container.add(this);
// .
// ,
// repaint() PingPointGameEngine
publicvoid paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
//
g.fillRect(0,0,TABLE_WIDTH,TABLE_HEIGHT);
g.setColor(Color.yellow);
//
g.fillRect(KID_RACKET_X_START,kidRacket_Y,5,30);
g.setColor(Color.blue);
Java , , 198
//
g.fillRect(ComputerRacket_X,100,5,30);
g.setColor(Color.red);
g.fillOval(25,110,10,10); //
g.setColor(Color.white);
g.drawRect(10,10,300,200);
g.drawLine(160,10,160,210);
// 2x2
if (point != null) {
}
}
//
public void setKidRacket_Y(int xCoordinate){
this.kidRacket_Y = xCoordinate;
//
public int getKidRacket_Y(int xCoordinate){
return kidRacket_Y;
//
JFrame f = new JFrame("Ping Pong Green Table");
// ,
//
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
table.addPaneltoFrame(f.getContentPane());
//
f.pack();
f.setVisible(true);
}
}
Java , , 199
GameConstants.
.
final
:
package screens;
,
final.
,
,
,
,
TABLE_WIDTH
TABLE_HEIGHT
GameConstants.
PingPongGameEngine,
2
,
.
MouseListener
mousePressed().
.
,
,
MouseEvent
,
JVM.
mousePressed()
point.
,
,
.
MouseMotionListener
,
mouseMoved()
.
mouseMoved()
.
(
Y
,
Y
),
,
.
PingPongGreenTable
PingPongGameEngine,
(
this
PingPongGreenTable).
,
PingPongGameEngine
,
,
Java , , 200
,
.
,
6
.
4
,
GameConstants
(
PingPongGameEngine
).
,
4
kidRacket_Y:
kidRacket_Y -= RACKET_INCREMENT;
,
Y
100,
96
.
:
kidRacket_Y = kidRacket_Y - RACKET_INCREMENT;
,
3.
PingPongGameEngine.
package engine;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import screens.*;
PingPongGreenTable table;
// .
public PingPongGameEngine(PingPongGreenTable greenTable){
table = greenTable;
// MouseListener
// X Y
// " "
table.point.x = e.getX();
table.point.y = e.getY();
Java , , 201
// paintComponent()
table.repaint();
// MouseMotionListener
//
//
// ,
kidRacket_Y -= RACKET_INCREMENT;
kidRacket_Y += RACKET_INCREMENT;
//
table.setKidRacket_Y(kidRacket_Y);
table.repaint();
}
}
.
,
,
.
,
(a
thread).
,
,
,
,
,
.
Java , , 202
,
:
,
.
,
o
(CPU).
,
,
,
,
,
,
..
,
(multiple
threads).
Java-
,
.
,
web-.
-,
.
-
.
,
.
,
,
,
.
Java , , 203
.
Kill
Time,
,
.
.
NoThreadsSample
,
.
,
.
,
,
.
,
JTextField
.
,
.
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
//
NoThreadsSample(){
//
this.getContentPane().add(myButton);
this.getContentPane().add(new JTextField());
}
//
public void actionPerformed(ActionEvent e){
// ,
// ,
for (int i=0; i<300000;i++){
this.setTitle("i="+i);
Java , , 204
//
NoThreadsSample myWindow = new NoThreadsSample();
// ,
myWindow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//
//
myWindow.setBounds(0,0,150, 100);
//
myWindow.setVisible(true);
}
}
,
,
.
:
Java-
Thread
,
Runnable.
Runnable,
:
Thread worker = new Thread(this);
run()
,
.
worker.start();
Thread
run().
,
,
start().
public class MyThread extends Thread{
//
}
}
ThreadsSample
,
JFrame,
Java
.
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
//
ThreadsSample(){
//
GridLayout gl =new GridLayout(2,1);
this.getContentPane().setLayout(gl);
this.getContentPane().add(new JTextField());
}
//
//
// , ,
//
this.setTitle("i="+i);
}
}
Java , , 206
//,
myWindow.setDefaultCloseOperation(
WindowConstants.EXIT_ON_CLOSE);
//
myWindow.setBounds(0,0,150, 100);
myWindow.setVisible(true);
}
}
Kill
Time,
ThreadsSample
.
,
.
(
),
!
,
,
.
-
,
-.
PingPongGreenTable.
.
point
,
paintComponent().
,
MouseListener,
.
,
(N
,
S
Q
).
addKeyListener().
,
,
repaint()
PingPongGameEngine
PingPongGreenTable.
,
,
PingPongGreenTable
.
Java , , 207
,
,
.
package screens;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
import java.awt.Dimension;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Color;
import engine.PingPongGameEngine;
/**
* -,
, ,
*/
// .
public Dimension getPreferredSize() {
return preferredSize;
// . .
PingPongGreenTable(){
//
addMouseMotionListener(gameEngine);
//
addKeyListener(gameEngine);
// JLabel
void addPaneltoFrame(Container container) {
Java , , 208
container.setLayout(new BoxLayout(container,BoxLayout.Y_AXIS));
container.add(this);
// .
// ,
// repaint() PingPointGameEngine
public void paintComponent(Graphics g) {
super.paintComponent(g);
//
g.setColor(Color.GREEN);
g.fillRect(0,0,TABLE_WIDTH,TABLE_HEIGHT);
//
g.setColor(Color.yellow);
g.fillRect(KID_RACKET_X, kidRacket_Y,
RACKET_WIDTH, RACKET_LENGTH);
//
g.setColor(Color.blue);
g.fillRect(COMPUTER_RACKET_X, computerRacket_Y,
RACKET_WIDTH,RACKET_LENGTH);
//
g.setColor(Color.red);
g.fillOval(ballX,ballY,10,10);
//
g.setColor(Color.white);
g.drawRect(10,10,300,200);
g.drawLine(160,10,160,210);
// ,
//
requestFocus();
//
this.kidRacket_Y = yCoordinate;
repaint();
//
public int getKidRacket_Y(){
Java , , 209
return kidRacket_Y;
//
public void setComputerRacket_Y(int yCoordinate){
this.computerRacket_Y = yCoordinate;
repaint();
}
//
public void setMessageText(String text){
label.setText(text);
repaint();
}
//
public void setBallPosition(int xPos, int yPos){
ballX=xPos;
ballY=yPos;
repaint();
}
//
JFrame f = new JFrame("Ping Pong Green Table");
// ,
//
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//
f.setBounds(0,0,TABLE_WIDTH+5, TABLE_HEIGHT+40);
f.setVisible(true);
}
final
GameConstants,
,
.
package screens;
/**
* ,
*/
public interface GameConstants {
//
public final int TABLE_WIDTH = 320;
Java , , 210
//
public final int BALL_INCREMENT = 4;
//
public final int BALL_MIN_X = 1+ BALL_INCREMENT;
public final int BALL_MIN_Y = 1 + BALL_INCREMENT;
public final int BALL_MAX_X = TABLE_WIDTH - BALL_INCREMENT;
public final int BALL_MAX_Y = TABLE_HEIGHT - BALL_INCREMENT;
//
public final int BALL_START_X = TABLE_WIDTH/2;
public final int BALL_START_Y = TABLE_HEIGHT/2;
//,
// ,
//
public final int SLEEP_TIME = 10; //
}
,
PingPongGameEngine:
MouseListener
,
.
MouseMotionListener.
Runnable,
run().
.
run()
,
if(ballServed).
if(ballServed==true).
,
,
canBounce
.
,
true,
false.
Java , , 211
KeyListener,
keyPressed()
,
/
,
.
,
,
N
n.
private
:
displayScore(),
kidServe()
isBallOnTheTable().
,
.
.|
,
.
Thread.sleep().
sleep()
.
,
.
X
,
Y.
package engine;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import screens.*;
/**
* .
* , .
*/
//
private int verticalSlide;
// .
public PingPongGameEngine(PingPongGreenTable greenTable){
table = greenTable;
// MouseMotionListener
// ( , )
public void mouseDragged(MouseEvent e) {
//
// ,
//
kidRacket_Y -= RACKET_INCREMENT;
kidRacket_Y += RACKET_INCREMENT;
//
table.setKidRacket_Y(kidRacket_Y);
// KeyListener
public void keyPressed(KeyEvent e){
startNewGame();
endGame();
kidServe();
}
Java , , 213
//
public void startNewGame(){
computerScore=0;
kidScore=0;
table.setMessageText("Score Computer: 0 Kid: 0");
kidServe();
}
//
public void endGame(){
System.exit(0);
// run() Runnable
public void run(){
boolean canBounce=false;
while (true) {
if(ballServed){ //
// 1. ?
if ( movingLeft && ballX > BALL_MIN_X){
ballX-=BALL_INCREMENT;
//
//
ballY-=verticalSlide;
table.setBallPosition(ballX,ballY);
// ?
if (ballX <= COMPUTER_RACKET_X && canBounce){
movingLeft=false;
}
}
// 2. ?
if ( !movingLeft && ballX <= BALL_MAX_X){
(kidRacket_Y + RACKET_LENGTH)?true:false);
ballX+=BALL_INCREMENT;
table.setBallPosition(ballX,ballY);
// ?
if (ballX >= KID_RACKET_X && canBounce){
movingLeft=true;
}
}
// 3. ,
//
if (computerRacket_Y < ballY
&& computerRacket_Y < TABLE_BOTTOM){
computerRacket_Y +=RACKET_INCREMENT;
computerRacket_Y -=RACKET_INCREMENT;
}
table.setComputerRacket_Y(computerRacket_Y);
// 4.
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
// 5. , ,
if (isBallOnTheTable()){
computerScore++;
displayScore();
kidScore++;
displayScore();
}
}
} // if ballServed
} // while
}// run()
Java , , 215
//
ballServed = true;
ballX = KID_RACKET_X-1;
ballY=kidRacket_Y;
verticalSlide=-1;
}else{
verticalSlide=1;
}
table.setBallPosition(ballX,ballY);
table.setKidRacket_Y(kidRacket_Y);
}
private void displayScore(){
ballServed = false;
if (computerScore ==WINNING_SCORE){
}else{
}
}
// ,
private boolean isBallOnTheTable(){
return true;
}else {
return false;
}
}
}
Java , , 216
!
.
.
,
,
,
,
.
, Robocode
,
Java,
:
http://robocode.sourceforge.net/?Open&ca=daw-prod-robocode
Java:
http://www.oracle.com/technetwork/java/socket-
140484.html
Java:
http://www-106.ibm.com/developerworks/edu/j-dw-
javathread-i.html
java.awt.Graphics:
http://download.oracle.com/javase/6/docs/api/java/awt/G
raphics.html
Java , , 217
1.
PingPongGameEngine
:
table.point.x = e.getX();
point
PingPongGreenTable
public
setPointCoordinates(int
x, int y).
PingPongGameEngine.
2.
-
:
,
,
S
.
.
1.
RACKET_INCREMENT
BALL_INCREMENT.
,
.
,
1
10.
.
2.
,
.
,
,
.
Java , , 218
A. Java - JARs
.
USB
,
jar.
1.
,
jar
.class,
,
,
:
jar cvf myClasses.jar *.class
Java , , 219
jar
.
,
v
,
f
,
.
.
,
myClasses.jar,
:
jar xvf myClasses.jar
.
x
.
jar-
,
,
t
.
jar tvf myClasses.jar
,
WinZip
,
,
jar-.
Java
,
jar-.
,
jar,
,
.
Jar
java-:
http://download.oracle.com/javase/7/docs/technotes/tools
/windows/jar.html
Java , , 220
.
Eclipse
Eclipse ,
Java
.
Eclipse,
,
,
.
,
.
F3.
,
.
,
,
.
Ctrl-F11,
.
,
Eclipse
.
,
,
Ctrl-.
,
Ctrl-V.
Java , , 221
,
,
,
Refactor
Rename
.
Eclipse
,
.
jar-
(,
-
),
,
Properties,
Java
Build
Path
Add
External
Jars.
Eclipse
,
50
,
,
,
.
(.
bug),
-
.
,
.
,
(.
debug)
.
.
,
,
2,
22.
,
.
,
.
Java , , 222
,
Eclipse
FishMaster
.
(breakpoint)
,
,
,
/
,
.
,
,
,
.
FishMaster,
myFish.dive(2).
.
,
Run,
Debug....
FishMaster
Debug.
FishMaster
myFish.dive(2),
.
,
:
Java , , 223
,
.
,
.
Variables,
myFish.
..
Fish,
,
,
currentDepth=20.
.
.
(
F5),
dive().
,
howDeep=2,
.
this
,
.
,
,
.
,
,
.
-
,
-
.
Java , , 224
,
,
(
F6).
,
F8.
,
,
,
.
,
,
.
?
,
,
.
,
,
main()
,
.
Java , , 225
.
-
- HTML (
JavaScript),
,
..
HTML
7,
-,
HTML.
:
www.w3schools.com.
,
-
,
-
,
,
.
HTML,
.
,
,
-
Java
(
!)
HTML
.
,
-,
,
HTML
,
,
.
,
,
()
,
.
-.
-,
-
.
,
,
HTML
.
:
Java , , 226
(
).
,
.
-
(URL)
,
.
,
,
.
100
,
.
,
.
,
.
FTP-.
FTP-
FTP
Explorer,
www.ftpx.com.
-
FTP-
FTP
Explorer
,
,
.
,
Connection
Tools
(
).
Java , , 227
Add
,
,
-.
Profile
Name
.
,
FTP-.
Connect
.
,
.
.
,
.
,
HTML
.
,
Open.
.
Java , , 228
,
.
index.html.
URL
,
.
,
www.xyz.com/~David
myMainPage.html,
www.xyz.com/~David/myMainPage.html.
,
index.html,
www.xyz.com/~David.
,
,
.
,
,
,
.
,
.
-,
,
JavaScript.
,
Java
-
.
,
HTML
,
.
(http://narod.yandex.ru/)
.
.
Java , , 229
1.
How
to
make/create
you
own
Web
site:
http://www.thesitewizard.com/gettingstarted/startwebsite.shtml
-
-
7.
,
,
TicTacToe.html
TicTacToe.class.
,
,
.
-
,
?
Java
Tutorial.
24-Hour
Trainer.
DVD,
.
-
.
.
URL
:
http://www.amazon.com/Java-Programming-24-Hour-Trainer-
Yakov/dp/04708896402
-!
Java , , 230
!, 63 File, 164
&&, 63 FileInputStream, 153
||, 62 FileOutputStream, 154
Access
Levels, 176 FileReader, 160
ActionListener, 100 FileWriter, 160
actionPerformed, 100 finally, 145, 146
Adapters, 114 FlowLayout, 82
algorithm, 124 frame, 78
argument, 38 FTP, 227
array, 69, 70, 71 GridBagConstraints, 89
ArrayList, 186, 187, 188 GridBagLayout, 89
arrays, 183 GridLayout, 82
AWT, 76 HelloWorld, 36
BorderLayout, 84, 125 HTML, 116, 117, 119, 122
BoxLayout, 88 I/O, 138
break, 66, 72 IDE, 23
Buffered Streams, 155 implement, 98
BufferedInputStream, 155 implements, 98
BufferedOutputStream, 157 import, 77
callback
methods, 121 instance, 105
CardLayout, 90 instance
variables, 67
Casting, 102 instanceof, 104
catch, 142, 144 interfaces, 97
checked
exceptions, 140 jar, 218
CLASSPATH, 18, 20 javadoc, 59
conditional
if, 63 JDK, 14
constructor, 67, 68 JRE, 21, 30
continue, 72, 73 JVM, 13
date, 169 Layout manager, 78
Debug, 222 listeners, 101
do while, 73 Logical Operators, 62
Loops, 71
Download Eclipse, 23
member
variable, 67
Eclipse, 23
method
overloading, 171
else if, 64
method signature, 36
encapsulation, 182, 183
new, 67
events, 79
Exception, 140, 143 Object, 54
override, 56
exceptions, 137
packages, 176, 178
extends, 52, 55
panel, 78
Java , , 231
PATH, 20 , 44
private, 179, 180, 189 , 173
Program
Arguments, 159 , 63
protected, 179, 182 , 62
public, 36, 179 , 63
run-time errors, 137 , 48
scope, 67 , 40
showConfirmDialog, 100 , 52
stack
trace, 138 , 43
static, 36, 67 if, 60
streams, 152 , 221
Swing, 76, 93 , 48
switch, 65 , 43
system
variables, 17 , 56
this, 68 , 125
thread, 201, 204
, 97
throw, 147
,
throws, 144
112
TicTacToe, 117
time, 169 , 112
try, 141, 144, 146 , 112
try/catch, 141 , 112
void, 36, 49 , 112
WindowsListener, 114 , 112
, 120 , 97
, 47 -, 52
, 40 , 81
, 225 , 42
, 98
while, 72
, 19
for, 71
, 46 , 160
, 40 , 105
-, 114
, 43
, 59