java2实用教程第三版

Java 2实用教程(第三版)
清华大学出版社
(编著 耿祥义 张跃平)
例子源代码

建议使用文档结构图
(选择Word菜单→视图→文档结构图)
第一章Java 语言入门
例子1
public class Hello
{
public static void main (String args[ ])
{
System.out.println(“你好,很高兴学习Java”);
}
}
例子2
public class People
{ int height;
String ear;
void speak(String s)
{ System.out.println(s);
}
}
class A
{ public static void main(String args[])
{ People zhubajie;
zhubajie=new People();
zhubajie.height=170;
zhubajie.ear=“两只大耳朵”;
System.out.println(“身高:”+zhubajie.height);
System.out.println(zhubajie.ear);
zhubajie.speak(“师傅,咱们别去西天了,改去月宫吧”);
}
}
例子3
import java.applet.;
import java.awt.
;
public class Boy extends Applet
{ public void paint(Graphics g)
{ g.setColor(Color.red);
g.drawString(“我一边喝着咖啡,一边学Java呢”,5,30);
g.setColor(Color.blue);
g.drawString(“我学得很认真”,10,50);
}
}

第二章标识符、关键字和数据类型
例子1
public class Example2_1
{ public static void main (String args[ ])
{ char chinaWord=‘你’,japanWord=‘ぁ’;
int p1=36328,p2=38358;
System.out.println(“汉字’你’在unicode表中的顺序位置:”+(int)chinaWord);
System.out.println(“日语’ぁ’在unicode表中的顺序位置:”+(int)japanWord);
System.out.println(“unicode表中第20328位置上的字符是:”+(char)p1);
System.out.println(“unicode表中第12358位置上的字符是:”+(char)p2);
}
}
例子2
public class Example2_2
{ public static void main (String args[ ])
{ int c=2200;
long d=8000;
float f;
double g=123456789.123456789;
c=(int)d;
f=(float)g; //导致精度的损失.
System.out.print(“c= “+c);
System.out.println(” d= “+d);
System.out.println(“f= “+f);
System.out.println(“g= “+g);
}
}
例子3
public class Example2_3
{ public static void main(String args[])
{ int a[]={100,200,300};
int b[]={10,11,12,13,14,15,16};
b=a;
b[0]=123456;
System.out.println(“数组a:”+a[0]+”,”+a[1]+”,”+a[2]);
System.out.println(“数组b:”+b[0]+”,”+b[1]+","+b[2]);
System.out.println(“数组b的长度:”+b.length);
}
}

第三章运算符、表达式和语句
例子1
class Example3_1
{ public static void main(String args[])
{ char a1=‘十’,a2=‘点’,a3=‘进’,a4=‘攻’;
char secret=‘8’;
a1=(char)(a1^secret);
a2=(char)(a2^secret);
a3=(char)(a3^secret);
a4=(char)(a4^secret);
System.out.println(“密文:”+a1+a2+a3+a4);
a1=(char)(a1^secret);
a2=(char)(a2^secret);
a3=(char)(a3^secret);
a4=(char)(a4^secret);
System.out.println(“原文:”+a1+a2+a3+a4);
}
}
例子2
class Example3_2
{ public static void main(String args[])
{ int x,y=10;
if(((x=0)==0)||((y=20)==20))
{ System.out.println(“现在y的值是:”+y);
}
int a,b=10;
if(((a=0)==0)|((b=20)==20))
{ System.out.println(“现在b的值是:”+b);
}
}
}
例子3
public class Example3_3
{ public static void main(String args[])
{ int a=9,b=5,c=7,t;
if(a>b)
{ t=a; a=b; b=t;
}
if(a>c)
{ t=a; a=c; c=t;
}
if(b>c)
{ t=b; b=c; c=t;
}
System.out.println(“a=”+a+",b="+b+",c="+c);
}
}
例子4
public class Example3_4
{ public static void main(String args[])
{ int math=65 ,english=85;
if(math>60)
{ System.out.println(“数学及格了”);
}
else
{ System.out.println(“数学不及格”);
}
if(english>90)
{ System.out.println(“英语是优”);
}
else
{ System.out.println(“英语不是优”);
}
System.out.println(“我在学习控制语句”);
}
}
例子5
public class Example3_5
{ public static void main(String args[])
{ int x=2,y=1;
switch(x+y)
{ case 1 :
System.out.println(x+y);
break;
case 3:
System.out.println(x+y);
case 0:
System.out.println(x+y);
break;
default: System.out.println(“没有般配的”+(x+y));
}
}
}
例子6
public class Example3_6
{ public static void main(String args[])
{ long sum=0,a=5,item=a,n=10,i=1;
for(i=1;i<=n;i++)
{ sum=sum+item;
item=item*10+a;
}
System.out.println(sum);
}
}

例子7
class Example3_7
{ public static void main(String args[])
{ double sum=0,a=1;
int i=1;
while(i<=20)
{ sum=sum+a;
i=i+1;
a=a*(1.0/i);
}
System.out.println(“sum=”+sum);
}
}
例子8
class Example3_8
{ public static void main(String args[])
{ int sum=0,i,j;
for( i=1;i<=10;i++)
{ if(i%20) //计算1+3+5+7+9
continue;
sum=sum+i;
}
System.out.println(“sum=”+sum);
for(j=2;j<=50;j++) //求50以内的素数
{ for( i=2;i<=j/2;i++)
{ if(j%i
0)
break;
}
if(i>j/2)
{ System.out.println(""+j+“是素数”);
}
}
}
}

第四章类、对象和接口
例子1
class XiyoujiRenwu
{ float height,weight;
String head, ear,hand,foot, mouth;
void speak(String s)
{ System.out.println(s);
}
}
class A
{ public static void main(String args[])
{ XiyoujiRenwu zhubajie; //声明对象
zhubajie=new XiyoujiRenwu(); //为对象分配内存,使用new 运算符和默认的构造方法
}
}
例子2
class Point
{ int x,y;
Point(int a,int b)
{ x=a;
y=b;
}
}
public class A
{ public static void main(String args[])
{ Point p1,p2; //声明对象p1和p2
p1=new Point(10,10); //为对象分配内存,使用 new 和类中的构造方法
p2=new Point(23,35); //为对象分配内存,使用 new 和类中的构造方法
}
}
例子3
class XiyoujiRenwu
{ float height,weight;
String head, ear,hand,foot,mouth;
void speak(String s)
{ head=“歪着头”;
System.out.println(s);
}
}
class Example4_3
{ public static void main(String args[])
{ XiyoujiRenwu zhubajie,sunwukong;//声明对象
zhubajie=new XiyoujiRenwu(); //为对象分配内存
sunwukong=new XiyoujiRenwu();
zhubajie.height=1.80f; //对象给自己的变量赋值
zhubajie.head=“大头”;
zhubajie.ear=“一双大耳朵”;
sunwukong.height=1.62f; //对象给自己的变量赋值
sunwukong.weight=1000f;
sunwukong.head=“绣发飘飘”;
System.out.println(“zhubajie的身高:”+zhubajie.height);
System.out.println(“zhubajie的头:”+zhubajie.head);
System.out.println(“sunwukong的重量:”+sunwukong.weight);
System.out.println(“sunwukong的头:”+sunwukong.head);
zhubajie.speak(“俺老猪我想娶媳妇”); //对象调用方法
System.out.println(“zhubajie现在的头:”+zhubajie.head);
sunwukong.speak(“老孙我重1000斤,我想骗八戒背我”); //对象调用方法
System.out.println(“sunwukong现在的头:”+sunwukong.head);
}
}
例子4
class 梯形
{ float 上底,下底,高,面积;
梯形(float x,float y,float h)
{ 上底=x;
下底=y;
高=h;
}
float 计算面积()
{ 面积=(上底+下底)高/2.0f;
return 面积;
}
void 修改高(float height)
{ 高=height;
}
float 获取高()
{ return 高;
}
}
public class Example4_4
{ public static void main(String args[])
{ 梯形 laderOne=new 梯形(12.0f,3.5f,50),laderTwo=new 梯形(2.67f,3.0f,10);
System.out.println(“laderOne的高是:”+laderOne.获取高());
System.out.println(“laderTwo的高是:”+laderTwo.获取高());
System.out.println(“laderOne的面积是:”+laderOne.计算面积());
System.out.println(“laderTwo的面积是:”+laderTwo.计算面积());
laderOne.修改高(10);
float h=laderOne.获取高();
laderTwo.修改高(h
2);
System.out.println(“laderOne现在的高是:”+laderOne.获取高());
System.out.println(“laderTwo现在的高是:”+laderTwo.获取高());
System.out.println(“laderOne现在的面积是:”+laderOne.计算面积());
System.out.println(“laderTwo现在的面积是:”+laderTwo.计算面积());
}
}
例子5
class People
{ String face;
void setFace(String s)
{ face=s;
}
}
class A
{ void f(int x,double y,People p)
{ x=x+1;
y=y+1;
p.setFace(“笑脸”);
System.out.println(“参数x和y的值分别是:”+x+","+y);
System.out.println(“参数对象p的face是:”+p.face);
}
}
public class Example4_5
{ public static void main(String args[])
{ int x=100;
double y=100.88;
People zhang=new People();
zhang.setFace(“很严肃的样子”);
A a=new A();
a.f(x,y,zhang);
System.out.println(“main方法中x和y的值仍然分别是:”+x+","+y);
System.out.println(“main方法中对象zhang的face是:”+zhang.face);
}
}
例子6
class 圆
{ double 半径;
圆(double r)
{ 半径=r;
}
double 计算面积()
{ return 3.14半径半径;
}
void 修改半径(double 新半径)
{ 半径=新半径;
}
double 获取半径()
{ return 半径;
}
}
class 圆锥
{ 圆 底圆;
double 高;
圆锥(圆 circle,double h)
{ this.底圆=circle;
this.高=h;
}
double 计算体积()
{ double volume;
volume=底圆.计算面积()高/3.0;
return volume;
}
void 修改底圆半径(double r)
{ 底圆.修改半径®;
}
double 获取底圆半径()
{ return 底圆.获取半径();
}
}
class Example4_6
{ public static void main(String args[])
{ 圆 circle=new 圆(10);
圆锥 circular=new 圆锥(circle,20);
System.out.println(“圆锥底圆半径:”+circular.获取底圆半径());
System.out.println(“圆锥的体积:”+circular.计算体积());
circular.修改底圆半径(100);
System.out.println(“圆锥底圆半径:”+circular.获取底圆半径());
System.out.println(“圆锥的体积:”+circular.计算体积());
}
}
例子7
class 梯形
{ float 上底,高;
static float 下底;
梯形(float x,float y,float h)
{ 上底=x; 下底=y; 高=h;
}
float 获取下底()
{ return 下底;
}
void 修改下底(float b)
{ 下底=b;
}
}
class Example4_7
{ public static void main(String args[])
{ 梯形 laderOne=new 梯形(3.0f,10.0f,20),laderTwo=new 梯形(2.0f,3.0f,10);
梯形.下底=200; //通过类名操作类变量
System.out.println(“laderOne的下底:”+laderOne.获取下底());
System.out.println(“laderTwo的下底:”+laderTwo.获取下底());
laderTwo.修改下底(60); //通过对象操作类变量
System.out.println(“laderOne的下底:”+laderOne.获取下底());
System.out.println(“laderTwo的下底:”+laderTwo.获取下底());
}
}
例子8
class Fibi
{ public static long fibinacii(int n)
{ long c=0;
if(n1||n2)
c=1;
else
c=fibinacii(n-1)+fibinacii(n-2);
return c;
}
}
public class Example4_8
{ public static void main(String args[])
{ System.out.println(Fibi.fibinacii(7));
}
}
例子9
package tom.jiafei;
public class PrimNumber
{ public void getPrimnumber(int n)
{ int sum=0,i,j;
for(i=1;i<=n;i++)
{ for(j=2;j<=i/2;j++)
{ if(i%j==0)
break;
}
if(j>i/2)
System.out.print(" "+i);
}
}
public static void main(String args[])
{ PrimNumber p=new PrimNumber();
p.getPrimnumber(20);
}
}
例子10
import java.applet.Applet;
import java.awt.
;
public class Example4_10 extends Applet
{ Button redbutton;
public void init()
{ redbutton=new Button(“我是一个红色的按钮”);
redbutton.setBackground(Color.red);
redbutton.setForeground(Color.white);
add(redbutton);
}
}
例子11
import tom.jiafei.; //引入包tom.jiafei中的类
public class Example4_11
{ public static void main(String args[])
{ PrimNumber num=new PrimNumber();//用包tom.jiafei中的类创建对象
num.getPrimnumber(30);
}
}
例子12
public class Example4_12
{ public static void main(String args[])
{ PrimNumber num=new PrimNumber();//要保证PrimNuber类和Example4_12类在同一目录中
num.getPrimnumber(120);
}
}
Trangel.java
package tom.jiafei;
public class Trangle
{ double sideA,sideB,sideC;
boolean boo;
public Trangle(double a,double b,double c)
{ sideA=a;
sideB=b;
sideC=c;
if(a+b>c&&a+c>b&&c+b>a)
{ System.out.println(“我是一个三角形”);
boo=true;
}
else
{ System.out.println(“我不是一个三角形”);
boo=false;
}
}
public void 计算面积()
{ if(boo)
{ double p=(sideA+sideB+sideC)/2.0;
double area=Math.sqrt(p
(p-sideA)(p-sideB)(p-sideC)) ;
System.out.println(“面积是:”+area);
}
else
{ System.out.println(“不是一个三角形,不能计算面积”);
}
}
public void 修改三边(double a,double b,double c)
{ sideA=a;
sideB=b;
sideC=c;
if(a+b>c&&a+c>b&&c+b>a)
{ boo=true;
}
else
{ boo=false;
}
}
}
例子13
import tom.jiafei.Trangle;
class Example4_13
{ public static void main(String args[])
{ Trangle trangle=new Trangle(12,3,1);
trangle.计算面积();
trangle.修改三边(3,4,5);
trangle.计算面积();
}
}
例子14
class Example4_14
{ private int money;
Example4_14()
{ money=2000;
}
private int getMoney()
{ return money;
}
public static void main(String args[])
{ Example4_14 exa=new Example4_14();
exa.money=3000;
int m=exa.getMoney();
System.out.println(“money=”+m);
}
}
例子15
class Father
{ private int money;
float weight,height;
String head;
void speak(String s)
{ System.out.println(s);
}
}
class Son extends Father
{ String hand,foot;
}
public class Example4_15
{ public static void main(String args[])
{ Son boy;
boy=new Son();
boy.weight=1.80f;
boy.height=120f;
boy.head=“一个头”;
boy.hand=“两只手 “;
boy.foot=“两只脚”;
boy.speak(“我是儿子”);
System.out.println(boy.hand+boy.foot+boy.head+boy.weight+boy.height);
}
}
例子16
class Chengji
{ float f(float x,float y)
{ return xy;
}
}
class Xiangjia extends Chengji
{ float f(float x,float y)
{ return x+y ;
}
}
public class Example4_16
{ public static void main(String args[])
{ Xiangjia sum;
sum=new Xiangjia();
float c=sum.f(4,6);
System.out.println©;
}
}
例子17
class Area
{ float f(float r )
{ return 3.14159f
rr;
}
float g(float x,float y)
{ return x+y;
}
}
class Circle extends Area
{ float f(float r)
{ return 3.14159f
2.0fr;
}
}
public class Example4_17
{ public static void main(String args[])
{ Circle yuan;
yuan=new Circle();
float length=yuan.f(5.0f);
float sum=yuan.g(232.645f,418.567f);
System.out.println(length);
System.out.println(sum);
}
}
例子18
class A
{
final double PI=3.1415926;
public double getArea(final double r)
{
return PI
rr;
}
}
public class Example4_18
{ public static void main(String args[])
{ A a=new A();
System.out.println(“面积:”+a.getArea(100));
}
}
例子19
class 类人猿
{ private int n=100;
void crySpeak(String s)
{ System.out.println(s);
}
}
class People extends 类人猿
{ void computer(int a,int b)
{ int c=a
b;
System.out.println©;
}
void crySpeak(String s)
{ System.out.println(”"+s+"”);
}
}
class Example4_19
{ public static void main(String args[])
{ 类人猿 monkey=new People();
monkey.crySpeak(“I love this game”);
People people=(People)monkey;
people.computer(10,10);
}
}
例子20
class 动物
{ void cry()
{
}
}
class 狗 extends 动物
{ void cry()
{ System.out.println(“汪汪…”);
}
}
class 猫 extends 动物
{ void cry()
{ System.out.println(“喵喵…”);
}
}
class Example4_20
{ public static void main(String args[])
{ 动物 dongwu;
dongwu=new 狗();
dongwu.cry();
dongwu=new 猫();
dongwu.cry();
}
}

