现在的位置: 首页 > 综合 > 正文

Java2入门学习代码

2018年05月24日 ⁄ 综合 ⁄ 共 244326字 ⁄ 字号 评论关闭
  

 
 
第一章    Java 语言入门 10
第一章               Java 语言入门
简单、面向对象、稳定、与平台无关、解释型、多线程、动态等特点。
Java程序的开发过程:
源文件→Java编译器→字节码文件(由解释器执行)→对于Java小应用程序→由Web浏览器执行
其中字节码文件是与平台无关的二进制码,执行时解释成本地机器码。
(Java编译器javac.exe和解释器java.exe)
Java程序分为两类:Java小程序和Java程序
例:
public class Hello
{
   public static void main (String args[ ])
   {
     System.out.println("hello, Java !");
   }
}
一个Java源程序由若干个类组成,其中public static void main (String args[ ])是类中一个方法,此为应用程序的主类。main方法必须被说明为public static void 。
String args[ ]声明一个字符串类型的数组args[ ],main方法是程序开始执行的位置。一般来说,源文件的名字与其中的public类名相同。
public class People     //People.java
{
    float hight,weight;
    String head, ear, mouth;
   void speak(String s)                    //普通成员函数
   {
      System.out.println(s);
   }
}
class A
{ public static void main(String args[])
  {People zhubajie;
    zhubajie=new People();
    zhubajie.weight=200f;   
    zhubajie.hight=1.70F;
    zhubajie.head=“大头”;
    zhubajie.ear="两只大耳朵";
    zhubajie.mouth="一只大嘴";
    System.out.println("重量"+zhubajie.weight+"身高" +zhubajie.hight);
    System.out.println(zhubajie.head+zhubajie.mouth+zhubajie.ear);
    zhubajie.speak("师傅,咱们别去西天了,改去月宫吧");
    }
}
import java.applet.*;
import java.awt.*;
public class boy extends Applet
   public void paint(Graphics g)
    {
     g.setColor(Color.red);  
     g.drawString("我一边喝着咖啡,一边学Java呢",2,30);
     g.setColor(Color.blue);
    g.drawString("我学得很认真",10,50);
    }
}    
 
public class Example2_1
   public static void main (String args[ ])
    {
     char chinaWord='你',japanWord='ぁ';
     int p1=20328,p2=12358;
     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);
    }
}
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);
    }
}
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);
     }
  }
}
    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);
   }
    }
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("英语不是优");
       }
    if(math>60&&english>90)
       { System.out.println("英语是优,数学也及格了");
       }
     System.out.println("我在学习控制语句");
    }
}
import Java.applet.*;import Java.awt.*;
public class Example3_5 extends Applet
{ public void paint(Graphics g)
    { int x=2,y=1;
      switch(x+y)
        {case 1 :
             g.setColor(Color.red);g.drawString("i am 1",5,10);
             break;   
         case 2:
             g.setColor(Color.blue); g.drawString("i am 2",5,10);
             break;  
         case 3:  
           g.setColor(Color.green); g.drawString("i am 3",5,10);
            break;    
         default: g.drawString("没有般配的",5,10);
        }
    }
import Java.applet.*;import Java.awt.*;
public class Example3_6 extends Applet
{ public void paint(Graphics g)
    { int sum=0;
       for(int i=1;i<=100;i++)
        { sum=sum+i;
        }
      g.drawString("sum= "+sum,10,20);
    }
}
import Java.applet.*;import Java.awt.*;
public class Example3_7  extends Applet
{ public void paint(Graphics g)
    { long jiecheng=1;
      for(int i=10;i>=1;i--)
       { jiecheng=jiecheng*i;
       }
      g.drawString("10的阶乘是 "+jiecheng,10,20);
    }
}
class Example3_8
{   public static void main(String args[])
    { double sum=0,a=1;int i=1;
      while(i<=20)
        { a=a*(1.0/i);
          sum=sum+a;
          i=i+1;         
        }
      System.out.println("sum="+sum);
    }
}
class Example3_9
{ public static void main(String args[])
   { int sum=0,i,j;
      for( i=1;i<=10;i++)                  //计算1+3+5+7+9。
       { if(i%2==0)
            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+"是素数");
          }
       }     
   }
}


 
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 运算符和默认的构造方法。
  }
}
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 和类中的构造方法。
 }
}
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(); //为对象分配内存,使用new 运算符和默认的构造方法。
         sunwukong=new XiyoujiRenwu();
         zhubajie.height=1.80f;     //对象给自己的变量赋值。
         zhubajie.weight=160f;      zhubajie.hand="两只黑手";
         zhubajie.foot="两只大脚";  zhubajie.head="大头";
         zhubajie.ear="一双大耳朵"; zhubajie.mouth="一只大嘴";
         sunwukong.height=1.62f;    //对象给自己的变量赋值。
         sunwukong.weight=1000f;   sunwukong.hand="白嫩小手";
         sunwukong.foot="两只绣脚"; sunwukong.head="绣发飘飘";
         sunwukong.ear="一对小耳"; sunwukong.mouth="樱头小嘴";
         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);
       }
    }
import Java.applet.*;
import Java.awt.*;
class Student
{ float math,english,sum;
   float f(float k1,float k2)
   { sum=k1*math+k2*english;
     return sum;
   }
}
public class Example4_4 extends Applet
{ Student wanghong,lihong;
   public void init()
   { wanghong=new Student(); lihong =new Student();
     wanghong.math=60.0f;     wanghong.english=80f;
     lihong.math=70.0f;       lihong.english=90.0f;
     wanghong.sum=wanghong.f(2.0f,2.0f);
     lihong.sum=lihong.f(2.0f,2.0f);
   }
   public void paint(Graphics g)
   { g.drawString("lihong sum= "+lihong.sum,12,45);
     g.drawString("wanghong sum="+wanghong.sum,12,60);
   }
class 梯形
{  float 上底,下底,高;
   梯形()
   { 上底=60;
     下底=40;
      高=20;
   }
   梯形(float x,float y,float h)
    { 上底=x;
     下底=y;
       高=h;
   }
    float 计算面积()
    { float 面积;
      面积=(上底+下底)*高/2.0f;
      return 面积;
   }
    void 修改高(float height)
    { 高=height;
   }
    float 获取高()
    { return 高;
   }
}
class Example4_5  
{    public static void main(String args[])
    { 梯形 laderOne=new 梯形(),laderTwo=new 梯形(2.0f,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.计算面积());
   }
}
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)
 { 底圆.修改半径(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.计算体积()); 
   }
}
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);
       System.out.println("laderOne的下底:"+laderOne.获取下底());
       System.out.println("laderTwo的下底:"+laderTwo.获取下底());
       laderTwo.修改下底(60);
       System.out.println("laderOne的下底:"+laderOne.获取下底());
       System.out.println("laderTwo的下底:"+laderTwo.获取下底());
    }
}
import Java.applet.*;
import Java.awt.*;
class Family
{ static String familyname;
       String name;
 int age;    
}
public class Example4_8 extends Applet
{ Family father,son1,son2;
   public void init()
   { father=new Family();
     son1=new Family();son2=new Family();
     Family.familyname="打"; father.name="鬼子";
     son1.name="汉奸"; son2.name="恶霸";
   }
   public void paint(Graphics g)
   { g.drawString("father: "+father.familyname+father.name,5,10);
      g.drawString("son1: "+son1.familyname+son1.name,5,20);
      g.drawString("son2: "+son2.familyname+son2.name,5,30);
      Family.familyname="杀";
      g.drawString("father:"+father.familyname+father.name,5,40);
      g.drawString("son1: "+son1.familyname+son1.name,5,50);
      g.drawString("son2: "+son2.familyname+son2.name,5,65);
   }
}
class Fibi
{ public long fibinacii(int n)
   {        long c=0;
           if(n==1||n==2)
                c=1;
           else
                c=fibinacii(n-1)+fibinacii(n-2);
           return c;
    }
}
public class Example4_9
{ public static void main(String args[])
   { Fibi a=new Fibi();
     for(int i=1;i<=10;i++)
       { System.out.print(" "+a.fibinacii(i));
       }
   }
}
class 三角形
{ double a,b,c;
   三角形(double a,double b,double c)
   { setABC(this,a,b,c);
   }
 void setABC(三角形 trangle,double a,double b,double c)
   { trangle.a=a;
     trangle.b=b;
     trangle.c=c;
   }
}
class Example4_10
{ public static void main(String args[])
    {三角形 tra=new 三角形(3,4,5);
     System.out.print("三角形型的三边是:"+tra.a+","+tra.b+","+tra.c+",");
     }
}
package tom.jiafei;
public class PrimNumber
{    public static void main(String args[])
     { int sum=0,i,j;
        for( i=1;i<=10;i++) //找出10以内的素数。
         { for(j=2;j<=i/2;j++)
             {   if(i%j==0)
                   break;
             }
           if(j>i/2) System.out.print(" 素数:"+i);
         }
    }
}
import Java.applet.Applet;import Java.awt.*;
public class Example4_12 extends Applet
{ Button redbutton;
    public void init()
     {   redbutton=new Button("我是一个红色的按钮");
         redbutton.setBackground(Color.red);
         add(redbutton);
     }
    public void paint(Graphics g)
     { g.drawString("it is a button",30,50);
     }
}
import tom.jiafei.*; //引入包tom.jiafei中的类。
public class Example4_13
{    public static void main(String args[])
     { PrimNumber num=new PrimNumber();//用包tom.jiafei中的类创建对象。
        String a[]={"ok"};
        System.out.println(a[0]);
        num.main(a);
     }
}
public class Example4_14
{ public static void main(String args[])
   { PrimNumber num=new PrimNumber();//要保证PrimNuber类和Example4_14类在同一目录中
    String a[]={"ok"};
     System.out.println(a[0]);
     num.main(a);
 }
     }
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;
     }
   }
}
 
import tom.jiafei.*;
class Example4_15
{ public static void main(String args[])
 { Trangle trangle=new Trangle(12,3,1);
            trangle.计算面积();
            trangle.修改三边(3,4,5);
            trangle.计算面积();
 }
}
class Example4_16
{    private int money;
    Example4_16()
    { money=2000;
    } 
    private int getMoney()
    { return money;
    }
    public static void main(String args[])
    { Example4_16 exa=new Example4_16();
      exa.money=3000;int m=exa.getMoney();
      System.out.println("money="+m);
    }
}
import Java.applet.*;
import Java.awt.*;
class Father
{ private int money;
  float weight,height;
  String head;
  String speak(String s)
   { return s ;
  }
}
class Son extends Father
{   String hand ,foot;
}
public class Example4_17 extends Applet
{  Son boy;
   public void init()
   { boy=new Son();
    boy.weight=1.80f; boy.height=120f;
    boy.head="一个头"; boy.hand="两只手 ";
    boy.foot="两只脚";
  }
  public void paint(Graphics g)
   { g.drawString(boy.speak("我是儿子"),5,20);
     g.drawString(boy.hand+boy.foot+boy.head+boy.weight+boy.height,5,40);
  }
}   
package tom.jiafei;
public class Father
{   int  height;
   protected int money;
   public   int weight;
   public Father(int m) {
   { money=m;
   }
   protected int getMoney()
   { return money;
   }
    void setMoney(int newMoney)
   { money=newMoney;
   }
}
package sun.com;
import tom.jiafei.Father;
public class Jerry extends Father   //Jerry和Father在不同的包中.
{ public Jerry()
   {   super(20);
   }
  public static void main(String args[])
   {  Jerry jerry=new Jerry();
      jerry.height=12;         //非法,因为Jerry没有继承友好的height。
      jerry.weight=200;        //合法。
      jerry.money=800;         //合法。
      int m=jerry.getMoney(); //合法。.
      jerry.setMoney(300);    //非法,因为Jerry没有继承友好的方法setMoney。
      System.out.println("m="+m);
  }
}
import Java.applet.*;
import Java.awt.*;
class Chengji
{ float f(float x,float y)
   {  return x*y;
  }
}
class Xiangjia extends Chengji
{ float f(float x,float y)
   { return x+y ;
  }
}
public class Example4_19 extends Applet
{ Xiangjia sum;
  public void init()
   { sum=new Xiangjia();
  }
  public void paint(Graphics g)
   { g.drawString("sum="+sum.f(4,6),100,40);
  }
}
import Java.applet.*;
import Java.awt.*;
class Area
{ float f(float r )
   { return 3.14159f*r*r;
   }
   float g(float x,float y)
   { return x+y;
   }
}
class Circle extends Area 
{   float f(float r)
   { return 3.14159f*2.0f*r;
   } 
}
public class Example4_20 extends Applet
{ Circle yuan;
  public void init()
   { yuan=new Circle();
  }
  public void paint(Graphics g)
   { g.drawString("yuan= "+yuan.f(5.0f),5,20); //调用子类重写的方法f。
    g.drawString(" "+yuan.g(2.0f,8.0f),5,40); //调用继承父类的方法g。
  }
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(c);
  }
 void crySpeak(String s)
  { System.out.println("**"+s+"**");
  } 
}
class Example4_21
{ public static void main(String args[])
   {  类人猿 monkey=new People();   //monkey是People对象的上转型对象。
      monkey.crySpeak("I love this game");
      People people=(People)monkey; //把上转型对象强制转化为子类的对象。
      people.computer(10,10);
  }
}
class 动物
{ void cry()
   {
  } 
}
class 狗 extends 动物 {
{ void cry()
   {  System.out.println("汪汪.....");
  } 
}
class 猫 extends 动物
{ void cry()
   {  System.out.println("喵喵.....");
  } 
}
class Example4_22
{ public static void main(String args[])
   { 动物 dongwu;
      if(Math.random()>=0.5)    
         {
           dongwu=new 狗();
           dongwu.cry();
         }
       else
         {
           dongwu=new 猫();
           ongwu.cry();
         }
  }
}
 
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)
   {  his.r=r;
   }
   public double 求面积()
   {  return(3.14*r*r);
   }
}
class 堆
   {  图形底;
      double 高;
    堆(图形 底,double 高)
   { this.底=底;
      this.高=高;
   }
    void 换底(图形 底)
   { this.底=底;
   }
    public double 求体积()
   {   return (底.求面积()*高)/3.0;
   }
}
public class Example4_23
{ 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.求体积());
  }
}
class Student
{ int number;String name;
   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_24
{ public static void main(String args[])
   { Univer_Student zhang=new Univer_Student(9901,"和晓林",false);
  }
}
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_25
{ 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);
   }
}
import Java.applet.*;import Java.awt.*;
interface Computable
{ final int MAX=100;
   void speak(String s);
   int f(int x);
    float g(float x,float y);
}
class China implements Computable
{ int xuehao;
   public int f(int x)   //不要忘记public关键字。
   { int sum=0;
      for(int i=1;i<=x;i++)
         { sum=sum+i;
         }
       return sum;
   }
   public float g(float x,float y)
   { return 6;                   //至少有return语句。 
   }
   public void speak(String s)
   {
  }
}
class Japan implements Computable
{ int xuehao;
   public int f(int x)
   { return 68;
   }
    public float g(float x,float y)
   { return x+y;
   }
 public void speak(String s)
   {                            //必须有方法体,但体内可以没有任何语句。
   }
}
public class Example4_26 extends Applet
{ China Li; Japan Henlu;
   public void init()
   { Li=new China();   Henlu=new Japan(); 
      Li.xuehao=991898; Henlu.xuehao=941448;
  }
   public void paint(Graphics g)
   { g.drawString("xuehao:"+Li.MAX+Li.xuehao+"从1到100求和"+Li.f(100),10,20);
      g.drawString("xuehao:"+Henlu.MAX+Henlu.xuehao+"加法"+Henlu.g(2.0f,3.0f),10,40);
   }
}  
interface 收费
{ public void 收取费用();
}
class 公共汽车 implements 收费
{ public void 收取费用()
   { System.out.println("公共汽车:一元/张,不计算公里数");
   }
 }
class 出租车 implements 收费
{ public void 收取费用()
   { System.out.println("出租车:1.60元/公里,起价3公里");
   }
 }
class 电影院 implements 收费
{ public void 收取费用()
   {  System.out.println("电影院:门票,十元/张");
   }
}
class Example4_27
{ public static void main(String args[])
   { 公共汽车 七路=new 公共汽车();
      出租车   天宇=new 出租车();
      电影院   红星=new 电影院();
      七路.收取费用();天宇.收取费用();
      红星.收取费用();
   }
}
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_28
{ public static void main(String args[])
   { ShowMessage sm;                  //声明接口变量。
      sm=new TV();                     //接口变量中存放对象的引用。
      sm.显示商标("长城牌电视机");      //接口回调。
      sm=new PC();                     //接口变量中存放对象的引用。
      sm.显示商标("联想奔月5008PC机"); //接口回调。
   }
}
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 求面积()
   { eturn(3.14*r*r);
   }
}
class 堆
{ Computerable 底;           //声明一个接口变量,可以回调"求面积"方法。
   double 高;
   堆(Computerable 底,double 高)
   { this.底=底;
      this.高=高;
   }
    void 换底(Computerable 底)
   { this.底=底;
   }
    public double 求体积()
   { return (底.求面积()*高)/3.0;
   }
}
public class Example4_29
{ public static void main(String args[])
   { 堆 zui;
      Computerable bottom;
      bottom=new 梯形(2.0,7.0,10.7); //接口变量中存放对象的引用。
      System.out.println("梯形的面积"+bottom.求面积()); //bottom接口回调,求面积。
      zui=new 堆(bottom,30);
      System.out.println("梯形底的堆的体积"+zui.求体积());
      bottom=new 圆形(10); //接口变量中存放对象的引用。
 System.out.println("半径是10的圆的面积"+bottom.求面积());
 zui.换底(bottom);
      System.out.println("圆形底的堆的体积"+zui.求体积());
   }
}


 
import Java.applet.*; import Java.awt.*;
public class Example5_1 extends Applet
{ float a[];
  public void init()
   { a=new float[5];
      a[0]=23.9f;a[1]=34.9f;a[2]=45f;a[3]=56.98f;a[4]=100f;
  }
  public void paint(Graphics g)
   {
g.drawString("a[0]="+a[0]+"a[1]="+a[1]+"a[2]"+a[2]+"a[3]="+a[3]+"a[4]="+ a[4],12,12);
  }
import Java.applet.*;import Java.awt.*;
public class Example5_2 extends Applet
{ String tom;
   public void init()
   { tom="220302620629021";
   }
   public void paint(Graphics g)
   { if((tom.startsWith("220302"))&&(tom.endsWith("1")||tom.endsWith("3")))
      g.drawString("tom是吉林人,男性",10,10);
   }
}
class Example5_3
{   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);
   }
}
class Example5_4
{ public static void main(String args[])
   { String a[]={"boy","apple","Applet","girl","Hat"};
      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]);
        }
   }
}
public class Example5_5
{ public static void main(String args[])
   { double n,sum=0.0 ;
      for(int i=0;i<args.length;i++)
       { sum=sum+Double.valueOf(args[i]).doubleValue();
       }
     n=sum/args.length;
     System.out.println("平均数:"+n);
  }
}
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()); 
   }
}
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+"个");
   }
}
import Java.util.*;
public class Example5_8
{ public static void main(String args[])
   { String s=new String("abcABC123");
      System.out.println(s);   
      char a[]=s.toCharArray();
      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]);
          }
       }
     s=new String(a);
     System.out.println(s);     
   }
}
class Example5_9
{   public static void main(String args[])
   { char c[],d[];
      String s="巴西足球队击败德国足球队";
      c=new char[2];
      s.getChars(5,7,c,0);
      System.out.println(c);
      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);
   }
}
class Example5_10
{ 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);
   }
}
public class Example5_11
{ 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);
   }
}


 
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("yyyy年MM月dd日 北京时间");
     System.out.println("现在的时间:"+matter1.format(nowTime));
      SimpleDateFormat matter2=
      new SimpleDateFormat("yyyy年MM月Edd日HH时mm分ss秒 北京时间");
      System.out.println("现在的时间:"+matter2.format(nowTime));
      SimpleDateFormat matter3=
      new SimpleDateFormat("北京时间dd日HH时MMM ss秒mm分EE");
      System.out.println("现在的时间:"+matter3.format(nowTime));
   }
}
import Java.util.Date;
class Example6_2
{ public static void main(String args[])
   { long time1=System.currentTimeMillis();
      Date date=new Date(time1);
      System.out.println(date);
      String s=String.valueOf(time1);
      int length=s.length(); s=s.substring(length-8);
      System.out.println(s);
 
      long result=f(28);
      System.out.println("result="+result);
      long time2=System.currentTimeMillis();//计算f(28)之后的时间。
      s=String.valueOf(time2);
      length=s.length(); s=s.substring(length-8);
      System.out.println(s);
      System.out.println("用时:"+(time2-time1)+"毫秒");  
   }
   public static long f(long n)
   { long c=0;
     if(n==1||n==2) c=1;
     else if(n>=3) c=f(n-1)+f(n-2);
     return c;
   }
}
import Java.util.*;
class Example6_3
{ 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(2003,9,5); //将日历翻到2003年10月5日。9表示十月。
      long time2003=calendar.getTimeInMillis();
      long 相隔天数=(time2003-time1962)/(1000*60*60*24);
      System.out.println("2003年10月5日和1962年6月29日相隔"+相隔天数+"天");
   } 
}
import Java.util.*;
class Example6_4
{ public static void main(String args[])
   { System.out.println(" 日 一 二 三 四 五 六");
      Calendar 日历=Calendar.getInstance(); //创建一个日历对象。
      日历.set(2004,0,1); //将日历翻到2004年1月1日,注意0表示一月。
      //获取1日是星期几(get方法返回的值是1表示星期日,星期六返回的值是7):
      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%7==0)
          { System.out.println("");      //换行。
          }
        System.out.print(" "+a[i]);
      }
   }
}
import Java.text.NumberFormat;
class Example6_5
{ public static void main(String args[])
   { double a=Math.sqrt(5);
      System.out.println("格式化前:"+a);
      NumberFormat f=NumberFormat.getInstance();
      f.setMaximumFractionDigits(5);f.setMinimumIntegerDigits(3);
      String s=f.format(a);
      System.out.println("格式化后:"+s);System.out.println("得到的随机数:");
      int number=8;
      for(int i=1;i<=20;i++)
       { int randomNumber=(int)(Math.random()*number)+1;//产生1到8之间的随机数。
         System.out.print(" "+randomNumber);
         if(i%10==0)
             System.out.println("");
       }
   }
}


 
import Java.awt.*;
class Example7_1
{ public static void main(String args[])
  { Frame fr=new Frame("媒体新闻");    // 一个容器对象。
     fr.setLayout(new FlowLayout());
     Button button1=new Button("确定 ");
     Button button2=new Button("取消");
     fr.add(button1);
     fr.add(button2);
     fr.setSize(200,300);             //调用方法setSize(int,int)设置容器的大小。
     fr.setBackground(Color.cyan);
     fr.setVisible(true);
    fr.validate();
   }
}  


 
import Java.applet.*;
import Java.awt.*;
public class Example8_1 extends Applet
{ Button button1; Button button2;
   int sum;
   public void init()
   { 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 destroy(){ }
   public void paint(Graphics g)
  {  g.setColor(Color.blue);
      g.drawString("程序设计方法",20,60);
      g.setColor(Color.red);
      g.drawString("sum="+sum,20,100);
   }
}
 
 
import Java.applet.*;import Java.awt.*;
public class Example8_3 extends Applet 
{ int x;
   public void init()
   { x=5;
   }  
   public void paint(Graphics g)
   { x=x+1;
      if(x>=200)
        x=5;
      g.drawString("我们在学习repaint方法",20,x);
      repaint();
   }  
}


 
import Java.applet.*;import Java.awt.*;
public class Boy extends Applet
{ TextField text1,text2,text3;
   public void init()
   { text1=new TextField("输入密码:",10);
      text1.setEditable(false);
      text2=new TextField(10);
      text2.setEchoChar('*');
      text3=new TextField("我是一个文本框",20);
      add(text1);add(text2);add(text3);
      text3.setText("重新设置了文本");
  }  
}
import Java.applet.*;import Java.awt.*;import Java.awt.event.*;
public class Example9_2 extends Applet implements ActionListener
{  TextField text1,text2,text3;
 public void init()
  {  text1=new TextField(10);
      text2=new TextField(10);
      text3=new TextField(20);
      add(text1);add(text2);add(text3);
      text1.addActionListener(this); //将主类的实例作为text1的监视器,
                                        //因此主类必须实现接口ActionListener 。
       text2.addActionListener(this);
  } 
  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("没有该单词");
        }
      }
  }
}
import Java.applet.*;import Java.awt.*;import Java.awt.event.*;  
public class Example9_3 extends Applet implements ActionListener
{ TextField text1,text2,text3;
  PoliceMan police;
  public void init()
   {  text1=new TextField(10);
      text2=new TextField(10);
      text3=new TextField(10);
      police=new PoliceMan(this);
      add(text1);add(text2);add(text3);
      text1.addActionListener(this);
      text1.addActionListener(police);
  }
   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
{ Example9_3 a=null;
  PoliceMan(Example9_3 a)
  { this.a=a;
  }
  public void actionPerformed(ActionEvent e)
   { String number=e.getActionCommand();
      int n=Integer.parseInt(number);
      int m=n*n*n;a.text3.setText(n+"的立方是:"+m);
  }
}
import Java.applet.*;import Java.awt.*;
public class Example9_4 extends Applet
{ TextArea text1,text2;
  public void init()
   {  text1=new TextArea("我是学生",6,16);
      text2=new TextArea(6,16);
      add(text1);add(text2);
      text2.append("我在学习Java语言");
      text1.insert("们",1);
      text1.selectAll();
      int length=text2.getText().length();
      text2.setSelectionStart(2);
      text2.setSelectionEnd(length);
  }
}
import Java.util.*;import Java.applet.*;
import Java.awt.*;import Java.awt.event.*; 
public class Example9_5 extends Applet implements TextListener
{ TextArea text1,text2;
   public void init()
   { text1=new TextArea(6,15);
      text2=new TextArea(6,15);
      add(text1);add(text2);
      text2.setEditable(false);
      text1.addTextListener(this) ;
   }
 public void textValueChanged(TextEvent e)
   { if(e.getSource()==text1)
      { 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;
           }
        for(int i=0;i<=n-1;i++)                //按字典序从小到大排序。
          { for(int j=i+1;j<=n-1;j++)
            { if(a[j].compareTo(a[i])<0)
                 { String t=a[j]; a[j]=a[i]; a[i]=t;
                 }
            }
          }   
        text2.setText(null); //刷新显示。
       for(int i=0;i<n;i++)
           { text2.append(a[i]+"/n");
           }
      }
   }
}


 
import Java.applet.*;import Java.awt.*;import Java.awt.event.*;
public class Example10_1 extends Applet implements ActionListener
{ TextField text;
   Button buttonEnter,buttonQuit;
   public void init(){
   { text=new TextField("0",10); add(text);
      buttonEnter=new Button("确定"); buttonQuit =new Button("清除");  
      add(buttonEnter); add(buttonQuit);
      buttonEnter.addActionListener(this);
      buttonQuit.addActionListener(this);
      text.addActionListener(this);
   }
 public void paint(Graphics g)
   { g.drawString("在文本框输入数字字符回车或单击按钮",10,100);
      g.drawString("第文本框显示该数的平方根",10,120);
   }
   public void actionPerformed(ActionEvent e)
   { if(e.getSource()==buttonEnter||e.getSource()==text)
        { double number=0;
           try { number=Double.valueOf(text.getText()).doubleValue();
                  text.setText(""+Math.sqrt(number));
               }
           catch(NumberFormatException event)
               { text.setText("请输入数字字符");
               }
        }
      else if(e.getSource()==buttonQuit)
       { text.setText("0");
       }
   }
}
import Java.awt.*;import Java.applet.*;import Java.awt.event.*;
//写一个按扭类的子类,增加一些新的功能:
class MyButton extends Button implements ActionListener,TextListener
{ TextArea text1,text2;      //类的成员变量。
   char save[];
   MyButton(String s,Container con)
   { super(s);
      text1=new TextArea(6,12); text2=new TextArea(6,12);
      text2.setEditable(false);
      text1.addTextListener(this); //创建的按扭监视其中一个文本区。
      this.addActionListener(this); //创建的按扭自己监视自己。
      con.add(text1);con.add(text2);con.add(this);
   }
   public void textValueChanged(TextEvent e) //实现接口。
   {
   String s=text1.getText();
   StringBuffer strbuffer=new StringBuffer(s);
   String temp=new String(strbuffer.reverse());  
   text2.setText(temp);
   }
   public void actionPerformed(ActionEvent e) //实现接口。
   { text2.setText(null);
      String s=text1.getText();
     int length=s.length();
     save=new char[length];
     //将字符串拷贝到数组save:
     s.getChars(0,length,save,0);
     for(int i=0;i<save.length;i++)
       { save[i]=(char)(save[i]^'你');
       }
     String temp=new String(save);
     text2.setText(temp);  
   }
}
public class Example10_2 extends Applet implements ActionListener
{ MyButton mybutton;
   Button button;
   public void init()
   { mybutton=new MyButton("加密",this);
      button=new Button("解密");
      button.addActionListener(this);
      add(button);
   }
   public void actionPerformed(ActionEvent e) //实现接口。
   { for(int i=0;i<mybutton.save.length;i++)
       { mybutton.save[i]=(char)(mybutton.save[i]^'你');
       }
      String temp=new String(mybutton.save);
      mybutton.text2.setText(temp);  
   }
}
import Java.awt.*;import Java.applet.*;
import Java.awt.event.*;
public class Example10_3 extends Applet
{   public void init()
   { MyButton1 button1=new MyButton1();
      MyButton2 button2=new MyButton2();
      setLayout(null);
      add(button1);add(button2);
      button1.setLocation(12,12);
      button2.setLocation(60,12);
   }
}
class MyButton1 extends Button implements ActionListener
{ int n=-1;
   MyButton1()
   { setSize(25,160); addActionListener(this);
   }
   public void paint(Graphics g)
   { g.drawString("我",6,14); g.drawString("是",6,34);
      g.drawString("一",6,54); g.drawString("个",6,74);
      g.drawString("竖",6,94); g.drawString("按",6,114);
      g.drawString("钮",6,134); g.drawString("!",8,154);
   }
   public void actionPerformed(ActionEvent e)
   { n=(n+1)%3;
      if(n==0)
         this.setBackground(Color.cyan);
      else if(n==1)
         this.setBackground(Color.orange);
      else if(n==2)
         this.setBackground(Color.pink);
   }
}
class MyButton2 extends Button
{ MyButton2()
   { setSize(38,80); setBackground(Color.cyan);
   }
   public void paint(Graphics g)
   { g.setColor(Color.red);
      g.fillOval(10,3,20,20);        //在按扭上画圆,见17章。
      g.setColor(Color.yellow);   g.fillOval(10,28,20,20);
      g.setColor(Color.green);    g.fillOval(10,53,20,20);
   }
}
import Java.awt.*;import Java.awt.event.*;import Java.applet.*;
class MyLabel extends Label implements ActionListener
{ String 标签上的初始名称;
   TextField inputNumber;TextArea showResult;Button button;
   MyLabel(String s,Container con)
   { super(s);
      标签上的初始名称=s;
      inputNumber=new TextField(10); showResult =new TextArea(10,10);
      button=new Button("Enter");
      button.addActionListener(this);inputNumber.addActionListener(this);
      con.add(this);con.add(inputNumber);con.add(showResult);con.add(button);
   }
   public void actionPerformed(ActionEvent e)
   { long n=0;
      showResult.setText(null);
      try{ n=Long.valueOf(inputNumber.getText()).longValue();
            this.setText(标签上的初始名称);
         }
      catch(NumberFormatException e1)
         { this.setText("请输入数字字符");
         }
      if(e.getSource()==inputNumber)
        { 求因子(n);
        }
      if(e.getSource()==button)
          { 求素数(n);
          }
   }
 public void 求因子(long n)
   { for(int i=1;i<=n;i++)
       { if(n%i==0)
            showResult.append("/n"+i);
       }
   }
   public void 求素数(long n)
  {  showResult.append("小于"+n+"的素数有:");
      for(int i=1;i<=n;i++)
         { int j=0;
            for(j=2;j<i;j++)
               { if(i%j==0) break;
               }
            if(j>=i)
              { showResult.append("/n"+i);
              }
          }
    }
}
public class Example10_4 extends Applet
{  MyLabel lab;
   public void init()
   {  lab=new MyLabel("回车求该数的因子,单击按钮求出小于这个数的素数",this);
   }
}


 
import Java.applet.*;import Java.awt.*;import Java.awt.event.*;
class Mypanel extends Panel implements ActionListener
{ Button button1,button2,button3;  
   Color backColor;
   Mypanel()   //构造方法。当创建面板对象时,面板被初始化为有三个按钮。
   { button1=new Button("确定");button2=new Button("取消");button3=new Button("保存");
      add(button1);add(button2);add(button3);
      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);
        }
   }
}
public class Example11_1 extends Applet
{ Mypanel panel1,panel2,panel3;
   Button button;
   public void init()
   { panel1=new Mypanel();panel2=new Mypanel();panel3=new Mypanel();
      button=new Button("我不在那些面板里");
      add(panel1);add(panel2);add(panel3);
      add(button);
   }
}
import Java.awt.*;import Java.applet.*;
public class Example11_2 extends Applet
{ Panel p ;
   ScrollPane scrollpane;
   public void init()
   { 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(p);//scrollpane添加一个面板。
      add(scrollpane);//小程序添加滚动窗口。
   }
}
import Java.awt.*;import Java.applet.*;
class Mycanvas extends Canvas
{ String s;
   Mycanvas(String s)
   { this.s=s;
      setSize(90,80);
      setBackground(Color.cyan);
   }
   public void paint(Graphics g)
   { if(s.equals("circle"))
         g.drawOval(20,25,30,30);
      else if(s.equals("rect"))
         g.drawRect(30,35,20,20);
   }
}
public class Example11_3 extends Applet
{ Mycanvas canvas1,canvas2;
   public void init() 
   { canvas1=new Mycanvas("circle");canvas2=new Mycanvas("rect");
      add(canvas1);
      Panel p=new Panel();p.setBackground(Color.pink);
      p.add(canvas2) ;
      add(p);
   }
}
 