例子21
abstract class A
{ abstract int min(int x,int y);
int max(int x,int y)
{ return x>y?x:y;
}
}
class B extends A
{ int min(int x,int y)
{ return x<y?x:y;
}
}
public class Example4_21
{ public static void main(String args[])
{ A a;
B b=new B();
int max=b.max(12,34);
int min=b.min(12,34);
System.out.println(“max=”+max+" min="+min);
a=b;
max=a.max(12,34);
System.out.println(“max=”+max);
}
}
例子22
abstract class 图形
{ public abstract double 求面积();
}
class 梯形 extends 图形
{ double a,b,h;
梯形(double a,double b,double h)
{ this.a=a;
this.b=b;
this.h=h;
}
public double 求面积()
{ return((1/2.0)(a+b)h);
}
}
class 圆形 extends 图形
{ double r;
圆形(double r)
{ this.r=r;
}
public double 求面积()
{ return(3.14
r
r);
}
}
class 堆
{ 图形 底;
double 高;
堆(图形 底,double 高)
{ this.底=底;
this.高=高;
}
void 换底(图形 底)
{ this.底=底;
}
public double 求体积()
{ return (底.求面积()高)/3.0;
}
}
public class Example4_22
{ public static void main(String args[])
{ 堆 zui;
图形 tuxing;
tuxing=new 梯形(2.0,7.0,10.7);
System.out.println(“梯形的面积”+tuxing.求面积());
zui=new 堆(tuxing,30);
System.out.println(“梯形底的堆的体积”+zui.求体积());
tuxing=new 圆形(10);
System.out.println(“半径是10的圆的面积”+tuxing.求面积());
zui.换底(tuxing);
System.out.println(“圆形底的堆的体积”+zui.求体积());
}
}
例子23
class Student
{ int number;String name;
Student()
{
}
Student(int number,String name)
{ this.number=number;
this.name=name;
System.out.println("I am "+name+ "my number is "+number);
}
}
class Univer_Student extends Student
{ boolean 婚否;
Univer_Student(int number,String name,boolean b)
{ super(number,name);
婚否=b;
System.out.println(“婚否=”+婚否);
}
}
public class Example4_23
{ public static void main(String args[])
{ Univer_Student zhang=new Univer_Student(9901,“和晓林”,false);
}
}
例子24
class Sum
{ int n;
float f()
{ float sum=0;
for(int i=1;i<=n;i++)
sum=sum+i;
return sum;
}
}
class Average extends Sum
{ int n;
float f()
{ float c;
super.n=n;
c=super.f();
return c/n;
}
float g()
{ float c;
c=super.f();
return c/2;
}
}
public class Example4_24
{ public static void main(String args[])
{ Average aver=new Average();
aver.n=100;
float result_1=aver.f();
float result_2=aver.g();
System.out.println(“result_1=”+result_1);
System.out.println(“result_2=”+result_2);
}
}
例子25
interface Computable
{ int MAX=100;
int f(int x);
}
class China implements Computable
{ int number;
public int f(int x) //不要忘记public关键字
{ int sum=0;
for(int i=1;i<=x;i++)
{ sum=sum+i;
}
return sum;
}
}
class Japan implements Computable
{ int number;
public int f(int x)
{ return 44+x;
}
}
public class Example4_25
{ public static void main(String args[])
{ China zhang;
Japan henlu;
zhang=new China();
henlu=new Japan();
zhang.number=991898+Computable.MAX;
henlu.number=941448+Computable.MAX;
System.out.println(“number:”+zhang.number+“求和”+zhang.f(100));
System.out.println(“number:”+henlu.number+“求和”+henlu.f(100));
}
}
例子26
interface 收费
{ public void 收取费用();
}
interface 调节温度
{ public void controlTemperature();
}
class 公共汽车 implements 收费
{ public void 收取费用()
{ System.out.println(“公共汽车:一元/张,不计算公里数”);
}
}
class 出租车 implements 收费, 调节温度
{ public void 收取费用()
{ System.out.println(“出租车:1.60元/公里,起价3公里”);
}
public void controlTemperature()
{ System.out.println(“安装了Hair空调”);
}
}
class 电影院 implements 收费,调节温度
{ public void 收取费用()
{ System.out.println(“电影院:门票,十元/张”);
}
public void controlTemperature()
{ System.out.println(“安装了中央空调”);
}
}
class Example4_26
{ public static void main(String args[])
{ 公共汽车 七路=new 公共汽车();
出租车 天宇=new 出租车();
电影院 红星=new 电影院();
七路.收取费用();
天宇.收取费用();
红星.收取费用();
天宇.controlTemperature();
红星.controlTemperature();
}
}
例子27
interface ShowMessage
{ void 显示商标(String s);
}
class TV implements ShowMessage
{ public void 显示商标(String s)
{ System.out.println(s);
}
}
class PC implements ShowMessage
{ public void 显示商标(String s)
{ System.out.println(s);
}
}
public class Example4_27
{ public static void main(String args[])
{ ShowMessage sm;
sm=new TV();
sm.显示商标(“长城牌电视机”);
sm=new PC();
sm.显示商标(“联想奔月5008PC机”);
}
}
例子28
interface Computerable
{ public double 求面积();
}
class 梯形 implements Computerable
{ double a,b,h;
梯形(double a,double b,double h)
{ this.a=a;
this.b=b;
this.h=h;
}
public double 求面积()
{ return((1/2.0)
(a+b)h);
}
}
class 圆形 implements Computerable
{ double r;
圆形(double r)
{ this.r=r;
}
public double 求面积()
{ return(3.14
rr);
}
}
class 堆
{ Computerable 底;
double 高;
堆(Computerable 底,double 高)
{ this.底=底;
this.高=高;
}
void 换底(Computerable 底)
{ this.底=底;
}
public double 求体积()
{ return (底.求面积()高)/3.0;
}
}
public class Example4_28
{ public static void main(String args[])
{ 堆 zui;
Computerable bottom;
bottom=new 梯形(2.0,7.0,10.7);
System.out.println(“梯形的面积”+bottom.求面积());
zui=new 堆(bottom,30);
System.out.println(“梯形底的堆的体积”+zui.求体积());
bottom=new 圆形(10);
System.out.println(“半径是10的圆的面积”+bottom.求面积());
zui.换底(bottom);
System.out.println(“圆形底的堆的体积”+zui.求体积());
}
}
例子29
interface SpeakHello
{ void speakHello();
}
class Chinese implements SpeakHello
{ public void speakHello()
{ System.out.println("中国人习惯问候语:你好,吃饭了吗? ");
}
}
class English implements SpeakHello
{ public void speakHello()
{ System.out.println(“英国人习惯问候语:你好,天气不错 “);
}
}
class KindHello
{ public void lookHello(SpeakHello hello)
{ hello.speakHello();
}
}
public class Example4_29
{ public static void main(String args[])
{ KindHello kindHello=new KindHello();
kindHello.lookHello(new Chinese());
kindHello.lookHello(new English());
}
}
例子30
class China
{ final String nationalAnthem=“义勇军进行曲”;
Beijing beijing;
China()
{ beijing=new Beijing();
}
String getSong()
{ return nationalAnthem;
}
class Beijing
{ String name=“北京”;
void speak()
{ System.out.println(“我们是”+name+” 我们的国歌是:”+getSong());
}
}
}
public class Example4_30
{ public static void main(String args[])
{ China china=new China();
china.beijing.speak();
}
}
例子31
class Cubic
{ double getCubic(int n)
{ return 0;
}
}
abstract class Sqrt
{ public abstract double getSqrt(int x);
}
class A
{ void f(Cubic cubic)
{ double result=cubic.getCubic(3);
System.out.println(result);
}
}
public class Example4_31
{ public static void main(String args[])
{ A a=new A();
a.f(new Cubic()
{ double getCubic(int n)
{ return n
n
n;
}
}
);
Sqrt ss=new Sqrt()
{ public double getSqrt(int x)
{ return Math.sqrt(x);
}
};
double m=ss.getSqrt(5);
System.out.println(m);
}
}
例子32
interface Cubic
{ double getCubic(int n);
}
interface Sqrt
{ public double getSqrt(int x);
}
class A
{ void f(Cubic cubic)
{ double result=cubic.getCubic(3);
System.out.println(result);
}
}
public class Example4_32
{ public static void main(String args[])
{ A a=new A();
a.f(new Cubic()
{ public double getCubic(int n)
{ return nnn;
}
}
);
Sqrt ss=new Sqrt()
{ public double getSqrt(int x)
{ return Math.sqrt(x);
}
};
double m=ss.getSqrt(5);
System.out.println(m);
}
}
例子33
public class Example4_33
{ public static void main(String args[ ])
{ int n=0,m=0,t=555;
try{ m=Integer.parseInt(“8888”);
n=Integer.parseInt(“abc789”);
t=9999;
}
catch(NumberFormatException e)
{ System.out.println(“发生异常:”+e.getMessage());
e.printStackTrace();
n=123;
}
System.out.println(“n=”+n+",m="+m+",t="+t);
}
}
例子34
class NopositiveException extends Exception
{ String message;
NopositiveException(int m,int n)
{ message=“数字”+m+“或”+n+“不是正整数”;
}
public String toString()
{ return message;
}
}
class Computer
{ public int getMaxCommonDivisor(int m,int n) throws NopositiveException
{ if(n<=0||m<=0)
{ NopositiveException exception=new NopositiveException(m,n);
throw exception;
}
if(m<n)
{ int temp=0;
temp=m;
m=n;
n=temp;
}
int r=m%n;
while(r!=0)
{ m=n;
n=r;
r=m%n;
}
return n;
}
}
public class Example4_34
{ public static void main(String args[])
{ int m=24,n=36,result=0;
Computer a=new Computer();
try { result=a.getMaxCommonDivisor(m,n);
System.out.println(m+“和”+n+"的最大公约数 "+result);
m=-12;
n=22;
result=a.getMaxCommonDivisor(m,n);
System.out.println(m+“和”+n+"的最大公约数 “+result);
}
catch(NopositiveException e)
{ System.out.println(e.toString());
}
}
}
例子35
import java.lang.reflect.;
class Rect
{ double width,height,area;
public double getArea()
{ area=height
width;
return area;
}
}
public class Example4_35
{ public static void main(String args[])
{ Rect rect=new Rect();
Class cs=rect.getClass();
String className=cs.getName();
Constructor[] con=cs.getDeclaredConstructors();
Field[] field=cs.getDeclaredFields() ;
Method[] method=cs.getDeclaredMethods();
System.out.println(“类的名字:”+className);
System.out.println(“类中有如下的成员变量:”);
for(int i=0;i<field.length;i++)
{ System.out.println(field[i].toString());
}
System.out.println(“类中有如下的方法:”);
for(int i=0;i<method.length;i++)
{ System.out.println(method[i].toString());
}
System.out.println(“类中有如下的构造方法:”);
for(int i=0;i<con.length;i++)
{ System.out.println(con[i].toString());
}
}
}
例子36
class Rect
{ double width,height,area;
public double getArea()
{ area=height*width;
return area;
}
}
public class Example4_36
{ public static void main(String args[])
{ try{ Class cs=Class.forName(“Rect”);
Rect rect=(Rect)cs.newInstance();
rect.width=100;
rect.height=200;
System.out.println(“rect的面积”+rect.getArea());
}
catch(Exception e){}
}
}
例子37
public class Example4_37
{ public static void main(String args[ ])
{ char a[]={‘a’,‘b’,‘c’,‘D’,‘E’,‘F’};
for(int i=0;i<a.length;i++)
{ if(Character.isLowerCase(a[i]))
{ a[i]=Character.toUpperCase(a[i]);
}
else if(Character.isUpperCase(a[i]))
{ a[i]=Character.toLowerCase(a[i]);
}
}
for(int i=0;i<a.length;i++)
{ System.out.print(” "+a[i]);
}
}
}
Mymoon.mf
Manifest-Version: 1.0
Main-Class: A
Created-By: 1.4(Sun Microsystems Inc.)
Test1.java
public class Test1
{ public void fTest1()
{ System.out.println(“I am a method In Test1 class”);
}
}
Test2.java
public class Test2
{ public void fTest2()
{ System.out.println(“I am a method In Test2 class”);
}
}
moon.mf
Manifest-Version: 1.0
Class: Test1 Test2
Created-By: 1.4(Sun Microsystems Inc.)

第五章字符串
例子1
class Example5_1
{ public static void main(String args[])
{ String s1,s2;
s1=new String(“we are students”);
s2=new String(“we are students”);
System.out.println(s1.equals(s2));
System.out.println(s1s2);
String s3,s4;
s3=“how are you”;
s4=“how are you”;
System.out.println(s3.equals(s4));
System.out.println(s3
s4);
}
}
例子2
class Example5_2
{ public static void main(String args[])
{ int number=0;
String s=“student;entropy;engage,english,client”;
for(int k=0;k<s.length();k++)
{ if(s.regionMatches(k,“en”,0,2))
{ number++;
}
}
System.out.println(“number=”+number);
}
}
例子3
class Example5_3
{ public static void main(String args[])
{ String a[]={“door”,“apple”,“Applet”,“girl”,“boy”};
for(int i=0;i<a.length-1;i++)
{ for(int j=i+1;j<a.length;j++)
{ if(a[j].compareTo(a[i])<0)
{ String temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(int i=0;i<a.length;i++)
{ System.out.print(" “+a[i]);
}
}
}
例子4
class Example5_4
{ public static void main(String args[])
{ String path=“c:\myfile\2000\result.txt”;
int index=path.lastIndexOf(”\");
String fileName=path.substring(index+1);
String newName=fileName.replaceAll(".txt",".java");
System.out.println(path);
System.out.println(fileName);
System.out.println(newName);
}
}

例子5
public class Example5_5
{ public static void main(String args[])
{ double n,sum=0,item=0;
boolean computable=true;
for(int i=0;i<args.length;i++)
{ try{ item=Double.parseDouble(args[i]);
sum=sum+item;
}
catch(NumberFormatException e)
{ System.out.println(“您键入了非数字字符:”+e);
computable=false;
}
}
if(computable)
{ n=sum/args.length;
System.out.println(“平均数:”+n);
}
int number=123456;
String binaryString=Long.toBinaryString(number);
System.out.println(number+“的二进制表示:”+binaryString);
System.out.println(number+“的十六进制表示:”+Long.toString(number,16));
String str=“1110110”;
int p=0,m=0;
for(int i=str.length()-1;i>=0;i–)
{ char c=str.charAt(i);
int a=Integer.parseInt(""+c);
p=p+(int)(aMath.pow(2,m));
m++;
}
System.out.println(str+“的十进制表示:”+p);
}
}
例子6
import java.util.Date;
import java.awt.
;
public class Example5_6
{ public static void main(String args[])
{ Date date=new Date();
Button button=new Button(“确定”);
System.out.println(date.toString());
System.out.println(button.toString());
}
}
例子7
import java.util.*;
public class Example5_7
{ public static void main(String args[])
{ String s=“I am Geng.X.y,she is my girlfriend”;
StringTokenizer fenxi=new StringTokenizer(s," ,");
int number=fenxi.countTokens();
while(fenxi.hasMoreTokens())
{ String str=fenxi.nextToken();
System.out.println(str);
System.out.println(“还剩”+fenxi.countTokens()+“个单词”);
}
System.out.println(“s共有单词:”+number+“个”);
}
}
例子8
class Example5_8
{ public static void main(String args[])
{ char c[],d[];
String s=“巴西足球队击败德国足球队”;
c=new char[2];
s.getChars(5,7,c,0);
System.out.println©;
d=new char[s.length()];
s.getChars(7,12,d,0);
s.getChars(5,7,d,5);
s.getChars(0,5,d,7);
System.out.println(d);
}
}
例子9
class Example5_9
{ public static void main(String args[])
{ String s=“清华大学出版社”;
char a[]=s.toCharArray();
for(int i=0;i<a.length;i++)
{ a[i]=(char)(a[i]^‘t’);
}
String secret=new String(a);
System.out.println(“密文:”+secret);
for(int i=0;i<a.length;i++)
{ a[i]=(char)(a[i]^‘t’);
}
String code=new String(a);
System.out.println(“原文:”+code);
}
}
例子10
public class Example5_10
{ public static void main(String args[])
{ byte d[]=“你我他”.getBytes();
System.out.println(“数组d的长度是(一个汉字占两个字节):”+d.length);
String s=new String(d,0,2);
System.out.println(s);
}
}
例子11
class Example5_11
{ public static void main(String args[ ])
{ StringBuffer str=new StringBuffer(“62791720”);
str.insert(0,“010-”);
str.setCharAt(7 ,‘8’);
str.setCharAt(str.length()-1,‘7’);
System.out.println(str);
str.append("-446");
System.out.println(str);
str.reverse();
System.out.println(str);
}
}
例子12
public class Example5_12
{ public static void main (String args[ ])
{
String regex="\w{1,}@\w{1,}\56\w{1,}" ;
String str1=“zhangsan@sina.com”;
String str2=“li@si@dl.cn”;
if(str1.matches(regex))
{ System.out.println(str1+“是一个Email地址”);
}
else
{ System.out.println(str1+“不是一个Email地址”);
}
if(str2.matches(regex))
{ System.out.println(str2+“是一个Email地址”);
}
else
{ System.out.println(str2+“不是一个Email地址”);
}
}
}

第六章时间、日期和数字
例子1
import java.util.Date;
import java.text.SimpleDateFormat;
class Example6_1
{ public static void main(String args[])
{ Date nowTime=new Date();
System.out.println(nowTime);
SimpleDateFormat matter1=
new SimpleDateFormat(" ‘time’:yyyy年MM月dd日E 北京时间");
System.out.println(matter1.format(nowTime));
SimpleDateFormat matter2=
new SimpleDateFormat(“北京时间:yyyy年MM月dd日HH时mm分ss秒”);
System.out.println(matter2.format(nowTime));
Date date1=new Date(1000),
date2=new Date(-1000);
System.out.println(matter2.format(date1));
System.out.println(matter2.format(date2));
System.out.println(new Date(System.currentTimeMillis()));
}
}
例子2
import java.util.;
class Example6_2
{ public static void main(String args[])
{ Calendar calendar=Calendar.getInstance();
calendar.setTime(new Date());
String 年=String.valueOf(calendar.get(Calendar.YEAR)),
月=String.valueOf(calendar.get(Calendar.MONTH)+1),
日=String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)),
星期=String.valueOf(calendar.get(Calendar.DAY_OF_WEEK)-1);
int hour=calendar.get(Calendar.HOUR_OF_DAY),
minute=calendar.get(Calendar.MINUTE),
second=calendar.get(Calendar.SECOND);
System.out.println(“现在的时间是:”);
System.out.println(""+年+“年”+月+“月”+日+“日 “+ “星期”+星期);
System.out.println(””+hour+“时”+minute+“分”+second+“秒”);
calendar.set(1962,5,29); //将日历翻到1962年6月29日,注意5表示六月。
long time1962=calendar.getTimeInMillis();
calendar.set(2006,9,1);
long time2006=calendar.getTimeInMillis();
long 相隔天数=(time2006-time1962)/(1000
606024);
System.out.println(“2006年10月1日和1962年6月29日相隔”+相隔天数+“天”);
}
}
例子3
import java.util.;
class Example6_3
{ public static void main(String args[])
{ System.out.println(" 日 一 二 三 四 五 六");
Calendar 日历=Calendar.getInstance();
日历.set(2006,11,1); //将日历翻到2006年12月1日。
int 星期几=日历.get(Calendar.DAY_OF_WEEK)-1;
String a[]=new String[星期几+31];
for(int i=0;i<星期几;i++)
{ a[i]="**";
}
for(int i=星期几,n=1;i<星期几+31;i++)
{ if(n<=9)
a[i]=String.valueOf(n)+" “;
else
a[i]=String.valueOf(n) ;
n++;
}
for(int i=0;i<a.length;i++)
{ if(i%70)
{ System.out.println("");
}
System.out.print(" “+a[i]);
}
}
}
例子4
import java.text.NumberFormat;
class Example6_4
{ public static void main(String args[])
{ double a=Math.sqrt(5);
System.out.println(“格式化前:”+a);
NumberFormat f=NumberFormat.getInstance();
f.setMaximumFractionDigits(7);
f.setMinimumIntegerDigits(3);
String s=f.format(a);
System.out.println(“格式化后:”+s);
MyNumberFormat myFormat=new MyNumberFormat();
System.out.println(“格式化后:”+myFormat.format(a,4));
System.out.println(“得到的随机数:”);
int number=8;
for(int i=1;i<=20;i++)
{ int randomNumber=(int)(Math.random()*number)+1;
System.out.print(” "+randomNumber);
if(i%10
0)
System.out.println(”");
}
}
}
class MyNumberFormat
{ public String format(double a,int n)
{ String str=String.valueOf(a);
int index=str.indexOf(".");
String temp=str.substring(index+1);
int leng=0;
leng=temp.length();
int min=Math.min(leng,n);
str=str.substring(0,index+min+1);
return str;
}
}
}
例子5
import java.math.
;
public class Example6_5
{ public static void main(String args[])
{ BigInteger sum=new BigInteger(“0”),
xiang=new BigInteger(“1”),
ONE=new BigInteger(“1”),
i=ONE,
m=new BigInteger(“30”);
while(i.compareTo(m)<=0)
{ sum=sum.add(xiang);
i=i.add(ONE);
xiang=xiang.multiply(i);
}
System.out.println(sum);
}
}

第七章AWT组件及事件处理
例子1
import java.awt.;
class FirstWindow extends Frame
{ MenuBar menubar;
Menu menu;
MenuItem item1,item2;
FirstWindow(String s)
{ setTitle(s);
Toolkit tool=getToolkit();
Dimension dim=tool.getScreenSize();
setBounds(0,0,dim.width,dim.height/2);
menubar=new MenuBar();
menu=new Menu(“文件”);
item1=new MenuItem(“打开”);
item2=new MenuItem(“保存”);
menu.add(item1);
menu.add(item2);
menubar.add(menu);
setMenuBar(menubar);
setVisible(true);
}
}
public class Example7_1
{ public static void main(String args[])
{ FirstWindow win=new FirstWindow(“一个带菜单的窗口”);
}
}
例子2
import java.awt.
;
class WindowText extends Frame
{ TextField text1,text2;
WindowText(String s)
{ super(s);
setLayout(new FlowLayout());
text1=new TextField(“输入密码:”,10);
text1.setEditable(false);
text2=new TextField(10);
text2.setEchoChar(’’);
add(text1);
add(text2);
setBounds(100,100,200,150);
setVisible(true);
validate();
}
}
public class Example7_2
{ public static void main(String args[])
{ WindowText win=new WindowText(“添加了文本框的窗口”);
}
}
例子3
import java.awt.
;
import java.awt.event.;
class MyWindow extends Frame implements ActionListener
{ TextField text1,text2,text3;
MyWindow()
{ setLayout(new FlowLayout());
text1=new TextField(8);
text2=new TextField(8);
text3=new TextField(15);
add(text1);
add(text2);
add(text3);
text1.addActionListener(this);
text2.addActionListener(this);
setBounds(100,100,150,150);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==text1)
{ String word=text1.getText();
if(word.equals(“boy”))
{ text3.setText(“男孩”);
}
else if (word.equals(“girl”))
{ text3.setText(“女孩”);
}
else if (word.equals(“sun”))
{ text3.setText(“太阳”);
}
else
{ text3.setText(“没有该单词”);
}
}
else if(e.getSource()==text2)
{ String word=text2.getText();
if(word.equals(“男孩”))
{ text3.setText(“boy”);
}
else if (word.equals(“女孩”))
{ text3.setText(“girl”);
}
else if (word.equals(“太阳”))
{ text3.setText(“sun”);
}
else
{ text3.setText(“没有该单词”);
}
}
}
}
public class Example7_3
{ public static void main(String args[])
{ MyWindow win=new MyWindow();
}
}
例子4
import java.awt.
;
import java.awt.event.;
class YourWindow extends Frame implements ActionListener
{ TextField text1,text2;
PoliceMan police;
YourWindow()
{ text1=new TextField(10);
text2=new TextField(10);
police=new PoliceMan();
setLayout(new FlowLayout());
add(text1);
add(text2);
text1.addActionListener(this);
text1.addActionListener(police);
setBounds(100,100,150,150);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{ String number=e.getActionCommand();
int n=Integer.parseInt(number);
int m=n
n;
text2.setText(n+“的平方是:”+m);
}
}
class PoliceMan implements ActionListener
{ public void actionPerformed(ActionEvent e)
{ String number=e.getActionCommand();
int n=Integer.parseInt(number);
int m=nnn;
System.out.println(n+“的立方是:”+m);
}
}
public class Example7_4
{ public static void main(String args[])
{ YourWindow win=new YourWindow();
}
}
例子5
import java.awt.;
import java.awt.event.
;
public class Example7_5
{ public static void main(String args[])
{ HisWindow win=new HisWindow();
}
}
class HisWindow extends Frame
{ TextField text1,text2,text3;
HisWindow()
{ text1=new TextField(10);
text2=new TextField(10);
text3=new TextField(10);
setLayout(new FlowLayout());
add(text1);
add(text2);
add(text3);
PoliceMan police=new PoliceMan();
text1.addActionListener(police);//内部类的实例做监视器
text1.addActionListener(new ActionListener()
{ //和接口有关的匿名类的实例做监视器
public void actionPerformed(ActionEvent e)
{ String number=e.getActionCommand();
int n=Integer.parseInt(number);
int m=nn;
text2.setText(n+“的平方是:”+m);
}
}
);
setBounds(100,100,150,150);
setVisible(true);
validate();
}
class PoliceMan implements ActionListener //内部类
{ public void actionPerformed(ActionEvent e)
{ String number=e.getActionCommand();
int n=Integer.parseInt(number);
int m=n
nn;
text3.setText(n+“的立方是:”+m);
}
}
}
例子6
import java.awt.
;
import java.awt.event.;
class WindowButton extends Frame
implements ActionListener
{ int number;
Label 提示条;
TextField 输入框;
Button buttonGetNumber,buttonEnter;
WindowButton(String s)
{ super(s);
setLayout(new FlowLayout());
buttonGetNumber=new Button(“得到一个随机数”);
add(buttonGetNumber);
提示条=new Label(“输入你的猜测:”,Label.CENTER);
提示条.setBackground(Color.cyan);
输入框=new TextField(“0”,10);
add(提示条);
add(输入框);
buttonEnter=new Button(“确定”);
add(buttonEnter);
buttonEnter.addActionListener(this);
buttonGetNumber.addActionListener(this);
setBounds(100,100,150,150);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==buttonGetNumber)
{ number=(int)(Math.random()100)+1;
提示条.setText(“输入你的猜测:”);
}
else if(e.getSource()buttonEnter)
{ int guess=0;
try { guess=Integer.parseInt(输入框.getText());
if(guess
number)
{ 提示条.setText(“猜对了!”);
}
else if(guess>number)
{ 提示条.setText(“猜大了!”);
输入框.setText(null);
}
else if(guess<number)
{ 提示条.setText(“猜小了!”);
输入框.setText(null);
}
}
catch(NumberFormatException event)
{ 提示条.setText(“请输入数字字符”);
}
}
}
}
public class Example7_6
{ public static void main(String args[])
{ WindowButton win=new WindowButton(“窗口”);
}
}
例子7
import java.awt.
;
import java.awt.event.
;
class MyButton extends Button
implements ActionListener
{ String name;
TextField text;
Container con;
MyButton(String s,Container con)
{ super(s);
this.con=con;
text=new TextField(8);
text.addActionListener(this);
this.addActionListener(this);
con.add(text);
con.add(this);
}
public void actionPerformed(ActionEvent e)
{ name=text.getText();
this.setLabel(name);
con.validate();
}
}
class WindowOk extends Frame
{ MyButton button;
WindowOk()
{ setLayout(new FlowLayout());
button=new MyButton(“确定”,this);
setBounds(100,100,150,150);
setVisible(true);
validate();
}
}
public class Example7_7
{ public static void main(String args[])
{ WindowOk win=new WindowOk();
}
}

例子8
import java.awt.;
import java.awt.event.
;
class WindowExit extends Frame
implements ActionListener
{ MenuBar menubar;
Menu menu;
MenuItem itemExit;
WindowExit()
{ menubar=new MenuBar();
menu=new Menu(“文件”);
itemExit=new MenuItem(“退出”);
itemExit.setShortcut(new MenuShortcut(KeyEvent.VK_E));
menu.add(itemExit);
menubar.add(menu);
setMenuBar(menubar);
itemExit.addActionListener(this);
setBounds(100,100,150,150);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{ System.exit(0);
}
}
public class Example7_8
{ public static void main(String args[])
{ WindowExit win=new WindowExit();
}
}
例子9
import java.awt.;
import java.awt.event.
;
import java.util.;
class WindowTextArea extends Frame implements TextListener,ActionListener
{ TextArea text1,text2;
Button buttonClear;
WindowTextArea()
{ setLayout(new FlowLayout());
text1=new TextArea(6,15);
text2=new TextArea(6,15);
buttonClear=new Button(“清空”);
add(text1);
add(text2);
add(buttonClear);
text2.setEditable(false);
text1.addTextListener(this);
buttonClear.addActionListener(this);
setBounds(100,100,350,160);
setVisible(true);
validate();
}
public void textValueChanged(TextEvent e)
{ String s=text1.getText();
StringTokenizer fenxi=new StringTokenizer(s," ,’\n’");
int n=fenxi.countTokens();
String a[]=new String[n];
for(int i=0;i<=n-1;i++)
{ String temp=fenxi.nextToken();
a[i]=temp;
}
Arrays.sort(a);
text2.setText(null);
for(int i=0;i<n;i++)
{ text2.append(a[i]+"\n");
}
}
public void actionPerformed(ActionEvent e)
{ text1.setText(null);
}
}
public class Example7_9
{ public static void main(String args[])
{ WindowTextArea win=new WindowTextArea();
}
}
例子10
import java.awt.
;
import java.awt.event.;
class Mypanel extends Panel
implements ActionListener
{ Button button1,button2;
Color backColor;
Mypanel()
{ button1=new Button(“确定”);
button2=new Button(“取消”);
add(button1);
add(button2);
setBackground(Color.pink);
backColor=getBackground();
button1.addActionListener(this);
button2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==button1)
{ setBackground(Color.cyan);
}
else if(e.getSource()==button2)
{ setBackground(backColor);
}
}
}
class WindowPanel extends Frame implements ActionListener
{ Mypanel panel1,panel2;
Button button;
WindowPanel()
{ setLayout(new FlowLayout());
panel1=new Mypanel();
panel2=new Mypanel();
button=new Button(“退出”);
add(panel1);
add(panel2);
add(button);
button.addActionListener(this);
setBounds(60,60,200,200);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{ System.exit(0);
}
}
public class Example7_10
{ public static void main(String args[])
{ new WindowPanel();
}
}
例子11
import java.awt.
;
import java.awt.event.*;
class WindoTen extends Frame
implements ActionListener
{ Panel p;
ScrollPane scrollpane;
WindoTen()
{ setLayout(new FlowLayout());
p=new Panel();
scrollpane=new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS);
p.add(new Button(“one”));
p.add(new Button(“two”));
p.add(new Button(“three”));
p.add(new Button(“four”));
scrollpane.add§;
add(scrollpane);
setBounds(60,60,200,200);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{ System.exit(0);
}
}
public class Example7_11
{ public static void main(String args[])
{ new WindoTen();
}
}

例子12
import java.awt.;
class WindowFlow extends Frame
{ WindowFlow(String s)
{ super(s);
FlowLayout flow=new FlowLayout();
flow.setAlignment(FlowLayout.LEFT);
flow.setHgap(2);
flow.setVgap(8);
setLayout(flow);
for(int i=1;i<=10;i++)
{ Button b=new Button("i am "+i);
add(b);
}
setBounds(100,100,150,120);
setVisible(true);
}
}
public class Example7_12
{ public static void main(String args[])
{ WindowFlow win=new WindowFlow(“FlowLayout布局窗口”);
}
}
例子13
import java.awt.
;
class Example7_13
{ public static void main(String args[])
{ Frame win=new Frame(“窗体”);
win.setBounds(100,100,300,300);
win.setVisible(true);
Button bSouth=new Button(“我在南边”),
bNorth=new Button(“我在北边”),
bEast =new Button(“我在东边”),
bWest =new Button(“我在西边”);
TextArea bCenter=new TextArea(“我在中心”);
win.add(bNorth,BorderLayout.NORTH);
win.add(bSouth,BorderLayout.SOUTH);
win.add(bEast,BorderLayout.EAST);
win.add(bWest,BorderLayout.WEST);
win.add(bCenter,BorderLayout.CENTER);
win.validate();
}
}
例子14
import java.awt.;
import java.awt.event.
;
class WinCard extends Frame implements ActionListener
{ CardLayout mycard;
Button buttonFirst,buttonLast,buttonNext;
Panel pCenter;
WinCard()
{ mycard=new CardLayout();
pCenter=new Panel();
pCenter.setLayout(mycard);
buttonFirst=new Button(“first”);
buttonLast=new Button(“last”);
buttonNext=new Button(“next”);
for(int i=1;i<=20;i++)
{ pCenter.add(“i am”+i,new Button(“我是第 “+i+” 个按钮”));
}
buttonFirst.addActionListener(this);
buttonLast.addActionListener(this);
buttonNext.addActionListener(this);
Panel pSouth=new Panel();
pSouth.add(buttonFirst);
pSouth.add(buttonNext);
pSouth.add(buttonLast);
add(pCenter,BorderLayout.CENTER);
add(pSouth,BorderLayout.SOUTH);
setBounds(10,10,200,190);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==buttonFirst)
{ mycard.first(pCenter);
}
else if(e.getSource()==buttonNext)
{ mycard.next(pCenter);
}
else if(e.getSource()==buttonLast)
{ mycard.last(pCenter);
}
}
}
public class Example7_14
{ public static void main(String args[])
{ new WinCard();
}
}

例子15
import java.awt.;
import java.awt.event.
;
class WinGrid extends Frame
{ GridLayout grid;
WinGrid()
{ grid=new GridLayout(12,12);
setLayout(grid);
Label label[][]=new Label[12][12];
for(int i=0;i<12;i++)
{ for(int j=0;j<12;j++)
{ label[i][j]=new Label();
if((i+j)%20)
label[i][j].setBackground(Color.black);
else
label[i][j].setBackground(Color.white);
add(label[i][j]);
}
}
setBounds(10,10,260,260);
setVisible(true);
validate();
}
}
public class Example7_15
{ public static void main(String args[])
{ new WinGrid();
}
}
例子16
import javax.swing.;
import java.awt.
;
import javax.swing.border.;
public class Example7_16
{ public static void main(String args[])
{ new WindowBox();
}
}
class WindowBox extends Frame
{ Box baseBox ,boxV1,boxV2;
WindowBox()
{ boxV1=Box.createVerticalBox();
boxV1.add(new Label(“姓名”));
boxV1.add(Box.createVerticalStrut(8));
boxV1.add(new Label(“email”));
boxV1.add(Box.createVerticalStrut(8));
boxV1.add(new Label(“职业”));
boxV2=Box.createVerticalBox();
boxV2.add(new TextField(12));
boxV2.add(Box.createVerticalStrut(8));
boxV2.add(new TextField(12));
boxV2.add(Box.createVerticalStrut(8));
boxV2.add(new TextField(12));
baseBox=Box.createHorizontalBox();
baseBox.add(boxV1);
baseBox.add(Box.createHorizontalStrut(10));
baseBox.add(boxV2);
setLayout(new FlowLayout());
add(baseBox);
setBounds(120,125,250,150);
setVisible(true);
}
}
例子17
import java.awt.
;
import java.awt.event.*;
class WindowNull extends Frame
{ WindowNull()
{ setLayout(null);
MyButton button=new MyButton();
Panel p=new Panel();
p.setLayout(null);
p.setBackground(Color.cyan);
p.add(button);
button.setBounds(20,10,25,70);
add§;
p.setBounds(50,50,90,100);
setBounds(120,125,200,200);
setVisible(true);
}
}
class MyButton extends Button implements ActionListener
{ int n=-1;
MyButton()
{ addActionListener(this);
}
public void paint(Graphics g)
{ g.drawString(“单”,6,16);
g.drawString(“击”,6,36);
g.drawString(“我”,6,56);
}
public void actionPerformed(ActionEvent e)
{ n=(n+1)%3;
if(n
0)
setBackground(Color.red);
else if(n1)
setBackground(Color.yellow);
else if(n
2)
setBackground(Color.green);
}
}
public class E
{ public static void main(String args[])
{ new WindowNull();
}
}
例子18
import java.awt.;
import java.awt.event.
;
class Mycanvas extends Canvas
{ int x,y,r;
Mycanvas()
{ setBackground(Color.cyan);
}
public void setX(int x)
{ this.x=x;
}
public void setY(int y)
{ this.y=y;
}
public void setR(int r)
{ this.r=r;
}
public void paint(Graphics g)
{ g.drawOval(x,y,2r,2r);
}
}
class WindowCanvas extends Frame implements ActionListener
{ Mycanvas canvas;
TextField inputR,inputX,inputY;
Button b;
WindowCanvas()
{ canvas=new Mycanvas();
inputR=new TextField(5);
inputX=new TextField(4);
inputY=new TextField(4);
Panel pNorth=new Panel(),
pSouth=new Panel();
pNorth.add(new Label(“圆的位置坐标:”));
pNorth.add(inputX);
pNorth.add(inputY);
pSouth.add(new Label(“圆的半径:”));
pSouth.add(inputR);
b=new Button(“确定”);
b.addActionListener(this);
pSouth.add(b);
add(canvas,BorderLayout.CENTER);
add(pNorth,BorderLayout.NORTH);
add(pSouth,BorderLayout.SOUTH);
setBounds(100,100,300,200);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ int x,y,r;
try { x=Integer.parseInt(inputX.getText());
y=Integer.parseInt(inputY.getText());
r=Integer.parseInt(inputR.getText());
canvas.setX(x);
canvas.setY(y);
canvas.setR®;
canvas.repaint();
}
catch(NumberFormatException ee)
{ x=0;y=0;r=0;
}
}
}
public class Example7_18
{ public static void main(String args[])
{ new WindowCanvas();
}
}
例子19
import java.awt.;
import java.awt.event.
;
class Mypanel1 extends Panel implements ItemListener
{ Checkbox box1,box2,box3;
CheckboxGroup sex;
TextArea text;
Mypanel1(TextArea text)
{ this.text=text;
sex=new CheckboxGroup();
box1=new Checkbox(“男”,true,sex);
box2=new Checkbox(“女”,false,sex);
box1.addItemListener(this);
box2.addItemListener(this);
add(box1);
add(box2);
}
public void itemStateChanged(ItemEvent e)
{ Checkbox box=(Checkbox)e.getSource();
if(box.getState())
{ int n=text.getCaretPosition();
text.insert(box.getLabel(),n);
}
}
}
class Mypanel2 extends Panel implements ItemListener
{ Checkbox box1,box2,box3;
TextArea text;
Mypanel2(TextArea text)
{ this.text=text;
box1=new Checkbox(“张三”);
box2=new Checkbox(“李四”);
box1.addItemListener(this);
box2.addItemListener(this);
add(box1);
add(box2);
}
public void itemStateChanged(ItemEvent e)
{ Checkbox box=(Checkbox)e.getItemSelectable();
if(box.getState())
{ int n=text.getCaretPosition();
text.insert(box.getLabel(),n);
}
}
}
class WindowBox extends Frame
{ Mypanel1 panel1;
Mypanel2 panel2;
TextArea text;
WindowBox()
{ text=new TextArea();
panel1=new Mypanel1(text);
panel2=new Mypanel2(text);
add(panel1,BorderLayout.SOUTH);
add(panel2,BorderLayout.NORTH);
add(text,BorderLayout.CENTER);
setSize(200,200);
setVisible(true);
validate();
}
}
public class Example7_19
{ public static void main(String args[])
{ new WindowBox();
}
}
例子20
import java.awt.;
import java.awt.event.
;
class WindowChoice extends Frame
implements ItemListener,ActionListener
{ Choice choice;
TextField text;
TextArea area;
Button add,del;
WindowChoice()
{ setLayout(new FlowLayout());
choice=new Choice();
text=new TextField(8);
area=new TextArea(6,25);
choice.add(“音乐天地”);
choice.add(“武术天地”);
choice.add(“象棋乐园”);
choice.add(“交友聊天”);
add=new Button(“添加”);
del=new Button(“删除”);
add.addActionListener(this);
text.addActionListener(this);
del.addActionListener(this);
choice.addItemListener(this);
add(choice);
add(del);
add(text);
add(add);
add(area);
setSize(200,200);
setVisible(true);
validate();
}
public void itemStateChanged(ItemEvent e)
{ String name=choice.getSelectedItem();
int index=choice.getSelectedIndex();
area.setText("\n"+index+":"+name);
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==add||e.getSource()text)
{ String name=text.getText();
if(name.length()>0)
{ choice.add(name);
choice.select(name);
area.append("\n列表添加:"+name);
}
}
else if(e.getSource()del)
{ area.append("\n列表删除:"+choice.getSelectedItem());
choice.remove(choice.getSelectedIndex());
}
}
}
public class Example7_20
{ public static void main(String args[])
{ new WindowChoice();
}
}
例子21
import java.awt.;
import java.awt.event.
;
class WindowList extends Frame
implements ItemListener,ActionListener
{ List list1,list2;
TextArea text1,text2;
int index=0;
WindowList()
{ setLayout(new FlowLayout());
list1=new List(3,false);
list2=new List(3,false);
text1=new TextArea(2,20);
text2=new TextArea(2,20);
list1.add(“计算1+2+…”);
list1.add(“计算11+22+…”);
list1.add(“计算111+222+…”);
for(int i=1;i<=100;i++)
{ list2.add(“前”+i+“项和”);
}
add(list1);
add(list2);
add(text1);
add(text2);
list1.addItemListener(this);
list2.addActionListener(this);
setSize(400,200);
setVisible(true);
validate();
}
public void itemStateChanged(ItemEvent e)
{ if(e.getItemSelectable()list1)
{ text1.setText(list1.getSelectedItem());
index=list1.getSelectedIndex();
}
}
public void actionPerformed(ActionEvent e)
{ int n=list2.getSelectedIndex(),sum=0;
String name=list2.getSelectedItem();
switch(index)
{ case 0:
for(int i=1;i<=n+1;i++)
{ sum=sum+i;
}
break;
case 1:
for(int i=1;i<=n+1;i++)
{ sum=sum+ii;
}
break;
case 2:
for(int i=1;i<=n+1;i++)
{ sum=sum+i
ii;
}
break;
default :
sum=-100;
}
text2.setText(name+“等于”+sum);
}
}
public class Example7_21
{ public static void main(String args[])
{ new WindowList();
}
}
例子22
import java.awt.
;
import java.awt.event.;
import javax.swing.JTextArea;
class Win extends Frame
implements ItemListener
{ Choice list;
JTextArea text;
Win()
{ list=new Choice();
text=new JTextArea();
text.setForeground(Color.blue);
GraphicsEnvironment ge=
GraphicsEnvironment.getLocalGraphicsEnvironment();
String fontName[]=ge.getAvailableFontFamilyNames();
for(int i=0;i<fontName.length;i++)
{ list.add(fontName[i]);
}
add(list,BorderLayout.NORTH);
add(text,BorderLayout.CENTER);
text.setForeground(Color.green);
list.addItemListener(this);
setVisible(true);
setBounds(100,120,300,300);
validate();
}
public void itemStateChanged(ItemEvent e)
{ String name=list.getSelectedItem();
Font f=new Font(name,Font.BOLD,32);
text.setFont(f);
text.setText("\nWelcome 欢迎");
}
}
public class Example7_22
{ public static void main(String args[])
{ Win win=new Win();
}
}
例子23
import java.awt.
;
import java.awt.event.;
class MyWin extends Frame
implements ActionListener
{ Button button;
Label label;
MyWin()
{
setLayout(null);
Cursor c=Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
setCursor©;
button=new Button(“横向走动”);
button.setBackground(Color.pink);
button.addActionListener(this);
label=new Label(“我可以被碰掉”,Label.CENTER);
label.setBackground(Color.yellow);
button.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
add(button);
add(label);
button.setBounds(20,80,80,20);
label.setBounds(150,80,80,20);
setVisible(true);
setBounds(100,120,300,300);
validate();
}
public void actionPerformed(ActionEvent e)
{ Rectangle rect=button.getBounds();
int x=(int)rect.getX();
int y=(int)rect.getY();
if(rect.intersects(label.getBounds()))
{ label.setVisible(false);
}
if(label.isVisible())
{ x=x+2;
button.setLocation(x,y);
}
else
{ y=y+3;
button.setLocation(x,y);
button.setLabel(“纵向走动”);
}
}
}
public class Example7_23
{ public static void main(String args[])
{ MyWin win=new MyWin();
}
}
例子24
import java.awt.
;
import java.awt.event.;
class MyButton extends Button
implements ActionListener
{ int x=10,y=10,i=0;
Color color[]={Color.red,Color.yellow,Color.green};
Color c=color[0];
MyButton()
{ setSize(38,85);
setBackground(Color.cyan);
addActionListener(this);
}
public void paint(Graphics g)
{ g.setColor©;
g.fillOval(x,y,20,20);
}
public void update(Graphics g)
{ g.clearRect(x,y,20,20);
paint(g);
}
public void actionPerformed(ActionEvent e)
{ i=(i+1)%3;
c=color[i];
y=y+23;
if(y>56)
y=10;
repaint();
}
}
class WindowCanvas extends Frame
{ WindowCanvas()
{ MyButton button=new MyButton();
setLayout(null);
add(button);
button.setLocation(30,30);
setBounds(60,125,100,200);
setVisible(true);
validate();
}
}
public class Example7_24
{ public static void main(String args[])
{ new WindowCanvas();
}
}
例子25
import java.awt.
;
import java.awt.event.;
class MyFrame extends Frame
implements WindowListener
{ TextArea text;
MyFrame()
{ setBounds(100,100,200,300);
setVisible(true);
text=new TextArea();
add(text,BorderLayout.CENTER);
addWindowListener(this);
validate();
}
public void windowActivated(WindowEvent e)
{ text.append("\n我被激活");
validate();
}
public void windowDeactivated(WindowEvent e)
{ text.append("\n我不是激活状态了");
setBounds(0,0,400,400);
validate();
}
public void windowClosing(WindowEvent e)
{ text.append("\n窗口正在关闭呢");
dispose();
}
public void windowClosed(WindowEvent e)
{ System.out.println(“程序结束运行”);
System.exit(0);
}
public void windowIconified(WindowEvent e)
{ text.append("\n我图标化了");
}
public void windowDeiconified(WindowEvent e)
{ text.append("\n我撤消图标化");
setBounds(0,0,400,400);
validate();
}
public void windowOpened(WindowEvent e){}
}
public class Example7_25
{ public static void main(String args[])
{ new MyFrame();
}
}
例子26
import java.awt.
;
import java.awt.event.;
class MyFrame extends Frame
{ TextArea text;
Boy police;
MyFrame(String s)
{ super(s);
police=new Boy(this);
setBounds(100,100,200,300);
setVisible(true);
text=new TextArea();
add(text,BorderLayout.CENTER);
addWindowListener(police);
validate();
}
}
class Boy extends WindowAdapter
{ MyFrame f;
public Boy(MyFrame f)
{ this.f=f;
}
public void windowActivated(WindowEvent e)
{ f.text.append("\n我被激活");
}
public void windowClosing(WindowEvent e)
{ System.exit(0);
}
}
public class Example7_26
{ public static void main(String args[])
{ new MyFrame(“窗口”);
}
}
例子27
import java.awt.
;
mport java.awt.event.;
class MyFrame extends Frame
{ TextArea text;
MyFrame(String s)
{ super(s);
setBounds(100,100,200,300);
setVisible(true);
text=new TextArea(); add(text,BorderLayout.CENTER);
addWindowListener(new WindowAdapter()
{ public void windowActivated(WindowEvent e)
{ text.append("\n我被激活");
}
public void windowClosing(WindowEvent e)
{ System.exit(0);
}
}
);
validate();
}
}
public class Example7_27
{ public static void main(String args[])
{ new MyFrame(“窗口”);
}
}
例子28
import java.awt.
;
import java.awt.event.;
class WindowMouse extends Frame
implements MouseListener
{ TextField text;
Button button;
TextArea textArea;
WindowMouse()
{ setLayout(new FlowLayout());
text=new TextField(10);
text.addMouseListener(this);
button=new Button(“按钮”);
button.addMouseListener(this);
addMouseListener(this);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
}
);
textArea=new TextArea(5,28);
add(button);
add(text);
add(textArea);
setBounds(100,100,220,120);
setVisible(true);
}
public void mousePressed(MouseEvent e)
{ textArea.append("\n鼠标按下,位置:"+"("+e.getX()+","+e.getY()+")");
}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e)
{ if(e.getClickCount()>=2)
textArea.setText(“鼠标连击,位置:”+"("+e.getX()+","+e.getY()+")");
}
}
public class Example7_28
{ public static void main(String args[])
{ new WindowMouse();
}
}
例子29
import java.awt.
;
import java.awt.event.*;
class MyCanvas extends Canvas
implements MouseListener
{ int left=-1,right=-1;
int x=-1,y=-1;
MyCanvas()
{ setBackground(Color.cyan) ;
addMouseListener(this);
}
public void paint(Graphics g)
{ if(left
1)
{ g.drawOval(x-10,y-10,20,20);
}
else if(right
1)
{ g.drawRect(x-8,y-8,16,16);
}
}
public void mousePressed(MouseEvent e)
{ x=e.getX();
y=e.getY();
if(e.getModifiers()InputEvent.BUTTON1_MASK)
{ left=1;
right=-1;
repaint();
}
else if(e.getModifiers()InputEvent.BUTTON3_MASK)
{ right=1;
left=-1;
repaint();
}
}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e)
{ left=-1;
right=-1;
repaint();
}
public void mouseClicked(MouseEvent e){}
public void update(Graphics g)
{ if(left
1||right
1)
{ paint(g);
}
else
{ super.update(g);
}
}
}
public class Example7_29
{ public static void main(String args[])
{ Frame f=new Frame();
f.setBounds(100,100,200,200);f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
f.add(new MyCanvas(),BorderLayout.CENTER);
f.validate();
}
}
例子30
import java.awt.;
import java.awt.event.
;
import javax.swing.SwingUtilities;
class Win extends Frame implements MouseListener,MouseMotionListener
{ Button button;
TextField text;
int x,y;
boolean move=false;
Win()
{ button=new Button(“用鼠标拖动我”);
text=new TextField(“用鼠标拖动我”,8);
button.addMouseListener(this);
button.addMouseMotionListener(this);
text.addMouseListener(this);
text.addMouseMotionListener(this);
addMouseMotionListener(this);
setLayout(new FlowLayout());
add(button);
add(text);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
setBounds(10,10,350,300);
setVisible(true);
validate();
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e)
{
move=false;
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e){}
public void mouseMoved(MouseEvent e){}
public void mouseDragged(MouseEvent e)
{ Component com=null;
if(e.getSource() instanceof Component)
{ com=(Component)e.getSource();
if(com!=this)
move=true;
e=SwingUtilities.convertMouseEvent(com,e,this);
if(move)
{ x=e.getX();
y=e.getY();
int w=com.getSize().width,
h=com.getSize().height;
com.setLocation(x-w/2,y-h/2);
}
}
}
}
public class Example7_30
{ public static void main(String args[])
{ Win win=new Win();
}
}
例子31
import java.awt.;
import java.awt.event.
;
class Win extends Frame implements MouseListener,MouseMotionListener
{ Button button;
TextField text;
int x,y,a,b,x0,y0;
Win()
{ button=new Button(“用鼠标拖动我”);
text=new TextField(“用鼠标拖动我”,8);
button.addMouseListener(this);
button.addMouseMotionListener(this);
text.addMouseListener(this);
text.addMouseMotionListener(this);
setLayout(new FlowLayout());
add(text);
add(button);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
setBounds(10,10,350,300);
setVisible(true);
validate();
}
public void mousePressed(MouseEvent e)
{ Component com=null;
com=(Component)e.getSource();
a=com.getBounds().x;
b=com.getBounds().y;
x0=e.getX();
y0=e.getY();
}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e){}
public void mouseMoved(MouseEvent e){}
public void mouseDragged(MouseEvent e)
{ Component com=null;
if(e.getSource() instanceof Component)
{ com=(Component)e.getSource();
a=com.getBounds().x;
b=com.getBounds().y;
x=e.getX();
y=e.getY();
a=a+x;
b=b+y;
com.setLocation(a-x0,b-y0);
}
}
}
public class Example7_31
{ public static void main(String args[])
{ Win win=new Win();
}
}
例子32
import java.awt.;
import java.awt.event.
;
class MyWindow extends Frame implements FocusListener
{ TextField text;
Button button;
MyWindow(String s)
{ super(s);
text=new TextField(10);
button=new Button(“按钮”);
text.requestFocusInWindow();
setLayout(new FlowLayout());
add(text);
add(button);
text.addFocusListener(this);
button.addFocusListener(this);
setBounds(100,100,150,150);
setVisible(true);
validate();
}
public void focusGained(FocusEvent e)
{ Component com=(Component)e.getSource();
com.setBackground(Color.blue);
if(com
text)
text.setText(null);
}
public void focusLost(FocusEvent e)
{ Component com=(Component)e.getSource();
com.setBackground(Color.red);
}
}
public class Example7_32
{ public static void main(String args[])
{ MyWindow win=new MyWindow(“窗口”);
}
}
例子33
import java.awt.;
import java.awt.event.
;
class Win extends Frame implements KeyListener
{ Button b[]=new Button[8];
int x,y;
Win()
{ setLayout(new FlowLayout());
for(int i=0;i<8;i++)
{ b[i]=new Button(""+i);
b[i].addKeyListener(this);
add(b[i]);
}
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
setBounds(10,10,300,300);
setVisible(true);
validate();
}
public void keyPressed(KeyEvent e)
{ Button button=(Button)e.getSource();
x=button.getBounds().x;
y=button.getBounds().y;
if(e.getKeyCode()==KeyEvent.VK_UP)
{ y=y-2;
if(y<=0) y=0;
button.setLocation(x,y);
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN)
{ y=y+2;
if(y>=300) y=300;
button.setLocation(x,y);
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT)
{ x=x-2;
if(x<=0) x=0;
button.setLocation(x,y);
}
else if(e.getKeyCode()KeyEvent.VK_RIGHT)
{ x=x+2;
if(x>=300) x=300;
button.setLocation(x,y);
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
public class Example7_33
{ public static void main(String args[])
{ Win win=new Win();
}
}
例子34
import java.awt.;
import java.awt.event.
;
class Win extends Frame implements KeyListener
{ Button b;
Win()
{ setLayout(new FlowLayout());
b=new Button(“我是一个按钮,”);
b.addKeyListener(this);
add(b);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
setBounds(10,10,300,300);
setVisible(true);
validate();
}
public void keyPressed(KeyEvent e)
{ Button button=(Button)e.getSource();
int x=0,y=0,w=0,h=0;
x=button.getBounds().x;
y=button.getBounds().y;
w=button.getBounds().width;
h=button.getBounds().height;
if(e.getModifiers()InputEvent.SHIFT_MASK&&e.getKeyCode()KeyEvent.VK_X)
{ button.setLocation(y,x);
}
else if(e.getModifiers()InputEvent.CTRL_MASK&&e.getKeyCode()KeyEvent.VK_X)
{ button.setSize(h,w);
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
public class Example7_34
{ public static void main(String args[])
{ Win win=new Win();
}
}
例子35
import java.awt.;
import java.awt.event.
;
class Win extends Frame
implements KeyListener, FocusListener
{ TextField text[]=new TextField[3];
Win()
{ addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
setLayout(new FlowLayout());
for(int i=0;i<3;i++)
{ text[i]=new TextField(7);
text[i].addKeyListener(this);
text[i].addFocusListener(this);
add(text[i]);
}
text[0].requestFocusInWindow();
setBounds(10,10,300,300);
setVisible(true);
validate();
}
public void keyPressed(KeyEvent e)
{ TextField text=(TextField)e.getSource();
if(text.getCaretPosition()>=6)
{ text.transferFocus();
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void focusGained(FocusEvent e)
{ TextField text=(TextField)e.getSource();
text.setText(null);
}
public void focusLost(FocusEvent e){}
}
public class Example7_35
{ public static void main(String args[])
{ Win win=new Win();
}
}
例子36
import java.awt.;
import java.awt.event.
;
import java.awt.datatransfer.;
class Win extends Frame implements ActionListener
{ MenuBar menubar;
Menu menu;
MenuItem copy,cut,paste;
TextArea text1,text2;
Clipboard clipboard=null;
Win()
{ clipboard=getToolkit().getSystemClipboard();
menubar=new MenuBar();
menu=new Menu(“Edit”);
copy=new MenuItem(“copy”);
cut=new MenuItem (“cut”);
paste=new MenuItem (“paste”);
text1=new TextArea(10,20);
text2=new TextArea(10,20);
copy.addActionListener(this);
cut.addActionListener(this);
paste.addActionListener(this);
setLayout(new FlowLayout());
menubar.add(menu);
menu.add(copy);
menu.add(cut);
menu.add(paste);
setMenuBar(menubar);
add(text1);
add(text2);
setBounds(100,100,400,350);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==copy)
{ String temp=text1.getSelectedText();
StringSelection text=new StringSelection(temp);
clipboard.setContents(text,null);
}
else if(e.getSource()==cut)
{ String temp=text1.getSelectedText();
StringSelection text=new StringSelection(temp);
clipboard.setContents(text,null);
int start=text1.getSelectionStart();
int end =text1.getSelectionEnd();
text1.replaceRange("",start,end) ;
}
else if(e.getSource()==paste)
{ Transferable contents=clipboard.getContents(this);
DataFlavor flavor= DataFlavor.stringFlavor;
if( contents.isDataFlavorSupported(flavor))
try{ String str;
str=(String)contents.getTransferData(flavor);
text2.append(str);
}
catch(Exception ee){}
}
}
}
public class Example7_36
{ public static void main(String args[])
{ Win win=new Win ();
}
}
例子37
import java.awt.
;import java.awt.event.;
public class Example7_37
{ public static void main(String args[])
{ MyFrame f=new MyFrame();
f.setBounds(70,70,70,89);f.setVisible(true);f.validate();
}
}
class MyFrame extends Frame implements ActionListener
{ PrintJob p=null; //声明一个PrintJob对象。
Graphics g=null;
TextArea text=new TextArea(10,10);
Button 打印文本框=new Button(“打印文本框”),
打印窗口=new Button(“打印窗口”),
打印按扭=new Button(“打印按扭”);
MyFrame()
{ super(“在应用程序中打印”);
打印文本框.addActionListener(this);
打印窗口.addActionListener(this);
打印按扭.addActionListener(this);
add(text,“Center”);
Panel panel=new Panel();
panel.add(打印文本框); panel.add(打印窗口); panel.add(打印按扭);
add(panel,“South”);
addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{System.exit(0); }
});
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==打印文本框)
{ p=getToolkit().getPrintJob(this,“ok”,null);
g=p.getGraphics();
g.translate(120,200);
text.printAll(g);
g.dispose();
p.end();
}
else if(e.getSource()==打印窗口)
{ p=getToolkit().getPrintJob(this,“ok”,null);
g=p.getGraphics();
g.translate(120,200);
this.printAll(g);
g.dispose();
p.end();
}
else if(e.getSource()==打印按扭)
{ p=getToolkit().getPrintJob(this,“ok”,null);
g=p.getGraphics();
g.translate(120,200);
打印文本框.printAll(g);
g.translate(78,0);
打印窗口.printAll(g);
g.translate(66,0);
打印按扭.printAll(g);
g.dispose();
p.end();
}
}
}
例子38
import java.awt.
;
import java.awt.event.;
class ChessPad extends Panel implements MouseListener,ActionListener
{ int x=-1,y=-1, 棋子颜色=1;
Button button=new Button(“重新开局”);
TextField text_1=new TextField(“请黑棋下子”),
text_2=new TextField();
ChessPad()
{ setSize(440,440);
setLayout(null);setBackground(Color.orange);
addMouseListener(this);add(button);button.setBounds(10,5,60,26);
button.addActionListener(this);
add(text_1);text_1.setBounds(90,5,90,24);
add(text_2);text_2.setBounds(290,5,90,24);
text_1.setEditable(false);text_2.setEditable(false);
}
public void paint(Graphics g)
{ for(int i=40;i<=380;i=i+20)
{ g.drawLine(40,i,400,i);
}
g.drawLine(40,400,400,400);
for(int j=40;j<=380;j=j+20)
{ g.drawLine(j,40,j,400);
}
g.drawLine(400,40,400,400);
g.fillOval(97,97,6,6); g.fillOval(337,97,6,6);
g.fillOval(97,337,6,6);g.fillOval(337,337,6,6);
g.fillOval(217,217,6,6);
}
public void mousePressed(MouseEvent e)
{ if(e.getModifiers()InputEvent.BUTTON1_MASK)
{ x=(int)e.getX();y=(int)e.getY();
ChessPoint_black chesspoint_black=new ChessPoint_black(this);
ChessPoint_white chesspoint_white=new ChessPoint_white(this);
int a=(x+10)/20,b=(y+10)/20;
if(x/20<2||y/20<2||x/20>19||y/20>19)
{}
else
{
if(棋子颜色
1)
{ this.add(chesspoint_black);
chesspoint_black.setBounds(a
20-10,b20-10,20,20);
棋子颜色=棋子颜色
(-1);
text_2.setText(“请白棋下子”);
text_1.setText("");
}
else if(棋子颜色
-1)
{ this.add(chesspoint_white);
chesspoint_white.setBounds(a20-10,b20-10,20,20);
棋子颜色=棋子颜色*(-1);
text_1.setText(“请黑棋下子”);
text_2.setText("");
}
}
}
}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e){}
public void actionPerformed(ActionEvent e)
{ this.removeAll();棋子颜色=1;
add(button);button.setBounds(10,5,60,26);
add(text_1);text_1.setBounds(90,5,90,24);
text_2.setText("");text_1.setText(“请黑棋下子”);
add(text_2);text_2.setBounds(290,5,90,24);
}
}
class ChessPoint_black extends Canvas implements MouseListener
{ ChessPad chesspad=null;
ChessPoint_black(ChessPad p)
{ setSize(20,20);chesspad=p; addMouseListener(this);
}
public void paint(Graphics g)
{ g.setColor(Color.black);g.fillOval(0,0,20,20);
}
public void mousePressed(MouseEvent e)
{ if(e.getModifiers()InputEvent.BUTTON3_MASK)
{ chesspad.remove(this);
chesspad.棋子颜色=1;
chesspad.text_2.setText("");chesspad.text_1.setText(“请黑棋下子”);
}
}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e)
{ if(e.getClickCount()>=2)
chesspad.remove(this);
}
}
class ChessPoint_white extends Canvas implements MouseListener
{ ChessPad chesspad=null;
ChessPoint_white(ChessPad p)
{ setSize(20,20);addMouseListener(this);
chesspad=p;
}
public void paint(Graphics g)
{ g.setColor(Color.white);g.fillOval(0,0,20,20);
}
public void mousePressed(MouseEvent e)
{ if(e.getModifiers()InputEvent.BUTTON3_MASK)
{ chesspad.remove(this);chesspad.棋子颜色=-1;
chesspad.text_2.setText(“请白棋下子”); chesspad.text_1.setText("");
}
}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e)
{ if(e.getClickCount()>=2)
chesspad.remove(this);
}
}
public class Chess extends Frame
{ ChessPad chesspad=new ChessPad();
Chess()
{ setVisible(true);
setLayout(null);
Label label=
new Label(“单击左键下棋子,双击吃棋子,用右键单击棋子悔棋”,Label.CENTER);
add(label);label.setBounds(70,55,440,26);
label.setBackground(Color.orange);
add(chesspad);chesspad.setBounds(70,90,440,440);
addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{System.exit(0);
}
});
pack();setSize(600,550);
}
public static void main(String args[])
{ Chess chess=new Chess();
}
}
例子39
import java.awt.;
import java.awt.event.
;
public class MoveExample
{ public static void main(String args[])
{ new Hua_Rong_Road();
}
}
class Person extends Button
implements FocusListener
{ int number;
Color c=new Color(255,245,170);
Person(int number,String s)
{ super(s);
setBackground©;
this.number=number;
c=getBackground();
addFocusListener(this);
}
public void focusGained(FocusEvent e)
{ setBackground(Color.red);
}
public void focusLost(FocusEvent e)
{ setBackground©;
}
}
class Hua_Rong_Road extends Frame implements MouseListener,KeyListener,ActionListener
{ Person person[]=new Person[10];
Button left,right,above,below;
Button restart=new Button(“重新开始”);
public Hua_Rong_Road()
{ init();
setBounds(100,100,320,360);
setVisible(true);
validate();
addWindowListener( new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
}
);
}
public void init()
{ setLayout(null);
add(restart);
restart.setBounds(100,320,120,25);
restart.addActionListener(this);
String name[]={“曹操”,“关羽”,“张飞”,“刘备”,“周瑜”,“黄忠”,“兵”,“兵”,“兵”,“兵”};
for(int k=0;k<name.length;k++)
{ person[k]=new Person(k,name[k]);
person[k].addMouseListener(this);
person[k].addKeyListener(this);
add(person[k]);
}
person[0].setBounds(104,54,100,100);
person[1].setBounds(104,154,100,50);
person[2].setBounds(54, 154,50,100);
person[3].setBounds(204,154,50,100);
person[4].setBounds(54, 54, 50,100);
person[5].setBounds(204, 54, 50,100);
person[6].setBounds(54,254,50,50);
person[7].setBounds(204,254,50,50);
person[8].setBounds(104,204,50,50);
person[9].setBounds(154,204,50,50);
person[9].requestFocus();
left=new Button(); right=new Button();
above=new Button(); below=new Button();
add(left); add(right);
add(above); add(below);
left.setBounds(49,49,5,260);
right.setBounds(254,49,5,260);
above.setBounds(49,49,210,5);
below.setBounds(49,304,210,5);
validate();
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public void keyPressed(KeyEvent e)
{ Person man=(Person)e.getSource();
if(e.getKeyCode()KeyEvent.VK_DOWN)
{ go(man,below);
}
if(e.getKeyCode()KeyEvent.VK_UP)
{ go(man,above);
}
if(e.getKeyCode()KeyEvent.VK_LEFT)
{ go(man,left);
}
if(e.getKeyCode()KeyEvent.VK_RIGHT)
{ go(man,right);
}
}
public void mousePressed(MouseEvent e)
{ Person man=(Person)e.getSource();
int x=-1,y=-1;
x=e.getX();
y=e.getY();
int w=man.getBounds().width;
int h=man.getBounds().height;
if(y>h/2)
{ go(man,below);
}
if(y<h/2)
{ go(man,above);
}
if(x<w/2)
{ go(man,left);
}
if(x>w/2)
{ go(man,right);
}
}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void go(Person man,Button direction)
{ boolean move=true;
Rectangle manRect=man.getBounds();
int x=man.getBounds().x;
int y=man.getBounds().y;
if(direction
below)
y=y+50;
else if(direction
above)
y=y-50;
else if(direction
left)
x=x-50;
else if(direction
right)
x=x+50;
manRect.setLocation(x,y);
Rectangle directionRect=direction.getBounds();
for(int k=0;k<10;k++)
{ Rectangle personRect=person[k].getBounds();
if((manRect.intersects(personRect))&&(man.number!=k))
{ move=false;
}
}
if(manRect.intersects(directionRect))
{ move=false;
}
if(move
true)
{ man.setLocation(x,y);
}
}
public void actionPerformed(ActionEvent e)
{ dispose();
new Hua_Rong_Road();
}
}
例子40
Example7_40.java
import java.awt.;
import java.awt.event.
;
class SelectWindow extends Frame implements ActionListener
{ PersonSelected personSelected[]; //存放候选人的数组
InputPerson input; //输入界面
SelectPane select; //选举界面
ResultArea show; //查看结果界面
Button buttonInput,buttonSelect,buttonResult,reNew;
int max=3; //每张选票上可推选的最多人数
CardLayout card;
Panel center=new Panel(),
south=new Panel();
SelectWindow()
{ personSelected=new PersonSelected[1]; //数组的初始大小是1
for(int k=0;k<personSelected.length;k++)
{ personSelected[k]=new PersonSelected(“无名”,0);
}
card=new CardLayout();
center.setLayout(card);
input=new InputPerson(personSelected);
select=new SelectPane(personSelected,max); //每张选票上最多推选max 人
show=new ResultArea(personSelected);
center.add(“001”,new Label(“选票程序”,Label.CENTER));
center.add(“input”,input);
center.add(“select”,select);
center.add(“show”,show);
buttonInput=new Button(“输入候选人界面”);
buttonInput.addActionListener(this);
buttonSelect=new Button(“统计选票界面,最多选”+max+“人”);
buttonSelect.addActionListener(this);
buttonResult=new Button(“查看得票界面”);
buttonResult.addActionListener(this);
reNew=new Button(“重新选举”);
reNew.addActionListener(this);
south.add(buttonInput);
south.add(buttonSelect);
south.add(buttonResult);
south.add(reNew);
add(center,BorderLayout.CENTER);
add(south,BorderLayout.SOUTH);
setSize(450,200);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{ Button b=(Button)e.getSource();
setTitle(b.getLabel());
if(b
buttonInput)
{ card.show(center,“input”); //切换到输入界面,以便修改personSelected数组
buttonInput.setEnabled(false);
}
if(b
buttonSelect)
{ personSelected=input.getPersonSelected(); //得到被输入界面修改后的数组
select.setPersonSelected(personSelected);
select.init();
card.show(center,“select”);
}
if(b
buttonResult)
{ personSelected=select.getPersonSelected(); //得到被选举界面修改后的数组
show.setPersonSelected(personSelected);
card.show(center,“show”);
}
if(b
reNew)
{ personSelected=new PersonSelected[1]; //数组的初始大小是1
for(int k=0;k<personSelected.length;k++)
{ personSelected[k]=new PersonSelected(“无名”,0);
}
center.removeAll();
input=new InputPerson(personSelected);
select=new SelectPane(personSelected,3); //每张选票上最多推选3人
show=new ResultArea(personSelected);
center.add(“001”,new Label(“选票程序”,Label.CENTER));
center.add(“input”,input);
center.add(“select”,select);
center.add(“show”,show);
card.show(center,“001”);
buttonInput.setEnabled(true);
center.validate();
}
}
}
public class Example7_40
{ public static void main(String args[])
{ SelectWindow win=new SelectWindow();
win.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
PersonSelected.java
import java.awt.;
public class PersonSelected extends Panel
{ String name; //候选人的名字
int count; //得票数
Checkbox box; //代表候选人外观的组件
public PersonSelected(String name,int count)
{ this.name=name;
this.count=count;
box=new Checkbox();
add(box);
}
public void setName(String name)
{ this.name=name;
box.setLabel(name);
}
public String getName()
{ return name;
}
public void addCount()
{ count++;
}
public int getCount()
{ return count;
}
public Checkbox getBox()
{ return box;
}
}
InputPerson.java
import java.awt.
;
import java.awt.event.;
import java.util.StringTokenizer;
public class InputPerson extends Panel implements ActionListener
{ TextField inputPeopleName;
PersonSelected personSelected[]; //存放候选人的数组
Button button;
InputPerson(PersonSelected personSelected[])
{ this.personSelected=personSelected;
add(new Label(“输入侯选人名字,用逗号分隔”));
inputPeopleName=new TextField(16);
add(inputPeopleName);
button=new Button(“确定”);
add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{ String tempStr=inputPeopleName.getText();
if(tempStr.length()>0)
{ StringTokenizer token=new StringTokenizer(tempStr,",,");
personSelected=new PersonSelected[token.countTokens()];
int k=0;
while(token.hasMoreTokens())
{ String temp=token.nextToken();
personSelected[k]=new PersonSelected(temp,0);
personSelected[k].setName(temp);
k++;
}
}
else
{ inputPeopleName.setText(“请输入名字,并用逗号分隔”);
}
}
public PersonSelected [] getPersonSelected()
{ return personSelected;
}
}
SelectPane.java
import java.awt.
;
import java.awt.event.*;
public class SelectPane extends Panel implements ActionListener,ItemListener
{ Label label=new Label(“请将你推选的人选中:”);
int maxSelectedNumber; //一张选票可推选的最多人数
int 弃权票数;
int totalVote;
PersonSelected personSelected[]; //存放候选人的数组
Button button;
SelectPane(PersonSelected personSelected[],int max)
{ this.personSelected=personSelected;
maxSelectedNumber=max;
button=new Button(“确认”);
button.addActionListener(this);
init();
}
public void init()
{ removeAll();
add(label);
for(int k=0;k<personSelected.length;k++)
{ personSelected[k].getBox().addItemListener(this);
add(personSelected[k].getBox());
}
add(button);
validate();
}
public void actionPerformed(ActionEvent e)
{ totalVote=totalVote+1; //记录下统计的票数
//检查选票上被推选的人数
int number=0;
for(int k=0;k<personSelected.length;k++)
{ if(personSelected[k].getBox().getState())
{ number++;
}
}
if(number
0)
{ 弃权票数++;
}
else
{ for(int k=0;k<personSelected.length;k++)
{ if(personSelected[k].getBox().getState())
{ personSelected[k].addCount();
personSelected[k].getBox().setState(false);
}
}
}
label.setText(“已统计了:”+totalVote+“张选票,其中弃权票:”+弃权票数);
validate();
}
public void itemStateChanged(ItemEvent e)
{ Checkbox box=(Checkbox)e.getItemSelectable();
//检查选票是否符合规定的最多可推选的人数
int number=0;
for(int k=0;k<personSelected.length;k++)
{ if(personSelected[k].getBox().getState())
{ number++;
}
}
if(number>maxSelectedNumber)
{ box.setState(false); //不允许推选该人
}
}
public PersonSelected [] getPersonSelected()
{ return personSelected;
}
public void setPersonSelected(PersonSelected personSelected[])
{ this.personSelected=personSelected;
}
}
ResultArea.java
import java.awt.*;
public class ResultArea extends Panel
{ PersonSelected personSelected[]; //存放候选人的数组
TextArea text;
ResultArea( PersonSelected personSelected[])
{ this.personSelected=personSelected;
text=new TextArea(12,40);
text.setText(null);
add(text);
}
public void setPersonSelected(PersonSelected personSelected[])
{ text.setText(null);
String str[]=new String[personSelected.length];
int count[]=new int[personSelected.length];
for(int k=0;k<str.length;k++)
{ str[k]=personSelected[k].getName();
count[k]=personSelected[k].getCount();
}
for(int k=0;k<str.length;k++)
{ for(int i=k+1;i<str.length;i++)
if(count[i]>count[k])
{ String temp=str[k];
int n=count[k];
str[k]=str[i];
count[k]=count[i];
str[i]=temp;
count[i]=n;
}
}
for(int k=0;k<str.length;k++)
{ text.append("\n"+str[k]+“得票:”+count[k]);
}
validate();
}
}

第八章建立对话框
例子1
import java.awt.event.; import java.awt.;
class MyDialog extends Dialog implements ActionListener //建立对话框类
{ static final int YES=1,NO=0;
int message=-1; Button yes,no;
MyDialog(Frame f,String s,boolean b) //构造方法
{ super(f,s,b);
yes=new Button(“Yes”); yes.addActionListener(this);
no=new Button(“No”); no.addActionListener(this);
setLayout(new FlowLayout());
add(yes); add(no);
setBounds(60,60,100,100);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ message=-1;setVisible(false);
}
}
);
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==yes)
{ message=YES;setVisible(false);
}
else if(e.getSource()==no)
{ message=NO;setVisible(false);
}
}
public int getMessage()
{ return message;
}
}
class Dwindow extends Frame implements ActionListener
{ TextArea text; Button button; MyDialog dialog;
Dwindow(String s)
{ super(s);
text=new TextArea(5,22); button=new Button(“打开对话框”);
button.addActionListener(this);
setLayout(new FlowLayout());
add(button); add(text);
dialog=new MyDialog(this,“我有模式”,true);
setBounds(60,60,300,300); setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==button)
{ dialog.setVisible(true); //对话框激活状态时,堵塞下面的语句
//对话框消失后下面的语句继续执行:
if(dialog.getMessage()==MyDialog.YES) //如果单击了对话框的"yes"按钮
{ text.append("\n你单击了对话框的yes按钮");
}
else if(dialog.getMessage()==MyDialog.NO) //如果单击了对话框的"no"按钮
{ text.append("\n你单击了对话框的No按钮");
}
}
}
}
public class Example8_1
{ public static void main(String args[])
{ new Dwindow(“带对话框的窗口”);
}
}
例子2
import java.awt.;
import java.awt.event.
;
class 圆 extends Dialog implements ActionListener//负责计算圆面积的对话框
{ double r,area;
TextField 半径=null,
结果=null;
Button b=null;
圆(Frame f,String s,boolean mode)
{
super(f,s,mode);
setLayout(new FlowLayout());
半径=new TextField(10);
结果=new TextField(10);
b=new Button(“确定”);
add(new Label(“输入半径”));
add(半径);
add(b);
add(new Label(“面积是:”));
add(结果);
validate();
b.addActionListener(this);
setBounds(60,60,260,100);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ setVisible(false);
}
}
);
}
public void actionPerformed(ActionEvent e)
{ try
{ r=Double.parseDouble(半径.getText());
area=Math.PIrr;
结果.setText(""+area);
}
catch(Exception ee)
{ 半径.setText(“请输入数字字符”);
}
}
}
class 三角形 extends Dialog implements ActionListener//负责计算三角形面积的对话框
{ double a=0,b=0,c=0,area;
TextField 边_a=new TextField(6),
边_b=new TextField(6),
边_c=new TextField(6),
结果=new TextField(8);
Button button=new Button(“确定”);
三角形(Frame f,String s,boolean mode)
{ super(f,s,mode);
setLayout(new FlowLayout());
add(new Label(“输入三边的长度:”));
add(边_a); add(边_b); add(边_c);
add(button);
add(new Label(“面积是:”));
add(结果);
validate();
button.addActionListener(this);
setBounds(60,60,360,100);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ setVisible(false);
}
}
);
}
public void actionPerformed(ActionEvent e)//获取三边的长度
{ try{ a=Double.parseDouble(边_a.getText());
b=Double.parseDouble(边_b.getText());
c=Double.parseDouble(边_c.getText());
if(a+b>c&&a+c>b&&c+b>a)
{ double p=(a+b+c)/2;
area=Math.sqrt(p*(p-a)(p-b)(p-c));//计算三角形的面积
结果.setText(""+area);
}
else
{ 结果.setText(“您输入的数字不能形成三角形”);
}
}
catch(Exception ee)
{ 结果.setText(“请输入数字字符”);
}
}
}
class Win extends Frame implements ActionListener
{ MenuBar bar=null; Menu menu=null;
MenuItem item1, item2;
圆 circle ;
三角形 trangle;
Win()
{ bar=new MenuBar();
menu=new Menu(“选择”);
item1=new MenuItem(“圆面积计算”);
item2=new MenuItem(“三角形面积计算”);
menu.add(item1);
menu.add(item2);
bar.add(menu);
setMenuBar(bar);
circle=new 圆(this,“计算圆的面积”,false);
trangle=new 三角形(this,“计算三角形的面积”,false);
item1.addActionListener(this);
item2.addActionListener(this);
setVisible(true);
setBounds(100,120,200,190);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==item1)
{ circle.setVisible(true);
}
else if(e.getSource()item2)
{ trangle.setVisible(true);
}
}
}
public class Example8_2
{ public static void main(String args[])
{ Win win=new Win();
}
}
例子3
import java.awt.;import java.awt.event.;
public class Example8_3
{ public static void main(String args[])
{ FWindow f=new FWindow(“窗口”);
}
}
class FWindow extends Frame implements ActionListener
{ FileDialog filedialog_save,
filedialog_load;//声明2个文件对话筐
MenuBar menubar;
Menu menu;
MenuItem itemSave,itemLoad;
TextArea text;
FWindow(String s)
{ super(s);
setSize(300,400);setVisible(true);
text=new TextArea(10,10);
add(text,“Center”); validate();
menubar=new MenuBar();menu=new Menu(“文件”);
itemSave=new MenuItem(“保存文件”); itemLoad=new MenuItem(“打开文件”);
itemSave.addActionListener(this); itemLoad.addActionListener(this);
menu.add(itemSave); menu.add(itemLoad);
menubar.add(menu);
setMenuBar(menubar);
filedialog_save=new FileDialog(this,“保存文件话框”,FileDialog.SAVE);
filedialog_save.setVisible(false);
filedialog_load=new FileDialog(this,“打开文件话框”,FileDialog.LOAD);
filedialog_load.setVisible(false);
filedialog_save.addWindowListener(new WindowAdapter()//对话框增加适配器
{ public void windowClosing(WindowEvent e)
{ filedialog_save.setVisible(false);
}
});
filedialog_load.addWindowListener(new WindowAdapter()//对话框增加适配器
{public void windowClosing(WindowEvent e)
{ filedialog_load.setVisible(false);
}
});
addWindowListener(new WindowAdapter() //窗口增加适配器
{public void windowClosing(WindowEvent e)
{ setVisible(false);System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e) //实现接口中的方法
{ if(e.getSource()itemSave)
{ filedialog_save.setVisible(true);
String name=filedialog_save.getFile();
if(name!=null)
{ text.setText(“你选择了保存文件,名字是”+name);
}
else
{ text.setText(“没有保存文件”);
}
}
else if(e.getSource()itemLoad)
{ filedialog_load.setVisible(true);
String name=filedialog_load.getFile();
if(name!=null)
{ text.setText(“你选择了打开文件,名字是”+name);
}
else
{ text.setText(“没有打开文件”);
}
}
}
}
例子4
import java.awt.event.;
import java.awt.
;
import javax.swing.JOptionPane;
class Dwindow extends Frame implements ActionListener
{ TextField inputNumber;
TextArea show;
Dwindow(String s)
{ super(s);
inputNumber=new TextField(22); inputNumber.addActionListener(this);
show=new TextArea();
add(inputNumber,BorderLayout.NORTH); add(show,BorderLayout.CENTER);
setBounds(60,60,300,300); setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent e)
{ boolean boo=false;
if(e.getSource()inputNumber)
{ String s=inputNumber.getText();
char a[]=s.toCharArray();
for(int i=0;i<a.length;i++)
{ if(!(Character.isDigit(a[i])))
boo=true;
}
if(boo
true) //弹出“警告”消息对话框
{ JOptionPane.showMessageDialog(this,“您输入了非法字符”,“警告对话框”,
JOptionPane.WARNING_MESSAGE);
inputNumber.setText(null);
}
else if(boo
false)
{ int number=Integer.parseInt(s);
show.append("\n"+number+“平方:”+(numbernumber));
}
}
}
}
public class Example8_4
{ public static void main(String args[])
{ new Dwindow(“带对话框的窗口”);
}
}
例子5
import java.awt.event.
;
import java.awt.*;
import javax.swing.JOptionPane;
class Dwindow extends Frame
implements ActionListener
{ TextField inputName;
TextArea save;
Dwindow(String s)
{ super(s);
inputName=new TextField(22);
inputName.addActionListener(this);
save=new TextArea();
add(inputName,BorderLayout.NORTH);
add(save,BorderLayout.CENTER);
setBounds(60,60,300,300);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent e)
{ String s=inputName.getText();
int n=JOptionPane.showConfirmDialog(this,“确认正确吗?”,“确认对话框”,
JOptionPane.YES_NO_OPTION );
if(n
JOptionPane.YES_OPTION)
{ save.append("\n"+s);
}
else if(n
JOptionPane.NO_OPTION)
{ inputName.setText(null);
}
}
}
public class Example8_5
{ public static void main(String args[])
{ new Dwindow(“带对话框的窗口”);
}
}
例子6
import java.awt.event.;
import java.awt.
;
import javax.swing.JColorChooser;
class Dwindow extends Frame implements ActionListener
{ Button button;
Dwindow(String s)
{ super(s);
button=new Button(“打开颜色对话框”);
button.addActionListener(this);
setLayout(new FlowLayout());
add(button);
setBounds(60,60,300,300);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent e)
{ Color newColor=JColorChooser.showDialog(this,“调色板”,button.getBackground());
button.setBackground(newColor);
}
}
public class Example8_6
{ public static void main(String args[])
{ new Dwindow(“带颜色对话框的窗口”);
}
}

第九章Java多线程机制
例子1
public class Example9_1
{ public static void main(String args[])
{ Lefthand left;
Righthand right;
left=new Lefthand() ; //创建线程
right=new Righthand();
left.start();
right.start();
for(int i=1;i<=6;i++)
{ System.out.println(“我是主线程”);
}
}
}
class Lefthand extends Thread
{ public void run()
{ for(int i=1;i<=9;i++)
{
System.out.println(“我是左手线程”);
}
}
}
class Righthand extends Thread
{ public void run()
{ for(int i=1;i<=9;i++)
{ System.out.println(“我是右手线程”);
}
}
}
例子2
public class Example9_2
{ public static void main(String args[])
{ People teacher,student;
ComputerSum sum=new ComputerSum();
teacher=new People(“老师”,200,sum);
student =new People(“学生”,200,sum);
teacher.start();
student.start();
}
}
class ComputerSum
{ int sum;
public void setSum(int n)
{ sum=n;
}
public int getSum()
{ return sum;
}
}
class People extends Thread
{ int timeLength; //线程休眠的时间长度
ComputerSum sum;
People(String s,int timeLength,ComputerSum sum)
{ setName(s); //调用Thread类的方法setName为线程起个名字
this.timeLength=timeLength;
this.sum=sum;
}
public void run()
{ for(int i=1;i<=5;i++)
{ int m=sum.getSum();
sum.setSum(m+1);
System.out.println(“我是”+getName()+",现在的和:"+sum.getSum());
try { sleep(timeLength);
}
catch(InterruptedException e){}
}
}
}
例子3
public class Example9_3
{ public static void main(String args[ ])
{ Bank bank=new Bank();
//线程的目标对象设置被线程共享的money
bank.setMoney(300);
bank.会计.start();
bank.出纳.start();
}
}
class Bank implements Runnable
{ private int money=0;
Thread 会计,出纳;
Bank()
{ 会计=new Thread(this);
会计.setName(“会计”);
出纳=new Thread(this); //会计和出纳的目标对象相同
出纳.setName(“出纳”);
}
public void setMoney(int mount)
{ money=mount;
}
public void run() //接口中的方法
{ while(true)
{ money=money-50;
if(Thread.currentThread()会计)
{ System.out.println(“我是”+会计.getName()+“现在有:”+money+“元”);
if(money<=150)
{ System.out.println(会计.getName()+“进入死亡状态”);
return; //如果money少于50, 会计的run方法结束
}
}
else if(Thread.currentThread()出纳)
{ System.out.println(“我是”+出纳.getName()+“现在有:”+money+“元”);
if(money<=0)
return; //如果money少于0, 出纳的run方法结束
}
try{ Thread.sleep(800);
}
catch(InterruptedException e){}
}
}
}
例子4
class Example9_4
{ public static void main(String args[ ])
{ Thread threadA,threadB,threadC,threadD;
TargetObject a1=new TargetObject(), //线程的目标对象
a2=new TargetObject();
threadA=new Thread(a1); //目标对象是a1的线程
threadB=new Thread(a1);
a1.setNumber(10);
threadA.setName(“add”);
threadB.setName(“add”);
threadC=new Thread(a2); //目标对象是a2的线程
threadD=new Thread(a2);
a2.setNumber(-10);
threadC.setName(“sub”);
threadD.setName(“sub”);
threadA.start();
threadB.start();
threadC.start();
threadD.start();
}
}
class TargetObject implements Runnable
{
private int number=0;
public void setNumber(int n)
{ number=n;
}
public void run()
{ while(true)
{ if(Thread.currentThread().getName().equals(“add”))
{ number++;
System.out.println(“现在number等于”+number);
}
if(Thread.currentThread().getName().equals(“sub”))
{ number–;
System.out.println(“现在number等于”+number);
}
try{ Thread.sleep(1000);
}
catch(InterruptedException e)
{
}
}
}
}
例子5
class Example9_5
{ public static void main(String args[])
{ Move move=new Move();
move.zhangsan.start();
move.lisi.start();
}
}
class Move implements Runnable
{ Thread zhangsan,lisi;
Move()
{ zhangsan=new Thread(this);
zhangsan.setName(“张三”);
lisi=new Thread(this);
lisi.setName(“李四”);
}
public void run()
{ int i=0;
while(i<=5)
{ if(Thread.currentThread()zhangsan)
{ i=i+1;
System.out.println(zhangsan.getName()+“线程的局部变量i=”+i);
}
else if(Thread.currentThread()lisi)
{ i=i+1;
System.out.println(lisi.getName()+“线程的局部变量i=”+i);
}
try{ Thread.sleep(800);
}
catch(InterruptedException e){}
}
}
}
例子6
public class Example9_6
{ public static void main(String args[])
{ Number number=new Number();
number.giveNumberThread.start();
number.guessNumberThread.start();
}
}
class Number implements Runnable
{
int realNumber,guessNumber,min=0,max=100,message;
final int SMALLER=-1,LARGER=1,SUCCESS=8;
Thread giveNumberThread,guessNumberThread;
Number()
{ giveNumberThread=new Thread(this);
guessNumberThread=new Thread(this);
}
public void run()
{
for(int count=1;true;count++)
{
if(Thread.currentThread()giveNumberThread)
{
if(count
1)
{ realNumber=(int)(Math.random()*100)+1;
System.out.println(“随机给你一个数,猜猜是多少?”);
}
else
{ if(realNumber>guessNumber)
{ message=SMALLER;
System.out.println(“你猜小了”);
}
else if(realNumber<guessNumber)
{ message=LARGER;
System.out.println(“你猜大了”);
}
else
{ message=SUCCESS;
System.out.println(“恭喜,你猜对了”);
return;
}
}
try{ Thread.sleep(1500);
}
catch(Exception e){}
}
if(Thread.currentThread()guessNumberThread)
{
if(count
1)
{ guessNumber=(min+max)/2;
System.out.println(“我第”+count+“次猜这个数是:”+guessNumber);
}
else
{ if(message
SMALLER)
{ min=guessNumber;
guessNumber=(min+max)/2;
System.out.println(“我第”+count+“次猜这个数是:”+guessNumber);
}
else if(message
LARGER)
{ max=guessNumber;
guessNumber=(min+max)/2;
System.out.println(“我第”+count+“次猜这个数是:”+guessNumber);
}
else if(message
SUCCESS)
{ System.out.println(“我成功了!”);
return;
}
}
try{ Thread.sleep(1500);
}
catch(Exception e){}
}
}
}
}
例子7
class Example9_7
{ public static void main(String args[ ])
{ ComputerSum sum=new ComputerSum();
sum.computer1.start();
}
}
class ComputerSum implements Runnable
{
Thread computer1,computer2;
int i=1,sum=0;
ComputerSum()
{ computer1=new Thread(this);
computer2=new Thread(this);
}
public void run()
{ while(i<=10)
{ sum=sum+i;
System.out.println(sum);
i++;
if(i
6&&Thread.currentThread()computer1)
{ System.out.println(computer1.getName()+“完成任务了!”);
computer2.start();
return;
}
}
}
}
例子8
import java.util.*;
public class Example9_8
{ public static void main(String args[ ])
{ A a=new A();
a.thread.start();
}
}
class A implements Runnable
{ Thread thread;
int n=0;
A()
{ thread=new Thread(this);
}
public void run()
{ while(true)
{ System.out.println(new Date());
n++;
try{ Thread.sleep(1000);
}
catch(InterruptedException e){}
if(n
3)
{ thread=new Thread(this);
thread.start();
}
if(n>=12)
return;
}
}
}
例子9
public class Example9_9
{ public static void main(String args[])
{ A a=new A();
a.student.start();
a.teacher.start();
}
}
class A implements Runnable
{ Thread student,teacher;
A()
{ teacher=new Thread(this);
student=new Thread(this);
teacher.setName(“王教授”);
student.setName(“张三”);
}
public void run()
{ if(Thread.currentThread()student)
{ try{ System.out.println(student.getName()+“正在睡觉,不听课”);
Thread.sleep(10006060);
}
catch(InterruptedException e)
{ System.out.println(student.getName()+“被老师叫醒了”);
}
System.out.println(student.getName()+“开始听课”);
}
else if(Thread.currentThread()teacher)
{
for(int i=1;i<=3;i++)
{ System.out.println(“上课!”);
try{ Thread.sleep(500);
}
catch(InterruptedException e){}
}
student.interrupt(); //吵醒student
}
}
}
例子10
import java.awt.;
import java.awt.event.
;
public class Example9_10
{ public static void main(String args[])
{ new ThreadFrame();
}
}
class ThreadFrame extends Frame implements ActionListener,Runnable
{ TextField text1,text2;
boolean boo;
Label label=
new Label(“欢迎使用本字典”);
Button fast=new Button(“加速”);
Thread Scrollwords=null;
ThreadFrame()
{ setLayout(new FlowLayout());
Scrollwords=new Thread(this);
text1=new TextField(10);
text2=new TextField(10);
add(text1);
add(text2);
add(fast);
add(label);
text1.addActionListener(this);
fast.addActionListener(this);
setBounds(100,100,400,280);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
Scrollwords.start();
}
public void run()
{ while(true)
{ int x=label.getBounds().x;
int y=120;
x=x+5;
label.setLocation(x,y);
if(x>380)
{ x=10;
label.setLocation(x,y);
}
try{ Scrollwords.sleep(1000);
}
catch(InterruptedException e){}
if(boo)
{ return; //结束run方法,导致线程死亡。
}
}
}
public void actionPerformed(ActionEvent e)
{ if(text1.getText().equals(“boy”))
{ text2.setText(“男孩”);
}
else if(text1.getText().equals(“die”))
{ boo=true;
}
else
{ text2.setText(“没有该单词”);
}
if(e.getSource()fast)
{ Scrollwords.interrupt(); //吵醒休眠的线程,以便加快字模的滚动
}
}
}
例子11
import java.awt.;
import java.awt.event.
;
public class Example9_11
{ public static void main(String args[])
{ MyFrame frame=new MyFrame();
frame.setBounds(10,10,500,500) ;
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
}
}
class MyFrame extends Frame implements Runnable
{ Thread 红色球,兰色球;
MyCanvas red,blue;
double t=0;
MyFrame()
{ 红色球=new Thread(this);
兰色球=new Thread(this);
red=new MyCanvas(Color.red);
blue=new MyCanvas(Color.blue);
setLayout(null);
add(red);
add(blue);
red.setLocation(60,100);
blue.setLocation(60,100);
红色球.start();
兰色球.start();
}
public void run()
{ while(true)
{ t=t+0.2;
if(t>20) t=0;
if(Thread.currentThread()红色球)
{ int x=60;
int h=(int)(1.0/2tt3.8)+60;
red.setLocation(x,h);
try{ 红色球.sleep(50);
}
catch(InterruptedException e){}
}
else if(Thread.currentThread()==兰色球)
{ int x=60+(int)(26
t);
int h=(int)(1.0/2tt3.8)+60;
blue.setLocation(x,h);
try{ 兰色球.sleep(50);
}
catch(InterruptedException e){}
}
}
}
}
class MyCanvas extends Canvas
{
Color c;
MyCanvas(Color c)
{ setSize(20,20);
this.c=c;
}
public void paint(Graphics g)
{ g.setColor©;
g.fillOval(0,0,20,20);
}
}
例子12
import java.awt.event.
;
import java.awt.;
import java.util.Date;
public class Example9_12
{ public static void main(String args[])
{ new Win();
}
}
class Win extends Frame
implements Runnable,ActionListener
{ Thread thread=null;
TextArea text=null;
Button buttonStart=new Button(“Start”),
buttonStop=new Button(“Stop”);
boolean die;
Win()
{ thread=new Thread(this);
text=new TextArea();
add(text,BorderLayout.CENTER);
Panel p=new Panel();
p.add(buttonStart);
p.add(buttonStop);
buttonStart.addActionListener(this);
buttonStop.addActionListener(this) ;
add(p,BorderLayout.NORTH);
setVisible(true);
setSize(500,500);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==buttonStart)
{ if(!(thread.isAlive()))
{ thread=new Thread(this);
die=false;
}
try { thread.start();
}
catch(Exception e1)
{ text.setText(“线程没有结束run方法之前,不要再调用start方法”);
}
}
else if(e.getSource()buttonStop)
{ die=true;
}
}
public void run()
{ while(true)
{ text.append("\n"+new Date());
try{ thread.sleep(1000);
}
catch(InterruptedException ee){}
if(die
true)
return;
}
}
}
例子13
import java.awt.
;
import java.awt.event.;
public class Example9_13
{ public static void main(String args[])
{ new FrameMoney();
}
}
class FrameMoney extends Frame
implements Runnable,ActionListener
{ int money=100;
TextArea text1,text2;
Thread 会计,出纳;
int weekDay;
Button start=new Button(“开始演示”);
FrameMoney()
{ 会计=new Thread(this);
出纳=new Thread(this);
text1=new TextArea(12,15);
text2=new TextArea(12,15);
setLayout(new FlowLayout());
add(start);
add(text1);
add(text2);
setVisible(true);
setSize(360,300);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{System.exit(0);
}
});
start.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{ if(!(出纳.isAlive()))
{ 会计=new Thread(this);
出纳=new Thread(this);
}
try
{ 会计.start();
出纳.start();
}
catch(Exception exp){}
}
public synchronized void 存取(int number) //存取方法
{ if(Thread.currentThread()==会计)
{ text1.append(“今天是星期”+weekDay+"\n");
for(int i=1;i<=3;i++) //会计使用存取方法存入90元,存入30元,稍歇一下
{ money=money+number; //这时出纳仍不能使用存取方法
try { Thread.sleep(1000); //因为会计还没使用完存取方法
}
catch(InterruptedException e){}
text1.append(“帐上有”+money+“万\n”);
}
}
else if(Thread.currentThread()==出纳)
{ text2.append(“今天是星期 “+weekDay+”\n”);
for(int i=1;i<=2;i++) //出纳使用存取方法取出30元,取出15元,稍歇一下
{ money=money-number/2; //这时会计仍不能使用存取方法
try { Thread.sleep(1000); //因为出纳还没使用完存取方法
}
catch(InterruptedException e){}
text2.append(“帐上有”+money+“万\n”);
}
}
}
public void run()
{ if(Thread.currentThread()==会计||Thread.currentThread()==出纳)
{ for(int i=1;i<=3;i++) //从周一到周三会计和出纳都要使用帐本
{ weekDay=i;
存取(30);
}
}
}
}
例子14
import java.awt.
;
import java.awt.event.*;
public class Example9_14
{ public static void main(String args[])
{ new MyFrame();
}
}
class MyFrame extends Frame
implements Runnable,ActionListener
{ 售票员 王小姐;
Thread 张平,李明;
static TextArea text;
Button start=new Button(“排队买票”);
MyFrame()
{ 王小姐=new 售票员();
张平=new Thread(this);
李明=new Thread(this);
text=new TextArea(10,30);
start.addActionListener(this);
add(text,BorderLayout.CENTER);
add(start,BorderLayout.NORTH);
setVisible(true);
setSize(360,300);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{ try{ 张平.start();
李明.start();
}
catch(Exception exp) {}
}
public void run()
{ if(Thread.currentThread()张平)
{ 王小姐.售票规则(20);
}
else if(Thread.currentThread()李明)
{ 王小姐.售票规则(5);
}
}
}
class 售票员
{ int 五元钱的个数=2,十元钱的个数=0,二十元钱的个数=0;
String s=null;
public synchronized void 售票规则(int money)
{ if(money
5) //如果使用该方法的线程传递的参数是5,就不用等待
{ 五元钱的个数=五元钱的个数+1;
s= “给您入场卷您的钱正好”;
MyFrame.text.append("\n"+s);
}
else if(money
20)
{ while(五元钱的个数<3)
{ try { wait(); //如果使用该方法的线程传递的参数是20须等待
}
catch(InterruptedException e){}
}
五元钱的个数=五元钱的个数-3;
二十元钱的个数=二十元钱的个数+1;
s=“给您入场卷”+" 您给我20,找您15元";
MyFrame.text.append("\n"+s);
}
notifyAll();
}
}
例子15
class A implements Runnable
{ int i=0;
String name;
public void run()
{ while(true)
{ i++;
System.out.println(name+“i=”+i);
if(i
5)
{ try{ 挂起线程();
}
catch(Exception e){}
}
try{ Thread.sleep(1000);
}
catch(Exception e){}
}
}
public synchronized void 挂起线程() throws InterruptedException
{ wait();
}
public synchronized void 恢复线程()
{ notifyAll();
}
}
public class Example9_15
{ public static void main(String args[])
{ int m=0;
A target=new A(); //线程的目标对象
target.name=“张三”;
Thread thread=new Thread(target);
thread.setName(target.name);
thread.start();
while(true)
{ m++;
System.out.println(“我是主线程m=”+m);
if(m
20)
{ System.out.println(“让”+thread.getName()+“继续工作”);
try { target.恢复线程(); //主线程占有CPU资源期间
} //让thread的目标对象调用notifyAll()
catch(Exception e){}
break;
}
try{ Thread.sleep(1000);
}
catch(Exception e){}
}
}
}
例子16
class MyThread extends Thread
{ int i=0;
public void run()
{ while(true)
{ i++;
System.out.println(“我的名字是”+getName()+“i=”+i);
if(i
10)
{ try{ 挂起线程();
}
catch(Exception e){}
}
try{ Thread.sleep(1000);
}
catch(Exception e){}
}
}
public synchronized void 挂起线程() throws InterruptedException
{ wait();
}
public synchronized void 恢复线程()
{ notifyAll();
}
}
class YourThread extends Thread
{ int m=0;
MyThread otherThread;
YourThread(MyThread a)
{ otherThread=a;
}
public void run()
{ while(true)
{ m++;
System.out.println(“我的名字是”+getName()+“m=”+m);
if(m
20)
{ System.out.println(“恢复线程: “+otherThread.getName());
System.out.println(getName()+“停止工作”);
try{ otherThread.恢复线程();
}
catch(Exception e){}
return;
}
try{ Thread.sleep(1000);
}
catch(Exception e){}
}
}
}
public class Example9_16
{ public static void main(String args[])
{ MyThread thread1=new MyThread();
thread1.setName(“张三”);
thread1.start();
YourThread thread2=new YourThread(thread1);
thread2.setName(“李四”);
thread2.start();
}
}
例子17
import java.awt.;
import java.awt.event.
;
public class Example9_17
{ public static void main(String args[])
{ Win win=new Win();
}
}
class Win extends Frame implements
Runnable,ActionListener
{ Thread moveOrStop;
Button 开始,挂起,恢复,终止;
Label moveLabel;
boolean move=false,die=false;
Win()
{ moveOrStop=new Thread(this);
开始=new Button(“线程开始”);
挂起=new Button(“线程挂起”);
恢复=new Button(“线程恢复”);
终止=new Button(“线程终止”);
开始.addActionListener(this);
挂起.addActionListener(this);
恢复.addActionListener(this);
终止.addActionListener(this);
moveLabel=new Label(“线程负责运动我”);
moveLabel.setBackground(Color.cyan);
setLayout(new FlowLayout());
add(开始); add(挂起);
add(恢复); add(终止);
add(moveLabel);
setSize(200,300);
validate();
setVisible(true);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==开始)
{ try { move=true;
moveOrStop.start();
}
catch(Exception event) {}
}
else if(e.getSource()==挂起)
{ move=false;
}
else if(e.getSource()==恢复)
{ move=true;
恢复线程();
}
else if(e.getSource()终止)
{ die=true;
}
}
public void run()
{ while(true)
{
while(!move) //如果 move是false,挂起线程。
{ try{ 挂起线程();
}
catch(InterruptedException e1) { }
}
int x=moveLabel.getBounds().x;
int y=moveLabel.getBounds().y;
y=y+2;
if(y>=200) y=10;
moveLabel.setLocation(x,y);
try{ moveOrStop.sleep(200);
}
catch(InterruptedException e2) { }
if(die
true)
{ return; //终止线程。
}
}
}
public synchronized void 挂起线程() throws InterruptedException
{ wait();
}
public synchronized void 恢复线程()
{ notifyAll();
}
}
例子18
import java.awt.;
import java.awt.event.
;
import javax.swing.Timer;
public class Example9_18
{ public static void main(String args[])
{ TimeWin Win=new TimeWin();
}
}
class TimeWin extends Frame implements ActionListener
{ TextField text;
Button bStart,bStop,bContinue;
Timer time;
int n=0,start=1;
TimeWin()
{time=new Timer(1000,this);//TimeWin对象做计时器的监视器。
text=new TextField(10);
bStart=new Button(“开始计时”);
bStop=new Button(“暂停计时”);
bContinue=new Button(“继续计时”);
bStart.addActionListener(this);
bStop.addActionListener(this);
bContinue.addActionListener(this);
setLayout(new FlowLayout());
add(bStart);
add(bStop);
add(bContinue);
add(text);
setSize(500,500);
validate();
setVisible(true);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
} );
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==time)
{ java.util.Date date=new java.util.Date();
String str=date.toString().substring(11,19);
text.setText(“时间:”+str);
int x=text.getBounds().x;
int y=text.getBounds().y;
y=y+2;
text.setLocation(x,y);
}
else if(e.getSource()==bStart)
{ time.start();
}
else if(e.getSource()==bStop)
{ time.stop();
}
else if(e.getSource()==bContinue)
{ time.restart();
}
}
}
例子19
public class Example9_19
{ public static void main(String args[ ])
{ ThreadJoin a=new ThreadJoin();
a.customer.start();
a.tvMaker.start();
}
}
class ThreadJoin implements Runnable
{ TV tv;
Thread customer,tvMaker;
ThreadJoin()
{ customer=new Thread(this);
tvMaker=new Thread(this);
customer.setName(“顾客”);
tvMaker.setName(“电视制造厂”);
}
public void run()
{ if(Thread.currentThread()==customer)
{
System.out.println(customer.getName()+“等”+tvMaker.getName()+“生产电视”);
try{ tvMaker.join(); //线程customer开始等待tvMaker结束
}
catch(InterruptedException e){}
System.out.println(customer.getName()+
“买了一台电视:”+tv.name+” 价钱:”+tv.price);
}
else if(Thread.currentThread()==tvMaker)
{ System.out.println(tvMaker.getName()+“开始生产电视,请等…”);
try { tvMaker.sleep(2000);
}
catch(InterruptedException e){}
tv=new TV(“红星牌”,3288) ;
System.out.println(tvMaker.getName()+“生产完毕”);
}
}
}
class TV
{ float price;
String name;
TV(String name,float price)
{ this.name=name;
this.price=price;
}
}
例子20
public class Example9_20
{ public static void main(String args[ ])
{ Daemon a=new Daemon ();
a.A.start();
a.B.setDaemon(true);
a.B.start();
}
}
class Daemon implements Runnable
{ Thread A,B;
Daemon()
{ A=new Thread(this);
B=new Thread(this);
}
public void run()
{ if(Thread.currentThread()==A)
{ for(int i=0;i<8;i++)
{ System.out.println(“i=”+i) ;
try { Thread.sleep(1000);
}
catch(InterruptedException e) {}
}
}
else if(Thread.currentThread()==B)
{ while(true)
{ System.out.println("线程B是守护线程 ");
try { Thread.sleep(1000);
}
catch(InterruptedException e){}
}
}
}
}