import Java.awt.*;
import Java.applet.*;
import Java.awt.event.*;
class Mycanvas extends Canvas
{ int x,y,r;
   int red,green,blue;
   Mycanvas()
   { setSize(100,100);
      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,2*r,2*r);
   }
}
public class Example11_4 extends Applet implements ActionListener
{ Mycanvas canvas;
   TextField inputR,inputX,inputY;
   Button b;
   public void init()
   { canvas=new Mycanvas();
      inputR=new TextField(6);
      inputX=new TextField(6);
      inputY=new TextField(6);
      add(new Label("输入圆的位置坐标:"));
      add(inputX);
      add(inputY);
      add(new Label("输入圆的半径:"));
      add(inputR);
      b=new Button("确定");
      b.addActionListener(this);
      add(b);
      add(canvas);
   }
   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(r);
             canvas.repaint();
           }
      catch(NumberFormatException ee)
           {
             x=0;y=0;r=0;
           }
   }
}
 


 
import Java.applet.*;import Java.awt.*;
public class Example12_1 extends Applet
{ public void init()
   { FlowLayout flow=new FlowLayout();
      flow.setAlignment(FlowLayout.LEFT);
      flow.setHgap(20);flow.setVgap(40);
      setLayout(flow);
      setBackground(Color.cyan);
      for(int i=1;i<=12;i++)
         { add(new Button("i am "+i));
         }
   }
}
   import Java.awt.*;import Java.applet.*;
public class Example12_2 extends Applet
{ Button button1,button2;
   Label label1,label2;
   TextArea text;
   public void init()
   { setLayout(new BorderLayout()); 
      text=new TextArea(10,10);
      button1=new Button("东");
      button2=new Button("西");
      label1=new Label("上北",Label.CENTER);
      label2=new Label("下南",Label.CENTER);   
      add(BorderLayout.NORTH,label1);
      add(label2,BorderLayout.SOUTH);
      add(button1,BorderLayout.EAST);
      add(BorderLayout.WEST,button2);
      add(BorderLayout.CENTER,text);
   }  
}
import Java.applet.*;import Java.awt.*;import Java.awt.event.*;
class Mycanvas extends Canvas
{ int x,y;
   Mycanvas(int a,int b)
   { x=a;y=b;
      setSize(100,160);
   }
   public void paint(Graphics g)
   { g.setColor(Color.red);
      g.fillOval(50,50,4*x,4*y);//画实心椭圆
      g.drawString("我是第 "+x,10,150);
   }
}
public class Example12_3 extends Applet implements ActionListener
{ CardLayout mycard;
   Button button1,button2,button3;
   Mycanvas mycanvas[];
   Panel p;
   public void init()
   { setLayout(new BorderLayout()); //小容器的布局是边界布局。
      mycard=new CardLayout();
      p=new Panel();
      p.setLayout(mycard);          //p的布局设置为mycard(卡片式布局)
      button1=new Button("first");
      button2=new Button("next");
      button3=new Button("last one");
      mycanvas=new Mycanvas[21];
      for(int i=1;i<=20;i++)
         { mycanvas[i]=new Mycanvas(i,i);
           p.add("i am"+i,mycanvas[i]);
         }
      button1.addActionListener(this);
      button2.addActionListener(this);
      button3.addActionListener(this);
      Panel p2=new Panel();
      p2.add(button1);p2.add(button2);p2.add(button3);
      add(p,BorderLayout.CENTER);add(p2,BorderLayout.SOUTH);
   }
   public void actionPerformed(ActionEvent e)
   { if(e.getSource()==button1)
        { mycard.first(p);
        }
      else if(e.getSource()==button2)
       { mycard.next(p);
       }
      else if(e.getSource()==button3)
       { mycard.last(p);
       }
   }
}
import Java.applet.*; import Java.awt.*;
import Java.awt.event.*;
public class Example12_4 extends Applet
{ GridLayout grid;
   public void init()
   { 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)%2==0)
                 label[i][j].setBackground(Color.black);
               else
                 label[i][j].setBackground(Color.white);
               add(label[i][j]);
            }
         }
   }
}
import Javax.swing.*;import Java.awt.*;import Java.awt.event.*;
import Javax.swing.border.*;
public class Example12_5 extends Java.applet.Applet
{ Box baseBox ,boxH,boxV;
   public void init()
   { baseBox=Box.createHorizontalBox();
      boxH=Box.createHorizontalBox();
      boxV=Box.createVerticalBox();
      for(int i=1;i<=5;i++)
         { boxH.add(new JButton("按钮 "+i));
           boxV.add(new JButton("按钮 "+i));
         }
      baseBox.add(boxH);baseBox.add(boxV);
      add(baseBox);
   }
}
import Javax.swing.*; import Java.awt.*;
import Javax.swing.border.*;
public class Example12_6 extends Java.applet.Applet
{ Box baseBox ,boxV1,boxV2;
   public void init()
   { 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(16));
      boxV2.add(Box.createVerticalStrut(8));
      boxV2.add(new TextField(16));
      boxV2.add(Box.createVerticalStrut(8));
      boxV2.add(new TextField(16));
      baseBox=Box.createHorizontalBox();
      baseBox.add(boxV1);
      baseBox.add(Box.createHorizontalStrut(10));
      aseBox.add(boxV2);
      add(baseBox);
   }
}
import Javax.swing.*;import Java.awt.*;
import Javax.swing.border.*;
public class Example12_7 extends Java.applet.Applet
{ Box baseBox ,boxV1,boxV2,boxV3;
   public void init()
   { boxV1=Box.createVerticalBox();
      for(int i=1;i<=3;i++)
       { boxV1.add(new JButton("按钮"+i));
       }
      boxV1.add(Box.createVerticalGlue());
      boxV2=Box.createVerticalBox();
      boxV2.add(Box.createVerticalGlue());
      for(int i=1;i<=8;i++)
       { boxV2.add(new JButton("按钮"+i));
       }
      boxV3=Box.createVerticalBox();
      for(int i=1;i<=6;i++)
       { boxV3.add(new JButton("按钮"+i));
          if(i==3)
             boxV3.add(Box.createVerticalGlue());
       }
      baseBox=Box.createHorizontalBox();
      baseBox.add(boxV1);baseBox.add(boxV2);
      baseBox.add(boxV3); add(baseBox);
   }
}


 
import Java.applet.*;import Java.awt.*;
class Mypanel1 extends Panel
{ Checkbox box1,box2,box3;CheckboxGroup sex;
   Mypanel1()
   { sex=new CheckboxGroup();
      box1=new Checkbox("男",true,sex);
      box2=new Checkbox("女",false,sex);
      add(box1);add(box2);
   }
}
class Mypanel2 extends Panel
{ Checkbox box1,box2,box3;  
   Mypanel2()
   { box1=new Checkbox("读书");
      box2=new Checkbox("电脑");
      box3=new Checkbox("电影");
      add(box1);add(box2);add(box3);
   }
}
public class Example13_1 extends Applet
{ Mypanel1 panel1;Mypanel2 panel2;
   public void init()
   { setLayout(new GridLayout(1,2));
      panel1=new Mypanel1();panel2=new Mypanel2();
      add(panel1);add(panel2);
   }
import Java.awt.*;import Java.awt.event.*;import Java.applet.*;
public class Example13_2 extends Applet implements ItemListener
{ Checkbox box1,box2,box3,box4;
   TextArea text; 
  public void init()
   { box1=new Checkbox("→");box2=new Checkbox("↑");
      box3=new Checkbox("←");box4=new Checkbox("↓");
      box1.addItemListener(this);
      box2.addItemListener(this);
      box3.addItemListener(this);
      box4.addItemListener(this);
      text=new TextArea(16,18);
     add(box1);add(box2);
     add(box3);add(box4);
      add(text); 
  }
  public void itemStateChanged(ItemEvent e)
   {  Checkbox box=(Checkbox)e.getItemSelectable(); //获取事件源。
      if(box.getState())
      {  int n=text.getCaretPosition();      //获取文本区活动光标位置。
         text.insert(box.getLabel(),n);      //插入字符。
         box.setState(false);
      }
  }
}
import Java.applet.*;import Java.awt.*;import Java.awt.event.*;
import Java.util.StringTokenizer;
public class Example13_3 extends Applet implements ActionListener
{ Label 候名字=new Label("首先输入候选人的名字(人数不超过10,名字之间用逗号分隔):"),
         统计选票=new Label("用下面的选择框统计选票:",Label.CENTER),
         结果=new Label("选举结果:");
   Button 确认=new Button("确认"),取消=new Button("取消"),
          确定=new Button("确定"),刷新=new Button("刷新"),
          排序=new Button("排序");
  TextField name=new TextField(48);          //输入候选人。
  TextField voteMessage=new TextField(46);   //显示选举信息。
  Checkbox checkbox[]=new Checkbox[10];      //选择框数组,代表候选人。
  TextField personVote[]=new TextField[10]; //文本条数组,显示每个人的得票情况。
 int count[]=new int[10],                  //记录每个人的得票数。
       totalVote=0,                          //总票数。
       peopleNumber=0;                       //候选人个数。
  Panel p2_1=new Panel();                    //添加候选人的面板。
  int 有效人数=3,                           //可选举的最多人数。
        废票数=0,弃权票数=0;
  public void init()
  { setLayout(new GridLayout(3,1));
      Panel p1=new Panel(),        //添加到小程序上部的面板和添加到该面板中的面板。
      p1_1=new Panel(),p1_2=new Panel(),p1_3=new Panel();
      p1.setLayout(new BorderLayout());
      p1_1.add(候名字); p1_2.add(name);
      p1_3.add(确认);p1_3.add(取消);p1_3.add(统计选票);  
      p1.add(p1_1,BorderLayout.NORTH);p1.add(p1_2,BorderLayout.CENTER);
      p1.add(p1_3,BorderLayout.SOUTH);
      Panel p2=new Panel(), //添加到小程序中间的面板p2,它里面的一个面板p2_1,
                            //将用来添加代表候选人的选择框。
      p2_2=new Panel();    
      p2.setLayout(new BorderLayout());p2.setBackground(Color.cyan);
      p2_1.setLayout(new GridLayout(2,5));
      p2_2.add(确定); p2_2.add(刷新); p2_2.add(排序);
      p2.add(p2_1,BorderLayout.CENTER);p2.add(p2_2,BorderLayout.SOUTH);
      for(int i=0;i<=9;i++)
        {  checkbox[i]=new Checkbox();
           p2_1.add(checkbox[i]);
        }
      Panel p3=new Panel(),     //添加到小程序底部的面板p3,及它里面的面板。
      p3_1=new Panel(),p3_2=new Panel();
      p3.setLayout(new BorderLayout());
      p3_1.add(结果);p3_1.add(voteMessage);
      p3_2.setLayout(new GridLayout(10,1));
      for(int i=0;i<=9;i++)   
        {  personVote[i]=new TextField();
           p3_2.add(personVote[i]);
        }
      ScrollPane scroll=new ScrollPane();
      scroll.add(p3_2);                    //把p3_2添加到一个滚动窗体中。
      p3.add(p3_1,BorderLayout.NORTH);
      p3.add(scroll,BorderLayout.CENTER);
      add(p1);add(p2); add(p3);                     //小程序添加这三个面板。
      确认.addActionListener(this); 取消.addActionListener(this);
      确定.addActionListener(this); 刷新.addActionListener(this);
      排序.addActionListener(this);
  }
  public void actionPerformed(ActionEvent e)
  { String s[]=new String[10];
      if(e.getSource()==确认)
        { p2_1.removeAll();
           String s_name=name.getText();
          //提取候选人的名字,名字用逗号(英文逗号或汉文逗号)分隔:
           StringTokenizer fenxi=new StringTokenizer(s_name,",,");
           peopleNumber=fenxi.countTokens();   //获取候选人的个数。
           int i=0;
           while(fenxi.hasMoreTokens()) //用单选框代表候选人,并添加到面板p2_1。
            {
               s[i]=fenxi.nextToken();
               p2_1.add(checkbox[i]);
               checkbox[i].setLabel(s[i]);  
               i++;
            }
          for(int k=0;k<peopleNumber;k++)
            { personVote[k].setText(null);
            }
        }
     else if(e.getSource()==取消) 
        { name.setText(null);
           确认.setEnabled(true);
           for(int k=0;k<peopleNumber;k++)
              { personVote[k].setText(null);
              }
         }
     else if(e.getSource()==确定)      //统计候选人的得票数目。
        {  totalVote=totalVote+1;          //记录下统计的票数。
           确认.setEnabled(false);
           //检查选票是否有效:
           int number=0;
           for(int k=0;k<peopleNumber;k++)
             {  if(checkbox[k].getState())
                    {  number++;
                    }
             }
           if(number>有效人数)
             { 废票数++;
                 for(int k=0;k<peopleNumber;k++)
                     {  checkbox[k].setState(false);
                     }
             }
            else if(number==0)
             { 弃权票数++;
             }
            else if(number>0&&number<=有效人数)
            {  for(int k=0;k<peopleNumber;k++)
                 { if(checkbox[k].getState())
                      {  count[k]=count[k]+1;
                         checkbox[k].setState(false);
                         personVote[k].setText(checkbox[k].getLabel()+
                                          " 的得票数:"+count[k]);
                      }
                    else
                      {  personVote[k].setText(checkbox[k].getLabel()+
                                         " 的得票数:"+count[k]);
                      }
                 }
             }
 voteMessage.setText("已统计了:"+totalVote+"张选票,其中弃权票:"+
                                     弃权票数+" 作废票:"+废票数);
      }
    else if(e.getSource()==排序) //对选举人按得票数,从大到小排序。
      {  for(int i=0;i<peopleNumber;i++)
          {  for(int j=i+1;j<peopleNumber;j++)
              {   if(count[j]>count[i])
                 {  String str_temp=personVote[i].getText();        
                    personVote[i].setText(personVote[j].getText());
                    personVote[j].setText(str_temp);
                    int nnn=count[i];count[i]=count[j];count[j]=nnn;
                  }
               }
           }
         排序.setEnabled(false);确定.setEnabled(false);
      }
    else if(e.getSource()==刷新)
      {  totalVote=0;
         voteMessage.setText("已统计了:"+totalVote+"张选票");
         name.setText(null);
         确认.setEnabled(true); 确定.setEnabled(true); 排序.setEnabled(true);
         for(int i=0;i<peopleNumber;i++)
           {  count[i]=0;
              personVote[i].setText(null);
              p2_1.removeAll();
            }   
       }
  }
}
import Java.awt.*;import Java.awt.event.*;
public class Example13_4 extends Java.applet.Applet implements
ItemListener,ActionListener
{ Choice choice;
   TextField text;
   TextArea area;
   Button add,del;
   public void init()
   { choice=new Choice();
      text=new TextField(8);
      area=new TextArea(6,15); 
      choice.add("音乐天地");
      choice.add("武术天地");
      choice.add("象棋乐园");    
      choice.add("交友聊天");
      add=new Button("添加");
      del=new Button("删除");
      add.addActionListener(this);del.addActionListener(this);
      choice.addItemListener(this);
      add(choice); 
      add(del);add(text);add(add);add(area);
   }
   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)
        { choice.remove(choice.getSelectedIndex());
           area.append("/n删除"+choice.getSelectedItem());
        }
   }
}
import Java.applet.*;import Java.awt.*;import Java.awt.event.*;
public class Example13_5 extends Applet implements ItemListener,ActionListener
{ List list1,list2;  
   TextArea text1,text2; int index=0;
   public void init()
   {  list1=new List(3,false); list2=new List(3,false);
      text1=new TextArea(6,15); text2=new TextArea(6,15);
      list1.add("计算1+2+..."); list1.add("计算1*1+2*2+3*3...");
      list1.add("计算1*1*1+2*2*2+3*3*3...");
      for(int i=1;i<=100;i++)
       { list2.add("前"+i+"项和");
       }
      add(list1);add(list2);add(text1);add(text2);
      list1.addItemListener(this); list2.addActionListener(this);
   }
   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+i*i;
                 }
                 break;
            case 2:
                 for(int i=1;i<=n+1;i++)
                 { sum=sum+i*i*i;
                 }
                 break;
             default :
                sum=-100;
        }
      text2.setText(name+"等于"+sum);
   }
}


 
import Java.applet.*;import Java.awt.*;
import Java.awt.event.*;
import Javax.swing.JTextArea;
public class Example14_1 extends Applet implements ItemListener
{ List list ;
   JTextArea text;
  public void init()
   { list=new List(6,false);
     text=new JTextArea(6,15);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);
      Panel p=new Panel();
      p.setBackground(Color.pink);
      p.add(text);
      add(p);
      list.addItemListener(this);
   }
   public void itemStateChanged(ItemEvent e)
   { String name=list.getSelectedItem();
      Font f=new Font(name,Font.BOLD,16);
      text.setFont(f);
      text.setText("/nWelcome 欢迎您");
   }
}
import Java.awt.*;import Java.awt.event.*;
public class Example14_2 extends Java.applet.Applet implements ActionListener
{ Button button;
   Label label;
   public void init()
   { button=new Button("横向走动"); button.setBackground(Color.red);
      button.addActionListener(this);
      label=new Label("我可以被碰掉",Label.CENTER);
      label.setBackground(Color.yellow);
      add(button); add(label);
   }
 public void actionPerformed(ActionEvent e)
   { Rectangle rect=button.getBounds();
      if(rect.intersects(label.getBounds()))
         { label.setVisible(false);
         }
      if(label.isVisible())
         { button.setLocation(rect.x+3,rect.y);
         }
      else
         { button.setLocation(rect.x,rect.y+3);
            button.setLabel("纵向走动");
         }
   }
}
import Java.awt.*;import Java.awt.event.*;
class MyCanvas extends Canvas
{ int n=-1;
   MyCanvas()
   { setSize(150,120);setBackground(Color.pink);
   }
   public void paint(Graphics g)
   { g.setColor(Color.red);
      g.drawString("部分清除时我将消失",10,12);
      g.drawString("我们正在学习repaint方法",10,80);
   }
   public void setN(int n)
   { this.n=n;
   }
   public void update(Graphics g)
   { int width=0, height=0;
      width=getSize().width;height=getSize().height;
      if(n==0)
        { g.clearRect(0,0,width,height);
           //paint(g); //如果取消该注释,update的功能就与父类相同。
        }
      else if(n==1)
        { g.clearRect(2,2,width,40);
        }
   }
}
public class Example14_3 extends Java.applet.Applet implements ActionListener
{ Button b1,b2;MyCanvas canvas;
   public void init()
   {  canvas=new MyCanvas();
      b1=new Button("全部清除"); b1.addActionListener(this);
      b2=new Button("部分清除"); b2.addActionListener(this);
      add(b1); add(b2); add(canvas);
   }
   public void actionPerformed(ActionEvent e)
   {  if(e.getSource()==b1)
       { canvas.setN(0);canvas.repaint();
       } 
      if(e.getSource()==b2)
       { canvas.setN(1);canvas.repaint();
       } 
   }
}


 
import Java.awt.*;import Java.awt.event.*;
class MyFrame extends Frame implements ItemListener,ActionListener
{ Checkbox box; TextArea text; Button button;
   MyFrame(String s)
   { super(s);
      box=new Checkbox("设置窗口是否可调整大小");
      text=new TextArea(12,12);
      button=new Button("关闭窗口");
      button.addActionListener(this);
      box.addItemListener(this);
      setBounds(100,100,200,300);
      setVisible(true);
      add(text,BorderLayout.CENTER);
      add(box,BorderLayout.SOUTH);
      add(button,BorderLayout.NORTH);
      setResizable(false);
      validate();
   }
   public void itemStateChanged(ItemEvent e)
   { if(box.getState()==true)
        { setResizable(true);
        }
       else
        { setResizable(false);
        }
   }
   public void actionPerformed(ActionEvent e)
   { dispose();
   }
}
class Example15_1
{ public static void main(String args[])
   { new MyFrame("窗口");
   }
}
import Java.awt.*;import Java.awt.event.*;
class MyFrame extends Frame implements ItemListener,ActionListener
{ Checkbox box; Button button;
   Toolkit tool; Dimension dim;
   MyFrame(String s)
   { super(s);
      box=new Checkbox("设置窗口和屏幕同样大小");
      add(box,BorderLayout.SOUTH);
      button=new Button("关闭窗口"); button.addActionListener(this);
      box.addItemListener(this);
      setBounds(100,100,200,300); setVisible(true);
      add(box,BorderLayout.SOUTH); add(button,BorderLayout.NORTH);
      tool=getToolkit();
      validate();
   }
   public void itemStateChanged(ItemEvent e)
   { if(box.getState()==true)
        { dim=tool.getScreenSize();
           setBounds(0,0,dim.width,dim.height);
           validate();
        }
      else
        { setBounds(0,0,dim.width,80);
           validate();
        }
   }
   public void actionPerformed(ActionEvent e)
   { dispose();
   }
}
class Example15_2
{ public static void main(String args[])
   {new MyFrame("窗口");
   }
}
import Java.awt.*;import Java.awt.event.*;
class 圆 extends Panel implements ActionListener//负责计算圆面积的类。
{ double r,area;
   TextField 半径=null,
              结果=null;
   Button b=null;
   圆()
   { 半径=new TextField(10);
      结果=new TextField(10);
      b=new Button("确定");
      add(new Label("输入半径"));
      add(半径);
      add(new Label("面积是:"));
      add(结果); add(b);
      b.addActionListener(this);
   }
   public void actionPerformed(ActionEvent e)
   { try
          { r=Double.parseDouble(半径.getText());
             area=Math.PI*r*r; 
             结果.setText(""+area);
          }
      catch(Exception ee)
          { 半径.setText("请输入数字字符");
          }
   }
}
class 三角形 extends Panel 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(24);
   Button button=new Button("确定");
   三角形()
   { add(new Label("输入三边的长度:"));
      add(边_a); add(边_b); add(边_c);
      add(new Label("面积是:"));
      add(结果); add(button);
      button.addActionListener(this);
   }
   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 圆();
      trangle=new 三角形(); //创建一个圆和一个三角形。
      item1.addActionListener(this); item2.addActionListener(this);
      setVisible(true); setBounds(100,120,100,90);
   }
   public void actionPerformed(ActionEvent e)
   { if(e.getSource()==item1) 
          { removeAll();
             add(circle,"Center");//添加圆面积计算的界面。
             validate();
          }
        else if(e.getSource()==item2) 
          { removeAll();
             add(trangle,"Center");//添加三角形面积计算的界面。
             validate();
          }
   }
}
public class Example15_3
{ public static void main(String args[])
   { Win win=new Win();win.setBounds(100,100,200,100);win.setVisible(true);
      win.addWindowListener(new WindowAdapter() 
           { public void windowClosing(WindowEvent e)
               { System.exit(0);
               }
           });
   }
}
import Java.awt.*;import Java.awt.event.*;
class Herwindow extends Frame implements ActionListener
{ MenuBar menubar;Menu menu;MenuItem item;
   MenuShortcut shortcut=new MenuShortcut(KeyEvent.VK_E);
   Herwindow(String s)
   { super(s);       
      setSize(160,170);setVisible(true);              
      menubar=new MenuBar(); menu=new Menu("文件");  
      item=new MenuItem("退出");
      item.setShortcut(shortcut);           //设置菜单选项的键盘快捷键。
      item.addActionListener(this);
      menu.add(item);
      menubar.add(menu);menubar.add(menu);
       setMenuBar(menubar);
   }
   public void actionPerformed(ActionEvent e)
   { if(e.getSource()==item)
       { System.exit(0);
       }
   }
}
public class Example15_4
{ public static void main(String args[])
   { Herwindow window=new Herwindow("法制之窗");
   }
}      
import Java.awt.*;import Java.awt.event.*;
class MyFrame extends Frame implements WindowListener
{ TextArea text;
   MyFrame(String s)
   { super(s);
      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){ }
}
class Example15_5
{ ublic static void main(String args[])
   { new MyFrame("窗口");
   }
}
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);
   }
}
class Example15_6
{ public static void main(String args[])
   { new MyFrame("窗口");
   }
}
import Java.awt.*;import 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();
   }
}
class Example15_7
{  public static void main(String args[])
   { new MyFrame("窗口");
   }
}
import Java.applet.*;import Java.awt.*;import Java.awt.event.*;
public class Example15_8 extends Applet
{ Frame f,g;
   public void init()
   { f=new Frame("音乐之窗");g=new Frame("体育之窗");
      f.setSize(150,150); f.setVisible(true);
      g.setSize(200,200); g.setVisible(false);
      f.addWindowListener(new WindowAdapter()
                  { public void windowClosing(WindowEvent e)
                     { f.setVisible(false);
                       g.setVisible(true);
                     }
                  } );         //适配器
      g.addWindowListener(new WindowAdapter()
                    {public void windowClosing(WindowEvent e)
                       { g.setVisible(false);
                          f.setVisible(true);
                        }
                    } );
  }
}
import Java.awt.*;import Java.awt.event.*;
public class Example15_9
{ public static void main(String args[])
   { MyFrame f=new MyFrame();
      f.setBounds(70,70,70,89);f.setVisible(true);f.pack();
   }
}
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);
//创建一个PrintJob对象p 。
          g=p.getGraphics();    //p获取一个用于打印的 Graphics对象。
          g.translate(120,200);
          text.printAll(g);
          g.dispose();          //释放对象 g。
          p.end();
       }
      else if(e.getSource()==打印窗口)
       { p=getToolkit().getPrintJob(this,"ok",null);
          g=p.getGraphics();    //p获取一个用于打印的 Graphics对象。
          g.translate(120,200);
          this.printAll(g);      //打印当前窗口及其子组件。
          g.dispose();          //释放对象 g。
          p.end();
        }
     else if(e.getSource()==打印按扭)
        { p=getToolkit().getPrintJob(this,"ok",null);
           g=p.getGraphics();
           g.translate(120,200); //在打印页的坐标(120,200)处打印第一个“按扭”。
           打印文本框.printAll(g);
           g.translate(78,0);   //在打印页的坐标(198,200)处打印第二个“按扭”。
           打印窗口.printAll(g);
           g.translate(66,0);   //在打印页的坐标(264,200)处打印第三个“按扭”。
           打印按扭.printAll(g);  
           g.dispose();         
           p.end();
         }
   }
}
import Java.awt.*;import Java.awt.event.*;
import Java.awt.datatransfer.*;
public class Example15_10 extends Frame implements ActionListener
{ MenuBar menubar; Menu menu;
   MenuItem copy,cut,paste;
   TextArea text1,text2;
   Clipboard clipboard=null; 
   Example15_10()
   { 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(20,20); text2=new TextArea(20,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,200,250); setVisible(true);pack();
       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) ; //从Text1中删除被选取的文本。
       }
      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 static void main(String args[])
   {  Example15_10 win=new Example15_10 ();
   }
}


 
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 Example16_1
{ public static void main(String args[])
   { new Dwindow("带对话框的窗口");
   }
}
import Java.awt.*;import Java.awt.event.*;
public class Example16_2
{ 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("没有打开文件");
            }
        }
   }
}
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+"平方:"+(number*number));
              }
        }
   }
}
public class Example16_3
{ public static void main(String args[])
   { new Dwindow("带对话框的窗口");
   }
}
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 Example16_4
{  public static void main(String args[])
   { new Dwindow("带对话框的窗口");
   }
}
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 Example16_5
{ public static void main(String args[])
   {
      new Dwindow("带颜色对话框的窗口");
   }
}


 
import Java.applet.*;import Java.awt.*;
public class Example17_1 extends Applet
{ public void paint(Graphics g)
   { int y,x=120;
      g.drawString("计算机科学技术",10,20);
      g.drawString("I Love This Game",20,40);
      char a[]="中国科学技术大学".toCharArray();
      for(int i=0;i<a.length;i++)
        { y=2*x-200;
           g.drawChars(a,i,1,x,y);
           x=x+6;
        }
   }
}
import Java.applet.*;import Java.awt.*;
public class Example17_2 extends Applet
{ public void paint(Graphics g)
   { int gap=0;
      for(int i=1;i<=10;i++)
       { g.drawLine(10,10+5*i,180,10+5*i);
        }
      for(int i=1;i<=8;i++)
       { g.drawLine(40+3*i,70,40+3*i,150);
       }
      g.drawLine(64,70,150,156);
   }
}
    import Java.applet.*;import Java.awt.*;
public class Example17_3 extends Applet
{ public void paint(Graphics g)
   {g.drawRect(24,22,60,34);   
       g.drawRoundRect(10,10,90,60,50,30);
       g.setColor(Color.cyan);
       g.fillOval(10,80,120,60);
       int k=0;
      for(int i=1;i<=8;i++)
        { Color c=new Color(i*32-1,0,0);
           g.setColor(c); k=k+5;
           g.drawOval(160+k,77+k,120-2*k,80-2*k);
        }
   }
}
import Java.applet.*;import Java.awt.*;
public class Example17_4 extends Applet
{ public void paint(Graphics g)
    { g.drawArc(0,40,100,50,0,180);
      g.drawArc(100,40,100,50,180,180);
      g.setColor(Color.blue);
      g.fillArc(0,100,40,40,0,270);
      g.setColor(Color.green);
      g.drawArc(55,120,120,60,-90,270);
   }     
}
import Java.applet.*;
import Java.awt.*;
public class Example17_5 extends Applet
{ int px1[]={40,80,0,40};
   int py1[]={5, 45,45,5};
   int px2[]={140,180,180,140,100,100,};
   int py2[]={5, 25, 45, 65, 45, 25,};
   public void paint(Graphics g)
    { g.drawPolygon(px1,py1,4);//从点(40,5)画到点(80,45),再从点(80,45)画到点(0,45)。
       g.drawPolygon(px2,py2,6);
   }
}
     import Java.applet.*; import Java.awt.*;
public class Example17_6 extends Applet
{ Font f1=new Font("Helvetica",Font.PLAIN,28);
   Font f2=new Font("Helvetica",Font.BOLD,15);
   Font f3=new Font("Courier",Font.PLAIN,12);
   Font f4=
   new Font("TimesRoman",Font.BOLD+Font.ITALIC,18);
   public void paint(Graphics g)
    { g.setFont(f1);
      g.drawString("28pt plain Helvetica",5,20);
      g.setFont(f2);
      g.drawString("15pt bold Helvetica",5,43);
      g.setFont(f3);
      g.drawString("12pt plain courier",5,75);
      g.setFont(f4);
      g.drawString("18pt bold & italic Times Roman",5,92);
   }
}
import Java.applet.*;import Java.awt.*;
public class Example17_7 extends Applet
{ public void init()
   {  setBackground(Color.yellow);
   }
   public void paint(Graphics g)
   { g.setColor(Color.red);
      g.fillOval(10,10,100,100);
      g.clearRect(40,40,40,40);
   }
}
 
import Java.applet.*;import Java.awt.*;
import Java.awt.event.*;
public class Example17_8 extends Applet
{ int i=0;
   public void paint(Graphics g)
   { i=(i+2)%360;
      Color c=new Color((3*i)%255,(7*i)%255,(11*i)%255);
      g.setColor(c); g.fillArc(30,50,120,100,i,2);
      g.fillArc(30,152,120,100,i,2);
      try{ //程序暂停300毫秒,再执行repaint()(见19章):
            Thread.sleep(300);
         }
      catch(InterruptedException e){}
      repaint();
   }
   public void update(Graphics g)
   { g.clearRect(30,152,120,100);
      paint(g);
   }
}
import Java.awt.*; import Java.applet.*;
import Java.awt.geom.*;
public class Example17_9 extends Applet
{ public void paint(Graphics g)
{ g.setColor(Color.red);
 Graphics2D g_2d=(Graphics2D)g; 
      Line2D line=new Line2D.Double(2,2,300,300);
      g_2d.draw(line);
      for(int i=1,k=1;i<=10;i++)
         { line.setLine(10,10+k,80,10+k);
            g_2d.draw(line); k=k+3;
         }  
   }
}
import Java.awt.*; import Java.applet.*;
import Java.awt.geom.*;
public class Example17_10 extends Applet
{ public void paint(Graphics g)
    { g.setColor(Color.blue) ;
      Graphics2D g_2d=(Graphics2D)g;
      Rectangle2D rect=
      new Rectangle2D. Double (20,30,30,30);
      g_2d.draw(rect);
      for(int i=1;i<=5;i++)
        { rect.setRect(12,12+i,50,80);
           g_2d.draw(rect);
        }
   }
}
import Java.awt.*;import Java.applet.*;
import Java.awt.geom.*;
public class Example17_11 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);
      g_2d.draw(ellipse);
      for(int i=1,k=0;i<=6;i++)
        { ellipse.setFrame(20+k,30,100-2*k,50);
           g_2d.draw(ellipse); k=k+5;
        }
   }
}
import Java.awt.*; import Java.applet.*;
import Java.awt.geom.*;
public class Example17_12 extends Applet
{ public void paint(Graphics g)
   { g.setColor(Color.red) ;
      Graphics2D g_2d=(Graphics2D)g;
      Arc2D arc=
      new Arc2D.Double (2,30,80,55,180,-90,Arc2D.OPEN);
      g_2d.draw(arc);
      arc.setArc(90,30,90,70,0,180,Arc2D.CHORD);
      g_2d.draw(arc);
      arc.setArc(190,30,50,90,0,270,Arc2D.PIE);
      g_2d.draw(arc);
   }
}
import Java.awt.*;import Java.applet.*;
import Java.awt.geom.*;
public class Example17_13 extends Applet
{ public void paint(Graphics g)
   { g.setColor(Color.red) ;
      Graphics2D g_2d=(Graphics2D)g;
      QuadCurve2D quadCurve=
      new QuadCurve2D.Double(2,10,51,90,100,10);
      g_2d.draw(quadCurve);
      quadCurve.setCurve(2,100,51,10,100,100);
      g_2d.draw(quadCurve);
   }
}
import Java.awt.*;import Java.applet.*;
import Java.awt.geom.*;
public class Example17_14 extends Applet
{ public void paint(Graphics g)
   { g.setColor(Color.red) ;
      Graphics2D g_2d=(Graphics2D)g;
      CubicCurve2D curve_1=new CubicCurve2D.Double(2,30,80,55,10,10,20,90);
      CubicCurve2D curve_2=new CubicCurve2D.Double(2,30,5,67,20,30,20,90);
      CubicCurve2D curve_3=new CubicCurve2D.Double(30,35,54,67,20,90,100,190);
      g_2d.draw(curve_1);g_2d.draw(curve_2);g_2d.draw(curve_3);
   }
}
 