第十章输入输出流
例子1
import java.io.;
public class Example10_1
{ public static void main(String args[])
{ File f1=new File(“F:\8000”,“Example20_1.java”);
File f2=new File(“F:\8000”);
System.out.println(“文件Example20_1是可读的吗:”+f1.canRead());
System.out.println(“文件Example20_1的长度:”+f1.length());
System.out.println(“文件Example20_1的绝对路径:”+f1.getAbsolutePath());
System.out.println(“F:\8000:是目录吗?”+f2.isDirectory());
}
}
例子2
import java.io.
;
class FileAccept implements FilenameFilter
{ String str=null;
FileAccept(String s)
{ str="."+s;
}
public boolean accept(File dir,String name)
{ return name.endsWith(str);
}
}
public class Example10_2
{ public static void main(String args[ ])
{ File dir=new File(“E:\chaper9”);
File deletedFile=new File(dir,“E.java”);
FileAccept acceptCondition=new FileAccept(“java”);
File fileName[]=dir.listFiles(acceptCondition);
for(int i=0;i< fileName.length;i++)
{ System.out.println(“文件名称:”+fileName[i].getName());
}
boolean boo=deletedFile.delete();
if(boo)
{ System.out.println(“文件:”+deletedFile.getName()+“被删除”);
}
}
}
例子3
import java.awt.;
import java.io.
;
import java.awt.event.;
public class Example10_3
{ public static void main(String args[])
{ try{
Runtime ce=Runtime.getRuntime();
ce.exec(“javac Example9_18.java”);
ce.exec(“java Example9_18”);
File file=new File(“c:/windows”,“Notepad.exe”);
ce.exec(file.getAbsolutePath());
}
catch(Exception e)
{ System.out.println(e);
}
}
}
例子4
import java.io.
;
import java.awt.;
import java.awt.event.
;
public class Example10_4
{ public static void main(String args[])
{ int b;
byte tom[]=new byte[25];
try{ File f=new File(“Example10_3.java”);
FileInputStream in=new FileInputStream(f);
while((b=in.read(tom,0,25))!=-1)
{ String s=new String (tom,0,b);
System.out.print(s);
}
in.close();
}
catch(IOException e)
{ System.out.println(“File read Error”+e);
}
}
}
例子5
import java.io.;
public class Example10_5
{ public static void main(String args[])
{ int b;
byte buffer[]=new byte[100];
try{ System.out.println(“输入一行文本,并存入磁盘:”);
b=System.in.read(buffer); //把从键盘敲入的字符存入buffer
FileOutputStream writefile=new FileOutputStream(“line.txt”);
writefile.write(buffer,0,b); // 通过流把 buffer写入到文件line.txt
}
catch(IOException e)
{ System.out.println("Error "+e);
}
}
}
例子6
import java.io.
;
import java.awt.;
import java.awt.event.
;
public class Example10_6
{ public static void main(String args[])
{ char a[]=
“今晚10点发起总攻”.toCharArray();
int n=0,m=0;
try{ File f=new File(“secret.txt”);
for(int i=0;i<a.length;i++)
{ a[i]=(char)(a[i]^‘R’);
}
FileWriter out=new FileWriter(f);
out.write(a,0,a.length);
out.close();
FileReader in=new FileReader(f);
char tom[]=new char[10];
System.out.println(“密文:”);
while((n=in.read(tom,0,10))!=-1)
{ String s=new String (tom,0,n);
System.out.print(s);
}
in.close();
in=new FileReader(f);
System.out.println("");
System.out.println(“明文:”);
while((n=in.read(tom,0,10))!=-1)
{ for(int i=0;i<n;i++)
{ tom[i]=(char)(tom[i]^‘R’);
}
String s=new String (tom,0,n);
System.out.print(s);
}
in.close();
}
catch(IOException e)
{ System.out.println(“File read Error”);
}
}
}
例子7
import java.io.;
public class Example10_7
{ public static void main(String args[ ])
{ File file=new File(“Student.txt”);
String content[]=
{“你好:”,“近来工作忙吗?”,“常联系”,“祝好”};
try{ FileWriter outOne=new FileWriter(file);
BufferedWriter outTwo= new BufferedWriter(outOne);
for(int k=0;k<content.length;k++)
{ outTwo.write(content[k]);
outTwo.newLine();
}
outTwo.close();
outOne.close();
FileReader inOne=new FileReader(file);
BufferedReader inTwo= new BufferedReader(inOne);
String s=null;
int i=0;
while((s=inTwo.readLine())!=null)
{ i++;
System.out.println(“第”+i+“行:”+s);
}
inOne.close();
inTwo.close();
}
catch(IOException e)
{ System.out.println(e);
}
}
}
例子8
import java.util.
;
import java.io.;
import java.awt.
;
import java.awt.event.;
import javax.swing.
;
public class Example10_8
{ public static void main(String args[])
{ EWindow w=new EWindow();
w.validate();
}
}
class EWindow extends Frame implements ActionListener,ItemListener
{ String str[]=new String[7],s;
FileReader file;
BufferedReader in;
Button start,next;
Checkbox checkbox[];
TextField 题目,分数;
int score=0;
CheckboxGroup age=new CheckboxGroup();
EWindow()
{ super(“英语单词学习”);
分数=new TextField(10);题目=new TextField(70);
start=new Button(“重新练习”);
start.addActionListener(this);
next=new Button(“下一题目”);
next.addActionListener(this);
checkbox=new Checkbox[4];
for(int i=0;i<=3;i++)
{ checkbox[i]=new Checkbox("",false,age);
checkbox[i].addItemListener(this);
}
try { file=new FileReader(“English.txt”);
in=new BufferedReader(file);
}
catch(IOException e){}
setBounds(20,100,660,300); setVisible(true);
Box box=Box.createVerticalBox();
Panel p1=new Panel(),p2=new Panel(),
p3=new Panel() ,p4=new Panel(),p5=new Panel();
p1.add(new Label(“题目:”));p1.add(题目);
p2.add(new Label(“选择答案:”));
for(int i=0;i<=3;i++)
{ p2.add(checkbox[i]);
}
p3.add(new Label(“您的得分:”));p3.add(分数);
p4.add(start); p4.add(next);
box.add(p1);box.add(p2);box.add(p3);box.add(p4);
addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{ System.exit(0);
}

                    });
 add(box,BorderLayout.CENTER);
 reading();

}
public void reading()
{ int i=0;
try { s=in.readLine();
if(!(s.startsWith(“endend”)))
{ StringTokenizer tokenizer=new StringTokenizer(s,"#");
while(tokenizer.hasMoreTokens())
{ str[i]=tokenizer.nextToken();
i++;
}
题目.setText(str[0]);
for(int j=1;j<=4;j++)
{ checkbox[j-1].setLabel(str[j]);
}
}
else if(s.startsWith(“endend”))
{ 题目.setText(“学习完毕”);
for(int j=0;j<4;j++)
{ checkbox[j].setLabel(“end”);
in.close();file.close();
}
}
}
catch(Exception exp){ 题目.setText(“无试题文件”) ; }
}
public void actionPerformed(ActionEvent event)
{ if(event.getSource()==start)
{ score=0;
分数.setText("得分: "+score);
try { file=new FileReader(“English.txt”);
in=new BufferedReader(file);
}
catch(IOException e){}
reading();
}
if(event.getSource()==next)
{ reading();
for(int j=0;j<4;j++)
{ checkbox[j].setEnabled(true);
}
}
}
public void itemStateChanged(ItemEvent e)
{ for(int j=0;j<4;j++)
{ if(checkbox[j].getLabel().equals(str[5])&&checkbox[j].getState())
{ score++;
分数.setText("得分: "+score);
}
checkbox[j].setEnabled(false);
}
}
}
例子9
import java.awt.;import java.io.;
import java.awt.event.;
public class Example10_9
{ public static void main(String args[])
{ FileWindows win=new FileWindows();
}
}
class FileWindows extends Frame implements ActionListener
{ FileDialog filedialog_save,filedialog_load;//声明2个文件对话筐
MenuBar menubar;
Menu menu;
MenuItem itemOpen,itemSave;
TextArea text;
BufferedReader in;
FileReader file_reader;
BufferedWriter out;
FileWriter tofile;
FileWindows()
{ super(“带文件对话框的窗口”);
setSize(260,270);
setVisible(true);
menubar=new MenuBar();
menu=new Menu(“文件”);
itemOpen=new MenuItem(“打开文件”);
itemSave=new MenuItem(“保存文件”);
itemOpen.addActionListener(this);
itemSave.addActionListener(this);
menu.add(itemOpen);
menu.add(itemSave);
menubar.add(menu);
setMenuBar(menubar);
filedialog_save=new FileDialog(this,“保存文件话框”,FileDialog.SAVE);
filedialog_load=new FileDialog(this,“打开文件话框”,FileDialog.LOAD);
filedialog_save.addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{ filedialog_save.setVisible(false);
}
});
filedialog_load.addWindowListener(new WindowAdapter()//对话框增加适配器
{public void windowClosing(WindowEvent e)
{ filedialog_load.setVisible(false);
}
});
addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{ System.exit(0);}
});
text=new TextArea(10,10);
add(text,BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==itemOpen)
{ filedialog_load.setVisible(true);
text.setText(null);
String s;
if(filedialog_load.getFile()!=null)
{ try{ File file= new
File(filedialog_load.getDirectory(),filedialog_load.getFile());
file_reader=new FileReader(file);
in=new BufferedReader(file_reader);
while((s=in.readLine())!=null)
text.append(s+’\n’);
in.close();
file_reader.close();
}
catch(IOException e2){}
}
}
else if(e.getSource()==itemSave)
{ filedialog_save.setVisible(true);
if(filedialog_save.getFile()!=null)
{ try { File file=new
File(filedialog_save.getDirectory(),filedialog_save.getFile());
tofile=new FileWriter(file);
out=new BufferedWriter(tofile);
out.write(text.getText(),0,(text.getText()).length());
out.close();
tofile.close();
}
catch(IOException e2){}
}
}
}
}
例子10
import java.io.
;
public class Example10_10
{ public static void main(String args[])
{ RandomAccessFile in_and_out=null;
int data[]={1,2,3,4,5,6,7,8,9,10};
try{ in_and_out=new RandomAccessFile(“tom.dat”,“rw”);
}
catch(Exception e){}
try{ for(int i=0;i<data.length;i++)
{ in_and_out.writeInt(data[i]);
}
for(long i=data.length-1;i>=0;i–)
{ in_and_out.seek(i4);
//每隔4个字节往前读取一个整数
System.out.print(","+in_and_out.readInt());
}
in_and_out.close();
}
catch(IOException e){}
}
}
例子11
import java.io.
;
class Example10_11
{ public static void main(String args[])
{ try{ RandomAccessFile in=new RandomAccessFile(“Example10_11.java”,“rw”);
long filePoint=0;
long fileLength=in.length();
while(filePoint<fileLength)
{ String s=in.readLine();
System.out.println(s);
filePoint=in.getFilePointer();
}
in.close();
}
catch(Exception e){}
}
}

例子12
import java.io.;
import javax.swing.
;
import java.awt.;
import java.awt.event.
;
public class Example10_12
{ public static void main(String args[])
{ new CommFrame();
}
}
class InputArea extends Panel
implements ActionListener
{ File f=null;
RandomAccessFile out;
Box baseBox ,boxV1,boxV2;
TextField name,email,phone;
Button button;
InputArea(File f)
{ setBackground(Color.cyan);
this.f=f;
name=new TextField(12);
email=new TextField(12);
phone=new TextField(12);
button=new Button(“录入”);
button.addActionListener(this);
boxV1=Box.createVerticalBox();
boxV1.add(new Label(“输入姓名”));
boxV1.add(Box.createVerticalStrut(8));
boxV1.add(new Label(“输入email”));
boxV1.add(Box.createVerticalStrut(8));
boxV1.add(new Label(“输入电话”));
boxV1.add(Box.createVerticalStrut(8));
boxV1.add(new Label(“单击录入”));
boxV2=Box.createVerticalBox();
boxV2.add(name);
boxV2.add(Box.createVerticalStrut(8));
boxV2.add(email);
boxV2.add(Box.createVerticalStrut(8));
boxV2.add(phone);
boxV2.add(Box.createVerticalStrut(8));
boxV2.add(button);
baseBox=Box.createHorizontalBox();
baseBox.add(boxV1);
baseBox.add(Box.createHorizontalStrut(10));
baseBox.add(boxV2);
add(baseBox);
}
public void actionPerformed(ActionEvent e)
{ try{
RandomAccessFile out=new RandomAccessFile(f,“rw”);
if(f.exists())
{ long length=f.length();
out.seek(length);
}
out.writeUTF(“姓名:”+name.getText());
out.writeUTF(“eamil:”+email.getText());
out.writeUTF(“电话:”+phone.getText());
out.close();
}
catch(IOException ee){}
}
}
class CommFrame extends Frame implements ActionListener
{ File file=null;
MenuBar bar;
Menu fileMenu;
MenuItem 录入,显示;
TextArea show;
InputArea inputMessage;
CardLayout card=null; //卡片式布局.
Panel pCenter;
CommFrame()
{ file=new File(“通讯录.txt”);
录入=new MenuItem(“录入”);
显示=new MenuItem(“显示”);
bar=new MenuBar();
fileMenu=new Menu(“菜单选项”);
fileMenu.add(录入);
fileMenu.add(显示);
bar.add(fileMenu);
setMenuBar(bar);
录入.addActionListener(this);
显示.addActionListener(this);
inputMessage=new InputArea(file);
show=new TextArea(12,20);
card=new CardLayout();
pCenter=new Panel();
pCenter.setLayout(card);
pCenter.add(“录入”,inputMessage);
pCenter.add(“显示”,show);
add(pCenter,BorderLayout.CENTER);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
setVisible(true);
setBounds(100,50,420,380);
validate();
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==录入)
{ card.show(pCenter,“录入”);
}
else if(e.getSource()==显示)
{ int number=1;
show.setText(null);
card.show(pCenter,“显示”);
try{ RandomAccessFile in=new RandomAccessFile(file,“r”);
String 姓名=null;
while((姓名=in.readUTF())!=null)
{ show.append("\n"+number+" “+姓名);
show.append(in.readUTF()); //读取email.
show.append(in.readUTF()); //读取phone
show.append(”\n------------------------- “);
number++;
}
in.close();
}
catch(Exception ee){}
}
}
}
例子13
import java.io.;
public class Example20_13
{ public static void main(String args[])
{ try
{ FileOutputStream fos=new FileOutputStream(“jerry.dat”);
DataOutputStream out_data=new DataOutputStream(fos);
out_data.writeInt(100);out_data.writeInt(10012);
out_data.writeLong(123456);
out_data.writeFloat(3.1415926f); out_data.writeFloat(2.789f);
out_data.writeDouble(987654321.1234);
out_data.writeBoolean(true);out_data.writeBoolean(false);
out_data.writeChars(“i am ookk”);
}
catch(IOException e){}
try
{ FileInputStream fis=new FileInputStream(“jerry.dat”);
DataInputStream in_data=new DataInputStream(fis);
System.out.println(":"+in_data.readInt());//读取第1个int整数
System.out.println(":"+in_data.readInt());//读取第2个int整数
System.out.println(":"+in_data.readLong()); //读取long整数
System.out.println(":"+in_data.readFloat());//读取第1个float数
System.out.println(":"+in_data.readFloat());//读取第2个float数
System.out.println(":"+in_data.readDouble());
System.out.println(":"+in_data.readBoolean());//读取第1个boolean
System.out.println(":"+in_data.readBoolean());//读取第2个boolean
char c;
while((c=in_data.readChar())!=’\0’) //’\0’表示空字符
System.out.print©;
}
catch(IOException e){}
}
}
例子14
import java.io.
;
public class Example10_14
{ public static void main(String args[])
{ int n=-1;
try{ ByteArrayOutputStream outByte=new ByteArrayOutputStream();
byte a[]=“你好,内存条!”.getBytes();
outByte.write(a);
outByte.close();
ByteArrayInputStream inByte=new ByteArrayInputStream(outByte.toByteArray());
byte tom[]=new byte[8];
while((n=inByte.read(tom,0,4))!=-1)
{ System.out.print(new String(tom,0,n));
}
inByte.close();
char jerry[]=new char[8];
CharArrayWriter outChar=new CharArrayWriter();
char b[]=“你的价钱如何?”.toCharArray();
outChar.write(b);
outChar.close();
CharArrayReader inChar=new CharArrayReader(outChar.toCharArray());
while((n=inChar.read(jerry,0,4))!=-1)
{ System.out.print(new String(jerry,0,n));
}
inChar.close();
}
catch(IOException e){}
}
}
例子15
import java.io.;
class Student implements Serializable//实现Serializable接口
{ String name=null;
double height;
Student(String name,double height)
{ this.name=name;
this.height=height;
}
public void setHeight (double c)
{ this.height=c;
}
}
public class Example10_15
{ public static void main(String args[])
{ Student zhang=new Student(“张三”,1.65);
try{
FileOutputStream file_out=new FileOutputStream(“s.txt”);
ObjectOutputStream object_out=new ObjectOutputStream(file_out);
object_out.writeObject(zhang);
FileInputStream file_in=new FileInputStream(“s.txt”);
ObjectInputStream object_in=new ObjectInputStream(file_in);
Student li=(Student)object_in.readObject();
li.setHeight(1.78); //设置身高。
li.name=“李四”;
System.out.println(zhang.name+" 身高是:"+zhang.height);
System.out.println(li.name+" 身高是:"+li.height);
}
catch(ClassNotFoundException event)
{ System.out.println(“不能读出对象”);
}
catch(IOException event)
{ System.out.println(“can not read file”+event);
}
}
}
例子16
import java.io.
;
class GetCloneObject
{ public Object getClone(Object a)
{ Object object=null;
try{
ByteArrayOutputStream outOne=new ByteArrayOutputStream();
ObjectOutputStream outTwo=new ObjectOutputStream(outOne);
outTwo.writeObject(a);
ByteArrayInputStream inOne=new ByteArrayInputStream(outOne.toByteArray());
ObjectInputStream inTwo=new ObjectInputStream(inOne);
object=inTwo.readObject();
}
catch(Exception event)
{ System.out.println(event);
}
return object;
}
}
class Student implements Serializable
{ String number=null;
double height;
Student(String number,double height)
{ this.number=number;
this.height=height;
}
public void setHeight (double c)
{ this.height=c;
}
public void setNumber(String number)
{ this.number=number;
}
}
class School
{ public void setStudent(Student s,String number,double m)
{ s.setNumber(number);
s.setHeight(m);
}
}
public class Example10_16
{ public static void main(String args[])
{ try
{ GetCloneObject cloneObject=new GetCloneObject();
School school=new School();
Student student=new Student(“0000000”,0.0);
Student studentClone=(Student)cloneObject.getClone(student);
school.setStudent(studentClone,“2006001”,1.78);
System.out.println(student.number+” 身高:"+student.height);
System.out.println(studentClone.number+" 身高:"+studentClone.height);
}
catch(Exception e){}
}
}
例子17
import java.awt.;
import java.awt.event.
;
import java.io.;
public class Example10_17
{ public static void main(String args[])
{ MyWin win=new MyWin();
}
}
class MyWin extends Frame
implements ActionListener
{ TextArea text=null;
Button 读入=null,写出=null;
FileInputStream inOne=null;
FileOutputStream outOne=null;
ObjectInputStream inTwo=null;
ObjectOutputStream outTwo=null;
MyWin()
{ setLayout(new FlowLayout());
text=new TextArea(6,10);
读入=new Button(“读入对象”);
写出=new Button(“写出对象”);
读入.addActionListener(this);
写出.addActionListener(this);
text.addTextListener(new Boy(text));
setVisible(true);
add(text);add(读入);
add(写出);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
setSize(300,300);
validate();
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==写出)
{ try{ outOne=new FileOutputStream(“tom.txt”);
outTwo=new ObjectOutputStream(outOne);
outTwo.writeObject(text);
outTwo.close();
outOne.close();
}
catch(IOException event){}
}
else if(e.getSource()==读入)
{ try{ inOne=new FileInputStream(“tom.txt”);
inTwo=new ObjectInputStream(inOne);
TextArea temp=(TextArea)inTwo.readObject();
temp.setBackground(Color.pink);
this.add(temp);
this.validate();
inTwo.close();
inOne.close();
}
catch(Exception event)
{ System.out.println(event);
}
}
}
}
class Boy implements TextListener,Serializable
{ TextArea text;
int i=10;
Boy(TextArea text)
{ this.text=text;
}
public void textValueChanged(TextEvent e)
{ i++;
text.setBackground(new Color((i
3)%255,(i7)%255,(i17)%255));
}
}
例子18
import java.io.;
import java.nio.
;
import java.nio.channels.;
public class Example10_18
{ public static void main(String args[])
{ int b;
byte tom[]=new byte[100];
try{
RandomAccessFile input=new RandomAccessFile(“Example10_17.java”,“rw”);
FileChannel channel=input.getChannel();
while((b=input.read(tom,0,10))!=-1)
{ FileLock lock=channel.tryLock();
String s=new String (tom,0,b);
System.out.println(s);
try { Thread.sleep(1000);
lock.release();
}
catch(Exception eee){System.out.println(eee);}
}
input.close();
}
catch(Exception ee)
{ System.out.println(ee);
}
}
}
例子19
import java.awt.
;
import java.io.;
import java.awt.event.
;
public class Example10_19
{ public static void main(String args[])
{ JDK f=new JDK();
}
}
class JDK extends Frame
implements ActionListener,Runnable
{ Thread compiler=null;
Thread run_prom=null;
boolean bn=true;
CardLayout mycard;
Panel p=new Panel();
File file_saved=null;
TextArea input_text=new TextArea(),//程序输入区
compiler_text=new TextArea(), //编译出错显示区
dos_out_text=new TextArea(); //显示System.out流输出的信息
Button button_input_text,button_compiler_text,
button_compiler,button_run_prom,button_see_doswin;
TextField input_flie_name_text=new TextField(“输入被编译的文件名字.java”);
TextField run_file_name_text=new TextField(“输入应用程序主类的名字”);
JDK()
{ super(“Java编程小软件”);
mycard=new CardLayout();
compiler=new Thread(this);
run_prom=new Thread(this);
button_input_text=new Button(“程序输入区”);
button_compiler_text=new Button(“编译结果区”);
button_compiler=new Button(“编译程序”);
button_run_prom=new Button(“运行应用程序”);
button_see_doswin=new Button(“查看System.out流输出的信息”);
p.setLayout(mycard);
p.add(“input”,input_text);
p.add(“compiler”,compiler_text);
p.add(“dos”,dos_out_text);
add(p,“Center”);
add( button_see_doswin,“South”);
compiler_text.setBackground(Color.pink);
Panel p1=new Panel();
p1.setLayout(new GridLayout(4,2));
p1.add(new Label(“输入程序:”));
p1.add(button_input_text);
p1.add(new Label(“编译结果:”));
p1.add(button_compiler_text);
p1.add(input_flie_name_text);
p1.add(button_compiler);
p1.add(run_file_name_text);
p1.add(button_run_prom);
add(p1,BorderLayout.NORTH);
button_input_text.addActionListener(this);
button_compiler_text.addActionListener(this);
button_compiler.addActionListener(this);
button_run_prom.addActionListener(this);
button_see_doswin.addActionListener(this);
addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
setBounds(100,120,700,360);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==button_input_text)
{ mycard.show(p,“input”);
}
else if(e.getSource()==button_compiler_text)
{ mycard.show(p,“compiler”);
}
else if(e.getSource()==button_see_doswin)
{ mycard.show(p,“dos”);
}
else if(e.getSource()==button_compiler)
{ if(!(compiler.isAlive()))
{ compiler=new Thread(this);
}
try{ compiler.start();
}
catch(Exception eee){}
mycard.show(p,“compiler”);
}
else if(e.getSource()==button_run_prom)
{ if(!(run_prom.isAlive()))
{ run_prom =new Thread(this);
}
try{ run_prom.start();
}
catch(Exception eee){}
mycard.show(p,“dos”);
}
}
public void run()
{ if(Thread.currentThread()==compiler)
{ compiler_text.setText(null);
String temp=input_text.getText().trim();
byte buffer[]=temp.getBytes();
int b=buffer.length;
String flie_name=input_flie_name_text.getText().trim();
try{ file_saved=new File(flie_name);
FileOutputStream writefile=new FileOutputStream(file_saved);
writefile.write(buffer,0,b);
writefile.close();
}
catch(IOException e5)
{ System.out.println("Error ");
}
try{ Runtime ce=Runtime.getRuntime();
InputStream in=ce.exec("javac "+flie_name).getErrorStream();
BufferedInputStream bin=new BufferedInputStream(in);
byte shuzu[]=new byte[100];
int n;boolean bn=true;
while((n=bin.read(shuzu,0,100))!=-1)
{ String s=null;
s=new String(shuzu,0,n);
compiler_text.append(s);
if(s!=null) bn=false;
}
if(bn)
{ compiler_text.append(“编译正确”);
}
}
catch(IOException e1){}
}
else if(Thread.currentThread()==run_prom)
{ dos_out_text.setText(null);
try{ Runtime ce=Runtime.getRuntime();
String path=run_file_name_text.getText().trim();
InputStream in=ce.exec("java "+path).getInputStream();
BufferedInputStream bin=new BufferedInputStream(in);
byte zu[]=new byte[150];
int m;String s=null;
while((m=bin.read(zu,0,150))!=-1)
{ s=new String(zu,0,m);
dos_out_text.append(s);
}
}
catch(IOException e1){}
}
}
}
例子20
import javax.swing.;
import java.io.
;
public class Example10_20
{ public static void main(String args[])
{ byte b[]=new byte[30];
try{ FileInputStream input=new FileInputStream(“Example10_20.java”);
ProgressMonitorInputStream in=
new ProgressMonitorInputStream(null,“读取java文件”,input);
ProgressMonitor p=in.getProgressMonitor(); //获得进度条
while(in.read(b)!=-1)
{ String s=new String(b);
System.out.print(s);
Thread.sleep(1000);//由于文件较小,为了看清进度条这里有意延缓1秒
}
}
catch(Exception e){}
}
}