import Java.awt.*;import Java.applet.*;
import Java.awt.geom.*;
public class Example17_15 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 line_1=new Line2D.Double(20,20,100,20);
      Line2D line_2=new Line2D.Double(20,50,100,50);
      Line2D line_3=new Line2D.Double(20,80,100,80);
      g_2d.setStroke(bs_1); //设置线条。
      g_2d.draw(line_1);
      g_2d.setStroke(bs_2); g_2d.draw(line_2);
      g_2d.setStroke(bs_3); g_2d.draw(line_3);
   }
}
import Java.awt.*;import Java.applet.*;
import Java.awt.geom.*;
public class Example17_16 extends Applet
{ public void paint(Graphics g)
   { Graphics2D g_2d=(Graphics2D)g;
      g_2d.setColor(Color.cyan);
      Rectangle2D rect=new Rectangle2D.Double(0,0,200,200);
      g_2d.fill(rect);
      Arc2D arc1=new Arc2D.Double(0,0,200,200,0,180,Arc2D.CHORD),
         arc2=new Arc2D.Double(0,0,200,200,0,-180,Arc2D.CHORD);
      RoundRectangle2D roundR1=new RoundRectangle2D.Double
                            (0,50,100,100,100,100),
                    roundR2=new RoundRectangle2D.Double
                            (100,50,100,100,100,100),
                    roundR3=new RoundRectangle2D.Double
                            (37.5,87.8,25,25,25,25),
                    roundR4=new RoundRectangle2D.Double
                            (137.5,87.8,25,25,25,25);
      g_2d.setColor(Color.white); g_2d.fill(arc1);
      g_2d.setColor(Color.black); g_2d.fill(arc2);
      g_2d.fill(roundR1);
      g_2d.setColor(Color.white);
      g_2d.fill(roundR2); g_2d.fill(roundR3);
      g_2d.setColor(Color.black);
      g_2d.fill(roundR4);
   }
}
import Java.awt.*;import Java.applet.*;
import Java.awt.geom.*;
public class Example17_17 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);
   }
}
import Java.awt.*;import Java.applet.*;
import Java.awt.geom.*;
public class Example17_18 extends Applet
{ public void paint(Graphics g)
   { Graphics2D g_2d=(Graphics2D)g;
      Ellipse2D ellipse=
      new Ellipse2D. Double (20,50,120,50);
      g_2d.setColor(Color.blue);
     
      AffineTransform trans=new AffineTransform();
      for(int i=1;i<=24;i++)
        { trans.rotate(15.0*Math.PI/180,80,75);
           g_2d.setTransform(trans);
           //现在画的就是旋转后的椭圆样子:
           g_2d.draw(ellipse);
        }
   }
}
import Java.awt.*;import Java.awt.event.*;
import Java.awt.geom.*;
import Java.applet.*;
public class Flower extends Applet
{ public void paint(Graphics g)
   { Graphics2D g_2d=(Graphics2D)g;
      //花叶两边的曲线: 
      QuadCurve2D
      curve_1=new QuadCurve2D.Double(200,200,150,160,200,100);
      CubicCurve2D curve_2=
      new CubicCurve2D.Double(200,200,260,145,190,120,200,100);
      //花叶中的纹线:
      Line2D line=new Line2D.Double(200,200,200,110); 
      QuadCurve2D leaf_line1=
      new QuadCurve2D.Double(200,180,195,175,190,170);
      QuadCurve2D leaf_line2=
      new QuadCurve2D.Double(200,180,210,175,220,170);
      QuadCurve2D leaf_line3=
      new QuadCurve2D.Double(200,160,195,155,190,150);
      QuadCurve2D leaf_line4=
      new QuadCurve2D.Double(200,160,214,155,220,150);  
      //利用旋转来绘制花朵: 
      AffineTransform trans=new AffineTransform();
      for(int i=0;i<6;i++)
       { trans.rotate(60*Math.PI/180,200,200);
          g_2d.setTransform(trans);
          GradientPaint gradient_1=
 new GradientPaint(200,200,Color.green,200,100,Color.yellow);
          g_2d.setPaint(gradient_1);
          g_2d.fill(curve_1);
          GradientPaint gradient_2=new
 GradientPaint(200,145,Color.green,260,145,Color.red,true);
          g_2d.setPaint(gradient_2);
          g_2d.fill(curve_2);
          Color c3=new Color(0,200,0); g_2d.setColor(c3);
          g_2d.draw(line);
          g_2d.draw(leaf_line1); g_2d.draw(leaf_line2); 
          g_2d.draw(leaf_line3); g_2d.draw(leaf_line4);
        }
    //花瓣中间的花蕾曲线:
      QuadCurve2D center_curve_1=
 new   QuadCurve2D.Double(200,200,190,185,200,180);
      AffineTransform trans_1=new AffineTransform();
      for(int i=0;i<12;i++)
        { trans_1.rotate(30*Math.PI/180,200,200);
           g_2d.setTransform(trans_1);
           GradientPaint gradient_3=
           new GradientPaint(200,200,Color.red,200,180,Color.yellow);
             g_2d.setPaint(gradient_3);
             g_2d.fill(center_curve_1);
         }
       //再绘制一个0.4倍的花朵:
       AffineTransform trans_2=new AffineTransform();
       trans_2.scale(0.4,0.4);
       for(int i=0;i<6;i++)
         { trans_2.rotate(60*Math.PI/180,200,200);
            g_2d.setTransform(trans_2);g_2d.setColor(Color.pink);
            g_2d.fill(curve_1);g_2d.setColor(Color.green);
            g_2d.fill(curve_2);
         }
    }
}
import Java.awt.*;import Java.applet.*;
import Java.awt.geom.*;
public class Example17_20 extends Applet
{ public void paint(Graphics g)
   { Graphics2D g_2d=(Graphics2D)g;
      Ellipse2D ellipse1=
      new Ellipse2D. Double (20,50,120,120);
      Ellipse2D ellipse2=
      new Ellipse2D. Double (80,50,120,120);
      Area a1=new Area(ellipse1); Area a2=new Area(ellipse2);
      a1.intersect(a2);             //"与"
      g_2d.fill(a1);
      ellipse1.setFrame(150,50,120,120); ellipse2.setFrame(260,50,50,100);
      a1=new Area(ellipse1); a2=new Area(ellipse2);
      a1.add(a2);             //"或"
      g_2d.fill(a1);
      ellipse1.setFrame(20,170,120,120);ellipse2.setFrame(80,170,160,160);
      a1=new Area(ellipse1); a2=new Area(ellipse2);
      a1.subtract(a2);             //"差"
      g_2d.fill(a1);
      ellipse1.setFrame(150,170,120,120); ellipse2.setFrame(260,170,50,100);
      a1=new Area(ellipse1); a2=new Area(ellipse2);
      a1.exclusiveOr(a2);         //"异或"
      g_2d.fill(a1);
   }
}
import Java.awt.*;import Java.applet.*;
import Java.awt.geom.*;
public class Example17_21 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.0*Math.PI/180,80,75);
            g_2d.setTransform(trans);
            g_2d.fill(a1);
         }
   }
}
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);//设置XOR绘图模式。
      g.setColor(Color.green);
      g.fillRect(20,20,80,40);//矩形的实际颜色是green+yellow的混合色:灰色。
      g.setColor(Color.yellow);
      g.fillRect(60,20,80,40);//该矩形的前一半是yellow+yellow+灰色=red+灰色,
                            //后一半是红色。
      g.setColor(Color.green);
      g.fillRect(20,70,80,40);//矩形的实际颜色是green+yellow的混合色:灰色。
      g.fillRect(60,70,80,40);// 该矩形的前一半是green+yellow+灰色=背景色,
                // 后一半是green+yellow:灰色。
      g.setColor(Color.green);
      g.drawLine(100,100,200,200);//该直线是green+yellow:灰色。
      //下面,在同一位置再绘制该直线,因此,该直线前半段是green+yellow+灰色=
     //灰色+灰色=背景色,该直线后半段是green+yellow=灰色: g.drawLine(100,100,220,220);
      //仔细分析下列直线颜色的变化:
      g.setColor(Color.yellow);
      g.drawLine(20,30,160,30); g.drawLine(20,75,160,75);
   }
}
import Java.awt.*;import Java.awt.event.*;
import Java.awt.geom.*;
public class Example17_23
{ public static void main(String args[])
   { Frame f=new Frame();
      f.setSize(70,70); f.setVisible(true);
      Mycanvas canvas=new Mycanvas();
      f.add(canvas,"Center");f.pack();
      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();
   }
}
 class Mycanvas extends Canvas
{ Mycanvas()
   { setSize(200,200);
   }
 public void paint(Graphics g)
   { g.drawRect(30,30,40,40);
   }
}


 
import Java.applet.*;import Java.awt.*;
import Java.awt.event.*;
public class Example18_1 extends Applet implements MouseListener
{ TextField text;
   public void init()
   { text=new TextField(40); add(text);
      addMouseListener(this) ;//向小程序增加鼠标事件监视器。
   }  
   public void mousePressed(MouseEvent e)
   { text.setText("鼠标键按下了,位置是"+e.getX()+","+e.getY() );
   }
   public void mouseReleased(MouseEvent e)
   { text.setText(" 鼠标松开了,位置是"+e.getX()+","+e.getY() );
   }
   public void mouseEntered(MouseEvent e)
   { text.setText(" 鼠标进来了,位置是"+e.getX()+","+e.getY() );
   }
   public void mouseExited(MouseEvent e)
   { text.setText(" 鼠标走开了");
   }
   public void mouseClicked(MouseEvent e)
   { if(e.getClickCount()==2)
       { text.setText("鼠标键双击,位置:"+e.getX()+","+e.getY());
       } 
      else {}
  }
}
import Java.awt.*;import Java.awt.event.*;
class MyCanvas extends Canvas implements MouseListener
{ int left=-1,right=-1; //记录左、右键用的变量。
   int x=-1,y=-1;        //记录鼠标位置用的变量。
   MyCanvas()
   { setSize(100,100);
      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 Example18_2
{ 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();   
   }
}
import Java.awt.*;import Java.awt.event.*;
import Java.applet.*;
public class Example18_3 extends Applet implements MouseListener
{ TextField text; Button button;
   TextArea textArea;
   public void init()
  { text=new TextField(10); text.addMouseListener(this);
      button=new Button("按钮"); button.addMouseListener(this);
      addMouseListener(this);
      textArea=new TextArea(8,28);
      add(button);add(text);add(textArea);
   }
   public void mousePressed(MouseEvent e)
   { if(e.getSource()==button)
      {textArea.append("/n在按钮上鼠标按下,位置:"+"("+e.getX()+","+e.getY()+")");
      }
     else if(e.getSource()==text)
      {textArea.append("/n在文本框上鼠标按下,位置:"+"("+e.getX()+","+e.getY()+")");
      }
    else if(e.getSource()==this)
     {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()+")");
   }
}
import Java.applet.*;import Java.awt.*;import Java.awt.event.*;
public class Example18_4 extends Applet implements MouseMotionListener
{ int x=-1,y=-1;
   public void init()
   { setBackground(Color.green);
      addMouseMotionListener(this);
   }
   public void paint(Graphics g)
   { if(x!=-1&&y!=-1)
       { g.setColor(Color.red);
          g.drawLine(x,y,x,y);
      }
   }
   public void mouseDragged(MouseEvent e)
   { x=(int)e.getX();y=(int)e.getY();
      repaint();
    }
   public void mouseMoved(MouseEvent e){}
   public void update(Graphics g)
   { paint(g);
   }
}
import Java.applet.*;import Java.awt.*;
import Java.awt.event.*;
public class Example18_5 extends Applet
implements ActionListener,MouseMotionListener
{ int x=-1,y=-1,橡皮擦通知=0,清除通知=0;
   Color c=new Color(255,0,0);int con=3;
   Button b_red,b_blue,b_green,
   清除,b_quit;
   public void init()
   { addMouseMotionListener(this);
      b_red=new Button("画红色图形");   
      b_blue=new Button("兰色图形");
      b_green=new Button("画绿色图形"); 
      b_quit=new Button("橡皮");
      清除=new Button("清除");
      add(b_red); add(b_green); add(b_blue); add(b_quit);add(清除);
      b_red.addActionListener(this); b_green.addActionListener(this);
      b_blue.addActionListener(this); b_quit.addActionListener(this);
      清除.addActionListener(this);
   }
   public void paint(Graphics g)
   { if(x!=-1&&y!=-1&&橡皮擦通知==0&&清除通知==0)
         { g.setColor(c); g.fillOval(x,y,con,con);
         }
       else if(橡皮擦通知==1&&清除通知==0)
        { g.clearRect(x,y,10,10);
        }
       else if(清除通知==1&&橡皮擦通知==0)
        { g.clearRect(0,0,getSize().width,getSize().height);
        }
   }
   public void mouseDragged(MouseEvent e)
   { x=(int)e.getX();y=(int)e.getY(); repaint();
   }
    public void mouseMoved(MouseEvent e){ }
   public void update(Graphics g)
   { paint(g);
   }
   public void actionPerformed(ActionEvent e)
   { if(e.getSource()==b_red)
        { 橡皮擦通知=0;清除通知=0; c=new Color(255,0,0);
        }
      else if(e.getSource()==b_green)
        { 橡皮擦通知=0;清除通知=0; c=new Color(0,255,0);
        }
      else if(e.getSource()==b_blue)
        { 橡皮擦通知=0;清除通知=0; c=new Color(0,0,255);
        }
      if(e.getSource()==b_quit)
       {   橡皮擦通知=1;清除通知=0 ;
       }
      if(e.getSource()==清除)
       {   清除通知=1; 橡皮擦通知=0;repaint();
       }
   }
}
import Java.awt.*;import Java.awt.event.*;import Java.applet.*;
import Javax.swing.SwingUtilities;
public class Example18_6 extends Frame implements MouseListener,MouseMotionListener
{ Button button;
   int x,y;
   boolean move=false;
   Example18_6()
   { button=new Button("按钮");
      button.addMouseListener(this);
      button.addMouseMotionListener(this);
      addMouseMotionListener(this);
      setLayout(new FlowLayout());
      add(button);
      addWindowListener(new WindowAdapter()
              {   public void windowClosing(WindowEvent e)
                  { System.exit(0);
                  }
              });
      setBounds(10,10,200,180);
      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)
   { Button b=null;
      if(e.getSource() instanceof Button) //在按钮上拖动鼠标导致按钮上发生鼠标事件。
         { b=(Button)e.getSource();  
           move=true;
          //将鼠标拖动事件转移到棋盘,导致棋盘上发生鼠标拖动事件:
          e=SwingUtilities.convertMouseEvent(button,e,this);
          //并将从按钮转移得到的鼠标事件e传递给mouseDragged方法的参数。
         }
      if(e.getSource()==this)
         { if(move&&b!=null)
              { x=e.getX(); y=e.getY();
                 int w=b.getSize().width,h=b.getSize().height;
                  b.setLocation(x-w/2,y-h/2);
               }
           }
   }
   public static void main(String args[])
   { new Example18_6();
   }
}
import Java.applet.*;import Java.awt.*;
import Java.awt.event.*;
public class Example18_7 extends Applet implements
KeyListener
{ Button b[]=new Button[10];
   int x,y;
   public void init()
   { for(int i=0;i<=9;i++)
         { b[i]=new Button(""+i);
            b[i].addKeyListener(this);
            add(b[i]);
         }
   }
   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) {}
}
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.pink);
      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)                       //当棋子颜色是1时下黑棋子。
               { this.add(chesspoint_black);
                  chesspoint_black.setBounds(a*20-7,b*20-7,16,16);
                  棋子颜色=棋子颜色*(-1);            
                  text_2.setText("请白棋下子");
                  text_1.setText("");
               }
              else if(棋子颜色==-1)                   //当棋子颜色是-1时下白棋子。
               { this.add(chesspoint_white);
                  chesspoint_white.setBounds(a*20-7,b*20-7,16,16);
                   棋子颜色=棋子颜色*(-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,14,14);
   }
   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,14,14);
   }
   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();
   }
}
import Java.awt.event.*;import Java.applet.*;
import Java.awt.*;
public class Move extends.Applet implements KeyListener,ActionListener
{ Button b_go=new Button("go"),
   b_replay=new Button("replay");
   Rectangle rect1,rect2,rect3;
   int b_x=0,b_y=0;
   public void init()
   { b_go.addKeyListener(this);
      b_replay.addActionListener(this);
      setLayout(null);
      //代表迷宫的矩形:
      rect1=new Rectangle(20,40,200,40);
      rect2=new Rectangle(200,40,24,240);
      rect3=new Rectangle(200,220,100,40);
      b_go.setBackground(Color.red);      //代表走迷宫者的按扭。
      add(b_go);b_go.setBounds(22,45,20,20);
      b_x=b_go.getBounds().x;b_y=b_go.getBounds().y;
      b_go.requestFocus() ;
      add(b_replay);b_replay.setBounds(2,2,45,16);//点击重新开始的按扭。  
   }
   public void paint(Graphics g)
   { //画出迷宫:
      g.setColor(Color.green);
      g.fillRect(20,40,200,40);
      g.setColor(Color.yellow);
      g.fillRect(200,40,40,240);
      g.setColor(Color.cyan);
      g.fillRect(200,220,100,40);
      g.drawString("出口",310,220);
      g.setColor(Color.black);
      g.drawString("点击红色按扭,然后用键盘上的方向键移动按扭",100,20);
   }
   public void keyPressed(KeyEvent e)
   { //按键盘上的上下、左右键在迷宫中行走:
      if((e.getKeyCode()==KeyEvent.VK_UP))
        { //创建一个和按扭:b_go 同样大小的矩形:
          Rectangle rect=new Rectangle(b_x,b_y,20,20);
         //要求必须在迷宫内行走:
           if(rect.intersects(rect1)||rect.intersects(rect2)||
rect.intersects(rect3))
             { b_y=b_y-2;b_go.setLocation(b_x,b_y);
             }
         }
       else if(e.getKeyCode()==KeyEvent.VK_DOWN)
         { Rectangle rect=new Rectangle(b_x,b_y,20,20);
            if(rect.intersects(rect1)||rect.intersects(rect2)||
rect.intersects(rect3))
             { b_y=b_y+2;b_go.setLocation(b_x,b_y);
             }
         }
       else if(e.getKeyCode()==KeyEvent.VK_LEFT)
         { Rectangle rect=new Rectangle(b_x,b_y,20,20);
            if(rect.intersects(rect1)||rect.intersects(rect2)
||rect.intersects(rect3))
             { b_x=b_x-2;b_go.setLocation(b_x,b_y);
             }
          }
      else if(e.getKeyCode()==KeyEvent.VK_RIGHT)
         { Rectangle rect=new Rectangle(b_x,b_y,20,20);
           if(rect.intersects(rect1)||rect.intersects(rect2)||
rect.intersects(rect3))
              { b_x=b_x+2;b_go.setLocation(b_x,b_y);
              }
      }
   }
   public void keyReleased(KeyEvent e){}
   public void keyTyped(KeyEvent e){}
   public void actionPerformed(ActionEvent e)
   { b_go.setBounds(22,45,20,20);
 b_x=b_go.getBounds().x;b_y=b_go.getBounds().y;
 b_go.requestFocus() ;
 }
}
import Java.awt.*;import Java.applet.*;import Java.awt.event.*;
class People extends Button implements FocusListener //代表华容道人物的类。
{ Rectangle rect=null;
   int left_x,left_y;//按扭的左上角坐标.
   int width,height; //按扭的宽和高.
   String name; int number;
   People(int number,String s,int x,int y,int w,int h,Hua_Rong_Road road)
   { super(s);
      name=s;this.number=number;
      left_x=x;left_y=y;
      width=w;height=h;setBackground(Color.orange);
      road.add(this);    addKeyListener(road);
      setBounds(x,y,w,h);addFocusListener(this);
      rect=new Rectangle(x,y,w,h);
   }
   public void focusGained(FocusEvent e)
   { setBackground(Color.red);
   }
   public void focusLost(FocusEvent e)
   {   setBackground(Color.orange);
   }
}
public class Hua_Rong_Road extends Applet implements KeyListener,ActionListener
{ People people[]=new People[10];
   Rectangle left,right,above ,below;//华容道的边界 .
   Button restart=new Button("重新开始");  
   public void init()
   { setLayout(null); add(restart);
      restart.setBounds(5,5,80,25);
      restart.addActionListener(this);
      people[0]=new People(0,"曹操",104,54,100,100,this);
      people[1]=new People(1,"关羽",104,154,100,50,this);
      people[2]=new People(2,"张飞",54, 154,50,100,this);
    people[3]=new People(3,"刘备",204,154,50,100,this);
    people[4]=new People(4,"张辽",54, 54, 50,100,this);
    people[5]=new People(5,"曹仁",204, 54, 50,100,this); 
    people[6]=new People(6,"兵 ",54,254,50,50,this); 
    people[7]=new People(7,"兵 ",204,254,50,50,this);
    people[8]=new People(8,"兵 ",104,204,50,50,this);
    people[9]=new People(9,"兵 ",154,204,50,50,this);
    people[9].requestFocus();
    left=new Rectangle(49,49,5,260);
 people[0].setForeground(Color.white) ;  
    right=new Rectangle(254,49,5,260);
      above=new Rectangle(49,49,210,5);
      below=new Rectangle(49,304,210,5);
   }
   public void paint(Graphics g)
   { //画出华容道的边界:
      g.setColor(Color.cyan);
      g.fillRect(49,49,5,260);//left.
      g.fillRect(254,49,5,260);//right.
      g.fillRect(49,49,210,5); //above.
      g.fillRect(49,304,210,5);//below.
      //提示曹操逃出位置和按键规则:
      g.drawString("点击相应的人物,然后按键盘上的上下左右箭头移动",100,20);
      g.setColor(Color.red);
      g.drawString("曹操到达该位置",110,300);
   }
   public void keyPressed(KeyEvent e)
   { People man=(People)e.getSource();//获取事件源.
       man.rect.setLocation(man.getBounds().x, man.getBounds().y);
       if(e.getKeyCode()==KeyEvent.VK_DOWN)
         { man.left_y=man.left_y+50;     //向下前进50个单位。
            man.setLocation(man.left_x,man.left_y);
            man.rect.setLocation(man.left_x,man.left_y);
              //判断是否和其它人物或下边界出现重叠,如果出现重叠就退回50个单位距离。      
            for(int i=0;i<10;i++)
                {if((man.rect.intersects(people[i].rect))&&(man.number!=i))
                    { man.left_y=man.left_y-50;
                       man.setLocation(man.left_x,man.left_y);
                       man.rect.setLocation(man.left_x,man.left_y);  
                    }
                 }
             if(man.rect.intersects(below))
                 { man.left_y=man.left_y-50;
                    man.setLocation(man.left_x,man.left_y);
                    man.rect.setLocation(man.left_x,man.left_y);
                 }
         }
       if(e.getKeyCode()==KeyEvent.VK_UP)
        { man.left_y=man.left_y-50;     //向上前进50个单位。
           man.setLocation(man.left_x,man.left_y);
           man.rect.setLocation(man.left_x,man.left_y);
           //判断是否和其它人物或上边界出现重叠,如果出现重叠就退回50个单位距离。
           for(int i=0;i<10;i++)
               { if((man.rect.intersects(people[i].rect))&&(man.number!=i))
                      { man.left_y=man.left_y+50;
                         man.setLocation(man.left_x,man.left_y);
                          man.rect.setLocation(man.left_x,man.left_y);  
                       }
               }
            if(man.rect.intersects(above))
               { man.left_y=man.left_y+50;
                  man.setLocation(man.left_x,man.left_y);
                  man.rect.setLocation(man.left_x,man.left_y);
               }
        }
      if(e.getKeyCode()==KeyEvent.VK_LEFT)
        { man.left_x=man.left_x-50;     //向左前进50个单位。
           man.setLocation(man.left_x,man.left_y);
           man.rect.setLocation(man.left_x,man.left_y);
           //判断是否和其它人物或左边界出现重叠,如果出现重叠就退回50个单位距离。
          for(int i=0;i<10;i++)
               { if((man.rect.intersects(people[i].rect))&&(man.number!=i))
                    { man.left_x=man.left_x+50;
                      man.setLocation(man.left_x,man.left_y);
                      man.rect.setLocation(man.left_x,man.left_y);  
                     }
               }
          if(man.rect.intersects(left))
              { man.left_x=man.left_x+50;
                 man.setLocation(man.left_x,man.left_y);
                 man.rect.setLocation(man.left_x,man.left_y);
               }
        }
      if(e.getKeyCode()==KeyEvent.VK_RIGHT)
       { man.left_x=man.left_x+50;     //向右前进50个单位。
          man.setLocation(man.left_x,man.left_y);
          man.rect.setLocation(man.left_x,man.left_y);
         //判断是否和其它人物或右边界出现重叠,如果出现重叠就退回50个单位距离。
          for(int i=0;i<10;i++)
              { if((man.rect.intersects(people[i].rect))&&(man.number!=i))
                    { man.left_x=man.left_x-50;
                      man.setLocation(man.left_x,man.left_y);
                      man.rect.setLocation(man.left_x,man.left_y);  
                     }
               }
           if(man.rect.intersects(right))
               { man.left_x=man.left_x-50;
                  man.setLocation(man.left_x,man.left_y);
                  man.rect.setLocation(man.left_x,man.left_y);
                }
         }
   }
   public void keyTyped(KeyEvent e){}
   public void keyReleased(KeyEvent e){}
   public void actionPerformed(ActionEvent e)
   { this.removeAll();
      this.init();
   }
}


 
public class Example19_1
{ public static void main(String args[])
   { Lefthand left;
      Righthand right; 
      left=new Lefthand() ;//创建线程。
      right=new Righthand();
      left.start();   //线程开始运行后,Lefthand类中的run方法将被执行。
      right.start();
   }
}
class Lefthand extends Thread
{ public void run()
   { for(int i=1;i<=5;i++)
       { System.out.print("A");
          try {
               sleep(500);
              }
         catch(InterruptedException e){}
       }
   }
}
class Righthand extends Thread
{ public void run()
   { for(int i=1;i<=5;i++)
         { System.out.print("B");
           try{ sleep(300);
              }
           catch(InterruptedException e){}
         }
   }
}
import Java.awt.*;import Java.awt.event.*;
public class Example19_3
{ public static void main(String args[])
   { Mywin win=new Mywin();win.pack();
   }
}
class Mywin extends Frame implements Runnable
{ Button b=new Button("ok");int x=5;
   Thread bird=null;
   Mywin()
   { setBounds(100,100,120,120);setLayout(new FlowLayout());
      setVisible(true);
      add(b);b.setBackground(Color.green);
      addWindowListener(new WindowAdapter()
           { public void windowClosing(WindowEvent e)
              { System.exit(0);
              }
           });
      bird=new Thread(this);//创建一个新的线程,窗口做目标对象,
                          //替线程bird实现接口Runnable。
      bird.start();         //在创建窗口时又开始了线程bird。
   }
   public void run()       //实现bird的操作。
   { while(true)
       { x=x+1;
          if(x>100) x=5;
          b.setBounds(40,40,x,x);
          try{ bird.sleep(200);
             }
          catch(InterruptedException e){}
       }
   }
}
import Java.applet.*;import Java.awt.*;import Java.awt.event.*;  
public class Example19_3 extends Appletimplements ActionListener,Runnable
{ TextField text1,text2;
   boolean boo; int x=0;
   Thread Scrollwords=null;
   public void init()
   { Scrollwords=new Thread(this);
      text1=new TextField(10);
      text2=new TextField(10);
      add(text1); add(text2);
      text1.addActionListener(this);
   }
   public void start()
   { boo=false;
      try{ Scrollwords.start();
         }
      catch(Exception ee) { }
   }
   public void run ()
   { while(true)
         { x=x+5;
            if(x>200)
               x=0;
           repaint();
            try{ Scrollwords .sleep(80);
               }
            catch(InterruptedException e){}
            if(boo)
              { return;           //结束run方法,导致线程死亡。
              }
          }
   }
   public void paint(Graphics g)
   { g.drawString("欢 迎使 用 本 字 典",x,70);
   }
   public void actionPerformed(ActionEvent e)
   { if(text1.getText().equals("boy"))
      { text2.setText("男孩");
      }
     else if(text1.getText().equals("moon"))
      { boo=true;         //将boo的值设置为true,以便杀死线程Scrollwords。
      }
     else
      { text2.setText("没有该单词");
      }
   }
}
import Java.applet.*;import Java.awt.*;import Java.awt.event.*;
public class Example19_4 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()
   { left.start();right.start();
   }
   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){}
           }
      }
   }
   public void stop()
  { left=null;right=null;
  }
}
import Java.awt.*;import Java.awt.event.*;
import Java.applet.*;
public class Example19_5 extends Applet
                  implements Runnable
{ Thread 红色球,兰色球;
   Graphics redPen,bluePen;
  double t=0;
  public void init()
  {  红色球=new Thread(this);
      兰色球=new Thread(this);
 redPen=getGraphics();bluePen=getGraphics();
 redPen.setColor(Color.red); bluePen.setColor(Color.blue);
  }
  public void start()
   { 红色球.start();兰色球.start();
  }
  public void run()
  {  while(true)
      { t=t+0.2;
         if(Thread.currentThread()==红色球)
            { if(t>20)  t=0;
               redPen.clearRect(0,0,38,300);
               redPen.fillOval(20,(int)(1.0/2*t*t*3.8),16,16);
               try{ 红色球.sleep(50);
                  }
               catch(InterruptedException e){}
             }
          else if(Thread.currentThread()==兰色球)
            { bluePen.clearRect(38,0,500,300);
               bluePen.fillOval(38+(int)(16*t),(int)(1.0/2*t*t*3.8),16,16);
               try{ 兰色球.sleep(50);
                  }
               catch(InterruptedException e){}
            }
      }  
  }
}
import Java.applet.*;import Java.awt.*;
import Java.awt.event.*;
public class Example19_6 extends Applet implements ActionListener
{  Toolkit toolkit;Button button;
  public void init()
   { toolkit=getToolkit();//获得一个工具包对象
      button=new Button("确定");add(button);
      button.addActionListener(this);
   }
  public void actionPerformed(ActionEvent e)
  { if(e.getSource()==button)
       { for(int i=0;i<=9;i++)
             { toolkit.beep();
                try { Thread.sleep(500);
                    }      //每隔半秒钟发出嘟声
               catch(InterruptedException e1){}
             }
       }
   }
}
import Java.applet.*;import Java.awt.*;
import Java.awt.event.*;
public class Example19_7 extends Applet implements Runnable
{ int money=100;TextArea text1,text2;
   Thread 会计,出纳;
   public void init()
   { 会计=new Thread(this); 出纳=new Thread(this);//创建两个线程:会计、出纳。
      text1=new TextArea(20,8); text2=new TextArea(20,8);
      add(text1);add(text2);
   }
   public void start()
   { 会计.start();出纳.start();                 //线程开始。
   }
   public synchronized void 存取(int number) //存取方法。
   { if(Thread.currentThread()==会计)
       { for(int i=1;i<=3;i++) //会计使用存取方法存入90元,存入30元,稍歇一下,
            { money=money+number;        //这时出纳仍不能使用存取方法,
               try { Thread.sleep(1000); //因为会计还没使用完存取方法。
                   }            
               catch(InterruptedException e){}
               text1.append("/n"+money);
            }
       }
      else if(Thread.currentThread()==出纳)
      { for(int i=1;i<=2;i++) //出纳使用存取方法取出30元,取出15元,稍歇一下,
            { money=money-number/2;      //这时会计仍不能使用存取方法,
               try { Thread.sleep(1000); //因为出纳还没使用完存取方法。
                   }
               catch(InterruptedException e){}
               text2.append("/n"+money);
            }
      }
   }
   public void run()
   { if(Thread.currentThread()==会计||Thread.currentThread()==出纳)
         { for(int i=1;i<=3;i++) //从周一到周三会计和出纳都要使用帐本。
                { 存取(30);
                }
         }
   }
}
import Java.applet.*;import Java.awt.*;
import Java.awt.event.*;
class 售票员
{ int 五元钱的个数=2,十元钱的个数=0,二十元钱的个数=0; String s=null;
   public synchronized void 售票规则(int money)
   { if(money==5)     //如果使用该方法的线程传递的参数是5,就不用等待。
        { 五元钱的个数=五元钱的个数+1;
           s= "给您入场卷您的钱正好";
           Example19_8.text.append("/n"+s);
        }
      else if(money==20)          
        { while(五元钱的个数<3)
            { try { wait();    //如果使用该方法的线程传递的参数是20须等待。
                   }
               catch(InterruptedException e){}
            }
           五元钱的个数=五元钱的个数-3;
           二十元钱的个数=二十元钱的个数+1;
           s="给您入场卷"+" 您给我20,找您15元";
           Example19_8.text.append("/n"+s);
        }
       notifyAll();
   }
}
public class Example19_8 extends Applet implements Runnable
{ 售票员 王小姐;
   Thread 张平,李明; //创建两个线程。
   static TextArea text;
   public void init()
   { 张平=new Thread(this);李明=new Thread(this);
      text=new TextArea(10,30);add(text);
      王小姐=new 售票员();
   }
   public void start()
   { 张平.start();李明.start();
   }
   public void run()
   { if(Thread.currentThread()==张平)
        { 王小姐.售票规则(20);
        }
      else if(Thread.currentThread()==李明)
        { 王小姐.售票规则(5);
        }
   }  
}
import Java.awt.event.*;
import Java.awt.*;import Java.util.Date;
class Example19_9 extends Frame implements Runnable,ActionListener
{ Thread thread=null; TextArea text=null;
   Button b_start=new Button("Start"),b_stop=new Button("Stop");
   Example19_9()
   { thread=new Thread(this);
      text=new TextArea();add(text,"Center");
      Panel p=new Panel();p.add(b_start);p.add(b_stop);
      b_start.addActionListener(this);
      b_stop.addActionListener(this) ;
     add(p,"North");setVisible(true);
     setSize(500,500);pack();setSize(500,500);
     setResizable(false);                     //让窗口的大小不能被调整。
     addWindowListener(new WindowAdapter()
                   { public void windowClosing(WindowEvent e)
                     {System.exit(0);
                     }
                   });
   }
   public void actionPerformed(ActionEvent e)
   { if(e.getSource()==b_start)
        {
           if(!(thread.isAlive()))
              { thread=new Thread(this);
              }   
          try { thread.start();
              }
          catch(Exception e1)
              { text.setText("线程没有结束run方法之前,不要再调用start方法");
              } 
       }
      else if(e.getSource()==b_stop)
       { thread.interrupt();
       }
   }
   public void run()
   { while(true)
           { text.append("/n"+new Date());
               try{ thread.sleep(1000);
                  }
               catch(InterruptedException ee)
                  { text.setText("我被消灭");return;//结束run语句,消灭该线程。
                  }
            }
   }
   public static void main(String args[])
   { Example19_9 tt=new Example19_9();
   }
}
import Java.awt.*;import Java.awt.event.*;import Java.applet.*;
public class Example19_10 extends Applet implements Runnable,ActionListener
{ Button b=new Button("go");TextField text=null;
   Thread 发令员,运动员_1,运动员_2;
   int x=10;//线程运动的起始位置。
   Graphics mypen=null;
   public void init()
   { b.addActionListener(this);text=new TextField(20);
      发令员=new Thread(this);运动员_1=new Thread(this);运动员_2=new Thread(this);
      add(b);add(text);
      mypen=getGraphics();
   }
   public void start()
   { 发令员.start();
   }
   public void actionPerformed(ActionEvent e)
   { 发令员.interrupt();//点击按扭结束发令员的生命。
   }
   public void run()
   { if(Thread.currentThread()==发令员)
      { while(true)
        { text.setText("准备跑... ...");text.setText("......");
           try { 发令员.sleep(30);
               }
           catch(InterruptedException e)
               { //点击按扭结束生命,并让运动员_1开始跑。
 text.setText("跑");
                   运动员_1.start(); break;
               } 
        }
     }
    if(Thread.currentThread()==运动员_1)
     { while(true)
        {   x=x+1;
            mypen.setColor(Color.blue);
            mypen.clearRect(10,80,99,100);//显示线程运动的动画。 
            mypen.fillRect(x,85,5,5);
            try { 运动员_1.sleep(10);
                 }
            catch(InterruptedException e)
                 {         //通知运动员_2开始跑,运动员_1结束生命:
运动员_2.start(); return;
}
            if(x>=100)
                { 运动员_1.interrupt();//运动员_1当跑到100米处时结束生命。
                }
        }
     }
     if(Thread.currentThread()==运动员_2)
     { while(true)
        {   x=x+1;
            mypen.setColor(Color.red);
            mypen.clearRect(105,80,150,100);//显示线程运动的动画。
            mypen.fillRect(x+5,85,7,7);
            try { 运动员_2.sleep(10);
                 }
            catch(InterruptedException e)
                 {text.setText("到达终点"); return;
                 }
            if(x>=200)             //运动员_2跑到200米处时结束生命。
                { 运动员_2.interrupt();
                }
        }
     }
   } 
}
import Java.awt.*;import Java.util.*;import Java.awt.event.*;
import Java.awt.geom.*;import Java.applet.*;
public class Example19_11 extends Applet implements Runnable
{   Thread 时针=null,分针=null,秒针=null;//用来表示时针,分针和秒针的线程.
     //表示时针,分针,秒针端点的整型变量:
     int hour_a,hour_b,munite_a,munite_b,second_a,second_b;
     //用来获取当前时间的整型变量:
     int hour=0,munite=0,second=0;
     //用来绘制时针,分针和秒针的Grapghics对象:
     Graphics g_second=null,g_munite=null,g_hour=null;
     //用来存放表盘刻度的数组,供指针走动时使用:
     double point_x[]=new double[61], point_y[]=new double[61] ;
     //用来存放表盘刻度的数组,供绘制表盘使用:
     double scaled_x[]=new double[61], scaled_y[]=new double[61] ;
    //用来判断小程序是否重新开始的变量:
      int start_count=0;
   public void init()
   {g_hour=this.getGraphics();   g_hour.setColor(Color.cyan);
    g_second=this.getGraphics(); g_second.setColor(Color.red);
    g_munite=this.getGraphics(); g_munite.setColor(Color.blue);
    g_second.translate(200,200);//进行坐标系变换,将新坐标系原点设在(200,200)处。
    g_munite.translate(200,200);
    g_hour.translate(200,200);
    point_x[0]=0;point_y[0]=-120; //各个时针十二点处的位置坐标(按新坐标系的坐标)。
    scaled_x[0]=0;scaled_y[0]=-140; //十二点处的刻度位置坐标(按新坐标系的坐标)。
    double jiaodu=6*Math.PI/180;
     //表盘分割成60分,将分割点处的坐标存放在数组中:
     for(int i=0;i<60;i++)
{ point_x[i+1]=point_x[i]*Math.cos(jiaodu)-
Math.sin(jiaodu)*point_y[i];
point_y[i+1]=point_y[i]*Math.cos(jiaodu)+
point_x[i]*Math.sin(jiaodu);
              }
      point_x[60]=0;point_y[60]=-120;//十二点各个时针的位置坐标(按新坐标系的坐标)。
    //表盘分割成60分,将分割点处的坐标存放在数组中:
     for(int i=0;i<60;i++)
{ scaled_x[i+1]=scaled_x[i]*Math.cos(jiaodu)-
Math.sin(jiaodu)*scaled_y[i];
scaled_y[i+1]=scaled_y[i]*Math.cos(jiaodu)+
scaled_x[i]*Math.sin(jiaodu);
}
scaled_x[60]=0; scaled_y[60]=-140;//十二点处刻度位置坐标(按新坐标系的坐标)。
 }
   public void start()
   { //每当小程序重新开始时,首先消灭线程,然后重新开始创建线程。
     if(start_count>=1)
     {秒针.interrupt();分针.interrupt();时针.interrupt();
     }
     秒针=new Thread(this);分针=new Thread(this);
     时针=new Thread(this);
     秒针.start();分针.start();时针.start();
     start_count++;if(start_count>=2) start_count=1;
   }
   public void stop()
   {秒针.interrupt();分针.interrupt();时针.interrupt();
   }
   public void paint(Graphics g)
   { //每当小程序重新绘制自己时,重新开始创建线程:
          this.start();
         //绘制表盘的外观:
         g.drawOval(50,50,300,300);//表盘的外圈。
         g.translate(200,200);
        //绘制表盘上的小刻度和大刻度:
        for(int i=0;i<60;i++)
           { if(i%5==0)
                { g.setColor(Color.red);
                  g.fillOval((int) scaled_x[i],(int) scaled_y[i],8,8);
                }
             else
               g.fillOval((int) scaled_x[i],(int) scaled_y[i],3,3);
           }
 }
 public void run()
 { //获取本地时间:
    Date 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));
    if(Thread.currentThread()==秒针)
      { second_a=(int)point_x[second];second_b=(int)point_y[second];
         g_second.drawLine(0,0,second_a,second_b); //秒针的初始位置。
         g_second.drawString("秒",second_a,second_b);
         int i=second;
         while(true) //秒针开始行走,每一秒走6度.
         {try{秒针.sleep(1000);
          Color c=getBackground();g_second.setColor(c);
          g_second.drawLine(0,0,second_a,second_b);//用背景色清除前一秒时的秒针。
          g_second.drawString("秒",second_a,second_b);
                  //如果这时秒针与分针重合,恢复分针的显示:
                  if((second_a==munite_a)&&(second_b==munite_b))
                   { g_munite.drawLine(0,0,munite_a,munite_b);
                     g_munite.drawString("分",munite_a,munite_b);
                   }
                  //如果这时秒针与时针重合,恢复时针的显示:
                  if((second_a==hour_a)&&(second_b==hour_b))
                   { g_hour.drawLine(0,0,hour_a,hour_b);
                    g_hour.drawString("时",hour_a,hour_b);
                   }
                 }
             catch(InterruptedException e)
                 { Color c=getBackground();g_second.setColor(c);
                  g_second.drawLine(0,0,second_a,second_b);//用背景色清除秒针。
                  g_second.drawString("秒",second_a,second_b);
                  return;
                 }
             //秒针向前走一个单位:
     second_a=(int)point_x[(i+1)%60];
     second_b=(int)point_y[(i+1)%60];//每一秒走6度(一个单位格)。
     g_second.setColor(Color.red);
     g_second.drawLine(0,0,second_a,second_b);   //绘制新的秒针。
     g_second.drawString("秒",second_a,second_b);
             i++;
           }
      } 
    if(Thread.currentThread()==分针)
      { 
          munite_a=(int)point_x[munite];munite_b=(int)point_y[munite];
          g_munite.drawLine(0,0,munite_a,munite_b);//分针的初始位置。
          g_munite.drawString("分",munite_a,munite_b);
          int i=munite;
          while(true)
           {     //第一次,过60-second秒就前进一分钟,以后每过60秒前进一分钟。
                 try{分针.sleep(1000*60-second*1000);second=0;
                  Color c=getBackground();g_munite.setColor(c);
                  //用背景色清除前一分钟的分针:
                  g_munite.drawLine(0,0,munite_a,munite_b);
g_munite.drawString("分",munite_a,munite_b);
                  //如果这时分针与时针重合,恢复时针的显示:
                   if((hour_a==munite_a)&&(hour_b==munite_b))
                   { g_hour.drawLine(0,0,hour_a,hour_b);
                     g_hour.drawString("时",hour_a,hour_b);
                   }
                 }
            catch(InterruptedException e)
                 {return;
                 }
                //分针向前走一个单位:
                munite_a=(int)point_x[(i+1)%60];
                munite_b=(int)point_y[(i+1)%60];//分针每分钟走6度(一个单位格)。
                g_munite.setColor(Color.blue);
                g_munite.drawLine(0,0,munite_a,munite_b);//绘制新的分针。
                g_munite.drawString("分",munite_a,munite_b);
                i++;   second=0;        
           }
      }
    if(Thread.currentThread()==时针)
      { int h=hour%12;
        hour_a=(int)point_x[h*5+munite/12];
hour_b=(int)point_y[h*5+munite/12]; 
        int i= h*5+munite/12;     
        g_hour.drawLine(0,0,hour_a,hour_b);
        g_hour.drawString("时",hour_a,hour_b);
      while(true)
      {//第一次,过12-munite%12分钟就前进一个刻度,以后每过12分钟前进一个刻度.
try{
时针.sleep(1000*60*12-1000*60*(munite%12)-second*1000);munite=0;
          Color c=getBackground();g_hour.setColor(c);
          g_hour.drawLine(0,0,hour_a,hour_b);// 用背景色清除前12分钟时的时针.
          g_hour.drawString("时",hour_a,hour_b);
          }
        catch(InterruptedException e)
                {return;
                }
       hour_a=(int)point_x[(i+1)%60];
      hour_b=(int)point_y[(i+1)%60];//时针每12分走6度(一个单位格)
       g_hour.setColor(Color.cyan);
       g_hour.drawLine(0,0,hour_a,hour_b);//绘制新的时针.
       g_hour.drawString("时",hour_a,hour_b);
       i++; munite=0;
       }
     }
 }  
}


 
import Java.io.*;
class Example20_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());
   }
}
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 Example20_2
{  public static void main(String args[])
  { File dir=new File("F:/8000");
      FileAccept acceptCondition=new FileAccept("Java");
      String fileName[]=dir.list(acceptCondition);
      for(int i=0;i<5;i++)
           { System.out.println(fileName[i]);
           }
  }
}
import Java.io.*;import Java.awt.*;import Java.awt.event.*;
class Example20_3
{ public static void main(String args[])
   { int b;
      TextArea text;
      Frame window=new Frame();
      byte tom[]=new byte[25];
      window.setSize(100,100);text=new TextArea(10,16);
      window.setVisible(true);window.add(text,BorderLayout.CENTER);
      window.pack();
      window.addWindowListener(new WindowAdapter()
                         {  public void windowClosing(WindowEvent e)
                           { System.exit(0);
                           }
                         });
  
      try{ File f=new File("F://8000","Example20_1.Java");
            FileInputStream readfile=new FileInputStream(f);
            while((b=readfile.read(tom,0,25))!=-1)
                {
                   String s=new String (tom,0,b);
                   System.out.println(s);
                   text.append(s);
                }
            readfile.close();
         }
      catch(IOException e)
         {  System.out.println("File read Error");
         }
   }
}
import Java.io.*;
class Example20_4
{ 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 ");
         }
 }
}
import Java.io.*;import Java.awt.*;import Java.awt.event.*;
class Example20_5
{ public static void main(String args[])
   { char a[]="今晚10点发起总攻".toCharArray();  
      int n=0,m=0;
      try{ File f=new File("F://8000","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);
            int length=(int)f.length();
            char tom[]=new char[length];
            while((n=in.read(tom,0,length))!=-1)
                {  String s=new String (tom,0,n);
                   m=n;  
                   System.out.println("密文:"+s);
                }
            in.close();
            for(int i=0;i<m;i++)
               {  tom[i]=(char)(tom[i]^'R');
               }
            String 明文=new String(tom,0,m);
            System.out.println("明文:"+明文);
         }
      catch(IOException e)
         {  System.out.println("File read Error");
         }
   }
}
import Java.io.*;
import Java.awt.*;
import Java.awt.event.*;
class EWindow extends Frame implements ActionListener
{ TextArea text;
   Button buttonRead,buttonWrite;
   BufferedReader bufferIn;
   FileReader in;
   BufferedWriter bufferOut;
   FileWriter out;
   EWindow()
   { super("流的读取");
      text=new TextArea(10,10);text.setBackground(Color.cyan);
      buttonRead =new Button("读取");
      buttonRead.addActionListener(this);
      buttonWrite =new Button("写出");
      buttonWrite.addActionListener(this);
      setLayout(new BorderLayout());
      setSize(340,340);
      setVisible(true);
      add(text,BorderLayout.CENTER);
      Panel pNorth=new Panel();
      pNorth.add(buttonRead);pNorth.add(buttonWrite);
      pNorth.validate();
      add(BorderLayout.NORTH,pNorth);
      addWindowListener(new WindowAdapter()
                       { public void windowClosing(WindowEvent e)
                            { System.exit(0);
                            }
                       });
   }
   public void actionPerformed(ActionEvent e)
   { String s;
      if(e.getSource()==buttonRead)
       { try{ text.setText(null);
                File f=new File("F://8000//","E.Java");
                in=new FileReader(f);
                bufferIn=new BufferedReader(in);
                while((s=bufferIn.readLine())!=null)
                 {  text.append(s+'/n');  
                 }
                bufferIn.close();
                in.close();
             }
          catch(IOException exp){System.out.println(exp);}
       }
      if(e.getSource()==buttonWrite)
       { try {  File f=new File("F://8000//","E.Java");
                 FileWriter out=new FileWriter(f);
                 BufferedWriter bufferOut=new BufferedWriter(out);
                 bufferOut.write(text.getText(),0,(text.getText()).length());
                 bufferOut.flush();
                 bufferOut.close();
                 out.close();
               }
          catch(IOException exp){ System.out.println(exp);}
       }
   }
}
public class Example20_6
{ public static void main(String args[])
   { EWindow w=new EWindow();
      w.validate();
   }
}
import Java.util.*;import Java.io.*;
import Java.awt.*;import Java.awt.event.*;
class EWindow extends Frame implements ActionListener,ItemListener
{ String str[]=new String[7];String s;
   FileReader file;
   BufferedReader in; 
   Button start,next;
   Checkbox box[];
   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);
      box=new Checkbox[4];
      for(int i=0;i<=3;i++)
       {  box[i]=new Checkbox("",false,age);
          box[i].addItemListener(this);
       }
      try {  file=new FileReader("English.txt");
             in=new BufferedReader(file);
          }
      catch(IOException e){}  
      setBounds(100,100,400,320); setVisible(true);
      setLayout(new GridLayout(4,1));
      setBackground(Color.pink);
      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(box[i]);
           }
      p3.add(new Label("您的得分:"));p3.add(分数);
      p4.add(start); p4.add(next);
      add(p1); add(p2);add(p3); add(p4);
      addWindowListener(new WindowAdapter()
                        {public void windowClosing(WindowEvent e)
                           { System.exit(0);
                           }
                        });
     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++)
                       {  box[j-1].setLabel(str[j]);
                       }
                  }
              else if(s.startsWith("endend"))
                  {  题目.setText("学习完毕");
                     for(int j=0;j<4;j++)
                       {  box[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++)
             {
               box[j].setEnabled(true); 
             }
         }
   }
   public void itemStateChanged(ItemEvent e)
   { for(int j=0;j<4;j++)
        { if(box[j].getLabel().equals(str[5])&&box[j].getState())
             { score++;
                分数.setText("得分: "+score);
             }
          box[j].setEnabled(false); 
        }
   }
}
public class Example20_7
{   public static void main(String args[])
    { EWindow w=new EWindow();
       w.pack();
    }
}
import Java.awt.*;import Java.io.*;
import Java.awt.event.*;
public class Example20_8
{ 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.flush();
                       out.close();
                       tofile.close();
                     }
                catch(IOException e2){}
              }
        }
   }
}
 