第十一章Java网络的基本知识
例子1
import java.awt.;
import java.awt.event.
;
import java.net.;
import java.io.
;
public class Example11_1
{ public static void main(String args[])
{ new NetWin();
}
}
class NetWin extends Frame
implements ActionListener,Runnable
{ Button button;
URL url;
TextField text;
TextArea area;
byte b[]=new byte[118];
Thread thread;
NetWin()
{ text=new TextField(20);
area=new TextArea(12,12);
button=new Button(“确定”);
button.addActionListener(this);
thread=new Thread(this);
Panel p=new Panel();
p.add(new Label(“输入网址:”));
p.add(text);
p.add(button);
add(area,BorderLayout.CENTER);
add(p,BorderLayout.NORTH);
setBounds(60,60,360,300);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
if(!(thread.isAlive()))
thread=new Thread(this);
try{
thread.start();
}
catch(Exception ee)
{ text.setText(“我正在读取”+url);
}
}
public void run()
{ try { int n=-1;
area.setText(null);
url=new URL(text.getText().trim());
InputStream in=url.openStream();
while((n=in.read(b))!=-1)
{ String s=new String(b,0,n);
area.append(s);
}
}
catch(MalformedURLException e1)
{ text.setText(""+e1);
return;
}
catch(IOException e1)
{ text.setText(""+e1);
return;
}
}
}
例子2
import java.awt.;
import java.awt.event.
;
import java.net.;
import java.io.
;
import javax.swing.JEditorPane;
public class Example11_2
{ public static void main(String args[])
{ new Win();
}
}
class Win extends Frame
implements ActionListener,Runnable
{ Button button;
URL url;
TextField text;
JEditorPane editPane;
byte b[]=new byte[118];
Thread thread;
public Win()
{ text=new TextField(20);
editPane=new JEditorPane();
editPane.setEditable(false);
button=new Button(“确定”);
button.addActionListener(this);
thread=new Thread(this);
Panel p=new Panel();
p.add(new Label(“输入网址:”));
p.add(text);
p.add(button);
ScrollPane scroll=new ScrollPane();
scroll.add(editPane);
add(scroll,BorderLayout.CENTER);
add(p,BorderLayout.NORTH);
setBounds(160,60,360,300);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{ if(!(thread.isAlive()))
thread=new Thread(this);
try{ thread.start();
}
catch(Exception ee)
{ text.setText(“我正在读取”+url);
}
}
public void run()
{ try { int n=-1;
editPane.setText(null);
url=new URL(text.getText().trim());
editPane.setPage(url);
}
catch(Exception e1)
{ text.setText(""+e1);
return;
}
}
}
例子3
import java.awt.;
import java.awt.event.
;
import java.net.;
import java.io.
;
import javax.swing.event.;
import javax.swing.
;
public class Example11_3
{ public static void main(String args[])
{ new LinkWin();
}
}
class LinkWin extends JFrame implements ActionListener,Runnable
{ Button button;
URL url;
TextField text;
JEditorPane editPane;
byte b[]=new byte[118];
Thread thread;
public LinkWin()
{ text=new TextField(20);
editPane=new JEditorPane();
editPane.setEditable(false);
button=new Button(“确定”);
button.addActionListener(this);
thread=new Thread(this);
Panel p=new Panel();
p.add(new Label(“输入网址:”));
p.add(text);
p.add(button);
ScrollPane scroll=new ScrollPane();
scroll.add(editPane);
add(scroll,BorderLayout.CENTER);
add(p,BorderLayout.NORTH);
setBounds(60,60,360,300);
setVisible(true);
validate();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editPane.addHyperlinkListener(new HyperlinkListener()
{
public void hyperlinkUpdate(HyperlinkEvent e)
{ if(e.getEventType()==
HyperlinkEvent.EventType.ACTIVATED)
{
try{ editPane.setPage(e.getURL());
}
catch(IOException e1)
{ editPane.setText(""+e1);
}
}
}});
}
public void actionPerformed(ActionEvent e)
{ if(!(thread.isAlive()))
thread=new Thread(this);
try{ thread.start();
}
catch(Exception ee)
{ text.setText(“我正在读取”+url);
}
}
public void run()
{ try {
int n=-1;
editPane.setText(null);
url=new URL(text.getText().trim());
editPane.setPage(url);
}
catch(Exception e1)
{ text.setText(""+e1);
return;
}
}
}

例子4
import java.net.;
public class DomainName
{ public static void main(String args[])
{ try{ InetAddress address_1=InetAddress.getByName(“www.sina.com.cn”);
System.out.println(address_1.toString());
InetAddress address_2=InetAddress.getByName(“166.111.222.3”);
System.out.println(address_2.toString());
}
catch(UnknownHostException e)
{ System.out.println(“无法找到 www.sina.com.cn”);
}
}
}
例子5
(1)客户端程序:
import java.io.
;
import java.net.;
public class Client
{ public static void main(String args[])
{ String s=null;
Socket mysocket;
DataInputStream in=null;
DataOutputStream out=null;
try{
mysocket=new Socket(“127.0.0.1”,4331);
in=new DataInputStream(mysocket.getInputStream());
out=new DataOutputStream(mysocket.getOutputStream());
for(int k=1;k<100;k=k+2)
{ out.writeUTF(""+k);
s=in.readUTF();//in读取服务器发来的信息,堵塞状态
System.out.println(“客户收到:”+s);
Thread.sleep(500);
}
}
catch(Exception e)
{ System.out.println(“服务器已断开”+e);
}
}
}
(2)服务器端程序:
import java.io.
;
import java.net.;
public class Server
{ public static void main(String args[])
{ ServerSocket server=null;
Socket you=null;
String s=null;
DataOutputStream out=null;
DataInputStream in=null;
try{ server=new ServerSocket(4331);
}
catch(IOException e1)
{System.out.println(e1);
}
try{ System.out.println(“等待客户呼叫”);
you=server.accept(); //堵塞状态,除非有客户呼叫
out=new DataOutputStream(you.getOutputStream());
in=new DataInputStream(you.getInputStream());
while(true)
{ s=in.readUTF(); // in读取客户放入"线路"里的信息,堵塞状态
int m=Integer.parseInt(s);
out.writeUTF(“你好:我是服务器”);
out.writeUTF(“你说的数是乘2后是:”+2
m);
System.out.println(“服务器收到:”+s);
Thread.sleep(500);
}
}
catch(Exception e)
{ System.out.println(“客户已断开”+e);
}
}
}
例子6
(1) 客户端
import java.net.;
import java.io.
;
import java.awt.;
import java.awt.event.
;
import javax.swing.;
public class Client
{ public static void main(String args[])
{ new ComputerClient();
}
}
class ComputerClient extends Frame implements Runnable,ActionListener
{ Button connection,send;
TextField inputText,showResult;
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread thread;
ComputerClient()
{ socket=new Socket();
setLayout(new FlowLayout());
Box box=Box.createVerticalBox();
connection=new Button(“连接服务器”);
send=new Button(“发送”);
send.setEnabled(false);
inputText=new TextField(12);
showResult=new TextField(12);
box.add(connection);
box.add(new Label(“输入三角形三边的长度,用逗号或空格分隔:”));
box.add(inputText);
box.add(send);
box.add(new Label(“收到的结果:”));
box.add(showResult);
connection.addActionListener(this);
send.addActionListener(this);
thread=new Thread(this);
add(box);
setBounds(10,30,300,400);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==connection)
{ try //请求和服务器建立套接字连接:
{ if(socket.isConnected())
{}
else
{ InetAddress address=InetAddress.getByName(“127.0.0.1”);
InetSocketAddress socketAddress=new InetSocketAddress(address,4331);
socket.connect(socketAddress);
in =new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
send.setEnabled(true);
thread.start();
}
}
catch (IOException ee){}
}
if(e.getSource()==send)
{ String s=inputText.getText();
if(s!=null)
{ try { out.writeUTF(s);
}
catch(IOException e1){}
}
}
}
public void run()
{ String s=null;
while(true)
{ try{ s=in.readUTF();
showResult.setText(s);
}
catch(IOException e)
{ showResult.setText(“与服务器已断开”);
break;
}
}
}
}
(2)服务器端
import java.io.
;
import java.net.;
import java.util.
;
public class Server
{ public static void main(String args[])
{ ServerSocket server=null;
Server_thread thread;
Socket you=null;
while(true)
{ try{ server=new ServerSocket(4331);
}
catch(IOException e1)
{ System.out.println(“正在监听”); //ServerSocket对象不能重复创建
}
try{ System.out.println(" 等待客户呼叫");
you=server.accept();
System.out.println(“客户的地址:”+you.getInetAddress());
}
catch (IOException e)
{ System.out.println(“正在等待客户”);
}
if(you!=null)
{ new Server_thread(you).start(); //为每个客户启动一个专门的线程
}
}
}
}
class Server_thread extends Thread
{ Socket socket;
DataOutputStream out=null;
DataInputStream in=null;
String s=null;
boolean quesion=false;
Server_thread(Socket t)
{ socket=t;
try { out=new DataOutputStream(socket.getOutputStream());
in=new DataInputStream(socket.getInputStream());
}
catch (IOException e)
{}
}
public void run()
{ while(true)
{ double a[]=new double[3] ;
int i=0;
try{ s=in.readUTF();//堵塞状态,除非读取到信息
quesion=false;
StringTokenizer fenxi=new StringTokenizer(s," ,");
while(fenxi.hasMoreTokens())
{ String temp=fenxi.nextToken();
try{ a[i]=Double.valueOf(temp).doubleValue();i++;
}
catch(NumberFormatException e)
{ out.writeUTF(“请输入数字字符”);
quesion=true;
}
}
if(quesionfalse)
{ double p=(a[0]+a[1]+a[2])/2.0;
out.writeUTF(" “+Math.sqrt(p*(p-a[0])(p-a[1])(p-a[2])));
}
}
catch (IOException e)
{ System.out.println(“客户离开”);
return;
}
}
}
}
例子7
(1)服务器
Server.java
import java.io.;
import java.net.
;
import java.util.zip.;
public class Server
{ public static void main(String args[])
{ ServerSocket server=null;
ServerThread thread;
Socket you=null;
while(true)
{ try{ server=new ServerSocket(4331);
}
catch(IOException e1)
{ System.out.println(“正在监听”);
}
try{ you=server.accept();
System.out.println(“客户的地址:”+you.getInetAddress());
}
catch (IOException e)
{ System.out.println(“正在等待客户”);
}
if(you!=null)
{ new ServerThread(you).start();
}
}
}
}
class ServerThread extends Thread
{ Socket socket;
ZipOutputStream out;
String s=null;
ServerThread(Socket t)
{ socket=t;
try { out=new ZipOutputStream(socket.getOutputStream());
}
catch (IOException e){}
}
public void run()
{ try{out.putNextEntry(new ZipEntry(“Example.java”));
FileInputStream reader=new FileInputStream(“Example.java”);
byte b[]=new byte[1024];
int n=-1;
while((n=reader.read(b,0,1024))!=-1)
{ out.write(b,0,n); //发送压缩后的数据到客户端。
}
out.putNextEntry(new ZipEntry(“E.java”));
reader=new FileInputStream(“E.java”);
n=-1;
while((n=reader.read(b,0,1024))!=-1)
{ out.write(b,0,n); //发送压缩后的数据到客户端。
}
reader.close();
out.close();
}
catch (IOException e) {}
}
}
(2)客户端
Client.java
import java.net.
;
import java.io.;
import java.awt.
;
import java.awt.event.;
import java.util.zip.
;
public class Client extends Frame implements Runnable,ActionListener
{ Button connection,getFile;
TextArea showResult;
Socket socket=null;
ZipInputStream in;
Thread thread;
public Client()
{ socket=new Socket();
connection=new Button(“连接服务器,获取文件内容”);
setLayout(new FlowLayout());
showResult=new TextArea(10,28);
add(connection);
add(showResult);
connection.addActionListener(this);
thread=new Thread(this);
setBounds(100,100,460,410);
setVisible(true);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
}
public void run()
{ byte b[]=new byte[1024];
ZipEntry zipEntry=null;
while(true)
{ try{ while((zipEntry=in.getNextEntry())!=null)
{ showResult.append(”\n"+zipEntry.toString()+":\n");
int n=-1;
while((n=in.read(b,0,1024))!=-1)
{ String str=new String(b,0,n);
showResult.append(str);
}
}
}
catch(IOException e) { }
}
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()connection)
{ try { if(socket.isConnected())
{}
else
{ InetAddress address=InetAddress.getByName(“127.0.0.1”);
InetSocketAddress socketAddress=new InetSocketAddress(address,4331);
socket.connect(socketAddress);
in=new ZipInputStream(socket.getInputStream());
thread.start();
}
}
catch (IOException ee)
{ System.out.println(ee);
}
}
}
public static void main(String args[])
{ Client win=new Client();
}
}
例子8
主机1
import java.net.;import java.awt.; import java.awt.event.*;
class Shanghai_Frame extends Frame implements Runnable,ActionListener
{ TextField out_message=new TextField(“发送数据到北京:”);
TextArea in_message=new TextArea();
Button b=new Button(“发送数据包到北京”);
Shanghai_Frame()
{ super(“我是上海”);
setSize(200,200);setVisible(true);
b.addActionListener(this);
add(out_message,“South”);add(in_message,“Center”);add(b,“North”);
Thread thread=new Thread(this);
thread.start();//线程负责接收数据包
}
public void actionPerformed(ActionEvent event) //点击按扭发送数据包
{ byte buffer[]=out_message.getText().trim().getBytes();
try{ InetAddress address=InetAddress.getByName(“127.0.0.1”);
DatagramPacket data_pack=
new DatagramPacket(buffer,buffer.length, address,888);
DatagramSocket mail_data=new DatagramSocket();
in_message.append(“数据报目标主机地址:”+data_pack.getAddress()+"\n");
in_message.append(“数据报目标端口是:”+data_pack.getPort()+"\n");
in_message.append(“数据报长度:”+data_pack.getLength()+"\n");
mail_data.send(data_pack);
}
catch(Exception e){}
}
public void run() // //接收数据包
{ DatagramPacket pack=null;
DatagramSocket mail_data=null;
byte data[]=new byte[8192];
try{ pack=new DatagramPacket(data,data.length);
mail_data=new DatagramSocket(666);
}
catch(Exception e){}
while(true)
{ if(mail_data
null) break;
else
try{ mail_data.receive(pack);
int length=pack.getLength();
InetAddress adress=pack.getAddress();
int port=pack.getPort();
String message=new String(pack.getData(),0,length);
in_message.append(“收到数据长度:”+length+"\n");
in_message.append(“收到数据来自:”+adress+“端口:”+port+"\n");
in_message.append(“收到数据是:”+message+"\n");
}
catch(Exception e){}
}
}
}
public class Shanghai
{ public static void main(String args[])
{ Shanghai_Frame shanghai_win=new Shanghai_Frame();
shanghai_win.addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{System.exit(0);
}
});
shanghai_win.validate();
}
}
主机2
import java.net.;import java.awt.; import java.awt.event.*;
class Beijing_Frame extends Frame implements Runnable,ActionListener
{ TextField out_message=new TextField(“发送数据到上海:”);
TextArea in_message=new TextArea();
Button b=new Button(“发送数据包到上海”);
Beijing_Frame()
{ super(“我是北京”);
setSize(200,200);setVisible(true);
b.addActionListener(this);
add(out_message,“South”);add(in_message,“Center”);add(b,“North”);
Thread thread=new Thread(this);
thread.start();//线程负责接收数据包
}
public void actionPerformed(ActionEvent event)
{ byte buffer[]=out_message.getText().trim().getBytes();
try{ InetAddress address=InetAddress.getByName(“127.0.0.1”);
DatagramPacket data_pack=
new DatagramPacket(buffer,buffer.length, address,666);
DatagramSocket mail_data=new DatagramSocket();
in_message.append(“数据报目标主机地址:”+data_pack.getAddress()+"\n");
in_message.append(“数据报目标端口是:”+data_pack.getPort()+"\n");
in_message.append(“数据报长度:”+data_pack.getLength()+"\n");
mail_data.send(data_pack);
}
catch(Exception e){}
}
public void run()
{ DatagramSocket mail_data=null;
byte data[]=new byte[8192];
DatagramPacket pack=null;
try{
pack=new DatagramPacket(data,data.length);
mail_data=new DatagramSocket(888);
}
catch(Exception e){}
while(true)
{ if(mail_data
null) break;
else
try{ mail_data.receive(pack);
int length=pack.getLength();
InetAddress adress=pack.getAddress();
int port=pack.getPort();
String message=new String(pack.getData(),0,length);
in_message.append(“收到数据长度:”+length+"\n");
in_message.append(“收到数据来自:”+adress+“端口:”+port+"\n");
in_message.append(“收到数据是:”+message+"\n");
}
catch(Exception e){}
}
}
}
public class Beijing
{ public static void main(String args[])
{ Beijing_Frame beijing_win=new Beijing_Frame();
beijing_win.addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{System.exit(0);
}
});
beijing_win.validate();
}
}
例子9
(1)广播信息的主机
BroadCast.java
import java.net.;
public class BroadCast extends Thread
{ String s=“天气预报,最高温度32度,最低温度25度”;
int port=5858; //组播的端口
InetAddress group=null; //组播组的地址
MulticastSocket socket=null; //多点广播套接字
BroadCast()
{try
{
group=InetAddress.getByName(“239.255.8.0”); //设置广播组的地址为239.255.8.0
socket=new MulticastSocket(port); //多点广播套接字将在port端口广播
socket.setTimeToLive(1); //多点广播套接字发送数据报范围为本地网络
socket.joinGroup(group); //加入广播组,加入group后,socket发送的数据报
} //可以被加入到group中的成员接收到
catch(Exception e)
{ System.out.println("Error: "+ e);
}
}
public void run()
{ while(true)
{ try{ DatagramPacket packet=null; //待广播的数据包
byte data[]=s.getBytes();
packet=new DatagramPacket(data,data.length,group,port);
System.out.println(new String(data));
socket.send(packet); //广播数据包
sleep(2000);
}
catch(Exception e)
{ System.out.println("Error: "+ e);
}
}
}
public static void main(String args[])
{ new BroadCast().start();
}
}
(2)接收广播的主机
Receive.java
import java.net.
;
import java.awt.;
import java.awt.event.
;
public class Receive extends Frame implements Runnable,ActionListener
{ int port; //组播的端口.
InetAddress group=null; //组播组的地址.
MulticastSocket socket=null; //多点广播套接字.
Button 开始接收,停止接收;
TextArea 显示正在接收内容,显示已接收的内容;
Thread thread; //负责接收信息的线程.
boolean 停止=false;
public Receive()
{ super(“定时接收信息”);
thread=new Thread(this);
开始接收=new Button(“开始接收”);
停止接收=new Button(“停止接收”);
停止接收.addActionListener(this);
开始接收.addActionListener(this);
显示正在接收内容=new TextArea(10,10);
显示正在接收内容.setForeground(Color.blue);
显示已接收的内容=new TextArea(10,10);
Panel north=new Panel();
north.add(开始接收);
north.add(停止接收);
add(north,BorderLayout.NORTH);
Panel center=new Panel();
center.setLayout(new GridLayout(1,2));
center.add(显示正在接收内容);
center.add(显示已接收的内容);
add(center,BorderLayout.CENTER);
validate();
port=5858; //设置组播组的监听端口
try{
group=InetAddress.getByName(“239.255.8.0”); //设置广播组的地址为239.255.8.0
socket=new MulticastSocket(port); //多点广播套接字将在port端口广播
socket.joinGroup(group); //加入广播组,加入group后,socket发送的数据报
} //可以被加入到group中的成员接收到
catch(Exception e){}
setBounds(100,50,360,380);
setVisible(true);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});

}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==开始接收)
{ 开始接收.setBackground(Color.blue);
停止接收.setBackground(Color.gray);
if(!(thread.isAlive()))
{ thread=new Thread(this);
}
try{ thread.start();
停止=false;
}
catch(Exception ee) {}
}
if(e.getSource()停止接收)
{ 开始接收.setBackground(Color.gray);
停止接收.setBackground(Color.blue);
停止=true;
}
}
public void run()
{ while(true)
{byte data[]=new byte[8192];
DatagramPacket packet=null;
packet=new DatagramPacket(data,data.length,group,port); //待接收的数据包。
try { socket.receive(packet);
String message=new String(packet.getData(),0,packet.getLength());
显示正在接收内容.setText(“正在接收的内容:\n”+message);
显示已接收的内容.append(message+"\n");
}
catch(Exception e) {}
if(停止
true)
{ break;
}
}
}
public static void main(String args[])
{ new Receive();
}
}

第十二章Java Applet基础
例子1
import java.applet.;
import java.awt.
;
public class Example12_1 extends Applet
{ Button button1,button2;
int sum;
public void init()
{ setBackground(Color.gray);
button1=new Button(“yes”);
button2=new Button(“No”);
add(button1);
add(button2);
}
public void start()
{ sum=0;
for(int i=1;i<=100;i++)
{ sum=sum+i;
}
}
public void stop() { }
public void paint(Graphics g)
{ g.setColor(Color.blue);
g.drawString(“程序设计方法”,20,60);
g.setColor(Color.red);
g.drawString(“sum=”+sum,20,100);
}
}
例子2
import java.awt.;
import java.applet.
;
public class Example12_2 extends Applet
{ int x=0,y=0;
public void init()
{ String s1=getParameter(“girl”);//从html得到"girl"的值。
String s2=getParameter(“boy”);//从html得到"boy"的值。
x=Integer.parseInt(s1);
y=Integer.parseInt(s2);
}
public void paint(Graphics g)
{ g.drawString(“x=”+x+","+“y=”+y,90,120);
}
}
Boy.html




例子3
import java.applet.;
import java.awt.
;
import java.awt.event.;
import java.net.
;
public class Boy extends Applet implements ActionListener
{ Button button;
URL url;
TextField text;
public void init()
{ text=new TextField(18);
button=new Button(“确定”);
add(new Label(“输入网址:”));
add(text); add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==button)
{ try { url=new URL(text.getText().trim());
getAppletContext().showDocument(url);
}
catch(MalformedURLException g)
{ text.setText(“不正确的URL:"+url);
}
}
}
}
例子4
import java.applet.;
import java.awt.
;
import java.net.;
import java.io.
;
public class ReadFile extends Applet
{ TextArea text;
URL url;
public void init()
{ text=new TextArea(12,40);
add(text);
}
public void start()
{ try { url=new URL(getCodeBase(),“hello.txt”);
InputStream in=url.openStream(); //url返回输入流
int n=-1;
byte b[]=new byte[100];
while((n=in.read(b))!=-1)
{ String str=new String(b,0,n);
text.append(str);
}
}
catch(Exception ee) {}
}
}