import Java.awt.*;import Java.io.*;
import Java.awt.event.*;
public class Example20_9
{ public static void main(String args[])
   { try{
            Runtime ce=Runtime.getRuntime();
            ce.exec("Java Example20_8");
            File file=new File("c:/windows","Notepad.exe");
            ce.exec(file.getAbsolutePath());
         }
      catch(Exception e){}
   }
}
import Java.io.*;
public class Example20_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--) //一个int型数据占4个字节,我们从
               { in_and_out.seek(i*4); //文件的第36个字节读取最后面的一个整数,
                  //每隔4个字节往前读取一个整数:
                  System.out.print(","+in_and_out.readInt());
               }
             in_and_out.close();
          }
       catch(IOException e){}
    }
}
import Java.io.*;
class Example20_11
{ public static void main(String args[])
   { try{ RandomAccessFile in=new RandomAccessFile("Example20_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){}
   }
}
import Java.io.*;
import Javax.swing.*;
import Java.awt.*;import
Java.awt.event.*;
import Javax.swing.border.*;
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){}
   }
}
 
public class Example20_12 extends Frame implements ActionListener
{ File file=null;
   MenuBar bar;
   Menu fileMenu;
   MenuItem 录入,显示;
   TextArea show;
   InputArea inputMessage;
   CardLayout card=null; //卡片式布局.
   Panel pCenter;
   Example20_12()
   {
       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;
         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){}
       }
   }
   public static void main(String args[])
   { new Example20_12();
   }
}
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(c);
         }
       catch(IOException e){}
  }
}
import Java.awt.*;import Java.awt.event.*;
import Java.io.*;
public class Example20_14 extends Frame implements ActionListener
{ TextArea text=null; Button 读入=null,写出=null;
   FileInputStream file_in=null; FileOutputStream file_out=null;
   ObjectInputStream object_in=null;                  //对象输入流。
   ObjectOutputStream object_out=null;               //对象输出流。
   Example20_14()
   { setLayout(new FlowLayout()); text=new TextArea(6,10);
      读入=new Button("读入对象"); 写出=new Button("写出对象");
      读入.addActionListener(this);写出.addActionListener(this);
      setVisible(true); add(text);add(读入);add(写出);
      addWindowListener(new WindowAdapter()
                  { public void windowClosing(WindowEvent e)
                            { System.exit(0);
                            }
                   });
       pack();setSize(300,300);
   }
   public void actionPerformed(ActionEvent e)
   { if(e.getSource()==写出)
         { try{ file_out=new FileOutputStream("tom.txt");
                  object_out=new ObjectOutputStream(file_out);//创建对象输出流。
                  object_out.writeObject(text);                //写对象到文件中。
                  object_out.close();
                }
            catch(IOException event){}
          }
       else if(e.getSource()==读入)
         { try{ file_in=new FileInputStream("tom.txt");
                  object_in=new ObjectInputStream(file_in);    //创建对象输入流。
                  TextArea temp=(TextArea)object_in.readObject();//从文件中读入对象。
                  temp.setBackground(Color.pink); this.add(temp);//添加该对象到窗口。
                  this.pack();this.setSize(600,600);
                  object_in.close();
                }
             catch(ClassNotFoundException event)
               { System.out.println("不能读出对象");
               }
             catch(IOException event)
               { System.out.println("can not read file");
               }
         }
   }
   public static void main(String args[])
   { Example20_14 win=new Example20_14();
   }
}
import Java.io.*;
class Student implements Serializable//实现接口Serializable的Student类。
{ 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 Example20_15
{ public static void main(String args[])
   { Student zhang=new Student("zhang ping",1.65);
      try{ FileOutputStream    file_out=new FileOutputStream("s.txt");
        ObjectOutputStream object_out=new ObjectOutputStream(file_out);
        object_out.writeObject(zhang); 
        System.out.println(zhang.name+"的身高是:"+zhang.height);
            FileInputStream file_in=new FileInputStream("s.txt");
            ObjectInputStream object_in=new ObjectInputStream(file_in);
        zhang=(Student)object_in.readObject();
            zhang.setHeight(1.78); //修改身高。
            System.out.println(zhang.name+"现在的身高是:"+zhang.height);
      }
       catch(ClassNotFoundException event)
          { System.out.println("不能读出对象");
          }
       catch(IOException event)
 { System.out.println("can not read file"+event);
 }
   }
}
import Java.awt.*;import Java.io.*;import Java.awt.event.*;
public class Example20_16
{ public static void main(String args[])
  {  JDK f=new JDK();
      f.pack();
      f.addWindowListener(new WindowAdapter() //窗口增加适配器。
                   {public void windowClosing(WindowEvent e)
                          { System.exit(0);
                          }
                    });
      f.setBounds(100,120,700,360);
      f.setVisible(true);
  }
}
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();      //程序运行时,负责显示在dos窗口的输出信息。
   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("查看应用程序运行时在dos窗口输出的信息");
      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);
      dos_out_text.setBackground(Color.blue);
     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);
  }
  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){}
        }
  }
}


 
import Java.applet.*;import Java.awt.*;
import Java.awt.event.*;import Java.net.*;
public class Example21_1 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);
             }
       }
   }
}
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("localhost",4331);
          in=new DataInputStream(mysocket.getInputStream());
          out=new DataOutputStream(mysocket.getOutputStream());
          out.writeUTF("你好!");//通过 out向"线路"写入信息。
          while(true)
            {
               s=in.readUTF();//通过使用in读取服务器放入"线路"里的信息。堵塞状态,
                             //除非读取到信息。
               out.writeUTF(":"+Math.random());
               System.out.println("客户收到:"+s);
               Thread.sleep(500);
            }
         }
       catch(IOException e)
         { System.out.println("无法连接");
         }
       catch(InterruptedException e){}
   }
}
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("ERRO:"+e1);}
     try{ you=server.accept();
           in=new DataInputStream(you.getInputStream());
           out=new DataOutputStream(you.getOutputStream());
           while(true)
           {
             s=in.readUTF();// 通过使用in读取客户放入"线路"里的信息。堵塞状态,
                             //除非读取到信息。
 
             out.writeUTF("你好:我是服务器");//通过 out向"线路"写入信息.
             out.writeUTF("你说的数是:"+s);
             System.out.println("服务器收到:"+s);
             Thread.sleep(500);
           }
        }
     catch(IOException e)
         { System.out.println(""+e);
         }
       catch(InterruptedException e){}
   }
}
import Java.net.*;import Java.io.*;
import Java.awt.*;import Java.awt.event.*;
import Java.applet.*;
public class Computer_client extends Applet implements Runnable,ActionListener
{ Button 计算;TextField 输入三边长度文本框,计算结果文本框;
   Socket socket=null;
   DataInputStream in=null; DataOutputStream out=null;
   Thread thread;
   public void init()
   { setLayout(new GridLayout(2,2));
      Panel p1=new Panel(),p2=new Panel();
      计算=new Button(" 计算");
      输入三边长度文本框=new TextField(12);计算结果文本框=new TextField(12);
      p1.add(new Label("输入三角形三边的长度,用逗号或空格分隔:"));
    p1.add( 输入三边长度文本框);
      p2.add(new Label("计算结果:"));p2.add(计算结果文本框);p2.add(计算);
      计算.addActionListener(this);
      add(p1);add(p2);
   }
   public void start()
   { try
         { //和小程序所驻留的服务器建立套接字连接:
            socket = new Socket(this.getCodeBase().getHost(), 4331);
            in =new DataInputStream(socket.getInputStream());
            out = new DataOutputStream(socket.getOutputStream());
         }
      catch (IOException e){}
      if(thread == null)
        { thread = new Thread(this);
           thread.start();
       }
   }
   public void run()
   { String s=null;
      while(true)
       {    try{ s=in.readUTF();//堵塞状态,除非读取到信息。
 
                  计算结果文本框.setText(s);
               }
           catch(IOException e)
{ 计算结果文本框.setText("与服务器已断开");
   break;
}  
       }
 }
 public void actionPerformed(ActionEvent e)
 { if(e.getSource()==计算)
      { String s=输入三边长度文本框.getText();
         if(s!=null)
           { try { out.writeUTF(s);
                  }
              catch(IOException e1){}
           }              
     }
 }
}
 
import Java.io.*;import Java.net.*;
import Java.util.*;import Java.sql.*;
public class Computer_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{ you=server.accept();
                System.out.println("客户的地址:"+you.getInetAddress());
             }
         catch (IOException e)
             { System.out.println("正在等待客户");
             }
         if(you!=null)
             { new Server_thread(you).start(); //为每个客户启动一个专门的线程。 
             }
         else
             { continue;
             }
      }
   }
}
class Server_thread extends Thread
{ Socket socket;Connection Con=null;Statement Stmt=null;
   DataOutputStream out=null;DataInputStream in=null;int n=0;
   String s=null;
   Server_thread(Socket t)
   { socket=t;
      try { in=new DataInputStream(socket.getInputStream());
             out=new DataOutputStream(socket.getOutputStream());
          }
      catch (IOException e)
          {}
   } 
   public void run()       
   { while(true)
      { double a[]=new double[3] ;int i=0;
         try{ s=in.readUTF();堵塞状态,除非读取到信息。
 
    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("请输入数字字符");
                         }
                   }
                double p=(a[0]+a[1]+a[2])/2.0;
                out.writeUTF(" "+Math.sqrt(p*(p-a[0])*(p-a[1])*(p-a[2])));
                sleep(2);   
            }
         catch(InterruptedException e){}
         catch (IOException e)
            { System.out.println("客户离开");
 break;
            }
      }
   }
}
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  
import Java.net.*;
public class DomainName
{ public static void main(String args[])
   { try{ InetAddress address=InetAddress.getByName("www.yahoo.com");
            String domain_name=address.getHostName();//获取 address所含的域名。
            String IP_name=address.getHostAddress(); //获取 address所含的IP地址。
            System.out.println(domain_name);       
            System.out.println(IP_name);
        }
    catch(UnknownHostException e)
       { System.out.println("无法找到 www.yahoo.com");
       }
   }
}
import Java.net.*;
public class DomainName
{ public static void main(String args[])
   { try{ InetAddress address=InetAddress.getLocalHost();
            String domain_name=address.getHostName();//获取 address所含的域名。
            String IP_name=address.getHostAddress();//获取 address所含的IP地址。
            System.out.println(domain_name);       
            System.out.println(IP_name);
        }
    catch(UnknownHostException e){}
   }
}
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("localhost");
           //数据包的目标端口是888(那么收方(北京)需在这个端口接收):
    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);
           //使用端口666来接收数据包(因为北京发来的数据报的目标端口是666)。
            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.pack();
   }
 
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("localhost");
            //数据包的目标端口是666(那么收方(上海)需在这个端口接收):
     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);
           //使用端口888来接收数据包(因为上海发来的数据报的目标端口是888)。
           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.pack();
   }
}
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();
   }
}
 
 
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);
        thread.interrupt();
        停止=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();
   }
}


 
import Java.applet.*;
import Java.awt.*;
public class Example22_1 extends Applet
{ Image img;
   public void start()
   { img=getImage(getCodeBase(),"vintdev.jpg");
   }
   public void paint(Graphics g)
  { g.drawImage(img,2,2,this);
   }
}
import Java.applet.*;import Java.awt.*;
public class Example22_2 extends Applet
{ Image img;int height,width;
   public void start()
   { img=getImage(getCodeBase(),"vintdev.jpg");
      height=img.getHeight(this);width=img.getWidth(this);
 }
   public void paint(Graphics g)
   { g.drawImage(img,22,72,width,height,this);
     g.drawImage(img,2+width,2+height,width,height,this);
   }
}
import Java.applet.*;import Java.awt.*;
public class Wuqiong extends Applet
{ static Image img; Canvas canvas; static int width,height;
   public void init()
   { setLayout(new GridLayout(3,1));add(new Button("祝好"));
      add(new Button("进步"));
      canvas=new Mycanvas(); add(canvas);
      width=getSize().width;height=getSize().height; 
   }
   public void start()
   { img=getImage(getCodeBase(),"Tom1.jpg");
   }
}
class Mycanvas extends Canvas
{ public void paint(Graphics g)
   { g.drawImage(Wuqiong.img,0,0,Wuqiong.width,(Wuqiong.height)/3,this);
   }
}
import Java.applet.*;import Java.awt.*;import Java.awt.event.*;
public class Example22_4 extends Applet implements MouseListener
{ final int number=38; int count=0;
   Image[] card=new Image[number];
   public void init()
   { addMouseListener(this);
      for(int i=0;i<number;i++)
          { card[i]=getImage(getCodeBase(),"jiafei"+i+".jpg"); 
          }
   }
   public void paint(Graphics g)
   { if((card[count])!=null)
     g.drawImage(card[count],10,10,
               card[count].getWidth(this),card[count].getHeight(this),this);
   }
   public void mousePressed(MouseEvent e)
   { count++;
      if(count>number)
        count=0;
     repaint();
   }
   public void mouseReleased(MouseEvent e){}
   public void mouseEntered(MouseEvent e){}
   public void mouseExited(MouseEvent e){}
   public void mouseClicked(MouseEvent e){}
}
import Java.applet.*;import Java.awt.*;import Java.awt.event.*;
public class Example22_5 extends Applet implements Runnable
{ final int number=59; int count=0;
   Thread mythread;
   Image[] pic=new Image[number];
   public void init()
   { for(int i=0;i<number;i++)
         { pic[i]=getImage(getCodeBase(),"tom"+i+".jpg"); 
         }
   }
   public void start()
   { mythread=new Thread(this);
      mythread.start();
   }
   public void stop()
   { mythread=null;
   }
   public void run()
   { while(true)
        { if(count>59)
             count=0;
           repaint();
           count++;
          try{ mythread.sleep(200);
             }
          catch(InterruptedException e){}
        }
   }
   public void paint(Graphics g)
   { if((pic[count])!=null)
      g.drawImage(pic[count],10,10,
                  pic[count].getWidth(this),pic[count].getHeight(this),this);
   }
}
import Java.applet.*;import Java.awt.*;
import Java.awt.event.*;
class Imagecanvas extends Canvas
{ Toolkit tool;  Image myimage;
   Imagecanvas()
   { setSize(200,200);
     tool=getToolkit();//得到一个Toolkit对象。
     myimage=tool.getImage("apple.jpg");//由tool负责获取图像。
   }
   public void paint(Graphics g)
   {
     g.drawImage(myimage,10,10,myimage.getWidth(this),myimage.getHeight(this),this);
   }
}
public class Example22_6
{ public static void main(String args[])
 {Imagecanvas canvas=new Imagecanvas();
   Frame frame=new Frame();
   frame.setLayout(new BorderLayout());
   frame.add(canvas,"Center");   frame.add("South",new Label());
   frame.add("West",new Label()); frame.add("North",new Label());
   frame.setSize(400,300);frame.setVisible(true);
   frame.pack();
   frame.addWindowListener(new WindowAdapter()
     {public void windowClosing(WindowEvent e)
         {System.exit(0);}
         });
   }
}
import Java.applet.*;import Java.awt.*;
import Java.awt.event.*;
class Imagecanvas extends Canvas implements MouseListener
{final int number=59; int count=0; Toolkit tool;
 Image[] card=new Image[number];
 Imagecanvas()
 { getSize(); tool=getToolkit(); addMouseListener(this);
   for(int i=0;i<number;i++)
   {card[i]=tool.getImage("tom"+i+".jpg");
  }
 }
 public void paint(Graphics g)
{if((card[count])!=null)
 g.drawImage(card[count],10,10,
 card[count].getWidth(this),card[count].getHeight(this),this);
 }
 public Dimension getPreferredSize()
 {return new Dimension(160,100);  
 }
 public void mousePressed(MouseEvent e)
 { count++;
    if(count>number-1)
    count=0;
    repaint();
 }
 public void mouseReleased(MouseEvent e){}
 public void mouseEntered(MouseEvent e){}
 public void mouseExited(MouseEvent e){}
 public void mouseClicked(MouseEvent e){}
}
public class Example226
{ public static void main(String args[])
 {Imagecanvas canvas=new Imagecanvas();
   Frame frame=new Frame(); frame.setLayout(new BorderLayout());
   frame.add(canvas,"Center");
   frame.add("South",new Label());frame.add("West",new Label());
   frame.add("North",new Label());
   frame.setSize(400,300);frame.setVisible(true); frame.pack();
   frame.addWindowListener(new WindowAdapter()
     {public void windowClosing(WindowEvent e)
        {System.exit(0);}
     });
   }
}
    import Java.awt.*;import Java.awt.event.*;
public class Frame_Icon
{ public static void main(String args[])
 { Frame frame=new Frame();
    Toolkit tool= frame.getToolkit();//得到一个Toolkit对象。
   Image myimage=tool.getImage("apple.jpg");//由tool负责获取图像。
   //设置窗口的图标是myimage指定的图象apple.jpg:
   frame.setIconImage(myimage);
   frame.setSize(400,300);frame.setVisible(true);
   frame.addWindowListener(new WindowAdapter()
     {public void windowClosing(WindowEvent e)
        { System.exit(0);
        }
     });
 }
}
 


 
import Java.sql.*;
public class Example23_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:redsun","snow","ookk");
             sql=con.createStatement();
             rs=sql.executeQuery("SELECT * FROM chengjibiao");
             while(rs.next())
             { String number=rs.getString(1);
               String name=rs.getString(2); 
               Date    date=rs.getDate(3);
               int     math=rs.getInt("数学");
               int physics=rs.getInt("物理");
               int english=rs.getInt("英语");
               System.out.println("学号:"+number);
               System.out.print(" 姓名:"+name);
               System.out.print(" 出生:"+date);
               System.out.print(" 数学:"+math);
               System.out.print(" 物理:"+physics); 
               System.out.print(" 英语:"+english);
             }
            con.close();
           }
      catch(SQLException e1) {}
  
   }   
import Java.sql.*;
public class Example23_2
{ 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:redsun","snow","ookk");
             sql=con.createStatement();
           rs=sql.executeQuery("SELECT 姓名,英语 FROM chengjibiao WHERE 英语 >= 80 ");
             while(rs.next())
             { String name=rs.getString(1); 
               int english=rs.getInt(2);
               System.out.println(" 姓名:"+name);
               System.out.print(" 英语:"+english);
             }
            con.close();
           }
      catch(SQLException e1) {}
   }   
import Java.awt.*;import Java.net.*;
import Java.sql.*;import Java.awt.event.*;
class DataWindow extends Frame implements ActionListener
{ TextField englishtext;TextArea chinesetext; Button button;
   DataWindow()
   { super("英汉小词典");
      setBounds(150,150,300,120);
      setVisible(true);
      englishtext=new TextField(16);
      chinesetext=new TextArea(5,10);
      button=new Button("确定");
      Panel p1=new Panel(),p2=new Panel();
      p1.add(new Label("输入要查询的英语单词:"));
      p1.add(englishtext);
      p2.add(button);
      add(p1,"North");add(p2,"South");add(chinesetext,"Center");
      button.addActionListener(this);
     addWindowListener(new WindowAdapter()
                      { public void windowClosing(WindowEvent e)
                             { System.exit(0); 
                             }
                      });
   }
   public void actionPerformed(ActionEvent e)
   { if(e.getSource()==button)
        { chinesetext.setText("查询结果");
           try{ Liststudent();
              }
           catch(SQLException ee) {}
        }
   }
   public void Liststudent() throws SQLException
   { String cname,ename;
     try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        }
     catch(ClassNotFoundException e){}
     Connection Ex1Con=DriverManager.getConnection("jdbc:odbc:test","gxy","ookk");
     Statement Ex1Stmt=Ex1Con.createStatement();
     ResultSet rs=Ex1Stmt.executeQuery("SELECT * FROM 表1 "); 
     boolean boo=false;
     while((boo=rs.next())==true)
        { ename=rs.getString("单词");
           cname=rs.getString("解释");
           if(ename.equals(englishtext.getText()))
              {
                chinesetext.append('/n'+cname);
               break;
              }
        }
     Ex1Con.close();
    if(boo==false)
       { chinesetext.append('/n'+"没有该单词");
       }
   }
}
public class Example23_3
{ public static void main(String args[])
     { DataWindow window=new DataWindow();window.pack();
     }
}
import Java.sql.*;
public class Example23_4
{ 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:redsun","snow","ookk");
             sql=con.createStatement();
             sql=
 con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
             //返回可滚动的结果集:
             rs=sql.executeQuery("SELECT 姓名,英语 FROM chengjibiao WHERE 英语 >= 80 ");
             //将游标移动到最后一行:
             rs.last();
             //获取最后一行的行号:
             int number=rs.getRow();
             System.out.println("该表共有"+number+"条记录");
             //为了逆序输出记录,需将游标移动到最后一行之后:
             rs.afterLast();
             while(rs.previous())
             { String name=rs.getString(1); 
               int english=rs.getInt("英语");
               System.out.println(" 姓名:"+name);
               System.out.print(" 英语:"+english);
             }
            System.out.println("单独输出第5条记录:");
            rs.absolute(5);
               String name=rs.getString(1); 
               int english=rs.getInt("英语");
               System.out.println(" 姓名:"+name);
               System.out.print(" 英语:"+english);
            con.close();
           }
      catch(SQLException e1) {}
   }   
 
import Java.sql.*;
public class Example23_5
{ 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:redsun","snow","ookk");
             sql=con.createStatement();
             String condition="SELECT 姓名,英语 FROM chengjibiao ORDER BY 英语";
             rs=sql.executeQuery(condition);
             while(rs.next())
             { String name=rs.getString(1); 
               int english=rs.getInt(2);
               System.out.println(" 姓名:"+name);
               System.out.print(" 英语:"+english);
             }
            con.close();
           }
      catch(SQLException e1) { System.out.print(e1);}
   }   
import Java.sql.*;
public class Example23_6
{ 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:redsun","snow","ookk");
             sql=con.createStatement();
     rs=sql.executeQuery("SELECT 姓名,数学 FROM chengjibiao WHERE 姓名 LIKE '%小%' ");
             while(rs.next())
             { String name=rs.getString(1); 
               int math=rs.getInt(2);
               System.out.println(" 姓名:"+name);
               System.out.print(" 数学:"+math);
             }
            con.close();
           }
      catch(SQLException e1) { System.out.print(e1);}
   }   
 
import Java.awt.*;
import Java.sql.*;import Java.awt.event.*;
class DataWindow extends Frame implements ActionListener
 { TextField   待查英文单词_文本条,汉语解释_文本条,
                 更新英文单词_文本条,更新汉语解释_文本条,
                 填加英文单词_文本条,填加汉语解释_文本条;
   Button       查询按扭,更新按扭,填加按扭;
   int 查询记录=0;
   Connection Con=null;Statement Stmt=null;
  DataWindow()
  { super("英汉小词典");
     setBounds(150,150,300,120);
     setVisible(true);setLayout(new GridLayout(3,1));
     try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");}
     catch(ClassNotFoundException e){}
      try{
Con=DriverManager.getConnection("jdbc:odbc:test","gxy","ookk");
           Stmt=Con.createStatement();
         }
      catch(SQLException ee) {}
      待查英文单词_文本条=new TextField(16);
汉语解释_文本条=new TextField(16);
      更新英文单词_文本条=new TextField(16);
更新汉语解释_文本条=new TextField(16);
      填加英文单词_文本条=new TextField(16);
填加汉语解释_文本条=new TextField(16);
      查询按扭=new Button("查询");
      更新按扭=new Button("更新");
      填加按扭=new Button("填加");
      Panel p1=new Panel(),p2=new Panel(),p3=new Panel();
      p1.add(new Label("输入要查询的英语单词:"));
p1.add( 待查英文单词_文本条);
      p1.add(new Label("显示英语单词的汉语解释:"));
p1.add(汉语解释_文本条);
      p1.add(查询按扭);
      p2.add(new Label("输入英语单词:"));p2.add( 更新英文单词_文本条);
      p2.add(new Label("输入该单词更新的汉语解释:"));
p2.add(更新汉语解释_文本条);
      p2.add(更新按扭);
      p3.add(new Label("输入英语单词:"));p3.add( 填加英文单词_文本条);
      p3.add(new Label("输入汉语解释:"));p3.add(填加汉语解释_文本条);
      p3.add(填加按扭);
      add(p1);add(p2);add(p3);
      查询按扭.addActionListener(this);更新按扭.addActionListener(this);
      填加按扭.addActionListener(this);
      addWindowListener(new WindowAdapter()
     {public void windowClosing(WindowEvent e)
                 {setVisible(false);System.exit(0); } } );
  }
  public void actionPerformed(ActionEvent e)
  {if(e.getSource()==查询按扭)
     { 查询记录=0;
        try{ 查询();}
        catch(SQLException ee) {}
     }
   else if(e.getSource()==更新按扭)
    { try{ 更新();}
       catch(SQLException ee) {}
    }
   else if(e.getSource()==填加按扭)
    { try{ 填加();}
       catch(SQLException ee) {}
    }
  }
  public void 查询() throws SQLException
  {  String cname,ename;
 Con=DriverManager.getConnection("jdbc:odbc:test","gxy","ookk");
      ResultSet rs=Stmt.executeQuery("SELECT * FROM 表1 "); 
      while (rs.next())
       { ename=rs.getString("单词"); cname=rs.getString("解释");
          if(ename.equals( 待查英文单词_文本条.getText().trim()))
          { 汉语解释_文本条.setText(cname);查询记录=1; break;
          }
     }
     Con.close();
    if(查询记录==0)
       { 汉语解释_文本条.setText("没有该单词"); 
       }
  }
 public void 更新() throws SQLException
   { String s1="'"+更新英文单词_文本条.getText().trim()+"'",
           s2="'"+更新汉语解释_文本条.getText().trim()+"'";
     String temp="UPDATE 表1 SET 解释 ="+s2+" WHERE 单词 = "+s1 ;
      Con=DriverManager.getConnection("jdbc:odbc:test","gxy","ookk");
      Stmt.executeUpdate(temp); Con.close();
  }
  public void 填加() throws SQLException
   { String s1="'"+填加英文单词_文本条.getText().trim()+"'",
           s2="'"+填加汉语解释_文本条.getText().trim()+"'";
    String temp="INSERT INTO 表1 VALUES ("+s1+","+s2+")";
    Con=DriverManager.getConnection("jdbc:odbc:test","gxy","ookk");
    Stmt.executeUpdate(temp);
    Con.close();
  }
}
public class Database
{ public static void main(String args[])
    {DataWindow window=new DataWindow();window.pack();
 }
}
import Java.net.*;import Java.io.*;
import Java.awt.*;import Java.awt.event.*;
import Java.applet.*;
public class Database_client extends Applet implements Runnable,ActionListener
{ Button 查询;TextField 英文单词_文本框,汉语解释_文本框;
 Socket socket=null;
 DataInputStream in=null;
 DataOutputStream out=null;
 Thread thread;
 public void init()
 {查询=new Button("查询");
 英文单词_文本框=new TextField(10);汉语解释_文本框=new TextField(10);
 add(new Label("输入要查询的英文单词"));add(英文单词_文本框);
 add(new Label("汉语解释:"));add(汉语解释_文本框);add(查询);
 查询.addActionListener(this);
 }
 public void start()
 { try
   {socket = new Socket(this.getCodeBase().getHost(), 4331);
   in = new DataInputStream(socket.getInputStream());
   out = new DataOutputStream(socket.getOutputStream());
   }
   catch (IOException e){}
 if (thread == null)
   {thread = new Thread(this);
    thread.setPriority(Thread.MIN_PRIORITY);
    thread.start();
   }
 }
 public void stop()
 {try{out.writeUTF("客户离开");}
 catch(IOException e1){}
 }
 public void destroy()
 {try{out.writeUTF("客户离开");}
 catch(IOException e1){}
 }
 public void run()
 {String s=null;
    while(true)
     { try{s=in.readUTF();
          }
        catch (IOException e)
 {汉语解释_文本框.setText("与服务器已断开");break;
}
     汉语解释_文本框.setText(s);
    }
 }
 public void actionPerformed(ActionEvent e)
 {if (e.getSource()==查询)
     { String s=英文单词_文本框.getText();
       if(s!=null)            
        { try{out.writeUTF(s);}
          catch(IOException e1){}
        }              
      
     }
 }
}
import Java.io.*;import Java.net.*;
import Java.util.*;import Java.sql.*;
public class Database_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)
                {System.out.println("正在等待客户");
                }
             if(you!=null)
                {new Server_thread(you).start();  
                }
             else {continue;}
         }
    }
}
class Server_thread extends Thread
{ Socket socket;Connection Con=null;Statement Stmt=null;
   DataOutputStream out=null;DataInputStream in=null;
   String s=null;
   Server_thread(Socket t)
      { socket=t;
        try {in=new DataInputStream(socket.getInputStream());
             out=new DataOutputStream(socket.getOutputStream());
            }
        catch (IOException e) {}
        try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            }
        catch(ClassNotFoundException e)
            {
            }
        try { Con=DriverManager.getConnection("jdbc:odbc:test","gxy","ookk");
              Stmt=Con.createStatement();
            }
        catch(SQLException ee) {}
      } 
   public void run()       
   { while(true)
       {try{ s=in.readUTF();
             int n=0;
             ResultSet rs=
             Stmt.executeQuery("SELECT * FROM 表1 WHERE 单词 ="+"'"+s+"'" );
             while (rs.next())
                 { String 英语单词=rs.getString("单词");
                   if(s.equals(英语单词))
                       { out.writeUTF(rs.getString("解释")); n=1;break;
                       }
                    if(n==0) {out.writeUTF("没有此单词");}
                 }
              sleep(45);
            }
        catch(Exception ee)
            { break;
            }
    
       }
   }
}
 


 
import Java.applet.*;import Java.awt.*;
import Java.awt.event.*;
public class Example24_1 extends Applet implements ActionListener
{ AudioClip clip;//声明一个音频对象
  Button button_play,button_loop,button_stop;
    public void init()
  {   clip=getAudioClip(getCodeBase(),"1.au");
     //根据程序所在的地址处的声音文件1.au创建音频对象,Applet类的
    // getCodeBase() 方法可以获得小程序所在的html页面的URL地址。
    button_play=new Button("开始播放");button_loop=new Button("循环播放");
    button_stop=new Button("停止播放");button_play.addActionListener(this);
    button_stop.addActionListener(this);button_loop.addActionListener(this);
    add(button_play);add(button_loop);add(button_stop);  
    }
    public void stop()
    { clip.stop();//当离开此页面时停止播放。
    }
    public void actionPerformed(ActionEvent e)
    { if(e.getSource()==button_play)
        { clip.play();}
      else if(e.getSource()==button_loop)
       { clip.loop();}
      if(e.getSource()==button_stop)
       { clip.stop();}
  }
}
import Java.applet.*;import Java.awt.*;import Java.awt.event.*;
public class Example24_2 extends Applet implements ActionListener,Runnable,ItemListener
{ AudioClip clip;//声明一个音频对象。
   Choice choice;
   TextField text;
   Thread thread;
   String item=null;
   Button button_play,button_loop,button_stop;
   public void init()
 { choice=new Choice();
     thread=new Thread(this);
     int N=Integer.parseInt(getParameter("总数"));
     for(int i=1;i<=N;i++)
       { choice.add(getParameter(String.valueOf(i))); 
       }
    button_play=new Button("开始播放"); 
    button_loop=new Button("循环播放");
    button_stop=new Button("停止播放"); 
    text=new TextField(12);
    button_play.addActionListener(this); 
    button_stop.addActionListener(this);
    button_loop.addActionListener(this);  
    choice.addItemListener(this);
    add(choice);
    add(button_play);add(button_loop);add(button_stop); add(text); 
    button_play.setEnabled(false);
    button_loop.setEnabled(false);
 }
 public void itemStateChanged(ItemEvent e)
 { item=choice.getSelectedItem();
    int index=item.indexOf(":");
    item=item.substring(index+1).trim();
    if(!(thread.isAlive()))
     { thread=new Thread(this);
     }
    try {
         thread.start();
        }
    catch(Exception exp)
        { text.setText("正在下载音频文件");
        }
 }
 public void stop()
 { clip.stop();
 }
 public void actionPerformed(ActionEvent e)
 { if(e.getSource()==button_play)
      { clip.play();
      }
    else if(e.getSource()==button_loop)
      { clip.loop();
      }
    else if(e.getSource()==button_stop)
      { clip.stop();
        button_play.setEnabled(false);
        button_loop.setEnabled(false);
      }
 }
 public void run()
 {
    clip=getAudioClip(getCodeBase(),item);
    text.setText("请稍等...");
     if(clip!=null)
    { button_play.setEnabled(true);
       button_loop.setEnabled(true);
       text.setText("您可以播放了");
    }
 }
}
import Java.applet.*;import Java.awt.*;
import Java.net.*;import Java.awt.event.*;
import Java.io.*;import Javax.media.*;
public class Example24_3 extends Applet
         implements ControllerListener,Runnable,ItemListener
{ Player player;
   String str;
   Thread mythread;
   Choice choice;
   Component visualComponent,controlComponent,progressBar;
   String mediaFile;
   URL mediaURL,codeBase;
   Frame frame;
   public void init()
   { str="Music01.MPG";
     mythread=new Thread(this);
     choice=new Choice();
     choice.add("Music01.MPG");
     choice.add("Music02.avi");
     choice.add("Music03.avi");
     choice.addItemListener(this);
     codeBase=getDocumentBase();
     frame=new Frame("视频系统");
     frame.setSize(660,580);
     frame.addWindowListener(new WindowAdapter()
            { public void windowClosing(WindowEvent e)
               { if(player!=null)
                    { player.stop();player.deallocate();
                    }
                 frame.setVisible(false);
                 System.exit(0);
               }
            });
     add(choice);
   }
   public void stop()
   { if(player!=null)
      { player.stop();
      }
   }
   public synchronized void controllerUpdate(ControllerEvent event)
   {   player.getDuration();
      if(event instanceof RealizeCompleteEvent)
        { if((visualComponent=player.getVisualComponent())!=null)
                 frame.add("Center",visualComponent);
          if((controlComponent=player.getControlPanelComponent())!=null)
                if(visualComponent!=null)
                     frame.add("South",controlComponent);
                else
                     frame.add( "Center",controlComponent);
          frame.validate();
          frame.pack();
        }
     else if(event instanceof PrefetchCompleteEvent)
        { player.start();
        }
   }
   public void itemStateChanged(ItemEvent e)
  { 
      str=choice.getSelectedItem();
      if(player==null)
         {
         }
      else
         { player.stop();player.deallocate();
         }
      frame.removeAll();
      frame.setVisible(true);
      frame.setBounds(300,100,150,100);
      frame.validate();
      if(!(mythread.isAlive()))
         { mythread=new Thread(this);
         }
      try{
            mythread.start();
         }
      catch(Exception ee)
         {
         }
   }
   public synchronized void run()
   { try{ mediaURL=new URL(codeBase,str);
            player=Manager.createPlayer(mediaURL);player.getDuration();
            if(player!=null)
             { player.addControllerListener(this);
             }
           else
             System.out.println("failed to creat player for"+mediaURL);
       }
     catch(MalformedURLException e)
       { System.out.println("URL for"+mediaFile+"is invalid");
       }
      catch(IOException e)
       { System.out.println("URL for"+mediaFile+"is invalid");
       }
     catch(NoPlayerException e)
       { System.out.println("canot find a player for"+mediaURL);
       }
     if(player!=null)
       { player.prefetch();
       }
   }
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
import Javax.swing.*;import Java.awt.*;import Java.awt.event.*;
public class Example25_1
{ public static void main(String args[])
    { JButton button=new JButton("轻组件按钮");
        JTextArea text=new JTextArea("轻组件",20,20);
        JFrame jframe=new JFrame("根窗体");
        jframe.setSize(200,300);jframe.setBackground(Color.blue);
        jframe.setVisible(true);jframe.pack();
        jframe.addWindowListener(new WindowAdapter()
              {public void windowClosing(WindowEvent e)
                {System.exit(0);}
                 });
         Container contentpane=jframe.getContentPane();//获得内容面板。
         contentpane.add(button,BorderLayout.SOUTH); //向内容面板加入组件。
         contentpane.add(text,BorderLayout.CENTER);
         jframe.pack();
 }
}
import Javax.swing.*;import Java.awt.*;import Java.awt.event.*;
class Mywindow extends JFrame
{ JButton button;JTextArea text;
   Mywindow()
   { setSize(200,400);setVisible(true);
     Container con=getContentPane(); con.setLayout(new FlowLayout());
     button=new JButton("ok");text=new JTextArea(10,20);
     con.add(button);con.add(text);pack();
     addWindowListener(new WindowAdapter()
         {public void windowClosing(WindowEvent e)
            {System.exit(0);}
         });
   }
}
public class Example25_2
{ public static void main(String args[])
   { Mywindow win=new Mywindow();win.pack();
   }
}
import Javax.swing.*;import Java.awt.BorderLayout;
public class Example25_3 extends JApplet
{   JButton button;   JTextArea text;
    public void init()
   { button=new JButton("确定");text=new JTextArea();
     getContentPane().add(text,BorderLayout.CENTER); //小程序容器得到内容面板。
     getContentPane().add(button,BorderLayout.WEST);//并向内容面板中添加组件。
   }
}
import Javax.swing.*;import Java.awt.*;import Java.awt.event.*;
class Dwindow extends JFrame //建立根窗体用的类。
{ JButton button1,button2;
   Dwindow(String s)
   { super(s);
      Container con=getContentPane(); 
      button1=new JButton("打开"); button2=new JButton("关闭");
      con.add(button1);con.add(button2);pack();
      setVisible(true);
      addWindowListener(new WindowAdapter()
        { public void windowClosing(WindowEvent e)
           {System.exit(0);}
           });
   }
}
class Mydialog extends JDialog //建立对话框类。
{ JButton button1,button2;
   Mydialog(JFrame F,String s)   //构造方法。
   { super(F,s);
     button1=new JButton("open");     button2=new JButton("close");
     setSize(90,90);setVisible(true);setModal(false);
     Container con=getContentPane();con.setLayout(new FlowLayout());
     con.add(button1);con.add(button2);
     addWindowListener(new WindowAdapter()
       { public void windowClosing(WindowEvent e)
          {System.exit(0);}});
   }
}
public class Example25_4 extends JApplet
{ Dwindow window; Mydialog dialog; JButton button;
   public void init()
   { window=new Dwindow("带对话框窗口");//创建窗口。
      dialog=new Mydialog(window,"我是对话框"); //创建依赖于窗口window的对话框。
      button=new JButton("ok"); getContentPane().add(button);
   }
}
import Javax.swing.*;import Java.awt.*;import Java.awt.event.*;
class Myframe extends JFrame implements ActionListener
{ JButton button;JTextArea text;
   Myframe()
   { setSize(200,400);setVisible(true);
      Container con=getContentPane();
      con.setLayout(new FlowLayout());
      button=new JButton("ok");text=new JTextArea(10,20);
      con.add(button);con.add(text);
      button.addActionListener(this);
      addWindowListener(new WindowAdapter()
       { public void windowClosing(WindowEvent e)
         {System.exit(0);}});
   }
   public void actionPerformed(ActionEvent e)
   { if(e.getSource()==button)
      text.setText("i am a boy,and you?");
   }
}
public class Example25_5
{ public static void main(String args[])
   { Myframe fr=new Myframe();fr.pack();
   }
}
 import Javax.swing.*; import Java.awt.*;
class Mycanvas extends JPanel
{ public void paintComponent(Graphics g)
   { super.paintComponent(g);
     g.setColor(Color.red); g.drawString("a Jpanel used as canvas",50,50);
   }
}
public class Example25_6 extends JApplet
{ Mycanvas canvas; JPanel panel;JButton button;
   public void init()
   { canvas=new Mycanvas();panel=new JPanel();button=new JButton("ok");
      panel.add(button); Container con=getContentPane();
      con.add(panel,BorderLayout.NORTH); con.add(canvas,BorderLayout.CENTER);
   }
}
import Javax.swing.*;import Java.awt.*;import Java.awt.event.*;
class Mywindow extends JFrame
{ JButton button;JTextArea text;JScrollPane scroll;
   Mywindow()
   { setSize(200,400);setVisible(true);
      Container con=getContentPane();
      button=new JButton("ok");text=new JTextArea(10,20);
      scroll=new JScrollPane(text);
      con.add(button,BorderLayout.SOUTH);con.add(scroll,BorderLayout.CENTER);
      addWindowListener(new WindowAdapter()
      {public void windowClosing(WindowEvent e)
        {System.exit(0);}});
   }
}
public class Example25_7
{ public static void main(String args[])
   { Mywindow win=new Mywindow();win.pack();
   }
}
import Javax.swing.*;import Java.awt.*;import Java.awt.event.*;
class Mywindow extends JFrame
{  JButton button1,button2;JTextArea text;JSplitPane split_one,split_two;
   Mywindow()
   { setSize(200,400);setVisible(true); Container con=getContentPane();
      button1=new JButton("ok"); button2=new JButton("No");
      text=new JTextArea("I love you,Java",10,20);
      split_one=new JSplitPane(JSplitPane.VERTICAL_SPLIT,button1,button2);
      split_two=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,split_one,text);
      con.add(split_two,BorderLayout.CENTER);
      addWindowListener(new WindowAdapter()
        {public void windowClosing(WindowEvent e)
        {System.exit(0);}});
   }
}
public class Example25_8
{  public static void main(String args[])
  { Mywindow win=new Mywindow();win.pack();
  }
}
import Javax.swing.*;
import Java.awt.*;
import Java.awt.event.*;
class Mywindow extends JFrame
{ JButton button1,button2;
   JInternalFrame interframe_1,
                interframe_2;
   Mywindow()
   { setSize(200,200); setVisible(true);
     Container con=getContentPane();
     con.setLayout(new GridLayout(1,2));
     button1=new JButton("Boy"); button2=new JButton("Girl");
     interframe_1=
     new JInternalFrame("内窗体1",true,true,true,true);
     interframe_1.setSize(100,100);interframe_1.setVisible(true);
     interframe_1.getContentPane().add(button1);
     JDesktopPane desk1=new JDesktopPane();
     desk1.add(interframe_1);
     interframe_2=new JInternalFrame("内窗体2",true,true,true,true);
     interframe_2.setSize(300,150);interframe_2.setVisible(true);
     interframe_2.getContentPane().add(button2,BorderLayout.CENTER);
     interframe_2.getContentPane().add(new JLabel("ookk"),BorderLayout.NORTH);
     JDesktopPane desk2=new JDesktopPane();
     desk2.add(interframe_2);
     con.add(desk1);con.add(desk2);
     addWindowListener(new WindowAdapter()
      {public void windowClosing(WindowEvent e)
        {System.exit(0);}});
   }
}
public class Exam25_9
{ public static void main(String args[])
 { Mywindow win=new Mywindow();win.pack();
 }
}
import Javax.swing.*; import Java.awt.*;
import Java.awt.event.*;
class MyWin extends JFrame
{ JButton b1,b2,b3;
 public MyWin()
 { setBounds(100,100,300,200); setVisible(true);
    addWindowListener(new WindowAdapter()
      { public void windowClosing(WindowEvent e)
         {  System.exit(0);
         }
      });
    b1=new JButton("按钮1",new ImageIcon("f:/2000/a1.gif"));
    b2=new JButton("按钮2",new ImageIcon("f:/2000/a2.gif"));
    b3=new JButton("按钮3",new ImageIcon("f:/2000/a3.gif"));
    b1.setRolloverIcon(b2.getIcon());
    b2.setRolloverIcon(b3.getIcon());
    b3.setRolloverIcon(b1.getIcon());
    b1.setHorizontalTextPosition(AbstractButton.LEFT);
    b1.setVerticalTextPosition(AbstractButton.TOP);
    b2.setHorizontalTextPosition(AbstractButton.RIGHT);
    b2.setVerticalTextPosition(AbstractButton.BOTTOM);
    b3.setHorizontalTextPosition(AbstractButton.CENTER);
    b3.setVerticalTextPosition(AbstractButton.CENTER);
    Container con=getContentPane();
    con.setLayout(new FlowLayout());
    con.add(b1);con.add(b2); con.add(b3);
    con.validate();
 }
}
public class Example25_10
{ public static void main(String args[])
 {  new MyWin();
 }
}
import Javax.swing.*;import Java.awt.BorderLayout;
import Java.awt.event.*;import Java.awt.*;
public class Example25_11 extends JApplet implements ActionListener
{  JLabel label_1,label_2;JButton button;JTextArea text;
   public void init()
   { button=new JButton("确定");text=new JTextArea();
     Icon icon=new ImageIcon("tom.jpg");
     label_1=new JLabel("标签1",icon,JLabel.CENTER);
     label_2=new JLabel("标签2");
     getContentPane().add(text,BorderLayout.CENTER);
     getContentPane().add(button,BorderLayout.WEST);
     getContentPane().add(label_1,BorderLayout.NORTH);
     getContentPane().add(label_2,BorderLayout.SOUTH);
     button.addActionListener(this);
   }
   public void actionPerformed(ActionEvent e)
   { button.setIcon(label_1.getIcon());
     label_1.setHorizontalTextPosition(JLabel.LEFT);
   }
 }