例子5
import java.applet.;
import java.awt.
;
import java.awt.event.;
public class CircleAndRect extends
Applet implements Runnable
{ Thread left ,right;
Graphics mypen;
int x,y;
public void init()
{ left=new Thread(this);
right=new Thread(this);
x=10;y=10;
mypen=getGraphics();
}
public void start()
{ try { left.start();
right.start();
}
catch(Exception e){}
}
public void run()
{ while(true)
{ if(Thread.currentThread()==left)
{ x=x+1;
if(x>240) x=10;
mypen.setColor(Color.blue);
mypen.clearRect(10,10,300,40);
mypen.drawRect(10+x,10,40,40);
try{ left.sleep(60);
}
catch(InterruptedException e){}
}
else if(Thread.currentThread()==right)
{ y=y+1;
if(y>240) y=10; mypen.setColor(Color.red);
mypen.clearRect(10,90,300,40);
mypen.drawOval(10+y,90,40,40);
try{ right.sleep(60);
}
catch(InterruptedException e){}
}
}
}
}
例子6
(1)客户端
import java.net.
;
import java.io.;
import java.awt.
;
import java.applet.;
public class Client extends Applet implements Runnable
{ TextField text;
Socket socket=null;
ObjectInputStream in=null;
ObjectOutputStream out=null;
Thread thread;
public void init()
{ thread=new Thread(this);
}
public void start()
{ try { thread.start();
socket=new Socket(this.getCodeBase().getHost(), 4331);
in=new ObjectInputStream(socket.getInputStream());
out=new ObjectOutputStream(socket.getOutputStream());
}
catch(Exception e){}
}
public void run()
{ String s=null;
while(true)
{ try{ text=(TextField)in.readObject();
add(text);
validate();
return;
}
catch(Exception e) {}
}
}
}
(2)服务器端
import java.io.
;
import java.net.;
import java.util.
;
import java.awt.*;
public class Server
{ public static void main(String args[])
{ ServerSocket server=null;
Server_thread thread;
Socket you=null;
while(true)
{ try{ server=new ServerSocket(4331);
}
catch(IOException e1)
{ System.out.println(“正在监听”);
}
try{ you=server.accept();
}
catch (IOException e){}
if(you!=null)
{ new Server_thread(you).start();
}
}
}
}
class Server_thread extends Thread
{ Socket socket;
ObjectOutputStream out=null;
ObjectInputStream in=null;
String s=null;
Server_thread(Socket t)
{ socket=t;
try { out=new ObjectOutputStream(socket.getOutputStream());
in=new ObjectInputStream(socket.getInputStream());
}
catch (IOException e){}
}
public void run()
{ TextField text=new TextField(“你好,我是服务器”,20);
try{ out.writeObject(text);
}
catch (IOException e){}
}
}

第十三章常见数据结构的Java实现
例子1
import java.util.;
public class Example13_1
{ public static void main(String args[])
{ List list=new LinkedList();
list.add(“is”);
list.add(“a”);
int number=list.size();
System.out.println(“现在链表中有”+number+
“个节点:”);
for(int i=0;i<number;i++)
{ String temp=(String)list.get(i);
System.out.println(“第”+i+“节点中的数据:”+temp);
}
list.add(0,“It”);
number=list.size();
list.add(number-1,“door”);
number=list.size();
System.out.println(“现在链表中有”+number+“个节点:”);
for(int i=0;i<number;i++)
{ String temp=(String)list.get(i);
System.out.println(“第”+i+“节点中的数据:”+temp);
}
list.remove(0);
list.remove(1);
list.set(0,“open”);
number=list.size();
System.out.println(“现在链表中有”+number+“个节点:”);
for(int i=0;i<number;i++)
{ String temp=(String)list.get(i);
System.out.println(“第”+i+“节点中的数据:”+temp);
}
}
}
例子2
import java.util.
;
class Student
{ String name ;
int number;
Student(String name,int number)
{ this.name=name;
this.number=number;
}
}
public class Example13_2
{ public static void main(String args[])
{ List list=new LinkedList();
for(int k=1;k<=22222;k++)
{ list.add(new Student(“I am “+k,k));
}
Iterator iter=list.iterator();
long time1=System.currentTimeMillis();
while(iter.hasNext())
{ Student te=(Student)iter.next();
}
long time2=System.currentTimeMillis();
System.out.println(“遍历链表用时:”+(time2-time1)+“毫秒”);
time1=System.currentTimeMillis();
for(int i=0;i<list.size();i++)
{ Student te=(Student)list.get(i);
}
time2=System.currentTimeMillis();
System.out.println(“遍历链表用时:”+(time2-time1)+“毫秒”);
}
}
例子3
import java.util.;
import java.awt.event.
;
import java.awt.;
import javax.swing.
;
import java.io.;
public class Example13_3
{ public static void main(String args[])
{ ShowWin win=new ShowWin();
win.setSize(320,200);
win.setVisible(true);
}
}
class 商品 implements Serializable
{ String name,price;
商品(String name,String price)
{ this.name=name;
this.price=price;
}
}
class ShowWin extends Frame implements ActionListener
{ LinkedList goods_list=null;
File file=new File(“商品信息.dat”) ;
TextField 名称文本框=new TextField(),
单价文本框=new TextField(),
删除文本框=new TextField();
Button b_add=new Button(“添加商品”),
b_del=new Button(“删除商品”);
TextArea 显示区=new TextArea(7,25);
ShowWin()
{ setLayout(new GridLayout(1,2));
goods_list=new LinkedList();
Box boxV1=Box.createVerticalBox();
boxV1.add(new Label(“输入名称:”));
boxV1.add(new Label(“输入单价:”));
boxV1.add(new Label(“点击添加:”));
boxV1.add(new Label(“删除的名称:”));
boxV1.add(new Label(“点击删除:”));
Box boxV2=Box.createVerticalBox();
boxV2.add(名称文本框);
boxV2.add(单价文本框);
boxV2.add(b_add);
boxV2.add(删除文本框);
boxV2.add(b_del);
Box baseBox=Box.createHorizontalBox();
baseBox.add(boxV1);
baseBox.add(boxV2);
Panel p=new Panel();
p.add(baseBox);
add§;
add(显示区);
b_add.addActionListener(this);
b_del.addActionListener(this);
addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==b_add)
{ String name,price;
name=名称文本框.getText();
price=单价文本框.getText();
if(file.exists())
{ if(name.length()>0&&price.length()>0)
{ 商品 goods=new 商品(name,price);
try { FileInputStream come_in=new FileInputStream(file);
ObjectInputStream in=new ObjectInputStream(come_in);
goods_list=(LinkedList)in.readObject();
in.close();
goods_list.add(goods);
FileOutputStream outOne=new FileOutputStream(file);
ObjectOutputStream out=new ObjectOutputStream(outOne);
out.writeObject(goods_list);
out.close();
}
catch(Exception event){}
}
else
{ 名称文本框.setText(“名称,价钱必须输入”);
}
}
else
{ if(name.length()>0&&price.length()>0)
{ 商品 goods=new 商品(name,price);
try { goods_list.add(goods);
FileOutputStream outOne=new FileOutputStream(file);
ObjectOutputStream out=new ObjectOutputStream(outOne);
out.writeObject(goods_list);
out.close();
}
catch(Exception event){}
}
else
{ 名称文本框.setText(“名称,价钱必须输入”);
}
}
showing();
}
else if(e.getSource()==b_del)
{ String name=删除文本框.getText();
try { FileInputStream come_in=new FileInputStream(file);
ObjectInputStream in=new ObjectInputStream(come_in);
goods_list=(LinkedList)in.readObject();
in.close();
for(int i=0;i<goods_list.size();i++)
{ 商品 temp=(商品)goods_list.get(i);
if(temp.name.equals(name))
goods_list.remove(i);
}
FileOutputStream outOne=new FileOutputStream(file);
ObjectOutputStream out=new ObjectOutputStream(outOne);
out.writeObject(goods_list);
out.close();
}
catch(Exception event){}
showing();
}
}
public void showing()
{ 显示区.setText(null);
try { FileInputStream come_in=new FileInputStream(file);
ObjectInputStream in=new ObjectInputStream(come_in);
goods_list=(LinkedList)in.readObject();
}
catch(Exception event){}
Iterator iter=goods_list.iterator();
while(iter.hasNext())
{ 商品 te=(商品)iter.next();
显示区.append(“名称:”+te.name+",");
显示区.append(“单价:”+te.price+".");
显示区.append("\n");
}
}
}
例子4
import java.util.
;
public class Example13_4
{ public static void main(String args[])
{ Stack mystack=new Stack();
for(char c=‘A’;c<=‘Z’;c++)
{ mystack.push(new Character©);
}
while(!(mystack.empty()))
{ Character temp=(Character)mystack.pop();
System.out.print(“弹出数据:”+temp.charValue());
System.out.println(” 栈中还剩”+mystack.size()+“个数据”);
}
}
}
例子5
import java.util.;
public class Example13_5
{ public static void main(String args[])
{ Stack mystack=new Stack();
System.out.print(" “+1);
System.out.print(” “+1);
mystack.push(new Long(1));
mystack.push(new Long(1));
int k=1;
while(k<=50)
for(long i=1;i<=2;i++)
{ Long F1=(Long)mystack.pop();
Long F2=(Long)mystack.pop();
long f1=F1.longValue();
long f2=F2.longValue();
System.out.print(” "+(f1+f2));
Long temp=new Long(f1+f2);
mystack.push(temp);
mystack.push(F2);
k++;
}
}
}
例子6
import java.util.
;
public class Example13_6
{ public static void main(String args[])
{ TreeSet mytree=new TreeSet();
mytree.add(“boy”);
mytree.add(“zoo”);
mytree.add(“apple”);
mytree.add(“girl”);
Iterator te=mytree.iterator();
while(te.hasNext())
System.out.println(""+te.next());
}
}
例子7
import java.util.;import java.awt.;
class Student implements Comparable
{ int english=0;
String name;
Student(int english,String name)
{ this.name=name;
this.english=english;
}
public int compareTo(Object b)
{ Student st=(Student)b;
return (this.english-st.english);
}
}
public class Example13_7
{ public static void main(String args[])
{ TreeSet mytree=new TreeSet(new Comparator()
{ public int compare(Object a,Object b)
{ Student stu1=(Student)a;
Student stu2=(Student)b;
return stu1.compareTo(stu2);
}
});
Student st1,st2,st3,st4;
st1=new Student(90,“赵一”);
st2=new Student(66,“钱二”);
st3=new Student(86,“孙三”);
st4=new Student(76,“李四”);
mytree.add(st1);
mytree.add(st2);
mytree.add(st3);
mytree.add(st4);
Iterator te=mytree.iterator();
while(te.hasNext())
{ Student stu=(Student)te.next();
System.out.println(""+stu.name+" “+stu.english);
}
}
}
例子8
import java.util.;
import java.awt.event.
;
import java.awt.;
import java.io.
;
public class Example13_8
{ public static void main(String args[])
{ Win win=new Win();
win.setSize(500,250);
win.setVisible(true);
win.addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{System.exit(0);
}
});
}
}
class 节目 implements Comparable,Serializable
{ String name;double time;
节目(String 名称,double 演出时间)
{ name=名称;
time=演出时间;
}
public int compareTo(Object b)
{ 节目 item=(节目)b;
return (int)((this.time-item.time)1000);
}
}
class Win extends Frame implements ActionListener
{ TreeSet 节目清单=null;
TextField 名称文本框=new TextField(10),
时间文本框=new TextField(5),
删除文本框=new TextField(5);
Button b_add=new Button(“添加节目”),
b_del=new Button(“删除节目”),
b_show =new Button(“显示节目清单”);
TextArea 显示区=new TextArea();
Win()
{ 节目清单=new TreeSet(new Comparator()
{ public int compare(Object a,Object b)
{ 节目 item_1=(节目)a;
节目 item_2=(节目)b;
return item_1.compareTo(item_2);
}
});
Panel 节目单输入区=new Panel();
节目单输入区.add(new Label(“节目名称:”));
节目单输入区.add(名称文本框);
节目单输入区.add(new Label(“演出时间:”));
节目单输入区.add(时间文本框);
节目单输入区.add(new Label(“点击添加:”));
节目单输入区.add(b_add);
节目单输入区.add(b_show);
Panel 节目单删除区=new Panel();
节目单删除区.add(new Label(“输入演出的时间:”));
节目单删除区.add(删除文本框);
节目单删除区.add(new Label(“点击删除:”));
节目单删除区.add(b_del);
Panel 节目单显示区=new Panel();
节目单显示区.add(显示区);
显示区.setBackground(Color.pink);
b_add.addActionListener(this);
b_del.addActionListener(this);
b_show.addActionListener(this);
add(节目单输入区,“North”);
add(节目单显示区,“Center”);
add(节目单删除区,“South”);
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==b_add)
{ String 名称=null;
double 时间=0.0;
名称=名称文本框.getText();
try{ 时间=Double.parseDouble(时间文本框.getText());
}
catch(NumberFormatException ee)
{ 时间文本框.setText(“请输入代表时间的实数”);
}
节目 programme=new 节目(名称,时间);
节目清单.add(programme);
showing();
}
else if(e.getSource()==b_del)
{ 节目 待删除节目=null;
double time=Double.valueOf(删除文本框.getText()).doubleValue();
Iterator te=节目清单.iterator();
while(te.hasNext())
{ 节目 item=(节目)te.next();
if(Math.abs(item.time-time)<=0.000001d)
{ 待删除节目=item;
}
}
if(待删除节目!=null)
节目清单.remove(待删除节目);
showing();
}
else if(e.getSource()==b_show)
{ showing();
}
}
void showing()
{ 显示区.setText(null);
Iterator iter=节目清单.iterator();
while(iter.hasNext())
{ 节目 item=(节目)iter.next();
显示区.append(“节目名称:”+item.name+“演出时间: “+item.time);
显示区.append(”\n”);
}
}
}
例子9
import java.util.
;
class StudentKey implements Comparable
{ double d=0;
StudentKey (double d)
{ this.d=d;
}
public int compareTo(Object b)
{ StudentKey st=(StudentKey)b;
if((this.d-st.d)==0)
{ return -1;
}
else
{ return (int)((this.d-st.d)1000);
}
}
}
class Student
{ String name=null;
double math,english;
Student(String s,double m,double e)
{ name=s;
math=m;
english=e;
}
}
public class Example13_9
{ public static void main(String args[ ])
{ TreeMap treemap= new TreeMap(new Comparator()
{ public int compare(Object a,Object b)
{ StudentKey key1=(StudentKey)a;
StudentKey key2=(StudentKey)b;
return key1.compareTo(key2);
}
});
String str[]={“赵一”,“钱二”,“孙三”,“李四”};
double math[]={89,45,78,76};
double english[]={67,66,90,56};
Student student[]=new Student[4];
for(int k=0;k<student.length;k++)
{ student[k]=new Student(str[k],math[k],english[k]);
}
StudentKey key[]=new StudentKey[4] ;
for(int k=0;k<key.length;k++)
{ key[k]=new StudentKey(student[k].math);
}
for(int k=0;k<student.length;k++)
{ treemap.put(key[k],student[k]);
}
int number=treemap.size();
System.out.println(“树映射中有”+number+“个对象,按数学成绩排序:”);
Collection collection=treemap.values();
Iterator iter=collection.iterator();
while(iter.hasNext())
{ Student stu=(Student)iter.next();
System.out.println("姓名 “+stu.name+” 数学 "+stu.math);
}
treemap.clear();
for(int k=0;k<key.length;k++)
{ key[k]=new StudentKey(student[k].english);
}
for(int k=0;k<student.length;k++)
{ treemap.put(key[k],student[k]);
}
number=treemap.size();
System.out.println(“树映射中有”+number+“个对象:按英语成绩排序:”);
collection=treemap.values();
iter=collection.iterator();
while(iter.hasNext())
{ Student stu=(Student)iter.next();
System.out.println("姓名 “+stu.name+” 英语 "+stu.english);
}
}
}
例子10
import java.util.
;
public class Example13_10
{ public static void main(String args[])
{ Integer one=new Integer(1),
two=new Integer(2),
three=new Integer(3),
four=new Integer(4),
five=new Integer(5),
six=new Integer(6);
HashSet A=new HashSet(),
B=new HashSet(),
tempSet=new HashSet();
A.add(one);
A.add(two);
A.add(three);
A.add(four);
B.add(one);
B.add(two);
B.add(five);
B.add(six);
tempSet=(HashSet)A.clone();
A.removeAll(B); //A变成调用该方法之前的A集合与B集合的差集
B.removeAll(tempSet); //B变成调用该方法之前的B集合与tempSet集合的差集
B.addAll(A); //B就是最初的A与B的对称差
int number=B.size();
System.out.println(“A和B的对称差集合有”+number+“个元素:”);
Iterator iter=B.iterator();
while(iter.hasNext())
{ Integer te=(Integer)iter.next();
System.out.print(” “+te.intValue());
}
}
}
例子11
MainClass.java
public class MainClass
{ public static void main(String args[])
{ new ManagerWindow();
}
}
Student.java
public class Student
implements java.io.Serializable
{ String number,name;
public void setNumber(String number)
{ this.number=number;
}
public String getNumber()
{ return number;
}
public void setName(String name)
{ this.name=name;
}
public String getName()
{ return name;
}
}
ManagerWindow.java
import java.awt.;
import java.awt.event.
;
import javax.swing.;
import java.io.
;
import java.util.Hashtable;
public class ManagerWindow extends Frame implements ActionListener
{ InputStudent 基本信息录入=null;
Inquest 基本信息查询=null;
Button 查询;
Hashtable 基本信息=null;
File file=null;
public ManagerWindow()
{ 基本信息=new Hashtable();
查询=new Button(“查询”);
查询.addActionListener(this);
file=new File(“基本信息.txt”);
if(!file.exists())
{ try{ FileOutputStream out=new FileOutputStream(file);
ObjectOutputStream objectOut=new ObjectOutputStream(out);
objectOut.writeObject(基本信息);
objectOut.close();
out.close();
}
catch(IOException e){}
}
基本信息录入=new InputStudent(file);
基本信息查询=new Inquest(this,file);
add(基本信息录入,BorderLayout.CENTER);
add(查询,BorderLayout.SOUTH);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
setVisible(true);
setBounds(100,50,420,380);
validate();
}
public void actionPerformed(ActionEvent e)
{ 基本信息查询.setVisible(true);
}
}
InputStudent.java
import java.awt.;
import java.awt.event.
;
import javax.swing.;
import java.io.
;
import java.util.;
public class InputStudent extends Panel implements ActionListener
{ Hashtable 基本信息表=null;
TextField 学号,姓名;
Student 学生=null;
Button 录入;
FileInputStream inOne=null;
ObjectInputStream inTwo=null;
FileOutputStream outOne=null;
ObjectOutputStream outTwo=null;
File file=null;
public InputStudent(File file)
{ this.file=file;
学号=new TextField(10);
姓名=new TextField(10);
录入=new Button(“录入”);
录入.addActionListener(this);
add(new Label(“学号:”,Label.CENTER));
add(学号);
add(new Label(“姓名:”,Label.CENTER));
add(姓名);
add(录入);
validate();
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()录入)
{ String number="";
number=学号.getText();
if(number.length()>0)
{ try { inOne=new FileInputStream(file);
inTwo=new ObjectInputStream(inOne);
基本信息表=(Hashtable)inTwo.readObject();
inOne.close();
inTwo.close();
}
catch(Exception ee){}
if(基本信息表.containsKey(number))
{ String m=“信息已存在,新的信息将覆盖原信息!”;
int ok=JOptionPane.showConfirmDialog(this,m,“确认”,
JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
if(ok
JOptionPane.YES_OPTION)
{ record(number);
}
}
else
{ record(number);
}
}
else
{ String warning=“必须要输入学号!”;
JOptionPane.showMessageDialog(this,warning,“警告”,
JOptionPane.WARNING_MESSAGE);
}
}
}
public void record(String number)
{ String name=姓名.getText();
学生=new Student();
学生.setNumber(number);
学生.setName(name);
try{ outOne=new FileOutputStream(file);
outTwo=new ObjectOutputStream(outOne);
基本信息表.put(number,学生);
outTwo.writeObject(基本信息表);
outTwo.close();
outOne.close();
学号.setText(null);
姓名.setText(null);
}
catch(Exception ee){}
}
}
Inquest.java
import java.awt.
;
import java.awt.event.;
import java.io.
;
import java.util.;
import javax.swing.
;
public class Inquest extends Dialog implements ActionListener
{ Hashtable 基本信息表=null;
TextField 学号;
Button 按学号查询,查询全部;
TextArea show=new TextArea(6,28);
FileInputStream inOne=null;
ObjectInputStream inTwo=null;
File file=null;
public Inquest(Frame f,File file)
{ super(f,“查询对话框”,false);
setLayout(new FlowLayout());
this.file=file;
学号=new TextField(10);
按学号查询=new Button(“按学号查询”);
按学号查询.addActionListener(this);
查询全部=new Button(“查询全部”);
查询全部.addActionListener(this);
add(new Label(“输入要查询的学号:”,JLabel.CENTER));
add(学号);
add(按学号查询);
add(查询全部);
add(show);
setBounds(100,200,360,270);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ setVisible(false);
}
});
}
public void actionPerformed(ActionEvent e)
{ show.setText(null);
readHashtable();
if(e.getSource()==按学号查询)
{ String number=”";
number=学号.getText();
if(number.length()>0)
{ if(基本信息表.containsKey(number))
{ Student stu=(Student)基本信息表.get(number);
show.setText(“学号:”+stu.getNumber()+" 姓名:"+stu.getName());
}
else
{ String warning=“该学号不存在!”;
JOptionPane.showMessageDialog(this,warning,“警告”,
JOptionPane.WARNING_MESSAGE);
}
}
else
{ String warning=“必须要输入学号!”;
JOptionPane.showMessageDialog(this,warning,“警告”,
JOptionPane.WARNING_MESSAGE);
}
}
if(e.getSource()==查询全部)
{ Enumeration enum=基本信息表.elements();
while(enum.hasMoreElements()) //遍历当前散列表
{ Student stu=(Student)enum.nextElement();
show.append(“学号:”+stu.getNumber()+" 姓名:"+stu.getName()+"\n");
}
}
}
public void readHashtable()
{ try { inOne=new FileInputStream(file);
inTwo=new ObjectInputStream(inOne);
基本信息表=(Hashtable)inTwo.readObject();
inOne.close();
inTwo.close();
}
catch(Exception ee) {}
}
}
例子12
import java.util.Vector;
public class Example13_12
{ public static void main(String args[])
{ Vector vector=new Vector();
int a[]={1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4};
System.out.println(“随机排列之前的数组:”);
for(int i=0;i<a.length;i++)
{ System.out.print(" “+a[i]);
}
System.out.println(”");
for(int i=0;i<a.length;i++)
{ vector.add(new Integer(a[i]));
}
int k=0;
while(vector.size()>0)
{ int index=(int)(Math.random()*vector.size());
int number=((Integer)vector.get(index)).intValue();
a[k]=number;
k++;
vector.removeElementAt(index);
}
System.out.println(“随机排列之后的数组:”);
for(int i=0;i<a.length;i++)
{ System.out.print(" "+a[i]);
}
}
}

第十四章 图形与图像
例子1
import java.applet.;
import java.awt.
;
public class Example14_1 extends Applet
{ public void paint(Graphics g)
{ g.drawOval(0,0,100,100);
g.drawRoundRect(110,10,90,60,50,30);
g.setColor(Color.black);
g.fillArc(0,0,100,100,-90,-180);
g.setColor(Color.white);
g.fillArc(0,0,100,100, -90,180);
g.fillArc(25,0,50,50,-90,-180);
g.setColor(Color.black);
g.fillOval(40,15,20,20);
g.fillArc(25,50,50,50,90,-180);
g.setColor(Color.white);
g.fillOval(40,65,20,20);
g.setColor(Color.black);
int px[]={50,70,170};
int py[]={120,150,80};
g.drawPolygon(px,py,3);
}
}
例子2
import java.applet.;
import java.awt.
;
public class Example14_2 extends Applet
{ Font f1=new Font(“隶书”,Font.BOLD,28);
Font f2= new Font(“TimesRoman”,Font.BOLD+Font.ITALIC,16);
public void paint(Graphics g)
{ g.setFont(f1);
g.drawString(“计算机科学技术”,10,30);
g.setFont(f2);
char a[]=“I Love You”.toCharArray();
int x=80,y=0;
for(int i=0;i<a.length;i++)
{ y=x-15;
g.drawChars(a,i,1,x,y);
x=x+8;
}
}
}
例子3
import java.applet.;
import java.awt.
;
import java.awt.event.;
public class Example14_3 extends Applet
{ int i=0;
public void paint(Graphics g)
{ i=(i+2)%360;
Color c=new Color((3
i)%255,(7i)%255,(11i)%255);
g.setColor©;
g.fillArc(30,50,120,100,i,2);
g.fillArc(30,152,120,100,i,2);
try{ Thread.sleep(300);
}
catch(InterruptedException e){}
repaint();
}
public void update(Graphics g)
{ g.clearRect(30,152,120,100);
paint(g);
}
}
例子4
import java.awt.;
import java.applet.
;
import java.awt.geom.;
public class Example14_4 extends Applet
{ public void paint(Graphics g)
{ g.setColor(Color.blue) ;
Graphics2D g_2d=(Graphics2D)g;
Ellipse2D ellipse=
new Ellipse2D.Double (20,30,100,50);
Line2D line=new Line2D.Double(70,30,70,10);
g_2d.setColor(Color.red);
g_2d.draw(line);
for(int i=1,k=0;i<=6;i++)
{ ellipse.setFrame(20+k,30,100-2
k,50);
if(i<=5)
g_2d.draw(ellipse);
else
g_2d.fill(ellipse);
k=k+5;
}
}
}
例子5
import java.awt.;
import java.applet.
;
import java.awt.geom.;
public class Example14_4 extends Applet
{ public void paint(Graphics g)
{ g.setColor(Color.red) ;
Graphics2D g_2d=(Graphics2D)g;
Arc2D arc=
new Arc2D.Double (2,2,80,80,0,270,Arc2D.OPEN);
g_2d.draw(arc);
arc.setArc(2,90,80,80,0,270,Arc2D.CHORD);
g_2d.draw(arc);
arc.setArc(90,2,80,80,0,270,Arc2D.PIE);
g_2d.fill(arc);
}
}
例子6
import java.awt.
;
import java.applet.;
import java.awt.geom.
;
public class Example14_6 extends Applet
{ public void paint(Graphics g)
{ Graphics2D g_2d=(Graphics2D)g;
QuadCurve2D quadCurve=
new QuadCurve2D.Double(2,10,51,70,100,10);
g_2d.drawString(“控制点”,51,70);
Line2D line=new Line2D.Double(2,10,51,70);
g_2d.draw(quadCurve);
g_2d.draw(line);
line.setLine(100,10,51,70);
g_2d.draw(line);
CubicCurve2D cubicCurve=
new CubicCurve2D.Double(2,96,40,180,70,50,136,96);
g_2d.draw(cubicCurve);
}
}
例子7
import java.awt.;
import java.applet.
;
import java.awt.geom.*;
public class Example14_7 extends Applet
{
public void paint(Graphics g)
{
Graphics2D g_2d=(Graphics2D)g;
BasicStroke bs_1
=new BasicStroke(16,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);
BasicStroke bs_2
=new BasicStroke(16f,BasicStroke.CAP_ROUND,BasicStroke.JOIN_MITER);
BasicStroke bs_3
=new BasicStroke(16f,BasicStroke.CAP_SQUARE,BasicStroke.JOIN_ROUND);
Line2D redLineOne=new Line2D.Double(0,16,120,16);
Line2D redLineTwo=new Line2D.Double(120,16,120,70);
g_2d.setStroke(bs_1);
g_2d.setColor(Color.red);
g_2d.draw(redLineOne);
g_2d.draw(redLineTwo);
g_2d.setColor(Color.blue);
Line2D blueLineOne=new Line2D.Double(0,40,85,40);
Line2D blueLineTwo=new Line2D.Double(85,40,85,80);
g_2d.setStroke(bs_2);
g_2d.draw(blueLineOne);
g_2d.draw(blueLineTwo);
g_2d.setColor(Color.green);
Line2D greanLineOne=new Line2D.Double(0,80,65,80);
Line2D greanLineTwo=new Line2D.Double(65,80,65,120);
g_2d.setStroke(bs_3);
g_2d.draw(greanLineOne);
g_2d.draw(greanLineTwo);

}

}
例子8
import java.awt.;
import java.applet.
;
import java.awt.geom.;
public class Example extends Applet
{ public void paint(Graphics g)
{ Graphics2D g_2d=(Graphics2D)g;
GradientPaint gradient_1
=new GradientPaint(0,0,Color.red,50,50,Color.green,false);
g_2d.setPaint(gradient_1);
Rectangle2D rect_1=new Rectangle2D.Double (0,0,50,50);
g_2d.fill(rect_1);
GradientPaint gradient_2
=new GradientPaint(60,50,Color.white,150,50,Color.red,false);
g_2d.setPaint(gradient_2);
Rectangle2D rect_2=new Rectangle2D.Double (60,50,90,50);
g_2d.fill(rect_2);
}
}
例子9
import java.awt.
;
import java.applet.;
import java.awt.geom.
;
public class Example14_9 extends Applet
{ public void paint(Graphics g)
{ Graphics2D g_2d=(Graphics2D)g;
String s=“旋转起来”;
Ellipse2D ellipse=
new Ellipse2D. Double (30,30,80,30);
AffineTransform trans=new AffineTransform();
for(int i=1;i<=24;i++)
{ trans.rotate(15.0Math.PI/180,70,45);
g_2d.setTransform(trans);
//现在画的就是旋转后的椭圆样子
g_2d.draw(ellipse);
}
for(int i=1;i<=12;i++)
{ trans.rotate(30.0
Math.PI/180,60,160);
g_2d.setTransform(trans);
//现在画的就是旋转后的字符串
g_2d.drawString(s,60,160);
}
}
}
例子10
import java.awt.geom.;
import java.awt.
;
import java.applet.;
public class Example14_8 extends Applet
{ public void paint(Graphics g)
{ Graphics2D g_2d=(Graphics2D)g;
Ellipse2D ellipse=
new Ellipse2D.Double(0,2,80,80);
Rectangle2D rect=
new Rectangle2D.Double(40,2,80,80);
Area a1=new Area(ellipse);
Area a2=new Area(rect);
a1.intersect(a2); //“与”
g_2d.fill(a1);
ellipse.setFrame(130,2,80,80);
rect.setFrame(170,2,80,80);
a1=new Area(ellipse);
a2=new Area(rect);
a1.add(a2); //“或”
g_2d.draw(a1);
ellipse.setFrame(0,90,80,80);
rect.setFrame(40,90,80,80);
a1=new Area(ellipse);
a2=new Area(rect);
a1.subtract(a2); //“差”
g_2d.draw(a1);
ellipse.setFrame(130,90,80,80);
rect.setFrame(170,90,80,80);
a1=new Area(ellipse);
a2=new Area(rect);
a1.exclusiveOr(a2); //“异或”
g_2d.fill(a1);
}
}
例子11
import java.awt.
;
import java.applet.;
import java.awt.geom.
;
public class Example14_11 extends Applet
{
public void paint(Graphics g)
{
Graphics2D g_2d=(Graphics2D)g;
Ellipse2D ellipse1=
new Ellipse2D. Double (20,80,60,60),
ellipse2=
new Ellipse2D. Double (40,80,80,80);
g_2d.setColor(Color.blue);
Area a1=new Area(ellipse1),
a2=new Area(ellipse2);
a1.subtract(a2); //“差”
AffineTransform trans=new AffineTransform();
for(int i=1;i<=10;i++)
{
trans.rotate(36.0Math.PI/180,95,105);
g_2d.setTransform(trans);
g_2d.fill(a1);
}
}
}
例子12
import java.awt.
;
import java.awt.event.;
import javax.swing.Timer;
import java.awt.geom.
;
import java.util.;
class Clock extends Canvas
implements ActionListener
{ Date date;
Timer secondTime;
int hour,munite,second;
Line2D secondLine,muniteLine,hourLine;
int a,b,c;
double pointSX[]=new double[60],//用来表示秒针端点坐标的数组
pointSY[]=new double[60],
pointMX[]=new double[60], //用来表示分针端点坐标的数组
pointMY[]=new double[60],
pointHX[]=new double[60], //用来表示时针端点坐标的数组
pointHY[]=new double[60];
Clock()
{ secondTime=new Timer(1000,this);
pointSX[0]=0; //12点秒针位置
pointSY[0]=-100;
pointMX[0]=0; //12点分针位置
pointMY[0]=-90;
pointHX[0]=0; //12点时针位置
pointHY[0]=-70;
double angle=6
Math.PI/180; //刻度为6度
for(int i=0;i<59;i++) //计算出各个数组中的坐标
{ pointSX[i+1]=pointSX[i]Math.cos(angle)-Math.sin(angle)pointSY[i];
pointSY[i+1]=pointSY[i]Math.cos(angle)+pointSX[i]Math.sin(angle);
pointMX[i+1]=pointMX[i]Math.cos(angle)-Math.sin(angle)pointMY[i];
pointMY[i+1]=pointMY[i]Math.cos(angle)+pointMX[i]Math.sin(angle);
pointHX[i+1]=pointHX[i]Math.cos(angle)-Math.sin(angle)pointHY[i];
pointHY[i+1]=pointHY[i]Math.cos(angle)+pointHX[i]Math.sin(angle);
}
for(int i=0;i<60;i++)
{ pointSX[i]=pointSX[i]+120; //坐标平移
pointSY[i]=pointSY[i]+120;
pointMX[i]=pointMX[i]+120; //坐标平移
pointMY[i]=pointMY[i]+120;
pointHX[i]=pointHX[i]+120; //坐标平移
pointHY[i]=pointHY[i]+120;
}
secondLine=new Line2D.Double(0,0,0,0);
muniteLine=new Line2D.Double(0,0,0,0);
hourLine=new Line2D.Double(0,0,0,0);
secondTime.start(); //秒针开始计时
}
public void paint(Graphics g)
{ for(int i=0;i<60;i++) //绘制表盘上的小刻度和大刻度
{ int m=(int)pointSX[i];
int n=(int)pointSY[i];
if(i%5==0)
{ g.setColor(Color.red);
g.fillOval(m-4,n-4,8,8);
}
else
{ g.setColor(Color.cyan);
g.fillOval(m-2,n-2,4,4);
}
}
g.fillOval(115,115,10,10); //钟表中心的实心圆
Graphics2D g_2d=(Graphics2D)g;
g_2d.setColor(Color.red);
g_2d.draw(secondLine);
BasicStroke bs=
new BasicStroke(3f,BasicStroke.CAP_ROUND,BasicStroke.JOIN_MITER);
g_2d.setStroke(bs);
g_2d.setColor(Color.blue);
g_2d.draw(muniteLine);
bs=new BasicStroke(6f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER);
g_2d.setStroke(bs);
g_2d.setColor(Color.green);
g_2d.draw(hourLine);
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==secondTime)
{ date=new Date();
String s=date.toString();
hour=Integer.parseInt(s.substring(11,13));
munite=Integer.parseInt(s.substring(14,16));
second=Integer.parseInt(s.substring(17,19)); //获取时间中的秒
int h=hour%12;
a=second; //秒针端点的坐标
b=munite; //分针端点的坐标
c=h
5+munite/12; //时针端点的坐标
secondLine.setLine(120,120,(int)pointSX[a],(int)pointSY[a]);
muniteLine.setLine(120,120,(int)pointMX[b],(int)pointMY[b]);
hourLine.setLine(120,120,(int)pointHX[c],(int)pointHY[c]);
repaint();
}
}
}
public class Example14_12
{ public static void main(String args[])
{ Frame win=new Frame();
win.add(new Clock(),BorderLayout.CENTER);
win.setVisible(true);
win.setSize(246,280);
win.validate();
win.addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
} );
}
}
例子13
import java.applet.
;
import java.awt.
;
public class Example14_13 extends Applet
{ Image img;
public void start()
{ img=getImage(getCodeBase(),“vintdev.jpg”);
}
public void paint(Graphics g)
{ g.drawImage(img,22,72,100,100,this);
}
}
例子14
import java.awt.
;
import java.awt.event.
;
class Imagecanvas extends Canvas
{ Toolkit tool;
Image image;
Imagecanvas()
{ setSize(200,200);
tool=getToolkit();//得到一个Toolkit对象。
image=tool.getImage(“dog.gif”);//由tool负责获取图像。
}
public void paint(Graphics g)
{ g.drawImage(image,10,10,image.getWidth(this),image.getHeight(this),this);
}
public Image getImage()
{ return image;
}
}
public class Example14_14
{ public static void main(String args[])
{ Imagecanvas canvas=new Imagecanvas();
Frame frame=new Frame();
frame.add(canvas,BorderLayout.CENTER);
frame.setSize(300,300);
frame.setVisible(true);
frame.setIconImage(canvas.getImage());
frame.validate();
frame.addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
}
}
例子15
import com.sun.image.codec.jpeg.
;
import java.awt.image.
;
import java.awt.
;
import java.util.
;
import java.awt.event.
;
import java.io.
;
class PaintCanvas extends Canvas
{ int x=-1,y=-1;
Vector v=new Vector();
BufferedImage image;
Graphics2D g2D;
PaintCanvas()
{ image=new BufferedImage(300,300,BufferedImage.TYPE_INT_RGB);
g2D=image.createGraphics();
addMouseMotionListener(new MouseMotionAdapter()
{ public void mouseDragged(MouseEvent e)
{ x=(int)e.getX();y=(int)e.getY();
Point p=new Point(x,y);
v.addElement§;
if(x!=-1&&y!=-1)
{ for(int i=0;i<v.size()-1;i++)
{ Point p1=(Point)v.elementAt(i);
Point p2=(Point)v.elementAt(i+1);
//在图像image上绘制
g2D.drawLine(p1.x,p1.y,p2.x,p2.y);
}
repaint();
}
}
}
);
addMouseListener(new MouseAdapter()
{ public void mouseReleased(MouseEvent e)
{ v.removeAllElements();
}
}
);
}
public void paint(Graphics g)
{ g.drawImage(image,0,0,this) ; //将内存中的图像iamge绘制在画布上
}
public void update(Graphics g)
{ paint(g);
}
}
class WindowCanvas extends Frame implements ActionListener
{ PaintCanvas canvas=new PaintCanvas();
Button button=new Button(“save”);
WindowCanvas()
{ button.addActionListener(this);
add(canvas,BorderLayout.CENTER);
add(button,BorderLayout.NORTH);
setBounds(100,100,400,400);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ try {JPEGImageEncoder encoder=
JPEGCodec.createJPEGEncoder(new FileOutputStream(“A.jpg”));
encoder.encode(canvas.image);
}
catch(Exception ee) {}
}
}
public class JPG
{ public static void main(String args[])
{ new WindowCanvas();
}
}
例子16
import java.awt.
;import java.applet.;
public class PaintTest extends Applet
{ public void init()
{ setBackground(Color.yellow);
}
public void paint(Graphics g)
{ g.setXORMode(Color.red);
g.setColor(Color.green);
g.fillRect(20,20,80,40);
g.setColor(Color.yellow);
g.fillRect(60,20,80,40);
g.setColor(Color.green);
g.fillRect(20,70,80,40);
g.fillRect(60,70,80,40);
g.drawLine(100,100,200,200);
g.drawLine(100,100,220,220); //该直线消失
}
}
例子17
import java.awt.
;
import java.awt.event.;
import java.awt.geom.
;
public class Example14_17
{ public static void main(String args[])
{ Frame f=new Frame();
f.setSize(170,170);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
PrintJob p=f.getToolkit().getPrintJob(f,“ok”,null);
Graphics g=p.getGraphics();
g.drawRect(30,30,40,40);
g.dispose();
p.end();
}
}