import Javax.swing.*;
import Java.awt.*;
import Java.awt.event.*;
import Javax.swing.border.*;
class 候选人 extends JCheckBox
{ int 得票数=0;
 候选人(String name,Icon icon)
 { super(name,icon);
 }
 public int 获取得票数()
 { return 得票数;
 }
 public void 增加票数()
 { 得票数++;
 }
}
 
class MyWin extends JFrame implements ActionListener
{   Box baseBox,boxH,boxV;
 JTextArea text;
 JButton button;
 候选人 候选人1, 候选人2, 候选人3;
 public MyWin()
 { setBounds(100,100,300,200);
    setVisible(true);
    addWindowListener(new WindowAdapter()
      { public void windowClosing(WindowEvent e)
         { System.exit(0);
         }
      });
    baseBox=Box.createHorizontalBox();
    boxH=Box.createHorizontalBox();
    boxV=Box.createVerticalBox();
    候选人1=new 候选人("张小兵",new ImageIcon("a1.gif"));
    候选人2=new 候选人("李大营",new ImageIcon("a2.gif"));
    候选人3=new 候选人("王中堂",new ImageIcon("a3.gif"));
    候选人1.setSelectedIcon(new ImageIcon("b1.gif"));
    候选人2.setSelectedIcon(new ImageIcon("b2.gif"));
    候选人3.setSelectedIcon(new ImageIcon("b3.gif"));
    boxH.add(候选人1); boxH.add(候选人2); boxH.add(候选人3);
    text=new JTextArea();
    button=new JButton("显示得票数");
    button.addActionListener(this);
    boxV.add(text); boxV.add(button); baseBox.add(boxH);
    baseBox.add(boxV);
    Container con=getContentPane();
    con.setLayout(new FlowLayout());
    con.add(baseBox);
    con.validate();
 }
 public void actionPerformed(ActionEvent e)
 {   text.setText(null);
   if(候选人1.isSelected())
      {    候选人1.增加票数();
      }
   if(候选人2.isSelected())
      { 候选人2.增加票数();
      }
   if(候选人3.isSelected())
      { 候选人3.增加票数();
      }
   text.append("/n"+候选人1.getText()+":"+候选人1.获取得票数());
   text.append("/n"+候选人2.getText()+":"+候选人2.获取得票数());
   text.append("/n"+候选人3.getText()+":"+候选人3.获取得票数());
   候选人1.setSelected(false);   候选人2.setSelected(false);
   候选人3.setSelected(false);
 }
}
public class Example25_12
{ public static void main(String args[])
 { new MyWin();
 }
}
import Javax.swing.*;
import Java.awt.*;import Java.awt.event.*;
class Mywindow extends JFrame implements ItemListener
{ JRadioButton button1,button2,button3;ButtonGroup fruit;
   JLabel label ;JScrollPane scroll;JPanel panel;JSplitPane split;
   Mywindow()
   { setSize(200,400);setVisible(true);
      Container con=getContentPane(); 
      fruit=new ButtonGroup();
      button1=new JRadioButton("苹果");
      fruit.add(button1);
      button2=new JRadioButton("香蕉");
      fruit.add(button2);
      button3=new JRadioButton("西瓜");
      fruit.add(button3);
      label=new JLabel();panel=new JPanel();
     scroll=new JScrollPane(label);
     panel.add(button1);panel.add(button2);panel.add(button3);
     split=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,panel, scroll);
     con.add(split);
     button1.addItemListener(this);button2.addItemListener(this);
     button3.addItemListener(this);
     addWindowListener(new WindowAdapter()
      {public void windowClosing(WindowEvent e)
        {System.exit(0);}});
   }
   public void itemStateChanged(ItemEvent e)
   {if(e.getItemSelectable()==button1)
    {label.setIcon(new ImageIcon("a.jpg")); }
   else if(e.getItemSelectable()==button2)
    {label.setIcon(new ImageIcon("b.jpg")); }
   else if(e.getItemSelectable()==button3)
    {label.setIcon(new ImageIcon("c.jpg")); }
   }
}
public class Example25_13
{ public static void main(String args[])
 { Mywindow win=new Mywindow();win.pack();
 }
}
import Javax.swing.*;import Java.awt.*;import Java.awt.event.*; import Java.net.*;
public class Example25_14 extends JApplet implements ItemListener
{ JComboBox choice1,choice2; JSplitPane split1,split2;
   JLabel label; URL url;
   public void init()
   { Container con=getContentPane(); String[] s={"苹果", "香蕉" ,"西瓜"};
    choice1=new JComboBox(s);choice2=new JComboBox();
    label=new JLabel();choice2.setEditable(true);
   split1=newJSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,choice1,choice2);
   split2=new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,split1,label);
    choice1.addItemListener(this);choice2.addItemListener(this);con.add(split2);
   }  
   public void itemStateChanged(ItemEvent e)
   { if(e.getItemSelectable()==choice1)
        { if(choice1.getSelectedIndex()==0)
         { label.setIcon(new ImageIcon("a.jpg"));}
         else if(choice1.getSelectedIndex()==1)
         { label.setIcon(new ImageIcon("b.jpg")); }
         else if(choice1.getSelectedIndex()==2)
         {label.setIcon(new ImageIcon("c.jpg"));}
       }     
    else if(e.getItemSelectable()==choice2)
       { try{url=new URL((String)choice2.getSelectedItem());
              label.setText("你正在连接到:"+choice2.getSelectedItem());
            }
         catch(MalformedURLException g)
            { label.setText("不正确的URL:"+url);
            }
             getAppletContext().showDocument(url);
      }
   }
}
import Javax.swing.*;
import Javax.swing.text.*;
import Java.awt.*;
class DigitDocumnet extends PlainDocument
{ public void insertString(int offset ,String s,AttributeSet a)
     { char c=s.charAt(0);
      if ((c<='9'&&c>='0')||(c=='.'))
        { try {super.insertString(offset,s,a);}
         catch(BadLocationException e){}
        }
     }
}
public class DigitText extends JApplet
{ JTextField text=null;
 DigitDocumnet document=new DigitDocumnet();
   public void init()
    { text=new JTextField(30);
      Container con= getContentPane();
      con.setLayout(new FlowLayout());
      text.setDocument(document);
      con.add(text);
    }
}
import Javax.swing.*;
import Javax.swing.text.*;
import Java.awt.*;
public class Example25_16 extends JApplet
{ JTextPane textpane;
   public void init()
 { textpane=new JTextPane();//创建文本窗格。
    getContentPane().add(textpane);
 }
}
import Javax.swing.*;import Javax.swing.text.*;
import Java.awt.*;
public class Example25_17 extends JApplet
 { JTextPane textpane;
    MutableAttributeSet center_align,char_style;
    public void init()
    { textpane=new JTextPane();//创建文本窗格。
JScrollPane scroll=
new ScrollPane(textpane,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                      JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
         center_align=new SimpleAttributeSet();
         char_style=new SimpleAttributeSet(); //创建属性对象。
         StyleConstants.setAlignment(center_align,StyleConstants.ALIGN_CENTER);
        StyleConstants.setFontFamily( char_style,"Serif");
        StyleConstants.setFontSize(char_style,70);
        StyleConstants.setForeground(char_style,Color.red);//为属性对象指定值
        textpane.setParagraphAttributes(center_align,true);//文本窗格设置文本的属性
         textpane.setCharacterAttributes(char_style,true);
         getContentPane().add(scroll);
    }
}
import Javax.swing.*;import Javax.swing.text.*;
import Java.awt.*;
public class Example25_18 extends JApplet
{ JTextPane textpane;
   MutableAttributeSet center_align,char_style_1,char_style_2;
   public void init()
   { textpane=new JTextPane();//创建文本窗口
     JScrollPane scroll=new
     JScrollPane(textpane,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
     JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
     Document mydocument=textpane.getDocument();//初始化一个文档。
     center_align=new SimpleAttributeSet();
     char_style_1=new SimpleAttributeSet();
     char_style_2=new SimpleAttributeSet(); 
     StyleConstants.setAlignment(center_align,StyleConstants.ALIGN_CENTER);
     StyleConstants.setFontFamily( char_style_1,"Courier");
     StyleConstants.setFontSize(char_style_1,20);
     StyleConstants.setForeground(char_style_1,Color.red);
     StyleConstants.setFontFamily( char_style_2,"Serif");
     StyleConstants.setFontSize(char_style_2,14);
     StyleConstants.setForeground(char_style_2,Color.blue);
     textpane.setParagraphAttributes(center_align,true);
     textpane.setCharacterAttributes(char_style_1,true);
     try{ textpane.insertIcon(new ImageIcon("a.jpg"));
     mydocument.insertString(mydocument.getLength(),"Lovely Apple/n",char_style_1);
        }
    catch(BadLocationException e) {}
    textpane.setParagraphAttributes(center_align,true);
    textpane.setCharacterAttributes(char_style_2,true);
    try{ mydocument.insertString(mydocument.getLength(),
                               "I Want It/n",char_style_2);
        }
    catch(BadLocationException e) {}
    getContentPane().add(scroll);
   }
}
import Javax.swing.*;
import Javax.swing.text.*;
import Java.awt.*;import Java.io.*;
public class Example25_19 extends JApplet
{ JTextPane textpane;FileInputStream readfile;
 public void init()
 { textpane=new JTextPane();//创建文本窗口
    JScrollPane scroll=new JScrollPane(textpane);
    try{ readfile=new FileInputStream("Example25_19.Java");  
       }
    catch(IOException ee){}
     try{textpane.read(readfile,this);
        }
     catch(Exception e)
      {}
     getContentPane().add(scroll);
 }
}
import Javax.swing.*;import Java.awt.*;
import Java.awt.event.*;import Java.io.*;
class FileWin extends JFrame implements ActionListener
{ JButton button; JTextArea text;JTextPane textpane;FileInputStream readfile;
 JScrollPane scroll;Container con;
  JFileChooser chooser=new JFileChooser();
 FileWin()
   { super("有文件选择器的窗口");
     button=new JButton("打开文件选取器");
     button.addActionListener(this);
     textpane=new JTextPane();
     scroll=new JScrollPane(textpane);
     setSize(200,200); setVisible(true);
     addWindowListener(new WindowAdapter()
            {public void windowClosing(WindowEvent e)
                 { System.exit(0);}} );
      con=getContentPane();con.add(button,BorderLayout.NORTH);
      con.add(scroll,BorderLayout.CENTER);
   }
 public void actionPerformed(ActionEvent e)
 {if(e.getSource()==button)
    {String s;
     int state=chooser.showOpenDialog(null);
     File file=chooser.getSelectedFile();
     if(file!=null&&state==JFileChooser.APPROVE_OPTION)
     { try{ readfile=new FileInputStream(file); //建立到文件的输入流。
          }
       catch(IOException ee){}
       try{ textpane.read(readfile,this);//从流中读取数据。
          }
      catch(IOException e1){}
     }
    }
 }
}
public class Example25_20
{public static void main(String args[])
 {FileWin Win=new FileWin(); Win.pack(); }
}
 
import Javax.swing.*;
import Java.awt.*;import Java.awt.event.*;
class TimeWin extends JFrame implements ActionListener
{ static JTextArea text1,text2; Boy boy=new Boy();
   JScrollPane scroll_1,scroll_2;Container con;
   Timer time_1,time_2 ;   //声明2个计时器对象。
   JSplitPane splitpane;
 TimeWin()
   {super("有计时器窗口");
    time_1=new Timer(1000,this);//TimeWin对象做计时器的监视器。
    time_2=new Timer(2000,boy);//Boy对象做计时器的监视器。
    text1=new JTextArea(); text2=new JTextArea();
    scroll_1=new JScrollPane(text1);
    scroll_2=new JScrollPane(text2);
    splitpane=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,scroll_1,
                          scroll_2);
    setSize(200,200);
    setVisible(true);
    con=getContentPane();con.add(splitpane);
    time_1.start();time_2.start();//启动计时器。
    addWindowListener(new WindowAdapter()
     {public void windowClosing(WindowEvent e)
       { System.exit(0);}} );
   }
 public void actionPerformed(ActionEvent e)
 {text1.append("欢迎光临!"+"/n"); }
}
class Boy implements ActionListener
{ public void actionPerformed(ActionEvent e)
 { TimeWin.text2.append("再见!"+"/n"); }
}
public class Example25_21
{public static void main(String args[])
 {TimeWin Win=new TimeWin(); Win.pack(); }
}
import Javax.swing.*;import Java.awt.*;
import Java.awt.event.*;
class BarWin extends JFrame implements ActionListener
{ Timer time_1; int sum=0,i=1;
   JProgressBar p_bar;Container con;
 BarWin()
   {super("窗口");
    time_1=new Timer(1000,this);//TimeWin对象做计时器的监视器,每
                                  //1000毫秒震铃一次。
    p_bar=new JProgressBar(0,55);
    p_bar.setBackground(Color.white);
    p_bar.setStringPainted(true);
    setSize(200,200);
    setVisible(true);
    con=getContentPane();con.add(p_bar,BorderLayout.NORTH);
    time_1.start();
    addWindowListener(new WindowAdapter()
     {public void windowClosing(WindowEvent e)
       { System.exit(0);}} );
     }
 public void actionPerformed(ActionEvent e)
 { sum=sum+i;
     p_bar.setValue(sum);//吃掉sum/55
     i=i+1;
     if(sum>=55)
     time_1.stop();
 }
}
public class Example25_22
{public static void main(String args[])
 {BarWin Win=new BarWin(); Win.pack(); }
}
import Javax.swing.*;
import Java.io.*;import Java.awt.*;import Java.awt.event.*;
public class Example25_23
{ public static void main(String args[])
 { byte b[]=new byte[30];
    JTextArea text=new JTextArea(20,20);
    JFrame jframe=new JFrame();
    jframe.setSize(200,300);jframe.setBackground(Color.blue);
    jframe.setVisible(true);
    jframe.addWindowListener(new WindowAdapter()
         {public void windowClosing(WindowEvent e)
            {System.exit(0);} });
    Container contentpane=jframe.getContentPane();
    contentpane.add(text,BorderLayout.CENTER);
  
 try{ FileInputStream input=new FileInputStream("Example25_23.Java");
        ProgressMonitorInputStream input_progress=
           new ProgressMonitorInputStream(contentpane,"读取Java文件",input);
       ProgressMonitor p=input_progress.getProgressMonitor();//获得进度条。
       while(input_progress.read(b)!=-1)
          { String s=new String(b);
            text.append(s);
            Thread.sleep(1000);//由于文件较小,为了看清进度条这里有意延缓1秒。
          }
     }
     catch(InterruptedException e){}
     catch(IOException e){}
 }
}
import Javax.swing.*;import Java.awt.*;
import Java.awt.event.*;
public class Example25_24 extends JFrame implements ActionListener
{ JTable table;Object a[][];
   Object name[]={"姓名","英语成绩","数学成绩","总成绩"};
   JButton button;
   Example25_24()
   { a=new Object[8][4];
     for(int i=0;i<8;i++)
      { for(int j=0;j<4;j++)
          {if(j!=0)
             a[i][j]="0";
           else
             a[i][j]="姓名";
          }
      }
     button=new JButton("计算每人总成绩");
     table=new JTable(a,name);
     button.addActionListener(this);
     getContentPane().add(new JScrollPane(table),BorderLayout.CENTER);
getContentPane().add(new JLabel("修改或录入数据后,需回车确认"),BorderLayout.SOUTH);
     getContentPane().add(button,BorderLayout.SOUTH);
     setSize(200,200);
     setVisible(true);
     validate();
     addWindowListener(new WindowAdapter()
            {public void windowClosing(WindowEvent e)
                   { System.exit(0);
                   }
            });
 }
 public void actionPerformed(ActionEvent e)
 { for(int i=0;i<8;i++)
      { double sum=0;
        boolean boo=true;
        for(int j=1;j<=2;j++)
          { try{
                  sum=sum+Double.parseDouble(a[i][j].toString());
                }
             catch(Exception ee)
               {
                  boo=false;
                  table.repaint();
               }
             if(boo==true)
              {
                a[i][3]=""+sum;
                table.repaint();
              }
          }
      }
   }
   public static void main(String args[])
   { Example25_24 Win=new Example25_24(); 
   }
}
import Javax.swing.*;
import Java.awt.event.*;
import Java.sql.*;
import Java.awt.*;
 class ResultWin extends JFrame implements ActionListener
{ Object a[][];
   Object columnName[]={"学号","姓名","出生日期","数学","物理","英语"};
   JTable table;JButton button;
   Container container;
   String name,xuehao;Date date; int math,physics,english;
   Connection con;Statement sql; ResultSet rs;
   JProgressBar p_bar;
 ResultWin()
 { super("数据查询");
     a=new Object[30][6];
     table=new JTable(a,columnName);
     setSize(300,300);setVisible(true);
     button=new JButton("确定");
     addWindowListener(new WindowAdapter()
     {public void windowClosing(WindowEvent e)
       { System.exit(0);}} );
     button.addActionListener(this);
     p_bar=new JProgressBar(JProgressBar.VERTICAL,0,50);
     p_bar.setStringPainted(true) ;
     container=getContentPane();
     container.add(button,BorderLayout.SOUTH);
     container.add(new JScrollPane(table),BorderLayout.CENTER);
     container.add(p_bar,BorderLayout.WEST); 
    }
 public void actionPerformed(ActionEvent evt)
 {if(evt.getSource()==button)
   {int i=0;
    try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); }
    catch(ClassNotFoundException e){}
    try
{con=DriverManager.getConnection("jdbc:odbc:redsun","snow","ookk");
       sql=con.createStatement();
       rs=sql.executeQuery("SELECT * FROM chengjibiao");
       while(rs.next())
       { xuehao=rs.getString(1); name=rs.getString(2);date=rs.getDate(3);
         math=rs.getInt("数学"); physics=rs.getInt("物理");english=rs.getInt("英语");
        a[i][0]=xuehao;a[i][1]=name;a[i][2]=date;a[i][3]=String.valueOf(math);
        a[i][4]=String.valueOf(physics);a[i][5]=String.valueOf(english);
        i++;
        p_bar.setValue(i);p_bar.setString("查询了"+i+"条记录");
       }
      con.close();
     }
    catch(SQLException e1) {}
   }  
 }
}
public class Example25_25
{ public static void main(String args[])
 {ResultWin win=new ResultWin(); win.pack(); }
}
import Javax.swing.*;
import Java.awt.*;
import Java.awt.event.*;
public class Example24_26 extends JApplet
{ Container con;
 public void init()
 {con=getContentPane(); 
 JMenuBar menubar=new JMenuBar();
 con.add(menubar,BorderLayout.NORTH);
 JMenu fileMenu=new JMenu("文件");
 JMenu editMenu=new JMenu("编辑");
 JMenu helpMenu=new JMenu("帮助");
 JMenuItem item1=new JMenuItem("打开");
 JMenuItem item2=new JMenuItem("保存"); //创建6个菜单项。
 fileMenu.add(item1); fileMenu.add(item2);
 menubar.add(fileMenu); menubar.add(editMenu);
 menubar.add(helpMenu);
 }
}
import Javax.swing.*;import Java.awt.*;
import Java.awt.event.*;
class ToolWin extends JFrame implements ActionListener
{ JButton button1,button2; JToolBar bar; Container con;
 ToolWin()
 {con=getContentPane();
 setSize(300,250);setVisible(true); 
 Icon open_icon =new ImageIcon("open.gif");
 Icon save_icon =new ImageIcon("save.gif");
 button1=new JButton(open_icon); button2=new JButton(save_icon);
 bar=new JToolBar();//工具条对象
 bar.add(button1);bar.add(button2);
 con.add(bar,BorderLayout.NORTH);
 button1.addActionListener(this);
 button1.setToolTipText("open");//设置组件的提示文字
 button2.setToolTipText("save");
 }
 public void actionPerformed(ActionEvent e)
 {if(e.getSource()==button1)
 {JFileChooser c=new JFileChooser();
    c.showOpenDialog(null); 
 }
 }
}
public class Example25_27
{static void main(String args[])
 {ToolWin win=new ToolWin() ;win.pack();}
}
 
import Javax.swing.*;import Javax.swing.tree.*;
import Java.awt.*;
public class Mytree extends JApplet
{ public void init()
 {Container con=getContentPane();
   DefaultMutableTreeNode root=new DefaultMutableTreeNode("c://");//树的根节点。
   DefaultMutableTreeNode t1=new DefaultMutableTreeNode("dos");//节点。
   DefaultMutableTreeNode t2=new DefaultMutableTreeNode("Java");//节点。
   DefaultMutableTreeNode t1_1=new DefaultMutableTreeNode("applet");
   DefaultMutableTreeNode t1_2=new DefaultMutableTreeNode("jre");
   root.add(t1);root.add(t2);
   t1.add(t1_1);t1.add(t1_2);//t1_1,t1_2成为t1的子节点。
   JTree tree =new JTree(root); //创建根为root的树。
   JScrollPane scrollpane=new JScrollPane(tree);
   con.add(scrollpane);
 }
}
import Javax.swing.*;
import Javax.swing.tree.*;import Java.awt.*;
import Java.awt.event.*;import Javax.swing.event.*;
public class Mytree2 extends JFrame implements TreeSelectionListener
{ JTree tree=null;JTextArea text=new JTextArea(20,20);
 Mytree2()
 {Container con=getContentPane();
   DefaultMutableTreeNode root=new DefaultMutableTreeNode("同学通讯录");
   DefaultMutableTreeNode t1=new DefaultMutableTreeNode("大学同学");
   DefaultMutableTreeNode t2=new DefaultMutableTreeNode("研究生同学");
   DefaultMutableTreeNode t1_1=new DefaultMutableTreeNode("董明光");
   DefaultMutableTreeNode t1_2=new DefaultMutableTreeNode("李晓");
   DefaultMutableTreeNode t2_1=new DefaultMutableTreeNode("王光明");
   DefaultMutableTreeNode t2_2=new DefaultMutableTreeNode("代学才");
   root.add(t1);root.add(t2);
   t1.add(t1_1);t1.add(t1_2); t2.add(t2_1);t2.add(t2_2);
   tree =new JTree(root);
   JScrollPane scrollpane=new JScrollPane(text);
   JSplitPane splitpane=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                            true,tree,scrollpane);
   tree.addTreeSelectionListener(this);  
   con.add(splitpane);
   addWindowListener(new WindowAdapter()
    { public void windowClosing(WindowEvent e)
      {System.exit(0);} });
   setVisible(true);setBounds(70,80,200,300);
    }
 public void valueChanged(TreeSelectionEvent e)
 { if(e.getSource()==tree)
     {DefaultMutableTreeNode node=
      (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
      if(node.isLeaf())
        { String str=node.toString();
           if(str.equals("董明光"))
             {text.setText(str+":联系电话:0411-4209876");}
           else if(str.equals("李晓"))
             {text.setText(str+":联系电话:010-62789876");}
           else if(str.equals("王光明"))
              {text.setText(str+":联系电话:0430-63596677");}
           else if(str.equals("代学才"))
              {text.setText(str+":联系电话:020-85192789");}
        }
      else
       {text.setText(node.getUserObject().toString());
       }
     }
 }
}
class Example25_29
{public static void main(String args[])
 { Mytree2 win=new Mytree2();win.pack();}
}
import Javax.swing.*;import Javax.swing.tree.*;
import Java.awt.*;
public class Mytree3 extends JApplet
{ public void init()
 {Container con=getContentPane();
   DefaultMutableTreeNode root=new DefaultMutableTreeNode("c://");//树的根节点。
   DefaultMutableTreeNode t1=new DefaultMutableTreeNode("dos");//节点。
   DefaultMutableTreeNode t2=new DefaultMutableTreeNode("Java");//节点。
   DefaultMutableTreeNode t1_1=new DefaultMutableTreeNode("wps");
   DefaultMutableTreeNode t1_2=new DefaultMutableTreeNode("epg");
   DefaultMutableTreeNode t2_1=new DefaultMutableTreeNode("applet");
   DefaultMutableTreeNode t2_2=new DefaultMutableTreeNode("jre");
   root.add(t1);root.add(t2);
   t1.add(t1_1);t1.add(t1_2);
   t2.add(t2_1);t2.add(t2_2);
   JTree tree =new JTree(root); //创建根为root的树。
   DefaultTreeCellRenderer render=new DefaultTreeCellRenderer();
   render.setLeafIcon(new ImageIcon("leaf.gif"));
   render.setBackground(Color.yellow);
   render.setClosedIcon(new ImageIcon("close.gif"));
   render.setOpenIcon(new ImageIcon("open.gif"));
   render.setTextSelectionColor(Color.red);
   render.setTextNonSelectionColor(Color.green);
   render.setFont(new Font("TimeRoman",Font.BOLD,16));
   tree.setCellRenderer(render);
   JScrollPane scrollpane=new JScrollPane(tree);
   con.add(scrollpane);
 }
}
import Javax.swing.*;
import Javax.swing.tree.*;
import Java.awt.*;
import Java.awt.event.*;
import Java.io.*;import Java.util.*;
class Classmate extends JFrame
{ JTree tree=null; DefaultMutableTreeNode root;
   BufferedReader in; FileReader file;
  Classmate()
   { Container con=getContentPane();
      String s=null;
      try { File f=new File("通讯录.txt");
           file=new FileReader(f);
           in=new BufferedReader(file);
          }
      catch(FileNotFoundException e){}
      try { s=in.readLine();                //读取第一行并用它创建根节点。
           root=new DefaultMutableTreeNode(s);        
          }
      catch(IOException exp){}
      try
         { while((s=in.readLine())!=null&&(s.startsWith("%")))
              { s=in.readLine();
                DefaultMutableTreeNode 同学种类=new DefaultMutableTreeNode(s);
                root.add(同学种类);
                while((s=in.readLine())!=null&&!(s.startsWith("end")))
                     { StringTokenizer tokenizer=new StringTokenizer(s,"#");
                        String temp=tokenizer.nextToken();
                        DefaultMutableTreeNode 同学种类_姓名
                        =new DefaultMutableTreeNode(temp);
                        同学种类.add(同学种类_姓名);
                         while(tokenizer.hasMoreTokens())
                         {
              同学种类_姓名.add(new DefaultMutableTreeNode(tokenizer.nextToken()));
                         }
                      }
              }
         }
       catch(IOException exp){}  
       tree =new JTree(root);
       JScrollPane scrollpane=new JScrollPane(tree);
       con.add(scrollpane);
       addWindowListener(new WindowAdapter()
               { public void windowClosing(WindowEvent e)
               {System.exit(0);} });
       setVisible(true);setBounds(70,80,200,300);
   }
 }
public class Example31
{ public static void main(String args[])
   { Classmate win=new Classmate();win.pack();}
}
import Javax.swing.*;
import Javax.swing.tree.*;
import Java.awt.*;
import Java.awt.event.*;
import Javax.swing.event.*;
import Java.io.*;
class Remember extends JFrame implements TreeSelectionListener,ActionListener
{ JTree tree=null;JTextArea text=new JTextArea(" ",20,20);int i=0;
   DefaultMutableTreeNode root;JButton b_save=new JButton("保存日志"),
   b_del=new JButton("删除日志");
   DefaultMutableTreeNode month[]=new DefaultMutableTreeNode[13];
   Remember()
   { Container con=getContentPane();
      DefaultMutableTreeNode root=new DefaultMutableTreeNode("日历记事本");
      for(i=1;i<=12;i++)
          { month[i]=new DefaultMutableTreeNode(""+i+"月");
             root.add(month[i]);
          }
      for(i=1;i<=12;i++)
      { if(i==1||i==3||i==5||i==7||i==8||i==10||i==12)
          { for(int j=1;j<=31;j++)
             month[i].add(new DefaultMutableTreeNode(j+"日"));
          }
         else if(i==4||i==6||i==9||i==11)
          { for(int j=1;j<=30;j++)
                month[i].add(new DefaultMutableTreeNode(j+"日"));
          }
         else
         { for(int j=1;j<=28;j++)
                month[i].add(new DefaultMutableTreeNode(j+"日"));
         }
      }
     b_save.addActionListener(this); b_del.addActionListener(this);
     tree =new JTree(root);
     JPanel p=new JPanel();p.setLayout(new BorderLayout());
     JScrollPane scrollpane_1=new JScrollPane(text);
     p.add(scrollpane_1,BorderLayout.CENTER);
     JPanel p_1=new JPanel();p_1.add(b_save);p_1.add(b_del);
     p.add(p_1,BorderLayout.NORTH);
     JScrollPane scrollpane_2=new JScrollPane(tree);
     JSplitPane splitpane=
   new SplitPane(JSplitPane.HORIZONTAL_SPLIT,true,scrollpane_2,p);
     tree.addTreeSelectionListener(this);  
     con.add(splitpane);
     addWindowListener(new WindowAdapter()
            { public void windowClosing(WindowEvent e)
                         {System.exit(0);
                         }
            });
     setVisible(true);setBounds(70,80,200,300);
   }
   public void valueChanged(TreeSelectionEvent e)
   { text.setText(" ");
      if(e.getSource()==tree)
        { DefaultMutableTreeNode node=
           (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
           if(node.isLeaf())
              { String str=node.toString();
                 for(int i=0;i<=12;i++)
                   { if(node.getParent()==month[i])
                      { try
                           { String temp=null;
                              File f=new File(node.getParent().toString()+str+".txt");
                              FileReader file=new FileReader(f);
                              BufferedReader in=new BufferedReader(file);
                              while((temp=in.readLine())!=null)
                                     text.append(temp+'/n');
                              file.close();in.close();
                            }
                         catch(FileNotFoundException e1){}
                         catch(IOException e1){} 
                       }          
                   }
               }
        }
   }
   public void actionPerformed(ActionEvent e)
   { if(e.getSource()==b_save)
        { DefaultMutableTreeNode node=
          (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
          String str=node.toString();
          if(node.isLeaf())
            { try
                 { File f=new File(node.getParent().toString()+str+".txt");
                   FileWriter tofile=new FileWriter(f);
                   BufferedWriter out=new BufferedWriter(tofile);
                   out.write(text.getText(),0,(text.getText()).length());
                   out.flush();
                   tofile.close();out.close();
                 }
               catch(FileNotFoundException e1){}
                catch(IOException e1){}  
             }
        }
      else if(e.getSource()==b_del)
       { DefaultMutableTreeNode node=
          (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
          String str=node.toString();
          if(node.isLeaf())
            {
              File f=new File(node.getParent().toString()+str+".txt");
              f.delete();
            }
        }
   }
}
public class Example25_32
{ public static void main(String args[])
   { Remember win=new Remember();win.pack();
   }
}


 
import Java.util.*;
public class LinkListOne
{public static void main(String args[])
 { LinkedList mylist=new LinkedList();
   mylist.add("It");          //链表中的第一个节点。
   mylist.add("is");   //链表中的第二个节点。
   mylist.add("a");      //链表中的第三个节点。
   mylist.add("door");    //链表中的第四个节点。
   int number=mylist.size();  //获取链表的长度。
   for(int i=0;i<number;i++)
   {String temp=(String)mylist.get(i);
    System.out.println("第"+i+"节点中的数据:"+temp);
   }
 }
}
import Java.util.*;
public class LinkListTwo
{public static void main(String args[])
 { LinkedList mylist=new LinkedList();
   mylist.add("is"); mylist.add("a");
   int number=mylist.size();
   System.out.println("现在链表中有"+number+"个节点:");
   for(int i=0;i<number;i++)
   {String temp=(String)mylist.get(i);
    System.out.println("第"+i+"节点中的数据:"+temp);
   }
   mylist.addFirst("It");mylist.addLast("door");
   number=mylist.size();
 System.out.println("现在链表中有"+number+"个节点:");
   for(int i=0;i<number;i++)
   {String temp=(String)mylist.get(i);
   System.out.println("第"+i+"节点中的数据:"+temp);
   }
   mylist.remove(0);mylist.remove(1);
   mylist.set(0,"open");
   number=mylist.size();
    System.out.println("现在链表中有"+number+"个节点:");
   for(int i=0;i<number;i++)
   {String temp=(String)mylist.get(i);
    System.out.println("第"+i+"节点中的数据:"+temp);
   }
 }
}
import Java.util.*;
class Student
{String name ;int number;float score;
 Student(String name,int number,float score)
 {this.name=name;this.number=number;this.score=score;
 }
}
public class LinkListThree
{public static void main(String args[])
 { LinkedList mylist=new LinkedList();
   Student stu_1=new Student("赵好民" ,9012,80.0f),
            stu_2=new Student("钱小青" ,9013,90.0f), 
            stu_3=new Student("孙力枚" ,9014,78.0f),
            stu_4=new Student("周左右" ,9015,55.0f);
    mylist.add(stu_1); mylist.add(stu_2);
    mylist.add(stu_3); mylist.add(stu_4);
    Iterator iter=mylist.iterator();
   while(iter.hasNext())
   { Student te=(Student)iter.next();
      System.out.println(te.name+" "+te.number+" "+te.score);
   }
 }
}
import Java.util.*;import Java.awt.event.*;import Java.awt.*;
import Javax.swing.*;import Java.io.*;
class 商品 extends Panel
{String 代号,名称;int 库存;float 单价;
 商品(String 代号,String 名称,int 库存,float 单价)
 {this.代号=代号;this.名称=名称;this.库存=库存;this.单价=单价;
 }
}
 
class ShowWin extends JFrame implements ActionListener
{ LinkedList goods_list=null;
 JTextField 代号文本框=new JTextField(),
名称文本框=new JTextField(),
            库存文本框=new JTextField(),
单价文本框=new JTextField(),
            删除文本框=new JTextField();
 JButton  b_add=new JButton("添加商品"),
b_del=new JButton("删除商品"),
            b_show =new JButton("显示商品清单");
 JTextArea  显示区=new JTextArea();
 ShowWin()
 {goods_list=new LinkedList();
   Container con=getContentPane();
   JScrollPane pane=new JScrollPane(显示区);
显示区.setEditable(false);
   JPanel save=new JPanel();save.setLayout(new GridLayout(5,2));
   save.add(new Label("输入代号:"));save.add(代号文本框);
   save.add(new Label("输入名称:"));save.add(名称文本框);
   save.add(new Label("输入库存:"));save.add(库存文本框);
   save.add(new Label("输入单价:"));save.add(单价文本框);
   save.add(new Label("点击添加:"));save.add(b_add);
   JPanel del=new JPanel();del.setLayout(new GridLayout(2,2));
   del.add(new Label("输入删除的代号:"));del.add(删除文本框);
   del.add(new Label("点击删除:"));del.add(b_del);
   JPanel show=new JPanel();show.setLayout(new BorderLayout());
   show.add(pane,BorderLayout.CENTER);show.add(b_show,BorderLayout.SOUTH);
   JSplitPane split_one,split_two;
   split_one=new JSplitPane(JSplitPane.VERTICAL_SPLIT,save,del);
   split_two=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,split_one,show);
   con.add(split_two,BorderLayout.CENTER);
   b_add.addActionListener(this);b_del.addActionListener(this);
   b_show.addActionListener(this);
 }
 public void actionPerformed(ActionEvent e)
 {if(e.getSource()==b_add)
 {String daihao=null,mingcheng=null;int kucun=0;float danjia=0.0f;
   daihao=代号文本框.getText();mingcheng=名称文本框.getText();
   kucun=Integer.parseInt(库存文本框.getText());
   danjia=Float.valueOf(单价文本框.getText()).floatValue();
  商品 goods=new 商品(daihao,mingcheng,kucun,danjia);
   goods_list.add(goods);
   try {FileOutputStream file=new FileOutputStream("goods.txt");
        ObjectOutputStream out=new ObjectOutputStream(file);
        out.writeObject(goods_list);out.close();
       }
   catch(IOException event){}
 }
 else if(e.getSource()==b_del)
 {String daihao=删除文本框.getText();
   try {FileInputStream come_in=new FileInputStream("goods.txt");
        ObjectInputStream in=new ObjectInputStream(come_in);
        goods_list=(LinkedList)in.readObject();in.close();
       }
   catch(ClassNotFoundException event){}
   catch(IOException event){}
   for(int i=0;i<goods_list.size();i++)
    {商品 temp=(商品)goods_list.get(i);
      if(temp.代号.equals(daihao)) {goods_list.remove(i);}
      try {FileOutputStream file=new FileOutputStream("goods.txt");
            ObjectOutputStream out=new ObjectOutputStream(file);
             out.writeObject(goods_list);
             out.close();
           }
       catch(IOException event){}
      }
 }
 else if(e.getSource()==b_show)
 { 显示区.setText(null);
    try {FileInputStream come_in=new FileInputStream("goods.txt");
        ObjectInputStream in=new ObjectInputStream(come_in);
        goods_list=(LinkedList)in.readObject();
       }
   catch(ClassNotFoundException event){}
   catch(IOException event){}
   Iterator iter=goods_list.iterator();
   while(iter.hasNext())
    { 商品 te=(商品)iter.next();
       显示区.append("商品代号:"+te.代号+"     ");
       显示区.append("商品名称:"+te.名称+"     ");
       显示区.append("商品库存:"+te.库存+"     ");
       显示区.append("商品单价:"+te.单价+"     ");
       显示区.append("/n");
    }
 }
 }
}
public class LinkListFour
{public static void main(String args[])
 { ShowWin win=new ShowWin();
   win.setSize(100,100);
   win.setVisible(true);
   win.addWindowListener(new WindowAdapter()
      {public void windowClosing(WindowEvent e)
        {System.exit(0);}});
 }
}
import Java.util.*;
class StackOne
{public static void main(String args[])
 {Stack mystack=new Stack();
 mystack.push(new Integer(1)); mystack.push(new Integer(2));
 mystack.push(new Integer(3)); mystack.push(new Integer(4));
 mystack.push(new Integer(5)); mystack.push(new Integer(6));
 while(!(mystack.empty()))
 {Integer temp=(Integer)mystack.pop();
   System.out.print("   "+temp.toString());}
 }
}
import Java.util.*;
class StackTwo
{public static void main(String args[])
 {Stack mystack=new Stack();
 mystack.push(new Integer(1)); mystack.push(new Integer(1));
 int k=1;
 while(k<=10)
 for(int i=1;i<=2;i++)
   {Integer F1=(Integer)mystack.pop();int f1=F1.intValue();
    Integer F2=(Integer)mystack.pop();int f2=F2.intValue();
    Integer temp=new Integer(f1+f2);
    System.out.println(""+temp.toString());
    mystack.push(temp);mystack.push(F2);k++;
   }
 }
}
import Java.util.*;
class TreeOne
{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());
 }
}
import Java.util.*;import Java.awt.*;
class TreeTwo
{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,"zhan ying");st2=new Student(66,"wang heng");
   st3=new Student(86,"Liuh qing");st4=new Student(76,"yage ming");
   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);
     }
 }
}
class Student implements Comparable
{ int english=0;String name;
 Student(int e,String n)
 {english=e;name=n;
 }
 public int compareTo(Object b)
 { Student st=(Student)b;
   return (this.english-st.english);
 }
}
import Java.util.*;import Java.awt.event.*;
import Java.awt.*;
class 节目 implements Comparable
{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.valueOf(时间文本框.getText()).doubleValue();
      }
   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");
    }
 }
}
public class Tree_3
{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);}});
 }
}
import Java.util.*;
class Student 
{ int english=0; String name,number;
 Student(String na,String nu,int e)
 {english=e;name=na;number =nu;}
}
public class HT
{ public static void main(String args[])
 { Hashtable hashtable=new Hashtable();
   hashtable.put("199901",new Student("199901","王小林",98));
   hashtable.put("199902",new Student("199902","能林茂",70));
   hashtable.put("199903",new Student("199903","多种林",93));
   hashtable.put("199904",new Student("199904","围林蛤",46));
   hashtable.put("199905",new Student("199905","夹贸林",77));
   hashtable.put("199906",new Student("199906","噔林可",55));
   hashtable.put("199907",new Student("199907","降王林",68));
   hashtable.put("199908",new Student("199908","纠林咯",76));
   Student stu=(Student)hashtable.get("199902");//检索一个元素。
   System.out.println(stu.number+" "+stu.name+" "+stu.english);
   hashtable.remove("199906"); //删除一个元素
 System.out.println("散列表中现在含有:"+hashtable.size()+"个元素");
    Enumeration enum=hashtable.elements();
    while(enum.hasMoreElements())   //遍历当前散列表。
    {Student s=(Student)enum.nextElement();
     System.out.println(s.number+" "+s.name+" "+s.english);
    }
 }    
}
import Java.util.*;import Java.awt.event.*;import Java.awt.*;
import Javax.swing.*;import Java.io.*;
class 学生 extends JPanel
{String 学号,姓名;float 分数;
   学生(String 学号,String 姓名,float 分数)
 {this.学号=学号;this.姓名=姓名;this.分数=分数;
 }
}
class ShowWin extends JFrame implements ActionListener
{ Hashtable hashtable=new Hashtable();
 JTextField 学号文本框=new JTextField(),
姓名文本框=new JTextField(),
            分数文本框=new JTextField(),
            查询文本框=new JTextField();
 JButton b_add=new JButton("添加成绩"),
          b_show =new JButton("显示成绩");
 JTextField 成绩显示条=new JTextField();
 ShowWin()
 {Container con=getContentPane();
   JPanel 成绩输入区=new JPanel();
          成绩输入区.setLayout(new GridLayout(5,2));
          成绩输入区.add(new Label("成绩输入区:"));
          成绩输入区.add(new Label());
          成绩输入区.add(new Label("考生学号:"));
          成绩输入区.add(学号文本框);
          成绩输入区.add(new JLabel("考生姓名:"));
          成绩输入区.add(姓名文本框);
          成绩输入区.add(new Label("考生成绩:"));
          成绩输入区.add(分数文本框);
          成绩输入区.add(new Label("点击添加:"));
          成绩输入区.add(b_add);
   JPanel 查询显示区=new JPanel();
          查询显示区.setLayout(new GridLayout(3,2));
          查询显示区.add(new Label("成绩查询区:"));
          查询显示区.add(new Label());
          查询显示区.add(new Label("输入考生的学号:"));
          查询显示区.add(查询文本框);
          查询显示区.add(b_show);
          查询显示区.add(成绩显示条);
 JSplitPane split;
split=new JSplitPane(JSplitPane.VERTICAL_SPLIT,成绩输入区,查询显示区);
   con.add(split,BorderLayout.CENTER);
   con.add(new Label("成绩输入和查询系统"),BorderLayout.NORTH);
   b_add.addActionListener(this);b_show.addActionListener(this);
 }
 public void actionPerformed(ActionEvent e)
 {if(e.getSource()==b_add)
 {String 学号=null,姓名=null;float 分数=0.0f;
    try {学号=学号文本框.getText();
         姓名=姓名文本框.getText();
        }
    catch(NullPointerException ee)
{ 学号文本框.setText("请输入学号");
姓名文本框.setText("请输入姓名");
      }
    try{分数=Float.valueOf(分数文本框.getText()).floatValue();}
    catch(NumberFormatException ee)
{分数文本框.setText("请输入数字字符");}
    学生 stu=new 学生(学号,姓名,分数);
    hashtable.put(学号,stu);
    try {FileOutputStream file=new FileOutputStream("score.txt");
         ObjectOutputStream out=new ObjectOutputStream(file);
         out.writeObject(hashtable); out.close();
        }
        catch(IOException event){}
   }
 else if(e.getSource()==b_show)
 { String temp=null;
    temp=查询文本框.getText();
    成绩显示条.setText(null);
    try {FileInputStream come_in=new FileInputStream("score.txt");
         ObjectInputStream in=new ObjectInputStream(come_in);
         hashtable=(Hashtable)in.readObject();in.close();
        }
   catch(ClassNotFoundException event){}
   catch(IOException event){System.out.println("文件无法读出");}
 学生 s=(学生)hashtable.get(temp);
 成绩显示条.setText("姓名:"+s.姓名+"学号:"+s.学号+"成绩:"+s.分数);
 }
 }
}
public class HT_2
{public static void main(String args[])
 { ShowWin win=new ShowWin();
   win.setSize(100,100); win.setVisible(true);
   win.addWindowListener(new WindowAdapter()
      {public void windowClosing(WindowEvent e)
        {System.exit(0);}});
 }
}
import Java.util.*;
 class Example26_12
 {public static void main(String args[])
 { Vector vector=new Vector(); Date date=new Date();
    vector.add(new Integer(1));vector.add(new Float(3.45f));
    vector.add(new Double(7.75));vector.add(new Boolean(true));
    vector.add(date);
    System.out.println(vector.size());
    Integer number1=(Integer)vector.get(0);
    System.out.println("向量的第1个元素: "+number1.intValue());
    Float number2=(Float)vector.get(1);
    System.out.println("向量的第2个元素: "+number2.floatValue());
    Double number3=(Double)vector.get(2);
    System.out.println("向量的第3个元素: "+number3.doubleValue());
    Boolean number4=(Boolean)vector.get(3);
    System.out.println("向量的第4个元素: "+number4.booleanValue());
    date=(Date)vector.lastElement();
    System.out.println("向量的第5个元素: "+date.toString());
    if(vector.contains(date))
      System.out.println("ok");
 }
 }   
import Java.applet.*;
import Java.awt.*;import Java.util.*;
import Java.awt.event.*;
class Point
{int x,y;
 Point(int x,int y)
 {this.x=x;this.y=y;
 }
}
public class Example26_13 extends Applet
implements MouseMotionListener,MouseListener
{ int x=-1,y=-1;
   Vector v=null;int n=1;
 public void init()
 { setBackground(Color.green);
   addMouseMotionListener(this); addMouseListener(this);
    v=new Vector();
 }
 public void paint(Graphics g)
 {if(x!=-1&&y!=-1)
 { n=v.size();
    for(int i=0;i<n-1;i++)
       {Point p1=(Point)v.elementAt(i);
        Point p2=(Point)v.elementAt(i+1);
        g.drawLine(p1.x,p1.y,p2.x,p2.y);
       }
   }
 
 }
public void mouseDragged(MouseEvent e)
 { x=(int)e.getX();y=(int)e.getY();
   Point p=new Point(x,y);
   v.addElement(p);
   repaint();
 }
 public void mouseMoved(MouseEvent e)
 {}
 public void mousePressed(MouseEvent e){}
 public void mouseReleased(MouseEvent e)
{v.removeAllElements();}
 public void mouseEntered(MouseEvent e){}
 public void mouseExited(MouseEvent e){}
 public void mouseClicked(MouseEvent e){}
 public void update(Graphics g)
 { paint(g);
 }
}


 

抱歉!评论已关闭.