第十五章 Java数据库连接(JDBC)
例子1
import java.sql.;
public class Example15_1
{ public static void main(String args[])
{ Connection con;
Statement sql;
ResultSet rs;
try { Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch(ClassNotFoundException e)
{ System.out.println(""+e);
}
try { con=DriverManager.getConnection(“jdbc:odbc:sun”,“gxy”,“123”);
sql=con.createStatement();
rs=sql.executeQuery(“SELECT * FROM chengjibiao”);
while(rs.next())
{ String number=rs.getString(1);
String name=rs.getString(2);
String date=rs.getString(3);
int math=rs.getInt(“math”);
int english=rs.getInt(“english”);
System.out.print(“学号:”+number);
System.out.print(" 姓名:"+name);
System.out.print(" 出生:"+date);
System.out.print(" 数学:"+math);
System.out.println(" 英语:"+english);
}
con.close();
}
catch(SQLException e)
{ System.out.println(e);
}
}
}
例子2
import java.sql.
;
public class Example15_2
{ public static void main(String args[])
{ Connection con;
Statement sql;
ResultSet rs;
try { Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch(ClassNotFoundException e){}
try { con=DriverManager.getConnection(“jdbc:odbc:sun”,“gxy”,“123”);
sql=con.createStatement();
rs=sql.executeQuery(“SELECT name,english FROM chengjibiao WHERE english >= 80 “);
while(rs.next())
{ String name=rs.getString(1);
int english=rs.getInt(“english”);
System.out.print(” 姓名:”+name);
System.out.println(" 英语:"+english);
}
con.close();
}
catch(SQLException e)
{ System.out.println(e);
}
}
}
例子3
import java.sql.;
public class Example15_3
{ public static void main(String args[])
{ Connection con;Statement sql; ResultSet rs;
try { Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch(ClassNotFoundException e)
{ System.out.println(""+e);
}
try { con=DriverManager.getConnection(“jdbc:odbc:sun”,“gxy”,“123”);
sql=
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs=sql.executeQuery(“SELECT name,english FROM chengjibiao”);
rs.last();
int number=rs.getRow();
System.out.println(“该表共有”+number+“条记录”);
rs.afterLast();
while(rs.previous())
{ String name=rs.getString(“name”);
int english=rs.getInt(“english”);
System.out.print(" 姓名:"+name);
System.out.println(" 英语:"+english);
}
System.out.println(“单独输出第5条记录:”);
rs.absolute(5);
String name=rs.getString(“name”);
int english=rs.getInt(“english”);
System.out.print(" 姓名:"+name);
System.out.println(" 英语:"+english);
con.close();
}
catch(SQLException e)
{ System.out.println(e);
}
}
}
例子4
import java.sql.
;
public class Example15_4
{ public static void main(String args[])
{ Connection con;Statement sql; ResultSet rs;
try { Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch(ClassNotFoundException e){}
try { con=DriverManager.getConnection(“jdbc:odbc:sun”,“gxy”,“123”);
sql=con.createStatement();
String condition=“SELECT name,english FROM chengjibiao ORDER BY english”;
rs=sql.executeQuery(condition);
while(rs.next())
{ String name=rs.getString(1);
int english=rs.getInt(2);
System.out.print(" 姓名:"+name);
System.out.println(" 英语:"+english);
}
con.close();
}
catch(SQLException e)
{ System.out.println(e);
}
}
}
例子5
import java.sql.*;
public class Example15_5
{ public static void main(String args[])
{ Connection con;
Statement sql;
ResultSet rs;
try { Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch(ClassNotFoundException e){}
try { con=DriverManager.getConnection(“jdbc:odbc:sun”,“gxy”,“123”);
sql=con.createStatement();
rs=sql.executeQuery(“SELECT name,math FROM chengjibiao WHERE name LIKE ‘%小%’ “);
while(rs.next())
{ String name=rs.getString(1);
int math=rs.getInt(2);
System.out.print(” 姓名:”+name);
System.out.println(" 数学:"+math);
}
con.close();
}
catch(SQLException e)
{ System.out.println(e);
}
}
}

例子6
import java.sql.;
import java.util.LinkedList;
public class Example15_6
{ public static void main(String args[])
{ LinkedList list=new LinkedList();
Connection con;
Statement sql;
ResultSet rs;
try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch(ClassNotFoundException e){}
try { con=DriverManager.getConnection(“jdbc:odbc:sun”,“gxy”,“123”);
sql=
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs=sql.executeQuery(“SELECT name,math FROM chengjibiao”);
rs.last();
int lownumber=rs.getRow();
int number=lownumber;
for(int i=1;i<=number;i++)
{ list.add(new Integer(i));
}
double sum=0;
int k=4;
int 抽取数目=k;
while(k>0)
{ int i=(int)(Math.random()list.size());
int index=((Integer)list.get(i)).intValue();
rs.absolute(index);
System.out.print(“姓名:”+rs.getString(1));
System.out.println(“数学:”+rs.getString(2));
int math=rs.getInt(“math”);
sum=sum+math;
k–;
list.remove(i);
}
System.out.println(“抽样的数学平均成绩:”+sum/抽取数目);
con.close();
}
catch(SQLException e)
{ System.out.println(e);
}
}
}
例子7
import java.sql.
;
public class Example15_7
{ public static void main(String args[])
{ Connection con;
Statement sql;
ResultSet rs;
try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch(ClassNotFoundException e){}
try { con=DriverManager.getConnection(“jdbc:odbc:sun”,“gxy”,“123”);
sql=con.createStatement();
int math=99,english=0;
String number=“2003001”,date,name,recode,updateStr,insertStr,delStr;
updateStr=
“UPDATE chengjibiao SET math =”+math+" WHERE number = “+”’"+number+"’";
math=92;
english=66;
number=“2003039”;
name=“周王”;
date=“1999-12-28”;
recode= “(”+"’"+number+"’"+","+"’"+name+"’"+","+"’"+date+"’"+","+math+","+english+")";
insertStr=“INSERT INTO chengjibiao VALUES “+recode;
delStr=“DELETE FROM chengjibiao WHERE number = ‘2003004’ “;
sql.executeUpdate(updateStr);
sql.executeUpdate(insertStr);
sql.executeUpdate(delStr);
rs=sql.executeQuery(“SELECT * FROM chengjibiao”);
while(rs.next())
{ number=rs.getString(1);
name=rs.getString(2);
date=rs.getString(3);
math=rs.getInt(“math”);
english=rs.getInt(“english”);
System.out.print(“学号:”+number);
System.out.print(” 姓名:”+name);
System.out.print(” 出生:”+date);
System.out.print(" 数学:"+math);
System.out.println(" 英语:"+english);
}
con.close();
}
catch(SQLException e)
{ System.out.println(e);
}
}
}
例子8
import java.sql.
;
public class Example15_8
{ public static void main(String args[])
{ Connection con;
PreparedStatement sql;
ResultSet rs;
try { Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch(ClassNotFoundException e)
{ System.out.println(""+e);
}
try { con=DriverManager.getConnection(“jdbc:odbc:sun”,“gxy”,“123”);
sql=con.prepareStatement(“SELECT * FROM chengjibiao”); //预处理语句
rs=sql.executeQuery();
while(rs.next())
{ String number=rs.getString(1);
String name=rs.getString(2);
System.out.print(“学号:”+number);
System.out.println(" 姓名:"+name);
}
con.close();
}
catch(SQLException e)
{ System.out.println(e);
}
}
}
例子9
import java.sql.;
public class Example15_9
{ public static void main(String args[])
{ Connection con;
PreparedStatement sqlOne,sqlTwo,sqlThree;
ResultSet rs;
try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch(ClassNotFoundException e){}
try { con=DriverManager.getConnection(“jdbc:odbc:sun”,“gxy”,“123”);
sqlOne=
con.prepareStatement(“UPDATE chengjibiao SET math = ? WHERE number= ? “);
sqlOne.setInt(1,100);
sqlOne.setString(2,“2003001”);
sqlOne.executeUpdate();
sqlOne.setInt(1,99);
sqlOne.setString(2,“2003002”);
sqlOne.executeUpdate();
sqlTwo=
con.prepareStatement(“INSERT INTO chengjibiao VALUES (?,?,?,?,?)”);
sqlTwo.setString(1,“2003888”);
sqlTwo.setString(2,“李向阳”);
sqlTwo.setString(3,“1919-05-04”);
sqlTwo.setInt(4,99);
sqlTwo.setInt(5,88);
sqlTwo.executeUpdate();
sqlThree=con.prepareStatement
(“SELECT number,math,english FROM chengjibiao WHERE english >= ? AND math >= ? “);
sqlThree.setInt(1,88);
sqlThree.setInt(2,90);
rs=sqlThree.executeQuery() ;
while(rs.next())
{ System.out.print(“学号:”+rs.getString(1));
System.out.print(” 数学:”+rs.getInt(2));
System.out.println(” 英语:”+rs.getInt(3));
}
con.close();
}
catch(SQLException e)
{ System.out.println(e);
}
}
}
例子10
(1) 客户端程序
Client.java
import java.net.
;
import java.io.;
import java.awt.
;
import java.awt.event.;
import javax.swing.
;
public class Client
{
public static void main(String args[])
{ new QueryClient();
}
}
class QueryClient extends Frame
implements Runnable,ActionListener
{ Button connection,send;
TextField inputText;
TextArea showResult;
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread thread;
QueryClient()
{ socket=new Socket();
Panel p=new Panel();
connection=new Button(“连接服务器”);
send=new Button(“发送”);
send.setEnabled(false);
inputText=new TextField(8);
showResult=new TextArea(6,42);
p.add(connection);
p.add(new Label(“输入学号”));
p.add(inputText);
p.add(send);
add(p,BorderLayout.NORTH);
add(showResult,BorderLayout.CENTER);
connection.addActionListener(this);
send.addActionListener(this);
thread=new Thread(this);
setBounds(10,30,350,400);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==connection)
{ try
{ if(socket.isConnected())
{}
else
{ InetAddress address=InetAddress.getByName(“127.0.0.1”);
InetSocketAddress socketAddress=new InetSocketAddress(address,4331);
socket.connect(socketAddress);
in =new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
send.setEnabled(true);
thread.start();
}
}
catch (IOException ee){}
}
if(e.getSource()==send)
{ String s=inputText.getText();
if(s!=null)
{ try { out.writeUTF(s);
}
catch(IOException e1){}
}
}
}
public void run()
{ String s=null;
while(true)
{ try{ s=in.readUTF();
showResult.append("\n"+s);
}
catch(IOException e)
{ showResult.setText(“与服务器已断开”);
break;
}
}
}
}
(2) 服务器端程序
Server.java
import java.io.;
import java.net.
;
import java.util.;
import java.sql.
;
public class Server
{ public static void main(String args[])
{ Connection con;
PreparedStatement sql=null;
ResultSet rs;
try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch(ClassNotFoundException e){}
try{ con=DriverManager.getConnection(“jdbc:odbc:sun”,“gxy”,“123”);
sql=con.prepareStatement(“SELECT * FROM chengjibiao WHERE number = ? “);
}
catch(SQLException e){}
ServerSocket server=null;
Server_thread thread;
Socket you=null;
while(true)
{ try{ server=new ServerSocket(4331);
}
catch(IOException e1)
{ System.out.println(“正在监听”);
}
try{ System.out.println(” 等待客户呼叫”);
you=server.accept();
System.out.println(“客户的地址:”+you.getInetAddress());
}
catch(IOException e)
{ System.out.println(“正在等待客户”);

Java2实用教程 rar 第1章Java入门 1 1Java的诞生 1 2Java的特点 1 3安装Sun公司的SDK 1 4一个Java程序的开发过程 1 5一个简单的Java应用程序的开发过程 1 6一个简单的Java小应用程序 1 7什么是JSP 习题 第2章标识符 关键字和数据类型 2 1标识符和关键字 2 2Java的基本数据类型 2 3Java的数组 习题 第3章运算符 表达式和语句 3 1运算符与表达式 3 2语句概述 3 3控制语句 3 4 循环语句 3 5break和continue语句 习题 第4章类 对象和接口 4 1编程语言的几个发展阶段 4 1 1机器语言 4 1 2过程语言 4 1 3面向对象编程 4 2类 4 2 1类声明 4 2 2类体 4 2 3成员变量和局部变量 4 2 4方法 4 2 5方法重载 4 2 6构造方法 4 2 7类方法和实例方法 4 2 8值得注意的问题 4 3对象 4 3 1创建对象 4 3 2使用对象 4 3 3于象的引用和实体 4 3 4参数传值 4 4static关键字 4 4 1实例变量和类变量的区别 4 4 2实例方法和类方法的区别 4 5this关键字 4 6包 4 6 1包语句 4 6 2import语句 4 6 3将类打包 4 7访问权限 4 7 1私有变量和私有方法 4 7 2共有变量和共有方法 4 7 3友好变量和友好方法 4 7 4受保护的成员变量和方法 4 7 5public类与友好类 4 8类的继承 4 8 1子类 4 8 2子类的继承性 4 8 3成员变量的隐藏和方法的重写 4 8 4final关键字 4 9对象的上转型对象 4 10多态性 4 11abstract类和abstract方法 4 12super关键字 4 13接口 4 13 1接口的声明与使用 4 13 2理解接口 4 13 3接口回调 4 13 4接口做参数 4 14内部类 4 15匿名类 4 15 1和类有关的匿名类 4 15 2和接口有关的匿名类 4 16异常类 4 16 1try catch语句 4 16 2自定义异常类 4 17Class类 4 17 1获取类的有关信息 4 17 2使用Class实例化一个对象 4 18基本类型的类包装 4 18 1Double类和Float类 4 18 2Byte Integer Short 工 ong类 4 18 3Character类 4 19反编译和文档生成器 4 20JAR文件 4 20 1将应用程序压缩为JAR文件 4 20 2将类压缩成JAR文件 4 20 3更新 查看JAR文件 习题 第5章字符串 5 1字符串 5 2字符串的常用方法 5 3字符串与基本数据的相互转化 5 4对象的字符串表示 5 5StringTokenizer类 5 6字符串与字符 字节数组 5 7StringBuffer类 5 8正则表达式 习题 第6章时间 日期和数字 6 1Date类 6 2Calendar类 6 3Math类 6 4BigInteger类 习题 第7章AWT组件及事件处理 7 1Java窗口 7 1 1 Frame常用方法 7 1 2菜单条 菜单 菜单项 7 1 3窗口与屏幕 7 2文本框 7 2 1TextField类的主要方法 7 2 2文本框上的ActionEvent事件 7 3内部类实例做监视器 7 4按钮与标签 7 4 1标签组件 7 4 2按钮组件 7 5菜单项 7 6文本区 7 6 1TextArea类主要方法 7 6 2文本区上的TextEvent事件 7 7面板 7 7 1Panel类 7 7 2ScrollPane类 7 8布局 7 8 1FlowLayout布局 7 8 2BorderLayout布局 7 8 3CardLayout布局 7 8 4GridLayout布局 7 8 5BoxLayout布局 7 8 6null布局 7 9画布 7 10选择型组件 7 10 1选择框 7 10 2下拉列表 7 10 3滚动列表 7 11Component类的常用方法 7 12窗口事件 7 13鼠标事件 7 14焦点事件 7 15键盘事件 7 16使用剪贴板 7 17打印 7 18综合实例 习题 第8章建立对话框 8 1Dialog类 8 2文件对话框 8 3消息对话框 8 4确认对话框 8 5颜色对话框 习题 第9章Java多线程机制 9 1Java中的线程 9 2Thread类的子类创建线程 9 3使用Runnable接口 9 4线程的常用方法 9 5GUI线程 9 6线程同步 9 7在同步方法中使用wait notif 和nodf3 All 方法 9 8挂起 恢复和终止线程 9 9计时器线程Timer 9 10线程联合 9 11守护线程 习题 第10章输入输出流 10 1File类 10 2FileInputStream类 10 3FileOutputStream类 10 4FileReader类和FileWriter类 10 5使用文件对话框打开和保存文件 10 6RandornAccessFile类 10 7数据流 10 8数组流 10 9对象流 10 10序列化与对象克隆 10 11文件锁FileLock 10 12Process类中的流 10 13带进度条的输入流 习题 第11章Java网络的基本知识 11 1使用URL 11 2读取URL中的资源 11 3显示URL资源中的HTML文件 11 4处理超链接 11 5InetAdress类 11 6套接字 11 7网络中的数据压缩与传输 11 8UDP数据报 11 9广播数据报 习题 第12JavaApplet基础 12 1JavaApplet的运行原理 12 2网页向JavaApplet传值 12 3JavaApplet扣使用URL 12 4JavaApplet中建立新线程 12 5JavaApplet中使用套接字 习题 第13章常见数据结构的Java实现 13 1链表 13 2栈 13 3树集 13 4树映射 13 5散列集 13 6散列表 13 7向量 习题 第14章图形与图像 14 1绘制文本 14 2绘制基本图形 14 3建立字体 14 4清除 14 5Java2D 14 6图形的布尔运算 14 7绘制钟表 14 8绘制图像 14 9制作JPG图像 14 10XOR绘图模式 14 11打印图形 图像 习题 第15章Java数据库连接 JDBC 15 1创建数据源 15 2JDBC ODBC桥接器 l5 3顺序查询 15 4可滚动结果集 15 5排序查询 15 6模糊查询 15 7随机查询 15 8更新 添加 删除记录 l5 9预处理语句 15 10数据库访问中的套接字技术 习题 第16章Java与多媒体 16 1在小程序中播放音频 16 2在另一个线程中创建音频对象 16 3在应用程序中播放音频 16 4Java媒体框架 JMF 习题 第17章JavaSwing基础 17 1几个重要的类 17 2中间容器 17 3各种组件 习题">Java2实用教程 rar 第1章Java入门 1 1Java的诞生 1 2Java的特点 1 3安装Sun公司的SDK 1 4一个Java程序的开发过程 1 5一个简单的Java应用程序的开发过程 1 6一个简单的Java小应用程序 1 7什么是JSP 习题 第2章标识符 关键字和数据类型 2 1标识 [更多]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吴越子坤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值