100个Java经典例子--初学者的利器高手的宝典JavaSE

来源:互联网 发布:360文件恢复软件下载 编辑:程序博客网 时间:2024/04/27 22:02
  1. package test1;  
  2.   
  3. /** 
  4.  * Title: Hello Java World 
  5.  * Description: 简单的Java程序,只显示一个信息。 
  6.  * filename: HelloWorld.java 
  7.  */  
  8.  public class HelloWorld {  
  9.   public static void main(String[] args) {  
  10.     System.out.println("Hello Java World!");  
  11.   }  
  12.  }  

view plaincopy to clipboardprint?
  1. package test2;  
  2. /** 
  3.  * Title: Java语言流程演示 
  4.  * Description: 演示Java中几种常用的流程控制操作 
  5.  * Filename: flowDome.java 
  6.  */  
  7.  public class flowDemo{  
  8.    public static void main(String[] arges){  
  9.      int iPara1,iPara2,iEnd;  
  10.      if(arges.length!=3)  
  11.      {  
  12.        System.out.println("USE :java flowDome parameter1 parameter2 circle");  
  13.        System.out.println("parameter1 : 比较条件1,数字类型");  
  14.        System.out.println("parameter2 : 比较条件2,数字类型");  
  15.        System.out.println("circle :循环次数");  
  16.        System.out.println("ego:java flowDome 1 2 5");  
  17.        return;  
  18.      }else{  
  19.        iPara1 = Integer.parseInt(arges[0]);  
  20.        iPara2 = Integer.parseInt(arges[1]);  
  21.        iEnd = Integer.parseInt(arges[2]);  
  22.      }  
  23.      //if语句   
  24.      if(iPara2>iPara1)  
  25.      {  
  26.       System.out.println("if 条件满足!");  
  27.       System.out.println("第2个数比第1个数大!");  
  28.      }  
  29.      else  
  30.      {  
  31.       System.out.println("if 条件不满足!");  
  32.       System.out.println("第2个数比第1个数小!");  
  33.      }  
  34.      //for循环操作   
  35.      for(int i=0;i<iEnd;i++)  
  36.      {  
  37.        System.out.println("这是for 第"+i+"次循环");  
  38.      }  
  39.      //while循环操作   
  40.      int i=0;  
  41.      while(i<iEnd)  
  42.      {  
  43.       System.out.println("这是while 第"+i+"次循环");  
  44.       i++;  
  45.      }  
  46.      //do-while循环操作   
  47.      int j=0;  
  48.      do  
  49.      {  
  50.       System.out.println("这是do-while 第"+j+"次循环");  
  51.       j++;  
  52.      }while(j<iEnd);  
  53.    }  
  54.  }  

view plaincopy to clipboardprint?
  1. package test3;  
  2.   
  3. /** 
  4.  * Title: 数组数据操作 
  5.  * Description: 演示一维数组和多维数组的初始化和基本操作 
  6.  * Filename: myArray.java 
  7.  */  
  8.  public class  myArray{  
  9.    //初始化数组变量   
  10.    char[] cNum = {'1','2','3','4','5','6','7','8','9','0'};  
  11.    char[] cStr = {'a','b','c','d','e','f','g','h',  
  12.                   'i','j','k','l','m','n','o','p',  
  13.                   'q','r','s','t','u','v','w','x','y','z'};  
  14.    int[] iMonth = {31,28,31,30,31,30,31,31,30,31,30,31};  
  15.    String[] sMail = {"@","."};  
  16. /** 
  17.  *<br>方法说明:校验电子邮件 
  18.  *<br>输入参数:String sPara 被校验的电子邮件字符 
  19.  *<br>返回类型:boolean 如果校验的格式符合电子邮件格式返回true;否则返回false 
  20.  */     
  21.    public boolean isMail(String sPara){  
  22.     for(int i=0;i<sMail.length;i++){  
  23.       if(sPara.indexOf(sMail[i])==-1)  
  24.         return false;           
  25.     }  
  26.     return true;  
  27.    }  
  28. /** 
  29.  *<br>方法说明:判断是否是数字 
  30.  *<br>输入参数:String sPara。 需要判断的字符串 
  31.  *<br>返回类型:boolean。如果都是数字类型,返回true;否则返回false 
  32.  */     
  33.    public boolean isNumber(String sPara){  
  34.      int iPLength = sPara.length();  
  35.      for(int i=0;i<iPLength;i++){  
  36.       char cTemp = sPara.charAt(i);  
  37.       boolean bTemp = false;  
  38.       for(int j=0;j<cNum.length;j++){  
  39.         if(cTemp==cNum[j]){  
  40.           bTemp = true;  
  41.           break;  
  42.         }  
  43.       }  
  44.       if(!bTemp) return false;   
  45.      }  
  46.     return true;  
  47.    }  
  48. /** 
  49.  *<br>方法说明:判断是否都是英文字符 
  50.  *<br>输入参数:String sPara。要检查的字符 
  51.  *<br>返回类型:boolean。如果都是字符返回true;反之为false 
  52.  */     
  53.    public boolean isString(String sPara){  
  54.      int iPLength = sPara.length();  
  55.      for(int i=0;i<iPLength;i++){  
  56.       char cTemp = sPara.charAt(i);  
  57.       boolean bTemp = false;  
  58.       for(int j=0;j<cStr.length;j++){  
  59.         if(cTemp==cStr[j]){  
  60.           bTemp = true;  
  61.           break;  
  62.         }  
  63.       }  
  64.       if(!bTemp) return false;   
  65.      }  
  66.     return true;  
  67.    }  
  68. /** 
  69.  *<br>方法说明:判断是否是闰年 
  70.  *<br>输入参数:int iPara。要判断的年份 
  71.  *<br>返回类型:boolean。如果是闰年返回true,否则返回false 
  72.  */     
  73.    public boolean chickDay(int iPara){  
  74.      return iPara%100==0&&iPara%4==0;  
  75.    }  
  76. /** 
  77.  *<br>方法说明:检查日期格式是否正确 
  78.  *<br>输入参数:String sPara。要检查的日期字符 
  79.  *<br>返回类型:int。0 日期格式正确,-1 月或这日不合要求, -2 年月日格式不正确  
  80.  */  
  81.    public int chickData(String sPara){  
  82.     @SuppressWarnings("unused")  
  83.     boolean bTemp = false;  
  84.     //所输入日期长度不正确   
  85.     if(sPara.length()!=10return -2;  
  86.     //获取年   
  87.     String sYear = sPara.substring(0,4);  
  88.     //判断年是否为数字   
  89.     if(!isNumber(sYear)) return -2;  
  90.     //获取月份   
  91.     String sMonth = sPara.substring(5,7);  
  92.     //判断月份是否为数字   
  93.     if(!isNumber(sMonth)) return -2;  
  94.     //获取日   
  95.     String sDay = sPara.substring(8,10);  
  96.     //判断日是否为数字   
  97.     if(!isNumber(sDay)) return -2;  
  98.     //将年、月、日转换为数字   
  99.     int iYear = Integer.parseInt(sYear);  
  100.     int iMon = Integer.parseInt(sMonth);  
  101.     int iDay = Integer.parseInt(sDay);  
  102.     if(iMon>12return -1;  
  103.     //闰年二月处理   
  104.     if(iMon==2&&chickDay(iYear)){  
  105.       if(iDay>29return 2;  
  106.     }else{  
  107.       if(iDay>iMonth[iMon-1]) return -1;  
  108.     }  
  109.     return 0;  
  110.    }  
  111. /** 
  112.  *<br>方法说明:主方法,测试用 
  113.  *<br>输入参数: 
  114.  *<br>返回类型: 
  115.  */   
  116.    public static void main(String[] arges){  
  117.      myArray mA = new myArray();  
  118.      //校验邮件地址   
  119.      boolean bMail = mA.isMail("tom@163.com");  
  120.      System.out.println("1 bMail is "+bMail);  
  121.      bMail = mA.isMail("tom@163com");  
  122.      System.out.println("2 bMail is "+bMail);  
  123.      //演示是否是数字   
  124.      boolean bIsNum = mA.isNumber("1234");  
  125.      System.out.println("1:bIsNum="+bIsNum);  
  126.      bIsNum = mA.isNumber("123r4");  
  127.      System.out.println("2:bIsNum="+bIsNum);  
  128.      //演示是否是英文字符   
  129.      boolean bIsStr = mA.isString("wer");  
  130.      System.out.println("1:bIsStr="+bIsStr);  
  131.      bIsStr = mA.isString("wer3");  
  132.      System.out.println("2:bIsStr="+bIsStr);  
  133.      //演示检查日期   
  134.      int iIsTime = mA.chickData("2003-12-98");  
  135.      System.out.println("1:iIsTime="+iIsTime);  
  136.      iIsTime = mA.chickData("2003-111-08");  
  137.      System.out.println("2:iIsTime="+iIsTime);  
  138.      iIsTime = mA.chickData("2003-10-08");  
  139.      System.out.println("3:iIsTime="+iIsTime);  
  140.      iIsTime = mA.chickData("2000-02-30");  
  141.      System.out.println("4:iIsTime="+iIsTime);  
  142.    }  
  143.  }  

view plaincopy to clipboardprint?
  1. package test4;  
  2.   
  3. import java.util.*;  
  4. /** 
  5.  * Title: 矢量操作< 
  6.  * Description: 演示一个矢量(Vector)的基本操作 
  7.  * Filename: operateVector.java 
  8.  */  
  9. public class operateVector   
  10. {  
  11. /* 
  12. *<br>方法说明:生成一个4*4的二维Vector,供使用。 
  13. *<br>输入参数: 
  14. *<br>输出变量:Vector 
  15. *<br>其它说明: 
  16. */  
  17.     public Vector<Object> buildVector(){  
  18.        Vector<Object> vTemps = new Vector<Object>();  
  19.        for(int i=0;i<4;i++){  
  20.           Vector<Object> vTemp = new Vector<Object>();  
  21.           for (int j=0;j<4;j++){  
  22.             vTemp.addElement("Vector("+i+")("+j+")");  
  23.           }  
  24.           vTemps.addElement(vTemp);  
  25.        }  
  26.        return vTemps;  
  27.     }  
  28. /* 
  29. *<br>方法说明:插入数据 
  30. *<br>输入参数:Vector vTemp 待插入的数据对象 
  31. *<br>输入参数:int iTemp 插入数据的位置 
  32. *<br>输入参数:Object oTemp 插入数据值 
  33. *<br>输出变量:Vector 结果 
  34. *<br>其它说明:如果插入位置超出实例实际的位置将返回null 
  35. */  
  36.     public Vector<Object> insert(Vector<Object> vTemp,int iTemp,Object oTemp){  
  37.         if(iTemp>vTemp.size()){  
  38.             print("数据超界!");  
  39.             return null;  
  40.         }else{  
  41.              vTemp.insertElementAt(oTemp,iTemp);  
  42.         }  
  43.         return vTemp;  
  44.     }  
  45. /* 
  46. *<br>方法说明:移除数据 
  47. *<br>输入参数:Vector vTemp 待删除矢量对象 
  48. *<br>输入参数:int iTemp 删除数据的位置 
  49. *<br>输出变量:Vector 
  50. *<br>其它说明:如果删除超界的数据,将返回null 
  51. */  
  52.     public Vector<Object> delete(Vector<Object> vTemp,int iTemp){  
  53.         if(iTemp>vTemp.size()){  
  54.             print("数据超界!");  
  55.             return null;  
  56.         }else{  
  57.              vTemp.removeElementAt(iTemp);  
  58.         }  
  59.         return vTemp;  
  60.     }  
  61. /* 
  62. *<br>方法说明:修改数据 
  63. *<br>输入参数:Vector vTemp 待修改矢量对象 
  64. *<br>输入参数:int iTemp 修改数据的位置 
  65. *<br>输入参数:Object oTemp 修改数据值 
  66. *<br>输出变量:Vector 
  67. *<br>其它说明:如果修改位置超界的数据,将返回null 
  68. */  
  69.     public Vector<Object> updata(Vector<Object> vTemp,int iTemp,Object oTemp){  
  70.         if(iTemp>vTemp.size()){  
  71.             print("数据超界!");  
  72.             return null;  
  73.         }else{  
  74.              vTemp.setElementAt(oTemp,iTemp);  
  75.         }  
  76.         return vTemp;  
  77.     }  
  78. /* 
  79. *<br>方法说明:输出信息 
  80. *<br>输入参数:String sTemp 输出信息名称 
  81. *<br>输入参数:Object oTemp 输出信息值 
  82. *<br>返回变量:无 
  83. */  
  84.     public void print(String sTemp,Vector<Object> oTemp){  
  85.         System.out.println(sTemp+"数据:");  
  86.         this.print(oTemp);  
  87.     }  
  88. /** 
  89.  *<br>方法说明:打印输出(过载) 
  90.  *<br>输入参数:Object oPara 输出的对象 
  91.  *<br>返回类型:无 
  92.  */  
  93.     public void print(Object oPara){  
  94.         System.out.println(oPara);  
  95.     }  
  96. /** 
  97.  *<br>方法说明:打印输出(过载) 
  98.  *<br>输入参数:Vector vPara 显示输出矢量对象 
  99.  *<br>返回类型:无 
  100.  */  
  101.     public void print(Vector<Object> vPara){  
  102.        for(int i=0;i<vPara.size();i++){  
  103.         System.out.println(vPara.elementAt(i));  
  104.        }  
  105.     }  
  106. /** 
  107.  *<br>方法说明:主方法,程序入口 
  108.  *<br>输入参数:String[] args 
  109.  *<br>返回类型:无 
  110.  */  
  111.     public static void main(String[] args)   
  112.     {  
  113.         operateVector ov = new operateVector();  
  114.         Vector<Object> vTemp = ov.buildVector();  
  115.         ov.print("vTemp0",vTemp);  
  116.         Vector<Object> vResult = ov.insert(vTemp,2,"添加的数据");  
  117.         ov.print("vResult",vResult);  
  118.         Vector<Object> vResultup = ov.updata(vResult,2,"修改的数据");  
  119.         ov.print("vResultmp",vResultup);  
  120.         Vector<Object> vResultnow = ov.delete(vResultup,2);  
  121.         ov.print("vResultnow",vResultnow);  
  122.     }  
  123. }  

view plaincopy to clipboardprint?
  1. package test5;  
  2.   
  3. import java.util.*;  
  4. /** 
  5.  * Title: 哈希表操作 
  6.  * Description: 这是一个权限认证的例子,使用了哈希表作为数据的存储 
  7.  * Filename: RoleRight.java 
  8.  */  
  9.  public class RoleRight  
  10.  {  
  11.  private static Hashtable<String, String> rightList = new Hashtable<String, String>();  
  12. /** 
  13.  *<br>方法说明:初始化数据 
  14.  *<br>输入参数: 
  15.  *<br>返回类型: 
  16.  */  
  17.  public void init()  
  18.  {  
  19.     String[] accRoleList = {"admin","satrap","manager","user","guest"};  
  20.     String[] rightCodeList = {"10001","10011","10021","20011","24011"};  
  21.     for(int i=0;i<accRoleList.length;i++)  
  22.     {  
  23.       rightList.put(accRoleList[i],rightCodeList[i]);  
  24.     }  
  25.  }  
  26. /** 
  27.  *<br>方法说明:获取角色权限代码 
  28.  *<br>输入参数:String accRole 角色名称 
  29.  *<br>返回类型:String 权限代码 
  30.  */  
  31.  public String getRight(String accRole)  
  32.  {  
  33.     if(rightList.containsKey(accRole))  
  34.       return (String)rightList.get(accRole);  
  35.     else  
  36.       return null;  
  37.  }  
  38. /** 
  39.  *<br>方法说明:添加角色和代码信息 
  40.  *<br>输入参数:String accRole 角色名称 
  41.  *<br>输入参数:String rightCode 角色权限代码  
  42.  *<br>返回类型:void (无) 
  43.  */  
  44.  public void insert(String accRole,String rightCode)  
  45.  {  
  46.    rightList.put(accRole,rightCode);  
  47.  }  
  48. /** 
  49.  *<br>方法说明:删除角色权限 
  50.  *<br>输入参数:String accRole 角色名称 
  51.  *<br>返回类型:void(无) 
  52.  */  
  53.  public void delete(String accRole)  
  54.  {  
  55.    if(rightList.containsKey(accRole))  
  56.      rightList.remove(accRole);  
  57.  }  
  58. /** 
  59.  *<br>方法说明:修改角色权限代码 
  60.  *<br>输入参数:String accRole 角色名称 
  61.  *<br>输入参数:String rightCode 角色权限代码  
  62.  *<br>返回类型:void(无) 
  63.  */  
  64.  public void update(String accRole,String rightCode)  
  65.  {  
  66.    //this.delete(accRole);   
  67.    this.insert(accRole,rightCode);  
  68.  }  
  69. /** 
  70.  *<br>方法说明:打印哈希表中角色和代码对应表 
  71.  *<br>输入参数:无 
  72.  *<br>返回类型:无 
  73.  */  
  74.  public void print()  
  75.  {  
  76.     Enumeration<String> RLKey = rightList.keys();  
  77.     while(RLKey.hasMoreElements())  
  78.     {  
  79.         String accRole = RLKey.nextElement().toString();  
  80.         print(accRole+"="+this.getRight(accRole));  
  81.     }  
  82.  }  
  83. /** 
  84.  *<br>方法说明:打印信息(过载) 
  85.  *<br>输入参数:Object oPara 打印的信息内容 
  86.  *<br>返回类型:无 
  87.  */  
  88.  public void print(Object oPara)  
  89.  {  
  90.     System.out.println(oPara);  
  91.  }  
  92. /** 
  93.  *<br>方法说明:主方法, 
  94.  *<br>输入参数: 
  95.  *<br>返回类型: 
  96.  */  
  97.  public static void main(String[] args)  
  98.  {  
  99.     RoleRight RR = new RoleRight();  
  100.     RR.init();  
  101.     RR.print();  
  102.     RR.print("___________________________");  
  103.     RR.insert("presider","10110");  
  104.     RR.print();  
  105.     RR.print("___________________________");  
  106.     RR.update("presider","10100");  
  107.     RR.print();  
  108.     RR.print("___________________________");  
  109.     RR.delete("presider");  
  110.     RR.print();  
  111.  }   
  112.  }//end:)~  

view plaincopy to clipboardprint?
  1. package test6;  
  2.   
  3. /** 
  4.  * Title: 树参数 
  5.  * Description: 使用继承类,柳树就是树 
  6.  * Filename: osier.java 
  7.  */  
  8. class tree  
  9. {  
  10. /** 
  11.  *<br>方法说明:树的树根 
  12.  */  
  13.   public void root()  
  14.   {  
  15.     String sSite = "土壤中";  
  16.     String sFunction = "吸收养份";  
  17.     print("位置:"+sSite);  
  18.     print("功能:"+sFunction);  
  19.   }  
  20. /** 
  21.  *方法说明:树的树干 
  22.  */  
  23.   public void bolo()  
  24.   {  
  25.     String sSite = "地面";  
  26.     String sFunction = "传递养份";  
  27.     print("位置:"+sSite);  
  28.     print("功能:"+sFunction);  
  29.   }  
  30. /** 
  31.  *方法说明:树的树枝 
  32.  */  
  33.   public void branch()  
  34.   {  
  35.     String sSite = "树干上";  
  36.     String sFunction = "传递养份";  
  37.     print("位置:"+sSite);  
  38.     print("功能:"+sFunction);  
  39.   }  
  40. /** 
  41.  *方法说明:树的叶子 
  42.  */  
  43.   public void leaf()  
  44.   {  
  45.     String sSite = "树梢";  
  46.     String sFunction = "光合作用";  
  47.     String sColor = "绿色";  
  48.     print("位置:"+sSite);  
  49.     print("功能:"+sFunction);  
  50.     print("颜色:"+sColor);  
  51.   }  
  52. /** 
  53.  *方法说明:显示信息 
  54.  *输入参数:Object oPara 显示的信息 
  55.  */  
  56.   public void print(Object oPara)  
  57.   {  
  58.     System.out.println(oPara);  
  59.   }  
  60. /** 
  61.  *方法说明:主方法: 
  62.  */  
  63.   public static void  main(String[] arges)  
  64.   {  
  65.     tree t = new tree();  
  66.     t.print("描述一棵树:");  
  67.     t.print("树根:");  
  68.     t.root();  
  69.     t.print("树干:");  
  70.     t.bolo();  
  71.     t.print("树枝:");  
  72.     t.branch();  
  73.     t.print("树叶:");  
  74.     t.leaf();  
  75.   }  
  76. }  
  77. /** 
  78.  * Title: 柳树参数 
  79.  * Description: 描述柳树的参数 
  80.  */  
  81. class osier extends tree  
  82. {  
  83.  /** 
  84.  *方法说明:过载树的树叶 
  85.  */  
  86.   public void leaf()  
  87.   {  
  88.     super.leaf();  
  89.     String sShape = "长形";  
  90.     super.print("形状:"+sShape);  
  91.   }  
  92.   /** 
  93.  *方法说明:扩展树的花 
  94.  */  
  95.   public void flower()  
  96.   {  
  97.     print("哈哈,柳树没有花!!");  
  98.   }  
  99. /** 
  100.  *方法说明:主方法 
  101.  */  
  102.   public static void  main(String[] args)  
  103.   {  
  104.     osier o = new osier();  
  105.     o.print("柳树树根:");  
  106.     o.root();  
  107.     o.print("柳树树干:");  
  108.     o.bolo();  
  109.     o.print("柳树树枝:");  
  110.     o.branch();  
  111.     o.print("柳树树叶:");  
  112.     o.leaf();  
  113.     o.print("柳树花:");  
  114.     o.flower();  
  115.   }  
  116. }  

view plaincopy to clipboardprint?
  1. package test7;  
  2.   
  3. /** 
  4.  *  Title:  接口和抽象函数  
  5.  *  Description: 演示继承抽象函数和实现接口  
  6.  *  Filename: newPlay.java 
  7.  */  
  8.    
  9. //接口    
  10. interface player  
  11. {  
  12.  int flag = 1;  
  13.  void play();//播放  
  14.  void pause();//暂停  
  15.  void stop();//停止  
  16. }//end :)   
  17.   
  18. //抽象类   
  19. abstract class playing  
  20. {  
  21.  public void display(Object oPara)  
  22.  {  
  23.    System.out.println(oPara);    
  24.  }  
  25.  abstract void winRun();  
  26. }//end :)   
  27.   
  28. //继承了playing抽象类和实现类player接口   
  29. public class newPlay extends playing implements player  
  30. {  
  31.   public void play()  
  32.   {  
  33.     display("newPlay.play()");//这里只是演示,去掉了代码。  
  34.   }  
  35.   public void pause()  
  36.   {  
  37.      display("newPlay.pause()");//这里只是演示,去掉了代码。  
  38.   }  
  39.   public void stop()  
  40.   {  
  41.     display("newPlay.stop()");//这里只是演示,去掉了代码。  
  42.   }  
  43.   void winRun()  
  44.   {  
  45.     display("newPlay.winRun()");//这里只是演示,去掉了代码。  
  46.   }  
  47.   public static void main(String[] args)  
  48.   {  
  49.     newPlay p = new newPlay();  
  50.     p.play();  
  51.     p.pause();  
  52.     p.stop();  
  53.     p.winRun();  
  54.   }  
  55. }//end :)  

view plaincopy to clipboardprint?
  1. package test8.com;  
  2.   
  3. /** 
  4.  * Title: 标识符 
  5.  * Description: 演示标识符对类的访问控制 
  6.  * Filename: 
  7.  */  
  8. public class classDemo1 {  
  9.     // 公有方法   
  10.     public void mechod1() {  
  11.         System.out.println("这是一个公有的方法!任何类都可以访问。");  
  12.     }  
  13.   
  14.     // 授保护的方法   
  15.     protected void mechod2() {  
  16.         System.out.println("这是一个受到保护的方法!只有子类可以访问。");  
  17.     }  
  18.   
  19.     // 私有的方法   
  20.     private void mechod3() {  
  21.         System.out.println("这是一个私有的方法!只有类本身才可以访问。");  
  22.     }  
  23.   
  24.     public static void main(String[] args) {  
  25.         classDemo1 d = new classDemo1();  
  26.         d.mechod1();  
  27.         d.mechod2();  
  28.         d.mechod3();  
  29.     }  
  30. }  

view plaincopy to clipboardprint?
  1. package test8.com;  
  2. /** 
  3.  * Title: 标识符 
  4.  * Description: 演示标识符对类的访问控制 
  5.  * Filename:  
  6.  */  
  7. public class classPlay  
  8. {  
  9.   public static void main(String[] args){  
  10.     classDemo1 d = new classDemo1();  
  11.     d.mechod1();  
  12.     d.mechod2();  
  13.     //d.mechod3();   
  14.   }  
  15. }  

view plaincopy to clipboardprint?
  1. package test8.net;  
  2.   
  3. import test8.com.classDemo1;  
  4. /** 
  5.  * Title: 标识符 
  6.  * Description: 演示标识符对类的访问控制 
  7.  * Filename:  
  8.  */  
  9. public class classPlay  
  10. {  
  11.   public static void main(String[] args){  
  12.     classDemo1 d = new classDemo1();  
  13.     d.mechod1();  
  14.   //d.mechod2();   
  15.   //d.mechod3();   
  16.   }  
  17. }  


view plaincopy to clipboardprint?
  1. package test9;  
  2.   
  3. /** 
  4.  * Title: 捕获异常和实现自己的异常 
  5.  * Description: 通过继承Exception类来实现自己的异常类。并使用try-catch来捕获这个异常。 
  6.  * Filename: 
  7.  */  
  8. class MyException extends Exception {  
  9.     private static final long serialVersionUID = 1L;  
  10.   
  11.     public MyException() {  
  12.     }  
  13.   
  14.     public MyException(String msg) {  
  15.         super(msg);  
  16.     }  
  17.   
  18.     public MyException(String msg, int x) {  
  19.         super(msg);  
  20.         i = x;  
  21.     }  
  22.   
  23.     public int val() {  
  24.         return i;  
  25.     }  
  26.   
  27.     private int i;  
  28. }  
  29.   
  30. public class DemoException {  
  31.     /** 
  32.      *方法说明:使用MyException类中默认的构造器 
  33.      */  
  34.     public static void a() throws MyException {  
  35.         System.out.println("Throwing MyException from a()");  
  36.         throw new MyException();  
  37.     }  
  38.   
  39.     /** 
  40.      *方法说明:使用MyException类中带信息的构造器 
  41.      */  
  42.     public static void b() throws MyException {  
  43.         System.out.println("Throwing MyException from b()");  
  44.         throw new MyException("Originated in b()");  
  45.     }  
  46.   
  47.     /** 
  48.      *方法说明:使用了MyException中有编码的构造器 
  49.      */  
  50.     public static void c() throws MyException {  
  51.         System.out.println("Throwing MyException from c()");  
  52.         throw new MyException("Originated in c()"47);  
  53.     }  
  54.   
  55.     public static void main(String[] args) {  
  56.         try {  
  57.             a();  
  58.         } catch (MyException e) {  
  59.             e.getMessage();  
  60.         }  
  61.         try {  
  62.             b();  
  63.         } catch (MyException e) {  
  64.             e.toString();  
  65.         }  
  66.         try {  
  67.             c();  
  68.         } catch (MyException e) {  
  69.             e.printStackTrace();  
  70.             System.out.println("error code: " + e.val());  
  71.         }  
  72.     }  
  73. // end :)  

view plaincopy to clipboardprint?
  1. package test10;  
  2.   
  3. import javax.swing.*;  
  4. import java.awt.*;  
  5.   
  6. /** 
  7.  * Title: 创建自己的窗体  
  8.  * Description:  
  9.  * Filename:mainFrame.java 
  10.  */  
  11. public class mainFrame extends JFrame {  
  12.   
  13.     private static final long serialVersionUID = 1L;  
  14.   
  15.     /** 
  16.      *方法说明:构造器,通过传递参数来完成窗体的绘制。  
  17.      *输入参数:String sTitle 窗体标题  
  18.      *输入参数:int iWidth 窗体的宽度 
  19.      *输入参数:int iHeight 窗体的高度 返回类型: 
  20.      */  
  21.     public mainFrame(String sTitle, int iWidth, int iHeight) {  
  22.         Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();// 获取屏幕尺寸  
  23.         ImageIcon ii = new ImageIcon("middle.gif");  
  24.         setTitle(sTitle);// 设置窗体标题   
  25.         setIconImage(ii.getImage());// 设置窗体的图标  
  26.         setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);// 设置但关闭窗体时退出程序  
  27.         setSize(iWidth, iHeight);// 设置窗体大小  
  28.         int w = getSize().width;// 获取窗体宽度  
  29.         int h = getSize().height;// 获取窗体高度  
  30.         System.out.println("窗体宽:" + w + " 窗体高:" + h);  
  31.         int x = (dim.width - w) / 2;  
  32.         int y = (dim.height - h) / 2;  
  33.         setLocation(x, y);// 将窗体移到屏幕中间  
  34.         setVisible(true);// 显示窗体  
  35.     }  
  36.   
  37.     public static void main(String[] args) {  
  38.         JFrame.setDefaultLookAndFeelDecorated(true);// 使用最新的SWING外观  
  39.         new mainFrame("main Frame Demo"400300);  
  40.     }  
  41. }  
  1. package test11;  
  2.   
  3. import java.awt.event.ActionEvent;  
  4. import java.awt.event.ActionListener;  
  5. import java.awt.event.KeyEvent;  
  6.   
  7. import javax.swing.AbstractButton;  
  8. import javax.swing.ImageIcon;  
  9. import javax.swing.JButton;  
  10. import javax.swing.JFrame;  
  11. import javax.swing.JPanel;  
  12.   
  13. /** 
  14.  * Title: 按钮演示 
  15.  * Description: 提供一个按钮的演示。如何实现按钮和是一个按钮失效 
  16.  * Filename:  
  17.  */  
  18. public class ButtonDemo extends JPanel  
  19.                         implements ActionListener {  
  20.       
  21.     private static final long serialVersionUID = 1L;  
  22.     protected JButton b1, b2, b3;  
  23. /** 
  24.  *方法说明:构造器,初始图形界面构建 
  25.  */  
  26.     public ButtonDemo() {  
  27.         ImageIcon leftButtonIcon = createImageIcon("images/right.gif");  
  28.         ImageIcon middleButtonIcon = createImageIcon("images/middle.gif");  
  29.         ImageIcon rightButtonIcon = createImageIcon("images/left.gif");  
  30.   
  31.         b1 = new JButton("失效中间按钮(D)", leftButtonIcon);  
  32.         b1.setVerticalTextPosition(AbstractButton.CENTER);//水平中间对齐  
  33.         b1.setHorizontalTextPosition(AbstractButton.LEADING);//相当于LEFT  
  34.         b1.setMnemonic(KeyEvent.VK_D);//将b1邦定alt+D键  
  35.         b1.setActionCommand("disable");  
  36.   
  37.         b2 = new JButton("M中间按钮", middleButtonIcon);  
  38.         b2.setVerticalTextPosition(AbstractButton.BOTTOM);  
  39.         b2.setHorizontalTextPosition(AbstractButton.CENTER);  
  40.         b2.setMnemonic(KeyEvent.VK_M);//将b2邦定alt+M键  
  41.   
  42.         b3 = new JButton("E激活中间按钮", rightButtonIcon);  
  43.         b3.setMnemonic(KeyEvent.VK_E);//将b3邦定alt+E键  
  44.         b3.setActionCommand("enable");  
  45.         b3.setEnabled(false);  
  46.   
  47.         //给1和3添加事件监听   
  48.         b1.addActionListener(this);  
  49.         b3.addActionListener(this);  
  50.         //设置按钮提示文本   
  51.         b1.setToolTipText("点击这个按钮,将使中间的按钮失效!");  
  52.         b2.setToolTipText("点击这个按钮,没有任何的事件发生!");  
  53.         b3.setToolTipText("点击这个按钮,将使中间的按钮有效");  
  54.   
  55.         //将按钮添加到JPanel中   
  56.         add(b1);  
  57.         add(b2);  
  58.         add(b3);  
  59.     }  
  60. /** 
  61.  *方法说明:事件处理 
  62.  */  
  63.     public void actionPerformed(ActionEvent e) {  
  64.         if ("disable".equals(e.getActionCommand())) {  
  65.             b2.setEnabled(false);  
  66.             b1.setEnabled(false);  
  67.             b3.setEnabled(true);  
  68.         } else {  
  69.             b2.setEnabled(true);  
  70.             b1.setEnabled(true);  
  71.             b3.setEnabled(false);  
  72.         }  
  73.     }  
  74. /** 
  75.  *方法说明:创建图标, 
  76.  *输入参数:String path 图标所在的路径 
  77.  *返回类型:ImageIcon 图标对象 
  78.  */  
  79.     protected static ImageIcon createImageIcon(String path) {  
  80.         java.net.URL imgURL = ButtonDemo.class.getResource(path);  
  81.         if (imgURL != null) {  
  82.             return new ImageIcon(imgURL);  
  83.         } else {  
  84.             System.err.println("Couldn't find file: " + path);  
  85.             return null;  
  86.         }  
  87.     }  
  88. /** 
  89.  *方法说明:主方法 
  90.  */  
  91.     public static void main(String[] args) {  
  92.         //设置使用新的swing界面   
  93.         JFrame.setDefaultLookAndFeelDecorated(true);  
  94.   
  95.         //创建一个窗体   
  96.         JFrame frame = new JFrame("ButtonDemo");  
  97.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  98.   
  99.         //创建一个面板   
  100.         ButtonDemo newContentPane = new ButtonDemo();  
  101.         newContentPane.setOpaque(true);   
  102.         frame.setContentPane(newContentPane);  
  103.   
  104.         //显示窗体   
  105.         frame.pack();  
  106.         frame.setVisible(true);  
  107.     }  
  108. }  

view plaincopy to clipboardprint?
  1. package test12;  
  2.   
  3. import java.awt.*;  
  4. import java.awt.event.*;  
  5. import javax.swing.*;  
  6. /** 
  7.  * Title: 检查盒演示 
  8.  * Description: 选择不同的选择框显示不同的图片 
  9.  * Filename: CheckBoxDemo.java< 
  10.  */  
  11. public class CheckBoxDemo extends JPanel  
  12.                           implements ItemListener {  
  13.      
  14.     private static final long serialVersionUID = 1L;  
  15.     JCheckBox chinButton;  
  16.     JCheckBox glassesButton;  
  17.     JCheckBox hairButton;  
  18.     JCheckBox teethButton;  
  19.   
  20.     /* 
  21.      * 有四个检查盒,分别对应下巴、眼镜、头发和牙齿 
  22.      * 图片不是拼出来的,而是根据检查盒选择拼写图片文件名 
  23.      * 图片文件名的定义格式为"geek-XXXX.gif" 
  24.      * 其中 XXXX 根据检查盒的不同选择,而不同。它的格式如下: 
  25.  
  26.        ----             //没有选择 
  27.  
  28.        c---             //一个选择 
  29.        -g-- 
  30.        --h- 
  31.        ---t 
  32.  
  33.        cg--             //两个选择 
  34.        c-h- 
  35.        c--t 
  36.        -gh- 
  37.        -g-t 
  38.        --ht 
  39.  
  40.        -ght             //三个选择 
  41.        c-ht 
  42.        cg-t 
  43.        cgh- 
  44.  
  45.        cght             //所有都选 
  46.      */  
  47.   
  48.     StringBuffer choices;  
  49.     JLabel pictureLabel;  
  50.   
  51.     public CheckBoxDemo() {  
  52.         super(new BorderLayout());  
  53.   
  54.         //创建检查盒   
  55.         chinButton = new JCheckBox("下巴(c)");  
  56.         chinButton.setMnemonic(KeyEvent.VK_C);  
  57.         chinButton.setSelected(true);  
  58.   
  59.         glassesButton = new JCheckBox("眼镜(g)");  
  60.         glassesButton.setMnemonic(KeyEvent.VK_G);  
  61.         glassesButton.setSelected(true);  
  62.   
  63.         hairButton = new JCheckBox("头发(h)");  
  64.         hairButton.setMnemonic(KeyEvent.VK_H);  
  65.         hairButton.setSelected(true);  
  66.   
  67.         teethButton = new JCheckBox("牙齿(t)");  
  68.         teethButton.setMnemonic(KeyEvent.VK_T);  
  69.         teethButton.setSelected(true);  
  70.   
  71.         //给检查盒添加监听   
  72.         chinButton.addItemListener(this);  
  73.         glassesButton.addItemListener(this);  
  74.         hairButton.addItemListener(this);  
  75.         teethButton.addItemListener(this);  
  76.   
  77.         choices = new StringBuffer("cght");  
  78.   
  79.         //放置一个带图片的标签   
  80.         pictureLabel = new JLabel();  
  81.         pictureLabel.setFont(pictureLabel.getFont().deriveFont(Font.ITALIC));  
  82.         updatePicture();  
  83.   
  84.         //将检查盒放置到面版中   
  85.         JPanel checkPanel = new JPanel(new GridLayout(01));  
  86.         checkPanel.add(chinButton);  
  87.         checkPanel.add(glassesButton);  
  88.         checkPanel.add(hairButton);  
  89.         checkPanel.add(teethButton);  
  90.   
  91.         add(checkPanel, BorderLayout.LINE_START);  
  92.         add(pictureLabel, BorderLayout.CENTER);  
  93.         setBorder(BorderFactory.createEmptyBorder(20,20,20,20));  
  94.     }  
  95. /** 
  96.  *<br>方法说明:监听检查盒事件,拼凑图片的文件名XXXX部分 
  97.  *<br>输入参数: 
  98.  *<br>返回类型: 
  99.  */  
  100.     public void itemStateChanged(ItemEvent e) {  
  101.         int index = 0;  
  102.         char c = '-';  
  103.         Object source = e.getItemSelectable();  
  104.   
  105.         if (source == chinButton) {  
  106.             index = 0;  
  107.             c = 'c';  
  108.         } else if (source == glassesButton) {  
  109.             index = 1;  
  110.             c = 'g';  
  111.         } else if (source == hairButton) {  
  112.             index = 2;  
  113.             c = 'h';  
  114.         } else if (source == teethButton) {  
  115.             index = 3;  
  116.             c = 't';  
  117.         }  
  118.           
  119.         //取消选择事件   
  120.         if (e.getStateChange() == ItemEvent.DESELECTED) {  
  121.             c = '-';  
  122.         }  
  123.   
  124.         //改变文件名字XXXX   
  125.         choices.setCharAt(index, c);  
  126.   
  127.         updatePicture();  
  128.     }  
  129. /** 
  130.  *<br>方法说明:绘制图片 
  131.  *<br>输入参数: 
  132.  *<br>返回类型: 
  133.  */  
  134.     protected void updatePicture() {  
  135.         //将得到的图片制成图标   
  136.         ImageIcon icon = createImageIcon(  
  137.                                     "images/geek/geek-"  
  138.                                     + choices.toString()  
  139.                                     + ".gif");  
  140.         pictureLabel.setIcon(icon);  
  141.         pictureLabel.setToolTipText(choices.toString());  
  142.         if (icon == null) {  
  143.             pictureLabel.setText("没有发现图片");  
  144.         } else {  
  145.             pictureLabel.setText(null);  
  146.         }  
  147.     }  
  148. /** 
  149.  *<br>方法说明:获取图标 
  150.  *<br>输入参数:String path 图片路径 
  151.  *<br>返回类型:ImageIcon对象 
  152.  */  
  153.     protected static ImageIcon createImageIcon(String path) {  
  154.         java.net.URL imgURL = CheckBoxDemo.class.getResource(path);  
  155.         if (imgURL != null) {  
  156.             return new ImageIcon(imgURL);  
  157.         } else {  
  158.             System.err.println("Couldn't find file: " + path);  
  159.             return null;  
  160.         }  
  161.     }  
  162. /** 
  163.  *<br>方法说明:主方法 
  164.  *<br>输入参数: 
  165.  *<br>返回类型: 
  166.  */  
  167.     public static void main(String s[]) {  
  168.          JFrame.setDefaultLookAndFeelDecorated(true);  
  169.   
  170.         //创建一个窗体,   
  171.         JFrame frame = new JFrame("CheckBoxDemo");  
  172.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  173.   
  174.         //创建一个面板   
  175.         JComponent newContentPane = new CheckBoxDemo();  
  176.         newContentPane.setOpaque(true);  
  177.         frame.setContentPane(newContentPane);  
  178.   
  179.         //显示窗体   
  180.         frame.pack();  
  181.         frame.setVisible(true);  
  182.     }  
  183. }  


view plaincopy to clipboardprint?
  1. package test13;  
  2.   
  3. import java.awt.*;  
  4. import java.awt.event.*;  
  5. import javax.swing.*;  
  6. import java.util.*;  
  7. import java.text.SimpleDateFormat;  
  8. /** 
  9.  * Title: ComboBox下拉域演示</p> 
  10.  * Description: 通过选择或这输入一种日期格式来格式化今天的日期 
  11.  * Filename: ComboBoxDemo.java 
  12.  */  
  13.   
  14. public class ComboBoxDemo extends JPanel  
  15.                            implements ActionListener {  
  16.   
  17.     private static final long serialVersionUID = 1L;  
  18.     static JFrame frame;  
  19.     JLabel result;  
  20.     String currentPattern;  
  21. /** 
  22.  *方法说明:构造器。初始化窗体构件 
  23.  */  
  24.     public ComboBoxDemo() {  
  25.         setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));  
  26.         String[] patternExamples = {  
  27.                  "dd MMMMM yyyy",  
  28.                  "dd.MM.yy",  
  29.                  "MM/dd/yy",  
  30.                  "yyyy.MM.dd G 'at' hh:mm:ss z",  
  31.                  "EEE, MMM d, ''yy",  
  32.                  "h:mm a",  
  33.                  "H:mm:ss:SSS",  
  34.                  "K:mm a,z",  
  35.                  "yyyy.MMMMM.dd GGG hh:mm aaa"  
  36.                  };  
  37.   
  38.         currentPattern = patternExamples[0];  
  39.   
  40.         //设置一个规范的用户界面   
  41.         JLabel patternLabel1 = new JLabel("输入一个字符格式或者");  
  42.         JLabel patternLabel2 = new JLabel("从下拉列表中选择一种:");  
  43.   
  44.         JComboBox patternList = new JComboBox(patternExamples);  
  45.         patternList.setEditable(true);//标注这里ComboBox可进行编辑  
  46.         patternList.addActionListener(this);  
  47.   
  48.         //创建一个显示结果用户界面   
  49.         JLabel resultLabel = new JLabel("当前 日期/时间",  
  50.                                         JLabel.LEADING);//相当于LEFT  
  51.         result = new JLabel(" ");  
  52.         result.setForeground(Color.black);  
  53.         result.setBorder(BorderFactory.createCompoundBorder(  
  54.              BorderFactory.createLineBorder(Color.black),  
  55.              BorderFactory.createEmptyBorder(5,5,5,5)  
  56.         ));  
  57.   
  58.         //布置构件   
  59.         JPanel patternPanel = new JPanel();  
  60.         patternPanel.setLayout(new BoxLayout(patternPanel,  
  61.                                BoxLayout.PAGE_AXIS));  
  62.         patternPanel.add(patternLabel1);  
  63.         patternPanel.add(patternLabel2);  
  64.         patternList.setAlignmentX(Component.LEFT_ALIGNMENT);  
  65.         patternPanel.add(patternList);  
  66.   
  67.         JPanel resultPanel = new JPanel(new GridLayout(01));  
  68.         resultPanel.add(resultLabel);  
  69.         resultPanel.add(result);  
  70.   
  71.         patternPanel.setAlignmentX(Component.LEFT_ALIGNMENT);  
  72.         resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);  
  73.   
  74.         add(patternPanel);  
  75.         add(Box.createRigidArea(new Dimension(010)));  
  76.         add(resultPanel);  
  77.   
  78.         setBorder(BorderFactory.createEmptyBorder(10,10,10,10));  
  79.   
  80.         reformat();  
  81.     }   
  82. /** 
  83.  *方法说明:事件处理 
  84.  */  
  85.     public void actionPerformed(ActionEvent e) {  
  86.         JComboBox cb = (JComboBox)e.getSource();  
  87.         String newSelection = (String)cb.getSelectedItem();  
  88.         currentPattern = newSelection;  
  89.         reformat();  
  90.     }  
  91. /** 
  92.  *方法说明:格式和显示今天的日期 
  93.  */  
  94.     public void reformat() {  
  95.         Date today = new Date();  
  96.         SimpleDateFormat formatter =  
  97.            new SimpleDateFormat(currentPattern);  
  98.         try {  
  99.             String dateString = formatter.format(today);  
  100.             result.setForeground(Color.black);  
  101.             result.setText(dateString);  
  102.         } catch (IllegalArgumentException iae) {  
  103.             result.setForeground(Color.red);  
  104.             result.setText("Error: " + iae.getMessage());  
  105.         }  
  106.     }  
  107. /** 
  108.  *方法说明:主方法 
  109.  */  
  110.     public static void main(String[] args) {  
  111.         JFrame.setDefaultLookAndFeelDecorated(true);  
  112.   
  113.         //创建一个窗体   
  114.         frame = new JFrame("ComboBoxDemo");  
  115.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  116.   
  117.         //创建一个面版容器   
  118.         JComponent newContentPane = new ComboBoxDemo();  
  119.         newContentPane.setOpaque(true);  
  120.         frame.setContentPane(newContentPane);  
  121.   
  122.         //显示窗体   
  123.         frame.pack();  
  124.         frame.setVisible(true);  
  125.     }  
  126. }  


view plaincopy to clipboardprint?
  1. package test14;  
  2.   
  3. import java.awt.*;  
  4. import java.awt.event.*;  
  5. import javax.swing.*;  
  6. import javax.swing.event.*;  
  7. /** 
  8.  * Title: 列表框 
  9.  * Description: 通过输入框添加元素和点击“删除”按钮删除列表元素 
  10.  * Filename: ListDemo.java 
  11.  */  
  12. public class ListDemo extends JPanel  
  13.                       implements ListSelectionListener {  
  14.     private static final long serialVersionUID = 1L;  
  15.     private JList list;  
  16.     private DefaultListModel listModel;  
  17.   
  18.     private static final String hireString = "添加";  
  19.     private static final String fireString = "删除";  
  20.     private JButton fireButton;  
  21.     private JTextField employeeName;  
  22.   
  23.     public ListDemo() {  
  24.         super(new BorderLayout());  
  25.         //构建List的列表元素   
  26.         listModel = new DefaultListModel();  
  27.         listModel.addElement("Alan Sommerer");  
  28.         listModel.addElement("Alison Huml");  
  29.         listModel.addElement("Kathy Walrath");  
  30.         listModel.addElement("Lisa Friendly");  
  31.         listModel.addElement("Mary Campione");  
  32.         listModel.addElement("Sharon Zakhour");  
  33.   
  34.         //创建一个List构件,并将列表元素添加到列表中   
  35.         list = new JList(listModel);  
  36.         //设置选择模式为单选   
  37.         list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  
  38.         //初始化选择索引在0的位置,即第一个元素   
  39.         list.setSelectedIndex(0);  
  40.         list.addListSelectionListener(this);  
  41.         //设置列表可以同时看5个元素   
  42.         list.setVisibleRowCount(5);  
  43.         //给列表添加一个滑动块   
  44.         JScrollPane listScrollPane = new JScrollPane(list);  
  45.   
  46.         JButton hireButton = new JButton(hireString);  
  47.         HireListener hireListener = new HireListener(hireButton);  
  48.         hireButton.setActionCommand(hireString);  
  49.         hireButton.addActionListener(hireListener);  
  50.         hireButton.setEnabled(false);  
  51.   
  52.         fireButton = new JButton(fireString);  
  53.         fireButton.setActionCommand(fireString);  
  54.         fireButton.addActionListener(new FireListener());  
  55.   
  56.         employeeName = new JTextField(10);  
  57.         employeeName.addActionListener(hireListener);  
  58.         employeeName.getDocument().addDocumentListener(hireListener);  
  59.         @SuppressWarnings("unused")  
  60.         String name = listModel.getElementAt(  
  61.                               list.getSelectedIndex()).toString();  
  62.   
  63.         //创建一个面板   
  64.         JPanel buttonPane = new JPanel();  
  65.         buttonPane.setLayout(new BoxLayout(buttonPane,  
  66.                                            BoxLayout.LINE_AXIS));  
  67.         buttonPane.add(fireButton);  
  68.         buttonPane.add(Box.createHorizontalStrut(5));  
  69.         buttonPane.add(new JSeparator(SwingConstants.VERTICAL));  
  70.         buttonPane.add(Box.createHorizontalStrut(5));  
  71.         buttonPane.add(employeeName);  
  72.         buttonPane.add(hireButton);  
  73.         buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));  
  74.   
  75.         add(listScrollPane, BorderLayout.CENTER);  
  76.         add(buttonPane, BorderLayout.PAGE_END);  
  77.     }  
  78. /** 
  79.  *类说明:“添加”按钮监听 
  80.  *类描述:当点击“添加”按钮后,实现将元素添加到列表框中 
  81.  */  
  82.     class FireListener implements ActionListener {  
  83.         public void actionPerformed(ActionEvent e) {  
  84.              
  85.             int index = list.getSelectedIndex();  
  86.             listModel.remove(index);  
  87.   
  88.             int size = listModel.getSize();  
  89.   
  90.             if (size == 0) { //如果没有了选择项,则是“删除”按钮实效  
  91.                 fireButton.setEnabled(false);  
  92.   
  93.             } else { //选择了一个  
  94.                 if (index == listModel.getSize()) {  
  95.                     //移除选项   
  96.                     index--;  
  97.                 }  
  98.   
  99.                 list.setSelectedIndex(index);  
  100.                 list.ensureIndexIsVisible(index);  
  101.             }  
  102.         }  
  103.     }  
  104.   
  105. /** 
  106.  *类说明:“删除”按钮监听事件 
  107.  *类描述:实现删除列表元素 
  108.  */  
  109.     class HireListener implements ActionListener, DocumentListener {  
  110.         private boolean alreadyEnabled = false;  
  111.         private JButton button;  
  112.   
  113.         public HireListener(JButton button) {  
  114.             this.button = button;  
  115.         }  
  116.   
  117.         //必须实现 ActionListener.  
  118.         public void actionPerformed(ActionEvent e) {  
  119.             String name = employeeName.getText();  
  120.   
  121.             //如果输入空或有同名   
  122.             if (name.equals("") || alreadyInList(name)) {  
  123.                 Toolkit.getDefaultToolkit().beep();  
  124.                 employeeName.requestFocusInWindow();  
  125.                 employeeName.selectAll();  
  126.                 return;  
  127.             }  
  128.   
  129.             int index = list.getSelectedIndex(); //获取选择项  
  130.             if (index == -1) { //如果没有选择,就插入到第一个  
  131.                 index = 0;  
  132.             } else {           //如果有选择,那么插入到选择项的后面  
  133.                 index++;  
  134.             }  
  135.   
  136.             listModel.insertElementAt(employeeName.getText(), index);  
  137.    
  138.             //重新设置文本   
  139.             employeeName.requestFocusInWindow();  
  140.             employeeName.setText("");  
  141.   
  142.             //选择新的元素,并显示出来   
  143.             list.setSelectedIndex(index);  
  144.             list.ensureIndexIsVisible(index);  
  145.         }  
  146. /** 
  147.  *方法说明:检测是否在LIST中有重名元素 
  148.  *输入参数:String name 检测的名字 
  149.  *返回类型:boolean 布尔值,如果存在返回true 
  150.  */  
  151.   
  152.         protected boolean alreadyInList(String name) {  
  153.             return listModel.contains(name);  
  154.         }  
  155.   
  156. /** 
  157.  *方法说明:实现DocumentListener接口,必需实现的方法: 
  158.  */  
  159.         public void insertUpdate(DocumentEvent e) {  
  160.             enableButton();  
  161.         }  
  162.   
  163. /** 
  164.  *方法说明:实现DocumentListener接口,必需实现的方法 
  165.  */  
  166.         public void removeUpdate(DocumentEvent e) {  
  167.             handleEmptyTextField(e);  
  168.         }  
  169.   
  170. /** 
  171.  *方法说明:实现DocumentListener接口,必需实现的方法 
  172.  */  
  173.         public void changedUpdate(DocumentEvent e) {  
  174.             if (!handleEmptyTextField(e)) {  
  175.                 enableButton();  
  176.             }  
  177.         }  
  178. /** 
  179.  *方法说明:按钮使能 
  180.  */  
  181.         private void enableButton() {  
  182.             if (!alreadyEnabled) {  
  183.                 button.setEnabled(true);  
  184.             }  
  185.         }  
  186. /** 
  187.  *方法说明:实现DocumentListener接口,必需实现的方法,修改按钮的状态 
  188.  */  
  189.         private boolean handleEmptyTextField(DocumentEvent e) {  
  190.             if (e.getDocument().getLength() <= 0) {  
  191.                 button.setEnabled(false);  
  192.                 alreadyEnabled = false;  
  193.                 return true;  
  194.             }  
  195.             return false;  
  196.         }  
  197.     }  
  198. /** 
  199.  *方法说明:实现ListSelectionListener接口,必需实现的方法: 
  200.  */  
  201.     public void valueChanged(ListSelectionEvent e) {  
  202.         if (e.getValueIsAdjusting() == false) {  
  203.   
  204.             if (list.getSelectedIndex() == -1) {  
  205.                 fireButton.setEnabled(false);  
  206.   
  207.             } else {  
  208.                 fireButton.setEnabled(true);  
  209.             }  
  210.         }  
  211.     }  
  212. /** 
  213.  *方法说明:主方法 
  214.  */  
  215.     public static void main(String[] args) {  
  216.   
  217.         JFrame.setDefaultLookAndFeelDecorated(true);  
  218.   
  219.         //创建一个窗体   
  220.         JFrame frame = new JFrame("ListDemo");  
  221.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  222.   
  223.         //创建一个面版   
  224.         JComponent newContentPane = new ListDemo();  
  225.         newContentPane.setOpaque(true);  
  226.         frame.setContentPane(newContentPane);  
  227.   
  228.         //显示窗体   
  229.         frame.pack();  
  230.         frame.setVisible(true);  
  231.     }  
  232. }  


view plaincopy to clipboardprint?
  1. package test15;  
  2.   
  3. import javax.swing.JTabbedPane;  
  4. import javax.swing.ImageIcon;  
  5. import javax.swing.JLabel;  
  6. import javax.swing.JPanel;  
  7. import javax.swing.JFrame;  
  8. /** 
  9.  * Title: 选项卡演示 
  10.  * Description: 这里是一个选项卡演示,点击不同的卡片,显示的内容不同 
  11.  * Filename: TabbedPaneDemo.java 
  12.  */  
  13. import java.awt.*;  
  14.   
  15. public class TabbedPaneDemo extends JPanel {  
  16.     /** 
  17.      *  
  18.      */  
  19.     private static final long serialVersionUID = 1L;  
  20.   
  21.     public TabbedPaneDemo() {  
  22.         super(new GridLayout(11));  
  23.   
  24.         ImageIcon icon = createImageIcon("images/middle.gif");  
  25.         JTabbedPane tabbedPane = new JTabbedPane();  
  26.   
  27.         Component panel1 = makeTextPanel("#第一个卡片#");  
  28.         tabbedPane.addTab("One", icon, panel1,  
  29.                           "第一个卡片提示信息!");  
  30.         tabbedPane.setSelectedIndex(0);  
  31.   
  32.         Component panel2 = makeTextPanel("##第二个卡片##");  
  33.         tabbedPane.addTab("Two", icon, panel2,  
  34.                           "第二个卡片提示信息!");  
  35.   
  36.         Component panel3 = makeTextPanel("###第三个卡片###");  
  37.         tabbedPane.addTab("Three", icon, panel3,  
  38.                           "第三个卡片提示信息!");  
  39.   
  40.         Component panel4 = makeTextPanel("####第四个卡片####");  
  41.         tabbedPane.addTab("Four", icon, panel4,  
  42.                           "第四个卡片提示信息!");  
  43.   
  44.         //将选项卡添加到panl中   
  45.         add(tabbedPane);  
  46.     }  
  47. /** 
  48.  *方法说明:添加信息到选项卡中 
  49.  *输入参数:String text 显示的信息内容 
  50.  *返回类型:Component 成员对象 
  51.  */  
  52.     protected Component makeTextPanel(String text) {  
  53.         JPanel panel = new JPanel(false);  
  54.         JLabel filler = new JLabel(text);  
  55.         filler.setHorizontalAlignment(JLabel.CENTER);  
  56.         panel.setLayout(new GridLayout(11));  
  57.         panel.add(filler);  
  58.         return panel;  
  59.     }  
  60. /** 
  61.  *方法说明:获得图片 
  62.  *输入参数:String path 图片的路径 
  63.  *返回类型:ImageIcon 图片对象 
  64.  */  
  65.     protected static ImageIcon createImageIcon(String path) {  
  66.         java.net.URL imgURL = TabbedPaneDemo.class.getResource(path);  
  67.         if (imgURL != null) {  
  68.             return new ImageIcon(imgURL);  
  69.         } else {  
  70.             System.err.println("Couldn't find file: " + path);  
  71.             return null;  
  72.         }  
  73.     }  
  74.   
  75.     public static void main(String[] args) {  
  76.         //使用Swing窗体描述   
  77.         JFrame.setDefaultLookAndFeelDecorated(true);  
  78.   
  79.         //创建窗体   
  80.         JFrame frame = new JFrame("TabbedPaneDemo");  
  81.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  82.         frame.getContentPane().add(new TabbedPaneDemo(),  
  83.                                  BorderLayout.CENTER);  
  84.   
  85.         //显示窗体   
  86.         frame.setSize(400200);  
  87.         frame.setVisible(true);  
  88.     }  
  89. }  


view plaincopy to clipboardprint?
  1. package test16;  
  2.   
  3. import javax.swing.JOptionPane;  
  4. import javax.swing.JDialog;  
  5. import javax.swing.JTextField;  
  6. import java.beans.*; //property change stuff  
  7. import java.awt.*;  
  8. import java.awt.event.*;  
  9. /** 
  10.  * Title: 用户自定义对话框 
  11.  * Description: 自己定义对话框的风格。这使得对话框的样式更加多样化 
  12.  * Filename: CustomDialog.java 
  13.  */  
  14. class CustomDialog extends JDialog  
  15.                    implements ActionListener,  
  16.                               PropertyChangeListener {  
  17.   
  18.     private static final long serialVersionUID = 1L;  
  19.     private String typedText = null;  
  20.     private JTextField textField;  
  21.     private DialogDemo dd;  
  22.   
  23.     private String magicWord;  
  24.     private JOptionPane optionPane;  
  25.   
  26.     private String btnString1 = "确定";  
  27.     private String btnString2 = "取消";  
  28. /** 
  29.  *方法说明:返回文本输入字符 
  30.  */  
  31.     public String getValidatedText() {  
  32.         return typedText;  
  33.     }  
  34. /** 
  35.  *方法说明:创建一个结果对话框 
  36.  */  
  37.     public CustomDialog(Frame aFrame, String aWord, DialogDemo parent) {  
  38.         super(aFrame, true);  
  39.         dd = parent;  
  40.           
  41.         magicWord = aWord.toUpperCase();  
  42.         setTitle("测试");  
  43.   
  44.         textField = new JTextField(10);  
  45.   
  46.         //定义显示信息   
  47.         String msgString1 = "李先生: jeck是你的英文名字吗?";  
  48.         String msgString2 = "(这个答案是: \"" + magicWord  
  49.                               + "\"。)";  
  50.         Object[] array = {msgString1, msgString2, textField};  
  51.   
  52.   
  53.         Object[] options = {btnString1, btnString2};  
  54.   
  55.         //创建对话框   
  56.         optionPane = new JOptionPane(array,  
  57.                                     JOptionPane.QUESTION_MESSAGE,  
  58.                                     JOptionPane.YES_NO_OPTION,  
  59.                                     null,  
  60.                                     options,  
  61.                                     options[0]);  
  62.   
  63.         //显示对话框   
  64.         setContentPane(optionPane);  
  65.   
  66.         //设置当关闭窗体动作模式   
  67.         setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);  
  68.         addWindowListener(new WindowAdapter() {  
  69.                 public void windowClosing(WindowEvent we) {  
  70.                   
  71.                     optionPane.setValue(new Integer(  
  72.                                         JOptionPane.CLOSED_OPTION));  
  73.             }  
  74.         });  
  75.   
  76.         //使的文本输入域得到焦点   
  77.         addComponentListener(new ComponentAdapter() {  
  78.             public void componentShown(ComponentEvent ce) {  
  79.                 textField.requestFocusInWindow();  
  80.             }  
  81.         });  
  82.   
  83.         //给文本域添加监听事件   
  84.         textField.addActionListener(this);  
  85.   
  86.         //监听输入改变   
  87.         optionPane.addPropertyChangeListener(this);  
  88.     }  
  89.   
  90.     /** 文本域监听处理 */  
  91.     public void actionPerformed(ActionEvent e) {  
  92.         optionPane.setValue(btnString1);  
  93.     }  
  94.   
  95.     /** 监听输入的改变 */  
  96.     public void propertyChange(PropertyChangeEvent e) {  
  97.         String prop = e.getPropertyName();  
  98.   
  99.         if (isVisible()  
  100.          && (e.getSource() == optionPane)  
  101.          && (JOptionPane.VALUE_PROPERTY.equals(prop) ||  
  102.              JOptionPane.INPUT_VALUE_PROPERTY.equals(prop))) {  
  103.             Object value = optionPane.getValue();  
  104.   
  105.             if (value == JOptionPane.UNINITIALIZED_VALUE) {  
  106.                  return;  
  107.             }  
  108.   
  109.             optionPane.setValue(  
  110.                     JOptionPane.UNINITIALIZED_VALUE);  
  111.   
  112.             if (btnString1.equals(value)) {  
  113.                     typedText = textField.getText();  
  114.                 String ucText = typedText.toUpperCase();  
  115.                 if (magicWord.equals(ucText)) {  
  116.                     //如果输入有效,则清楚文本域并隐藏对话框   
  117.                     clearAndHide();  
  118.                 } else {  
  119.                     //文本输入无效   
  120.                     textField.selectAll();  
  121.                     JOptionPane.showMessageDialog(  
  122.                                     CustomDialog.this,  
  123.                                     "对不起, \"" + typedText + "\" "  
  124.                                     + "是无效的输入。\n"  
  125.                                     + "请重新输入"  
  126.                                     + magicWord + ".",  
  127.                                     "再试一次",  
  128.                                     JOptionPane.ERROR_MESSAGE);  
  129.                     typedText = null;  
  130.                     textField.requestFocusInWindow();  
  131.                 }  
  132.             } else { //用户关闭了对话框或点击了“cancel”  
  133.                 dd.setLabel("好吧! "  
  134.                          + "我们不能影响你的决定输入"  
  135.                          + magicWord + "。");  
  136.                 typedText = null;  
  137.                 clearAndHide();  
  138.             }  
  139.         }  
  140.     }  
  141. /** 
  142.  *方法说明:清楚文本域并隐藏痘翱蝌 
  143.  
  144.  */  
  145.     public void clearAndHide() {  
  146.         textField.setText(null);  
  147.         setVisible(false);  
  148.     }  
  149. }  


view plaincopy to clipboardprint?
  1. package test16;  
  2.   
  3. import javax.swing.JOptionPane;  
  4. import javax.swing.JDialog;  
  5. import javax.swing.JButton;  
  6. import javax.swing.JRadioButton;  
  7. import javax.swing.ButtonGroup;  
  8. import javax.swing.JLabel;  
  9. import javax.swing.ImageIcon;  
  10. import javax.swing.BoxLayout;  
  11. import javax.swing.Box;  
  12. import javax.swing.BorderFactory;  
  13. import javax.swing.border.Border;  
  14. import javax.swing.JTabbedPane;  
  15. import javax.swing.JPanel;  
  16. import javax.swing.JFrame;  
  17. import java.beans.*;   
  18. import java.awt.*;  
  19. import java.awt.event.*;  
  20.   
  21. /** 
  22.  *Title: 对话框演示 
  23.  *Description: 全面的演示各种类型的对话框的使用 
  24.  *Filename: DialogDemo.java 
  25.  */  
  26. public class DialogDemo extends JPanel {  
  27.   
  28.     private static final long serialVersionUID = 1L;  
  29.     JLabel label;  
  30.     ImageIcon icon = createImageIcon("images/middle.gif");  
  31.     JFrame frame;  
  32.     String simpleDialogDesc = "简单的信息提示对话窗";  
  33.     String iconDesc = "带有图标的对话窗";  
  34.     String moreDialogDesc = "复杂信息对话窗";  
  35.     CustomDialog customDialog;  
  36. /** 
  37.  *方法说明:构造器,生成一个面板添加到JFrame中 
  38.  *输入参数: 
  39.  *返回类型: 
  40.  */  
  41.     public DialogDemo(JFrame frame) {  
  42.         super(new BorderLayout());  
  43.         this.frame = frame;  
  44.         customDialog = new CustomDialog(frame, "tom"this);  
  45.         customDialog.pack();  
  46.   
  47.         //创建成员   
  48.         JPanel frequentPanel = createSimpleDialogBox();  
  49.         JPanel featurePanel = createFeatureDialogBox();  
  50.         JPanel iconPanel = createIconDialogBox();  
  51.         label = new JLabel("点击\"显示\" 按钮"  
  52.                            + " 显示一个选择的对话框",  
  53.                            JLabel.CENTER);  
  54.   
  55.         //放置对象   
  56.         Border padding = BorderFactory.createEmptyBorder(20,20,5,20);  
  57.         frequentPanel.setBorder(padding);  
  58.         featurePanel.setBorder(padding);  
  59.         iconPanel.setBorder(padding);  
  60.         //创建选项卡   
  61.         JTabbedPane tabbedPane = new JTabbedPane();  
  62.         tabbedPane.addTab("简单对话窗"null,  
  63.                           frequentPanel,  
  64.                           simpleDialogDesc);   
  65.         tabbedPane.addTab("复杂对话窗"null,  
  66.                           featurePanel,  
  67.                           moreDialogDesc);  
  68.         tabbedPane.addTab("图标对话窗"null,  
  69.                           iconPanel,  
  70.                           iconDesc);  
  71.   
  72.         add(tabbedPane, BorderLayout.CENTER);  
  73.         add(label, BorderLayout.PAGE_END);  
  74.         label.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));  
  75.     }  
  76. /** 
  77.  *方法说明:设置按钮上的文字 
  78.  *输入参数:String newText 添加的文字 
  79.  *返回类型: 
  80.  */  
  81.     void setLabel(String newText) {  
  82.         label.setText(newText);  
  83.     }  
  84. /** 
  85.  *方法说明:获取图片 
  86.  *输入参数:String path 图片完整路径和名字 
  87.  *返回类型:ImageIcon 图片对象 
  88.  */  
  89.     protected static ImageIcon createImageIcon(String path) {  
  90.         java.net.URL imgURL = DialogDemo.class.getResource(path);  
  91.         if (imgURL != null) {  
  92.             return new ImageIcon(imgURL);  
  93.         } else {  
  94.             System.err.println("Couldn't find file: " + path);  
  95.             return null;  
  96.         }  
  97.     }  
  98. /** 
  99.  *方法说明:创建一个JPanel,给第一个选项卡 
  100.  *输入参数: 
  101.  *返回类型: 
  102.  */  
  103.     private JPanel createSimpleDialogBox() {  
  104.         final int numButtons = 4;  
  105.         JRadioButton[] radioButtons = new JRadioButton[numButtons];  
  106.         final ButtonGroup group = new ButtonGroup();  
  107.   
  108.         JButton showItButton = null;  
  109.   
  110.         final String defaultMessageCommand = "default";  
  111.         final String yesNoCommand = "yesno";  
  112.         final String yeahNahCommand = "yeahnah";  
  113.         final String yncCommand = "ync";  
  114.         //添加单选到数字   
  115.         radioButtons[0] = new JRadioButton("只有“OK”按钮");  
  116.         radioButtons[0].setActionCommand(defaultMessageCommand);  
  117.   
  118.         radioButtons[1] = new JRadioButton("有“Yes/No”二个按钮");  
  119.         radioButtons[1].setActionCommand(yesNoCommand);  
  120.   
  121.         radioButtons[2] = new JRadioButton("有“Yes/No”两个按钮 "  
  122.                       + "(程序添加文字)");  
  123.         radioButtons[2].setActionCommand(yeahNahCommand);  
  124.   
  125.         radioButtons[3] = new JRadioButton("有“Yes/No/Cancel”三个按钮 "  
  126.                            + "(程序添加文字)");  
  127.         radioButtons[3].setActionCommand(yncCommand);  
  128.         //将四个单选组成一个群   
  129.         for (int i = 0; i < numButtons; i++) {  
  130.             group.add(radioButtons[i]);  
  131.         }  
  132.         //设置第一个为默认选择   
  133.         radioButtons[0].setSelected(true);  
  134.         //定义“显示”按钮   
  135.         showItButton = new JButton("显示");  
  136.         //给“显示”按钮添加监听   
  137.         showItButton.addActionListener(new ActionListener() {  
  138.             public void actionPerformed(ActionEvent e) {  
  139.                 String command = group.getSelection().getActionCommand();  
  140.   
  141.                 //ok对话窗   
  142.                 if (command == defaultMessageCommand) {  
  143.                     JOptionPane.showMessageDialog(frame,  
  144.                                 "鸡蛋不可能是绿色的!");  
  145.   
  146.                 //yes/no 对话窗   
  147.                 } else if (command == yesNoCommand) {  
  148.                     int n = JOptionPane.showConfirmDialog(  
  149.                             frame, "你喜欢吃酸菜鱼吗?",  
  150.                             "一个很无聊的问题!!",  
  151.                             JOptionPane.YES_NO_OPTION);  
  152.                     if (n == JOptionPane.YES_OPTION) {//选择yes  
  153.                         setLabel("哇!我也是!");  
  154.                     } else if (n == JOptionPane.NO_OPTION) {//选择no  
  155.                         setLabel("唉!我喜欢吃!");  
  156.                     } else {  
  157.                         setLabel("快告诉我吧!");  
  158.                     }  
  159.   
  160.                 //yes/no (自己输入选项)   
  161.                 } else if (command == yeahNahCommand) {  
  162.                     Object[] options = {"是的""不喜欢"};  
  163.                     int n = JOptionPane.showOptionDialog(frame,  
  164.                                     "你喜欢酸菜鱼吗?",  
  165.                                     "又一个无聊的问题!",  
  166.                                     JOptionPane.YES_NO_OPTION,  
  167.                                     JOptionPane.QUESTION_MESSAGE,  
  168.                                     null,  
  169.                                     options,  
  170.                                     options[0]);  
  171.                     if (n == JOptionPane.YES_OPTION) {  
  172.                         setLabel("你哄人的吧,我也喜欢。");  
  173.                     } else if (n == JOptionPane.NO_OPTION) {  
  174.                         setLabel("其实我也不喜欢!");  
  175.                     } else {  
  176.                         setLabel("这都不肯告诉我,小气鬼!");  
  177.                     }  
  178.   
  179.                 //yes/no/cancel 对话框  
  180.                 } else if (command == yncCommand) {  
  181.                     Object[] options = {"是的,给我来一份。",  
  182.                                         "不,谢谢!",  
  183.                                         "不,我要水煮鱼!"};  
  184.                     //构造对话框   
  185.                     int n = JOptionPane.showOptionDialog(frame,  
  186.                                     "先生!我们这里有鲜美的酸菜鱼,您需要吗?",  
  187.                                     "服务生的问题。",  
  188.                                     JOptionPane.YES_NO_CANCEL_OPTION,  
  189.                                     JOptionPane.QUESTION_MESSAGE,  
  190.                                     null,  
  191.                                     options,  
  192.                                     options[2]);  
  193.                     if (n == JOptionPane.YES_OPTION) {  
  194.                         setLabel("你要的酸菜鱼来了!");  
  195.                     } else if (n == JOptionPane.NO_OPTION) {  
  196.                         setLabel("好的,你需要其它的。");  
  197.                     } else if (n == JOptionPane.CANCEL_OPTION) {  
  198.                         setLabel("好的,我们给你做水煮鱼!");  
  199.                     } else {  
  200.                         setLabel("对不起!你还没有点菜呢!");  
  201.                     }  
  202.                 }  
  203.                 return;  
  204.             }  
  205.         });  
  206.   
  207.         return createPane(simpleDialogDesc + ":",  
  208.                           radioButtons,  
  209.                           showItButton);  
  210.     }  
  211. /** 
  212.  *方法说明:提供给createSimpleDialogBox和createFeatureDialogBox方法 
  213.  *方法说明:创建带提示信息、一列单选框和“显示”按钮 
  214.  *输入参数:String description 提示帮助信息 
  215.  *输入参数:JRadioButton[] radioButtons 单选框组 
  216.  *输入参数:JButton showButton “显示”按钮 
  217.  *返回类型:JPanel 添加好的面板 
  218.  */  
  219.     private JPanel createPane(String description,  
  220.                               JRadioButton[] radioButtons,  
  221.                               JButton showButton) {  
  222.   
  223.         int numChoices = radioButtons.length;  
  224.         JPanel box = new JPanel();  
  225.         JLabel label = new JLabel(description);  
  226.   
  227.         box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));  
  228.         box.add(label);  
  229.         //添加radio   
  230.         for (int i = 0; i < numChoices; i++) {  
  231.             box.add(radioButtons[i]);  
  232.         }  
  233.   
  234.         JPanel pane = new JPanel(new BorderLayout());  
  235.         pane.add(box, BorderLayout.PAGE_START);  
  236.         pane.add(showButton, BorderLayout.PAGE_END);  
  237.         return pane;  
  238.     }  
  239. /** 
  240.  *方法说明:提供给createSimpleDialogBox和createFeatureDialogBox方法 
  241.  *方法说明:创建带提示信息、二列单选框和“显示”按钮 
  242.  *输入参数:String description 提示帮助信息 
  243.  *输入参数:JRadioButton[] radioButtons 单选框组 
  244.  *输入参数:JButton showButton “显示”按钮 
  245.  *返回类型:JPanel 添加好的面板 
  246.  */  
  247.      private JPanel create2ColPane(String description,  
  248.                                   JRadioButton[] radioButtons,  
  249.                                   JButton showButton) {  
  250.         JLabel label = new JLabel(description);  
  251.         int numPerColumn = radioButtons.length/2;  
  252.   
  253.         JPanel grid = new JPanel(new GridLayout(02));  
  254.         for (int i = 0; i < numPerColumn; i++) {  
  255.             grid.add(radioButtons[i]);  
  256.             grid.add(radioButtons[i + numPerColumn]);  
  257.         }  
  258.   
  259.         JPanel box = new JPanel();  
  260.         box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));  
  261.         box.add(label);  
  262.         grid.setAlignmentX(0.0f);  
  263.         box.add(grid);  
  264.   
  265.         JPanel pane = new JPanel(new BorderLayout());  
  266.         pane.add(box, BorderLayout.PAGE_START);  
  267.         pane.add(showButton, BorderLayout.PAGE_END);  
  268.   
  269.         return pane;  
  270.     }  
  271. /** 
  272.  *方法说明:创建第三个选项卡的面板 
  273.  *方法说明:这里都是实现showMessageDialog类,但是也可以指定图标 
  274.  *输入参数: 
  275.  *返回类型:JPanel 构造好的面板 
  276.  */  
  277.   
  278.     private JPanel createIconDialogBox() {  
  279.         JButton showItButton = null;  
  280.   
  281.         final int numButtons = 6;  
  282.         JRadioButton[] radioButtons = new JRadioButton[numButtons];  
  283.         final ButtonGroup group = new ButtonGroup();  
  284.   
  285.         final String plainCommand = "plain";  
  286.         final String infoCommand = "info";  
  287.         final String questionCommand = "question";  
  288.         final String errorCommand = "error";  
  289.         final String warningCommand = "warning";  
  290.         final String customCommand = "custom";  
  291.   
  292.         radioButtons[0] = new JRadioButton("普通(没有图标)");  
  293.         radioButtons[0].setActionCommand(plainCommand);  
  294.   
  295.         radioButtons[1] = new JRadioButton("信息图标");  
  296.         radioButtons[1].setActionCommand(infoCommand);  
  297.   
  298.         radioButtons[2] = new JRadioButton("问题图标");  
  299.         radioButtons[2].setActionCommand(questionCommand);  
  300.   
  301.         radioButtons[3] = new JRadioButton("错误图标");  
  302.         radioButtons[3].setActionCommand(errorCommand);  
  303.   
  304.         radioButtons[4] = new JRadioButton("警告图标");  
  305.         radioButtons[4].setActionCommand(warningCommand);  
  306.   
  307.         radioButtons[5] = new JRadioButton("自定义图标");  
  308.         radioButtons[5].setActionCommand(customCommand);  
  309.   
  310.         for (int i = 0; i < numButtons; i++) {  
  311.             group.add(radioButtons[i]);  
  312.         }  
  313.         radioButtons[0].setSelected(true);  
  314.   
  315.         showItButton = new JButton("显示");  
  316.         showItButton.addActionListener(new ActionListener() {  
  317.             public void actionPerformed(ActionEvent e) {  
  318.                 String command = group.getSelection().getActionCommand();  
  319.   
  320.                 //没有图标   
  321.                 if (command == plainCommand) {  
  322.                     JOptionPane.showMessageDialog(frame,  
  323.                                     "水煮鱼里不要放酸菜!",  
  324.                                     "无图标",  
  325.                                     JOptionPane.PLAIN_MESSAGE);  
  326.                 //信息图标   
  327.                 } else if (command == infoCommand) {  
  328.                     JOptionPane.showMessageDialog(frame,  
  329.                                     "水煮鱼里不要放酸菜!",  
  330.                                     "信息图标",  
  331.                                     JOptionPane.INFORMATION_MESSAGE);  
  332.   
  333.                 //问题图标   
  334.                 } else if (command == questionCommand) {  
  335.                     JOptionPane.showMessageDialog(frame,  
  336.                                     "请你吃饭前洗手,好吗?",  
  337.                                     "问题",  
  338.                                     JOptionPane.QUESTION_MESSAGE);  
  339.                 //错误图标   
  340.                 } else if (command == errorCommand) {  
  341.                     JOptionPane.showMessageDialog(frame,  
  342.                                     "对不起,你的信用卡没有资金了!",  
  343.                                     "错误信息",  
  344.                                     JOptionPane.ERROR_MESSAGE);  
  345.                 //警告图标   
  346.                 } else if (command == warningCommand) {  
  347.                     JOptionPane.showMessageDialog(frame,  
  348.                                     "警告!你严重透支信用卡,请尽快补齐金额!",  
  349.                                     "警告信息",  
  350.                                     JOptionPane.WARNING_MESSAGE);  
  351.                 //自定义图标   
  352.                 } else if (command == customCommand) {  
  353.                     JOptionPane.showMessageDialog(frame,  
  354.                                     "哈哈。我想用什么图标都可以!",  
  355.                                     "自定义对话窗",  
  356.                                     JOptionPane.INFORMATION_MESSAGE,  
  357.                                     icon);  
  358.                 }  
  359.             }  
  360.         });  
  361.   
  362.         return create2ColPane(iconDesc + ":",  
  363.                               radioButtons,  
  364.                               showItButton);  
  365.     }  
  366. /** 
  367.  *方法说明:创建一个JPanel,放在第二个选项卡上 
  368.  *输入参数: 
  369.  *返回类型: 
  370.  */  
  371.     private JPanel createFeatureDialogBox() {  
  372.         final int numButtons = 5;  
  373.         JRadioButton[] radioButtons = new JRadioButton[numButtons];  
  374.         final ButtonGroup group = new ButtonGroup();  
  375.   
  376.         JButton showItButton = null;  
  377.         //定义操作命令   
  378.         final String pickOneCommand = "pickone";  
  379.         final String textEnteredCommand = "textfield";  
  380.         final String nonAutoCommand = "nonautooption";  
  381.         final String customOptionCommand = "customoption";  
  382.         final String nonModalCommand = "nonmodal";  
  383.         //定义radio数组   
  384.         radioButtons[0] = new JRadioButton("选择一个");  
  385.         radioButtons[0].setActionCommand(pickOneCommand);  
  386.   
  387.         radioButtons[1] = new JRadioButton("输入信息");  
  388.         radioButtons[1].setActionCommand(textEnteredCommand);  
  389.   
  390.         radioButtons[2] = new JRadioButton("关闭按钮无效");  
  391.         radioButtons[2].setActionCommand(nonAutoCommand);  
  392.   
  393.         radioButtons[3] = new JRadioButton("输入校验"  
  394.                                            + "(用户输入信息)");  
  395.         radioButtons[3].setActionCommand(customOptionCommand);  
  396.   
  397.         radioButtons[4] = new JRadioButton("没有模式");  
  398.         radioButtons[4].setActionCommand(nonModalCommand);  
  399.         //合成一个组群   
  400.         for (int i = 0; i < numButtons; i++) {  
  401.             group.add(radioButtons[i]);  
  402.         }  
  403.         //设置第一个为默认选择   
  404.         radioButtons[0].setSelected(true);  
  405.   
  406.         showItButton = new JButton("显示");  
  407.         showItButton.addActionListener(new ActionListener() {  
  408.             @SuppressWarnings("static-access")  
  409.             public void actionPerformed(ActionEvent e) {  
  410.                 String command = group.getSelection().getActionCommand();  
  411.   
  412.                 //选择一个   
  413.                 if (command == pickOneCommand) {  
  414.                     Object[] possibilities = {"辣椒""西红柿""洋葱"};  
  415.                     //设置对话框   
  416.                     String s = (String)JOptionPane.showInputDialog(  
  417.                                         frame,    //所属窗体  
  418.                                         "请选择项目:\n"  
  419.                                         + "\"鸡蛋炒\"",  //输出信息  
  420.                                         "客户选择",  
  421.                                         JOptionPane.PLAIN_MESSAGE,  //对话框模式  
  422.                                         icon,           //显示图标  
  423.                                         possibilities,   //选项内容  
  424.                                         "辣椒");    //默认选项  
  425.   
  426.                     //如果有选择   
  427.                     if ((s != null) && (s.length() > 0)) {  
  428.                         setLabel("鸡蛋炒" + s + "!");  
  429.                         return;  
  430.                     }  
  431.   
  432.                     //如果客户没有选择   
  433.                     setLabel("快点!");  
  434.   
  435.                 //文本输入   
  436.                 } else if (command == textEnteredCommand) {  
  437.                     String s = (String)JOptionPane.showInputDialog(  
  438.                                         frame,  
  439.                                         "选择一个配料\n"  
  440.                                         + "\"鸡蛋炒\"",  
  441.                                         "客户输入",  
  442.                                         JOptionPane.PLAIN_MESSAGE,  
  443.                                         icon,  
  444.                                         null,  
  445.                                         "辣椒");  
  446.   
  447.                     //如果用户有输入   
  448.                     if ((s != null) && (s.length() > 0)) {  
  449.                         setLabel("你要的是鸡蛋炒" + s + "!");  
  450.                         return;  
  451.                     }  
  452.   
  453.                     //如果返回的是空或者是null。  
  454.                     setLabel("快些选择!");  
  455.   
  456.                 //关闭按钮无效   
  457.                 } else if (command == nonAutoCommand) {  
  458.                     //构造一个对话框面板   
  459.                     final JOptionPane optionPane = new JOptionPane(  
  460.                                     "关闭这个对话框\n"  
  461.                                     + "请点击下面的按钮\n"  
  462.                                     + "明白吗?",  
  463.                                     JOptionPane.QUESTION_MESSAGE,  
  464.                                     JOptionPane.YES_NO_OPTION);  
  465.   
  466.                     JDialog.setDefaultLookAndFeelDecorated(false);  
  467.                     //构造一个对话框   
  468.                     final JDialog dialog = new JDialog(frame,  
  469.                                                  "点击一个按钮",  
  470.                                                  true);  
  471.                     //将对话框面板添加到对话框中  
  472.                     dialog.setContentPane(optionPane);  
  473.                     //设置对话框关闭时的操作模式  
  474.                     dialog.setDefaultCloseOperation(  
  475.                         JDialog.DO_NOTHING_ON_CLOSE);  
  476.                     dialog.addWindowListener(new WindowAdapter() {  
  477.                         public void windowClosing(WindowEvent we) { //当点击关闭按钮  
  478.                             setLabel("阻碍用户视图关闭窗体!");  
  479.                         }  
  480.                     });  
  481.                       
  482.                     JDialog.setDefaultLookAndFeelDecorated(true);  
  483.                       
  484.                     optionPane.addPropertyChangeListener(  
  485.                         new PropertyChangeListener() {  
  486.                             public void propertyChange(PropertyChangeEvent e) {  
  487.                                 String prop = e.getPropertyName();  
  488.   
  489.                                 if (dialog.isVisible()  
  490.                                  && (e.getSource() == optionPane)  
  491.                                  && (JOptionPane.VALUE_PROPERTY.equals(prop))) {  
  492.                                     //如果你要阻止关闭按钮,可以在这里进行处理。  
  493.                                       
  494.                                     dialog.setVisible(false);  
  495.                                 }  
  496.                             }  
  497.                         });  
  498.                     dialog.pack();  
  499.                     dialog.setLocationRelativeTo(frame);  
  500.                     dialog.setVisible(true);  
  501.                       
  502.                     int value = ((Integer)optionPane.getValue()).intValue();  
  503.                     if (value == JOptionPane.YES_OPTION) {  
  504.                         setLabel("好的");  
  505.                     } else if (value == JOptionPane.NO_OPTION) {  
  506.                         setLabel("试图点击关闭按钮来关闭一个不能关闭的对话框!"  
  507.                                  + "你不能!");  
  508.                     } else {  
  509.                         setLabel("窗体可以使用ESC键关闭。");  
  510.                     }  
  511.   
  512.                  //自己定义版面   
  513.                 } else if (command == customOptionCommand) {  
  514.                     customDialog.setLocationRelativeTo(frame);  
  515.                     customDialog.setVisible(true);  
  516.   
  517.                     String s = customDialog.getValidatedText();  
  518.                     if (s != null) {  
  519.                         //The text is valid.  
  520.                         setLabel("欢迎你!"  
  521.                                  + "你已经进入了\""  
  522.                                  + s  
  523.                                  + "\"。");  
  524.                     }  
  525.   
  526.                 //没有模式   
  527.                 } else if (command == nonModalCommand) {  
  528.                     //创建一个对话框   
  529.                     final JDialog dialog = new JDialog(frame,  
  530.                                                        "一个没有模式的对话框");  
  531.                     //使用html语言来显示信息  
  532.                     JLabel label = new JLabel("<html><p align=center>"  
  533.                         + "这是一个没有模式的对话框"  
  534.                         + "你可以使用更多的格式"  
  535.                         + "甚至可以使用主窗体!");  
  536.                     label.setHorizontalAlignment(JLabel.CENTER);  
  537.                     Font font = label.getFont();  
  538.                       
  539.                     label.setFont(label.getFont().deriveFont(font.PLAIN,  
  540.                                                              14.0f));  
  541.   
  542.                     JButton closeButton = new JButton("关闭");  
  543.                     closeButton.addActionListener(new ActionListener() {  
  544.                         public void actionPerformed(ActionEvent e) {  
  545.                             dialog.setVisible(false);  
  546.                             dialog.dispose();  
  547.                         }  
  548.                     });  
  549.                     JPanel closePanel = new JPanel();  
  550.                     closePanel.setLayout(new BoxLayout(closePanel,  
  551.                                                        BoxLayout.LINE_AXIS));  
  552.                     closePanel.add(Box.createHorizontalGlue());  
  553.                     closePanel.add(closeButton);  
  554.                     closePanel.setBorder(BorderFactory.  
  555.                         createEmptyBorder(0,0,5,5));  
  556.   
  557.                     JPanel contentPane = new JPanel(new BorderLayout());  
  558.                     contentPane.add(label, BorderLayout.CENTER);  
  559.                     contentPane.add(closePanel, BorderLayout.PAGE_END);  
  560.                     contentPane.setOpaque(true);  
  561.                     dialog.setContentPane(contentPane);  
  562.   
  563.                     //显示窗体   
  564.                     dialog.setSize(new Dimension(300150));  
  565.                     dialog.setLocationRelativeTo(frame);  
  566.                     dialog.setVisible(true);  
  567.                 }  
  568.             }  
  569.         });  
  570.   
  571.         return createPane(moreDialogDesc + ":",  
  572.                           radioButtons,  
  573.                           showItButton);  
  574.     }  
  575.   
  576.     public static void main(String[] args) {  
  577.   
  578.         JFrame.setDefaultLookAndFeelDecorated(true);  
  579.         JDialog.setDefaultLookAndFeelDecorated(true);  
  580.   
  581.         //创建和设置一个窗体   
  582.         JFrame frame = new JFrame("DialogDemo");  
  583.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  584.   
  585.         //设置一个面板   
  586.         Container contentPane = frame.getContentPane();  
  587.         contentPane.setLayout(new GridLayout(1,1));  
  588.         contentPane.add(new DialogDemo(frame));  
  589.   
  590.         //显示窗体   
  591.         frame.pack();  
  592.         frame.setVisible(true);  
  593.     }  
  594. }  


view plaincopy to clipboardprint?
  1. package test17;  
  2.   
  3. import java.io.*;  
  4. import java.awt.*;  
  5. import java.awt.event.*;  
  6. import javax.swing.*;  
  7. /** 
  8.  * Title: 文件对话框演示 
  9.  * Description: 演示打开文件对话框和保存文件对话框,使用了文件过滤。 
  10.  * Filename: FileChooserDemo.java 
  11.  */  
  12.   
  13. public class FileChooserDemo extends JPanel  
  14.                              implements ActionListener {  
  15.   
  16.     private static final long serialVersionUID = 1L;  
  17.     static private final String newline = "\n";  
  18.     JButton openButton, saveButton;  
  19.     JTextArea log;  
  20.     JFileChooser fc;  
  21.   
  22.     public FileChooserDemo() {  
  23.         super(new BorderLayout());  
  24.   
  25.         log = new JTextArea(15,40);  
  26.         log.setMargin(new Insets(10,10,10,10));  
  27.         log.setEditable(false);  
  28.         JScrollPane logScrollPane = new JScrollPane(log);  
  29.   
  30.         //创建一个文件过滤,使用当前目录   
  31.         fc = new JFileChooser(".");  
  32.         //过滤条件在MyFilter类中定义   
  33.         fc.addChoosableFileFilter(new MyFilter());  
  34.   
  35.         openButton = new JButton("打开文件",  
  36.                                  createImageIcon("images/Open16.gif"));  
  37.         openButton.addActionListener(this);  
  38.   
  39.         saveButton = new JButton("保存文件",  
  40.                                  createImageIcon("images/Save16.gif"));  
  41.         saveButton.addActionListener(this);  
  42.   
  43.         //构建一个面板,添加“打开文件”和“保存文件”  
  44.         JPanel buttonPanel = new JPanel();   
  45.         buttonPanel.add(openButton);  
  46.         buttonPanel.add(saveButton);  
  47.   
  48.         add(buttonPanel, BorderLayout.PAGE_START);  
  49.         add(logScrollPane, BorderLayout.CENTER);  
  50.     }  
  51. /** 
  52.  *方法说明:事件处理 
  53.  *输入参数: 
  54.  *返回类型: 
  55.  */  
  56.     public void actionPerformed(ActionEvent e) {  
  57.   
  58.         //当点击“打开文件”按钮   
  59.         if (e.getSource() == openButton) {  
  60.             int returnVal = fc.showOpenDialog(FileChooserDemo.this);  
  61.   
  62.             if (returnVal == JFileChooser.APPROVE_OPTION) {  
  63.                 File file = fc.getSelectedFile();  
  64.                 //在这里添加一些对文件的处理   
  65.                 log.append("打开文件: " + file.getName() + newline);  
  66.             } else {  
  67.                 log.append("打开文件被用户取消!" + newline);  
  68.             }  
  69.   
  70.         //点击“保存文件”按钮   
  71.         } else if (e.getSource() == saveButton) {  
  72.             int returnVal = fc.showSaveDialog(FileChooserDemo.this);  
  73.             if (returnVal == JFileChooser.APPROVE_OPTION) {  
  74.                 File file = fc.getSelectedFile();  
  75.                 //在这里添加一些对文件的处理  
  76.                 log.append("保存文件: " + file.getName()  + newline);  
  77.             } else {  
  78.                 log.append("保存文件被用户取消!" + newline);  
  79.             }  
  80.         }  
  81.     }  
  82. /** 
  83.  *方法说明:获取图像对象 
  84.  *输入参数:String path 图片路径 
  85.  *返回类型:ImageIcon 图片对象 
  86.  */  
  87.     protected static ImageIcon createImageIcon(String path) {  
  88.         java.net.URL imgURL = FileChooserDemo.class.getResource(path);  
  89.         if (imgURL != null) {  
  90.             return new ImageIcon(imgURL);  
  91.         } else {  
  92.             System.err.println("Couldn't find file: " + path);  
  93.             return null;  
  94.         }  
  95.     }  
  96.   
  97.     public static void main(String[] args) {  
  98.         JFrame.setDefaultLookAndFeelDecorated(true);  
  99.         JDialog.setDefaultLookAndFeelDecorated(true);  
  100.   
  101.         //创建窗体   
  102.         JFrame frame = new JFrame("FileChooserDemo");  
  103.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  104.   
  105.         //创建一个面板   
  106.         JComponent newContentPane = new FileChooserDemo();  
  107.         newContentPane.setOpaque(true);  
  108.         frame.setContentPane(newContentPane);  
  109.   
  110.         //显示窗体   
  111.         frame.pack();  
  112.         frame.setVisible(true);  
  113.     }  
  114. }  


view plaincopy to clipboardprint?
  1. package test17;  
  2.   
  3. import java.io.File;  
  4. import javax.swing.filechooser.*;  
  5. /** 
  6.  * Title: 文件过滤器演示 
  7.  * Description: FileChooserDemo文件使用的文件过滤器 
  8.  * Filename: MyFilter.java 
  9.  */  
  10.   
  11. public class MyFilter extends FileFilter {  
  12.    @SuppressWarnings("unused")  
  13. private String files;  
  14.    public boolean accept(File f) {  
  15.         if (f.isDirectory()) {  
  16.             return true;  
  17.         }  
  18.   
  19.         String extension = getExtension(f);  
  20.         if (extension != null) {  
  21.               
  22.             if (extension.equals("java")) {//定义过滤Java文件  
  23.                     return true;  
  24.             } else {  
  25.                 return false;  
  26.             }  
  27.   
  28.         }  
  29.   
  30.         return false;  
  31.     }  
  32.   
  33.     //过滤器描述   
  34.     public String getDescription() {  
  35.         return "Java";  
  36.     }  
  37. /** 
  38.  *方法说明:获取文件扩展名 
  39.  */  
  40.     public static String getExtension(File f) {  
  41.         String ext = null;  
  42.         String s = f.getName();  
  43.         int i = s.lastIndexOf('.');  
  44.   
  45.         if (i > 0 &&  i < s.length() - 1) {  
  46.             ext = s.substring(i+1).toLowerCase();  
  47.         }  
  48.         return ext;  
  49.     }  
  50. }  


view plaincopy to clipboardprint?
  1. package test18;  
  2.   
  3. import javax.swing.*;  
  4. import java.awt.*;  
  5. import java.awt.event.*;  
  6. /** 
  7.  * Description: 这里演示使用html语言在swing面板上构造显示信息 
  8.  * Filename: HtmlDemo.java 
  9.  */  
  10.   
  11. public class HtmlDemo extends JPanel  
  12.                       implements ActionListener {  
  13.   
  14.     private static final long serialVersionUID = 1L;  
  15.     JLabel theLabel;  
  16.     JTextArea htmlTextArea;  
  17. /** 
  18.  *方法说明:构造器,描述窗体中的成员 
  19.  *输入参数: 
  20.  *返回类型: 
  21.  */  
  22.     public HtmlDemo() {  
  23.         setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));  
  24.   
  25.         String initialText = "<html>\n" +  
  26.                 "颜色和字体测试:\n" +  
  27.                 "<ul>\n" +  
  28.                 "<li><font color=red>red</font>\n" +  
  29.                 "<li><font color=blue>blue</font>\n" +  
  30.                 "<li><font color=green>green</font>\n" +  
  31.                 "<li><font size=-2>small</font>\n" +  
  32.                 "<li><font size=+2>large</font>\n" +  
  33.                 "<li><i>italic</i>\n" +  
  34.                 "<li><b>bold</b>\n" +  
  35.                 "</ul>\n";  
  36.         //定义一个文本框   
  37.         htmlTextArea = new JTextArea(1020);  
  38.         htmlTextArea.setText(initialText);  
  39.         JScrollPane scrollPane = new JScrollPane(htmlTextArea);  
  40.         //定义按钮   
  41.         JButton changeTheLabel = new JButton("改变显示");  
  42.         changeTheLabel.setMnemonic(KeyEvent.VK_C);  
  43.         changeTheLabel.setAlignmentX(Component.CENTER_ALIGNMENT);  
  44.         changeTheLabel.addActionListener(this);  
  45.         //定义标签   
  46.         theLabel = new JLabel(initialText) {  
  47.            
  48.             private static final long serialVersionUID = 1L;  
  49.             public Dimension getPreferredSize() {  
  50.                 return new Dimension(200200);  
  51.             }  
  52.             public Dimension getMinimumSize() {  
  53.                 return new Dimension(200200);  
  54.             }  
  55.             public Dimension getMaximumSize() {  
  56.                 return new Dimension(200200);  
  57.             }  
  58.         };  
  59.         //设置标签的对齐方式   
  60.         theLabel.setVerticalAlignment(SwingConstants.CENTER);  
  61.         theLabel.setHorizontalAlignment(SwingConstants.CENTER);  
  62.         //构造一个带边框的左边的编辑面板   
  63.         JPanel leftPanel = new JPanel();  
  64.         leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));  
  65.         leftPanel.setBorder(BorderFactory.createCompoundBorder(  
  66.                 BorderFactory.createTitledBorder(  
  67.                     "编辑HTML,点击按钮显示结果。"),  
  68.                 BorderFactory.createEmptyBorder(10,10,10,10)));  
  69.         leftPanel.add(scrollPane);  
  70.         leftPanel.add(Box.createRigidArea(new Dimension(0,10)));  
  71.         leftPanel.add(changeTheLabel);  
  72.          //构造一个带边框的右边显示的面板   
  73.         JPanel rightPanel = new JPanel();  
  74.         rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.PAGE_AXIS));  
  75.         rightPanel.setBorder(BorderFactory.createCompoundBorder(  
  76.                         BorderFactory.createTitledBorder("这里使用标签显示HTML结果"),  
  77.                         BorderFactory.createEmptyBorder(10,10,10,10)));  
  78.         rightPanel.add(theLabel);  
  79.           
  80.         setBorder(BorderFactory.createEmptyBorder(10,10,10,10));  
  81.         add(leftPanel);  
  82.         add(Box.createRigidArea(new Dimension(10,0)));  
  83.         add(rightPanel);  
  84.     }  
  85. /** 
  86.  *方法说明:事件监听,当用户点击按钮触发 
  87.  *输入参数: 
  88.  *返回类型: 
  89.  */  
  90.     public void actionPerformed(ActionEvent e) {  
  91.         theLabel.setText(htmlTextArea.getText());  
  92.     }  
  93. /** 
  94.  *方法说明:主方法 
  95.  *输入参数: 
  96.  *返回类型: 
  97.  */  
  98.     public static void main(String[] args) {  
  99.   
  100.         JFrame.setDefaultLookAndFeelDecorated(true);  
  101.   
  102.         //创建窗体   
  103.         JFrame frame = new JFrame("HtmlDemo");  
  104.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  105.   
  106.         //创建面板   
  107.         JComponent newContentPane = new HtmlDemo();  
  108.         newContentPane.setOpaque(true);  
  109.         frame.setContentPane(newContentPane);  
  110.   
  111.         //显示窗体   
  112.         frame.pack();  
  113.         frame.setVisible(true);  
  114.     }  
  115. }  


view plaincopy to clipboardprint?
  1. package test19;  
  2.   
  3. import java.awt.*;  
  4. import java.awt.event.*;  
  5. import javax.swing.JPopupMenu;  
  6. import javax.swing.JMenu;  
  7. import javax.swing.JMenuItem;  
  8. import javax.swing.JCheckBoxMenuItem;  
  9. import javax.swing.JRadioButtonMenuItem;  
  10. import javax.swing.ButtonGroup;  
  11. import javax.swing.JMenuBar;  
  12. import javax.swing.KeyStroke;  
  13. import javax.swing.ImageIcon;  
  14.   
  15. import javax.swing.JPanel;  
  16. import javax.swing.JTextArea;  
  17. import javax.swing.JScrollPane;  
  18. import javax.swing.JFrame;  
  19. /** 
  20.  * Title: 菜单演示 
  21.  * Description: 演示菜单的建立和快捷键的使用。 
  22.  * Filename: MenuDemo.java 
  23.  */  
  24.   
  25. public class MenuDemo implements ActionListener, ItemListener {  
  26.     JTextArea output;  
  27.     JScrollPane scrollPane;  
  28.     String newline = "\n";  
  29. /** 
  30.  *方法说明:组建菜单栏 
  31.  *输入参数: 
  32.  *返回类型: 
  33.  */  
  34.     public JMenuBar createMenuBar() {  
  35.         JMenuBar menuBar;  
  36.         JMenu menu, submenu;  
  37.         JMenuItem menuItem;  
  38.         JRadioButtonMenuItem rbMenuItem;  
  39.         JCheckBoxMenuItem cbMenuItem;  
  40.   
  41.         //定义菜单条   
  42.         menuBar = new JMenuBar();  
  43.   
  44.         //定义第一个菜单   
  45.         menu = new JMenu("(A)菜单");  
  46.         menu.setMnemonic(KeyEvent.VK_A);  
  47.         menuBar.add(menu);  
  48.   
  49.         //下面开始定义菜单项   
  50.           
  51.         //只有文字   
  52.         menuItem = new JMenuItem("(O)只有文本的菜单",  
  53.                                  KeyEvent.VK_O);  
  54.         //设置快捷键   
  55.         menuItem.setAccelerator(KeyStroke.getKeyStroke(  
  56.                 KeyEvent.VK_1, ActionEvent.ALT_MASK));  
  57.         //添加监听   
  58.         menuItem.addActionListener(this);  
  59.         menu.add(menuItem);  
  60.         //有图标还有文字   
  61.         ImageIcon icon = createImageIcon("images/middle.gif");  
  62.         menuItem = new JMenuItem("(B)有图标和文字的菜单", icon);  
  63.         menuItem.setMnemonic(KeyEvent.VK_B);  
  64.         menuItem.addActionListener(this);  
  65.         menu.add(menuItem);  
  66.         //只有图标   
  67.         menuItem = new JMenuItem(icon);  
  68.         menuItem.setMnemonic(KeyEvent.VK_D);  
  69.         menuItem.addActionListener(this);  
  70.         menu.add(menuItem);  
  71.   
  72.         //定义一组radio button(单选按钮)菜单   
  73.         menu.addSeparator();  
  74.         ButtonGroup group = new ButtonGroup();  
  75.   
  76.         rbMenuItem = new JRadioButtonMenuItem("(R)使用radio的菜单");  
  77.         rbMenuItem.setSelected(true);  
  78.         rbMenuItem.setMnemonic(KeyEvent.VK_R);  
  79.         group.add(rbMenuItem);  
  80.         rbMenuItem.addActionListener(this);  
  81.         menu.add(rbMenuItem);  
  82.   
  83.         rbMenuItem = new JRadioButtonMenuItem("(d)另外一个radio菜单");  
  84.         rbMenuItem.setMnemonic(KeyEvent.VK_D);  
  85.         group.add(rbMenuItem);  
  86.         rbMenuItem.addActionListener(this);  
  87.         menu.add(rbMenuItem);  
  88.   
  89.         //定义一组check box(检查盒)菜单  
  90.         menu.addSeparator();  
  91.         cbMenuItem = new JCheckBoxMenuItem("(C)使用检查盒的菜单");  
  92.         cbMenuItem.setMnemonic(KeyEvent.VK_C);  
  93.         cbMenuItem.addItemListener(this);  
  94.         menu.add(cbMenuItem);  
  95.   
  96.         cbMenuItem = new JCheckBoxMenuItem("(H)另外一个检查盒");  
  97.         cbMenuItem.setMnemonic(KeyEvent.VK_H);  
  98.         cbMenuItem.addItemListener(this);  
  99.         menu.add(cbMenuItem);  
  100.   
  101.         //定义一个带子菜单   
  102.         menu.addSeparator();  
  103.         submenu = new JMenu("(S)带有子菜单");  
  104.         submenu.setMnemonic(KeyEvent.VK_S);  
  105.         //定义子菜单   
  106.         menuItem = new JMenuItem("这是子菜单");  
  107.         //定义快捷键   
  108.         menuItem.setAccelerator(KeyStroke.getKeyStroke(  
  109.                 KeyEvent.VK_2, ActionEvent.ALT_MASK));  
  110.         menuItem.addActionListener(this);  
  111.         submenu.add(menuItem);  
  112.   
  113.         menuItem = new JMenuItem("子菜单项");  
  114.         menuItem.addActionListener(this);  
  115.         submenu.add(menuItem);  
  116.         menu.add(submenu);  
  117.   
  118.         //定义第二个菜单   
  119.         menu = new JMenu("(N)第二个菜单");  
  120.         menu.setMnemonic(KeyEvent.VK_N);  
  121.         menuBar.add(menu);  
  122.   
  123.         return menuBar;  
  124.     }  
  125. /** 
  126.  *方法说明:构建面板 
  127.  *输入参数: 
  128.  *返回类型: 
  129.  */  
  130.     public Container createContentPane() {  
  131.         //构造一个面板   
  132.         JPanel contentPane = new JPanel(new BorderLayout());  
  133.         contentPane.setOpaque(true);  
  134.   
  135.         //定义一个文本域   
  136.         output = new JTextArea(530);  
  137.         output.setEditable(false);  
  138.         scrollPane = new JScrollPane(output);  
  139.   
  140.         //将文本域添加到面板中   
  141.         contentPane.add(scrollPane, BorderLayout.CENTER);  
  142.   
  143.         return contentPane;  
  144.     }  
  145. /** 
  146.  *方法说明:构建弹出菜单 
  147.  *输入参数: 
  148.  *返回类型: 
  149.  */  
  150.     public void createPopupMenu() {  
  151.         JMenuItem menuItem;  
  152.   
  153.         //构件弹出菜单   
  154.         JPopupMenu popup = new JPopupMenu();  
  155.         ImageIcon openicon = createImageIcon("images/Open16.gif");  
  156.         menuItem = new JMenuItem("打开文件",openicon);  
  157.         menuItem.addActionListener(this);  
  158.         popup.add(menuItem);  
  159.         ImageIcon saveicon = createImageIcon("images/Save16.gif");  
  160.         menuItem = new JMenuItem("保存文件",saveicon);  
  161.         menuItem.addActionListener(this);  
  162.         popup.add(menuItem);  
  163.   
  164.         //添加一个监听给文本域,以便点击右键时响应   
  165.         MouseListener popupListener = new PopupListener(popup);  
  166.         output.addMouseListener(popupListener);  
  167.     }  
  168. /** 
  169.  *方法说明:监听普通的菜单选择 
  170.  *输入参数:ActionEvent e 事件 
  171.  *返回类型: 
  172.  */  
  173.     public void actionPerformed(ActionEvent e) {  
  174.         JMenuItem source = (JMenuItem)(e.getSource());  
  175.         String s = "监测事件。"  
  176.                    + newline  
  177.                    + "    事件源: " + source.getText()  
  178.                    + " (选择对象" + getClassName(source) + ")";  
  179.         output.append(s + newline);  
  180.     }  
  181. /** 
  182.  *方法说明:监听检查盒菜单选择项 
  183.  *输入参数:ItemEvent e 检查盒触发的事件 
  184.  *返回类型: 
  185.  */  
  186.     public void itemStateChanged(ItemEvent e) {  
  187.         JMenuItem source = (JMenuItem)(e.getSource());  
  188.         String s = "菜单项监听"  
  189.                    + newline  
  190.                    + "    事件源: " + source.getText()  
  191.                    + " (选择对象 " + getClassName(source) + ")"  
  192.                    + newline  
  193.                    + "    新的状态: "  
  194.                    + ((e.getStateChange() == ItemEvent.SELECTED) ?  
  195.                      "选择":"不选择");  
  196.         output.append(s + newline);  
  197.     }  
  198. /** 
  199.  *方法说明:获得类的名字 
  200.  *输入参数: 
  201.  *返回类型: 
  202.  */  
  203.     protected String getClassName(Object o) {  
  204.         String classString = o.getClass().getName();  
  205.         int dotIndex = classString.lastIndexOf(".");  
  206.         return classString.substring(dotIndex+1);  
  207.     }  
  208. /** 
  209.  *方法说明:根据路径查找图片 
  210.  *输入参数:String path 图片的路径 
  211.  *返回类型:ImageIcon 图片对象 
  212.  */  
  213.     protected static ImageIcon createImageIcon(String path) {  
  214.         java.net.URL imgURL = MenuDemo.class.getResource(path);  
  215.         if (imgURL != null) {  
  216.             return new ImageIcon(imgURL);  
  217.         } else {  
  218.             System.err.println("Couldn't find file: " + path);  
  219.             return null;  
  220.         }  
  221.     }  
  222.   
  223.     public static void main(String[] args) {  
  224.         JFrame.setDefaultLookAndFeelDecorated(true);  
  225.   
  226.         //创建一个窗体   
  227.         JFrame frame = new JFrame("MenuDemo");  
  228.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  229.   
  230.         //创建菜单,并添加到面板中   
  231.         MenuDemo demo = new MenuDemo();  
  232.         frame.setJMenuBar(demo.createMenuBar());  
  233.         frame.setContentPane(demo.createContentPane());  
  234.   
  235.         //生成弹出菜单   
  236.         demo.createPopupMenu();  
  237.   
  238.         //显示窗体   
  239.         frame.setSize(450260);  
  240.         frame.setVisible(true);  
  241.     }  
  242. //弹出菜单监听类   
  243.     class PopupListener extends MouseAdapter {  
  244.         JPopupMenu popup;  
  245.   
  246.         PopupListener(JPopupMenu popupMenu) {  
  247.             popup = popupMenu;  
  248.         }  
  249.           
  250.         public void mousePressed(MouseEvent e) {  
  251.             maybeShowPopup(e);  
  252.         }  
  253.   
  254.         public void mouseReleased(MouseEvent e) {  
  255.             maybeShowPopup(e);  
  256.         }  
  257.   
  258.         private void maybeShowPopup(MouseEvent e) {  
  259.             if (e.isPopupTrigger()) {  
  260.                 popup.show(e.getComponent(),  
  261.                            e.getX(), e.getY());  
  262.             }  
  263.         }  
  264.     }  
  265. }  


view plaincopy to clipboardprint?
  1. package test20;  
  2.   
  3. import javax.swing.JToolBar;  
  4. import javax.swing.JButton;  
  5. import javax.swing.ImageIcon;  
  6.   
  7. import javax.swing.JFrame;  
  8. import javax.swing.JTextArea;  
  9. import javax.swing.JScrollPane;  
  10. import javax.swing.JPanel;  
  11.   
  12. import java.net.URL;  
  13.   
  14. import java.awt.*;  
  15. import java.awt.event.*;  
  16. /** 
  17.  * Title: 工具栏演示 
  18.  * Description: 提供一个工具栏,包括“打开”、“保存”、“搜索”工具按钮 
  19.  * Filename: ToolBarDemo.java 
  20.  */  
  21. public class ToolBarDemo extends JPanel  
  22.                          implements ActionListener {  
  23.   
  24.     private static final long serialVersionUID = 1L;  
  25.     protected JTextArea textArea;  
  26.     protected String newline = "\n";  
  27.     static final private String OPEN = "OPEN";  
  28.     static final private String SAVE = "SAVE";  
  29.     static final private String SEARCH = "SEARCH";  
  30. /** 
  31.  *方法说明:构造器 
  32.  *输入参数: 
  33.  *返回类型: 
  34.  */  
  35.     public ToolBarDemo() {  
  36.         super(new BorderLayout());  
  37.   
  38.         //创建工具栏   
  39.         JToolBar toolBar = new JToolBar();  
  40.         addButtons(toolBar);  
  41.   
  42.         //创建一个文本域,用来输出一些信息   
  43.         textArea = new JTextArea(1530);  
  44.         textArea.setEditable(false);  
  45.         JScrollPane scrollPane = new JScrollPane(textArea);  
  46.   
  47.         //安放成员   
  48.         setPreferredSize(new Dimension(450110));  
  49.         add(toolBar, BorderLayout.PAGE_START);  
  50.         add(scrollPane, BorderLayout.CENTER);  
  51.     }  
  52. /** 
  53.  *方法说明:构建工具栏 
  54.  *输入参数:JToolBar toolBar 工具条 
  55.  *返回类型: 
  56.  */  
  57.     protected void addButtons(JToolBar toolBar) {  
  58.         JButton button = null;  
  59.   
  60.         //第一个按钮,“打开”   
  61.         button = makeNavigationButton("Open16", OPEN,  
  62.                                       "打开一个文件!",  
  63.                                       "打开");  
  64.         toolBar.add(button);  
  65.   
  66.         //第二个按钮,“保存”   
  67.         button = makeNavigationButton("Save16", SAVE,  
  68.                                       "保存当前文件!",  
  69.                                       "保存");  
  70.         toolBar.add(button);  
  71.   
  72.         //第三个按钮,“搜索”   
  73.         button = makeNavigationButton("Search16", SEARCH,  
  74.                                       "搜索文件中的字符!",  
  75.                                       "搜索");  
  76.         toolBar.add(button);  
  77.     }  
  78. /** 
  79.  *方法说明:构造工具栏上的按钮 
  80.  *输入参数: 
  81.  *返回类型: 
  82.  */  
  83.     protected JButton makeNavigationButton(String imageName,  
  84.                                            String actionCommand,  
  85.                                            String toolTipText,  
  86.                                            String altText) {  
  87.         //搜索图片   
  88.         String imgLocation = "images/"  
  89.                              + imageName  
  90.                              + ".gif";  
  91.         URL imageURL = ToolBarDemo.class.getResource(imgLocation);  
  92.   
  93.         //初始化工具按钮   
  94.         JButton button = new JButton();  
  95.         //设置按钮的命令   
  96.         button.setActionCommand(actionCommand);  
  97.         //设置提示信息   
  98.         button.setToolTipText(toolTipText);  
  99.         button.addActionListener(this);  
  100.           
  101.         if (imageURL != null) {                      //找到图像  
  102.             button.setIcon(new ImageIcon(imageURL));  
  103.         } else {                                     //没有图像  
  104.             button.setText(altText);  
  105.             System.err.println("Resource not found: "  
  106.                                + imgLocation);  
  107.         }  
  108.   
  109.         return button;  
  110.     }  
  111. /** 
  112.  *方法说明:事件监听 
  113.  *输入参数: 
  114.  *返回类型: 
  115.  */  
  116.     public void actionPerformed(ActionEvent e) {  
  117.         String cmd = e.getActionCommand();  
  118.         String description = null;  
  119.   
  120.         if (OPEN.equals(cmd)) { //点击第一个按钮  
  121.             description = "打开一个文件操作!";  
  122.         } else if (SAVE.equals(cmd)) { //点击第二个按钮  
  123.             description = "保存文件操作";  
  124.         } else if (SEARCH.equals(cmd)) { //点击第三个按钮  
  125.             description = "搜索字符操作";  
  126.         }  
  127.   
  128.         displayResult("如果这里是真正的程序,你将进入: "  
  129.                         + description);  
  130.     }  
  131.   
  132.     protected void displayResult(String actionDescription) {  
  133.         textArea.append(actionDescription + newline);  
  134.     }  
  135.   
  136.     public static void main(String[] args) {  
  137.         JFrame.setDefaultLookAndFeelDecorated(true);  
  138.   
  139.         //定义窗体   
  140.         JFrame frame = new JFrame("ToolBarDemo");  
  141.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  142.   
  143.         //定义面板   
  144.         ToolBarDemo newContentPane = new ToolBarDemo();  
  145.         newContentPane.setOpaque(true);  
  146.         frame.setContentPane(newContentPane);  
  147.   
  148.         //显示窗体   
  149.         frame.pack();  
  150.         frame.setVisible(true);  
  151.     }  
view plaincopy to clipboardprint?
  1. package test21;  
  2.   
  3. import javax.swing.JDesktopPane;  
  4. import javax.swing.JMenu;  
  5. import javax.swing.JMenuItem;  
  6. import javax.swing.JMenuBar;  
  7. import javax.swing.JFrame;  
  8. import javax.swing.KeyStroke;  
  9.   
  10. import java.awt.event.*;  
  11. import java.awt.*;  
  12. /** 
  13.  * Title: 内部窗体演示 
  14.  * Description: 这是演示一个内部窗体。可以选择“新文档”菜单不停的生成内部窗体。 
  15.  * Filename:  
  16.  */  
  17. public class InternalFrameDemo extends JFrame  
  18.                                implements ActionListener {  
  19.     
  20.     private static final long serialVersionUID = 1L;  
  21.     JDesktopPane desktop;  
  22. /** 
  23.  *方法说明:构造器,添加窗体成员 
  24.  *输入参数: 
  25.  *返回类型: 
  26.  */  
  27.     public InternalFrameDemo() {  
  28.         super("InternalFrameDemo");  
  29.   
  30.         //这里设置了一个比较大的窗体,给四周只留了50px的边界   
  31.         int inset = 50;  
  32.         Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();  
  33.         setBounds(inset, inset,  
  34.                   screenSize.width  - inset*2,  
  35.                   screenSize.height - inset*2);  
  36.           
  37.         //定义界面   
  38.         desktop = new JDesktopPane(); //桌面面板  
  39.         createFrame(); //创建第一个内部窗体  
  40.         setContentPane(desktop);//将桌面添加到窗体  
  41.         setJMenuBar(createMenuBar());  
  42.   
  43.         //设置托拽模式   
  44.         desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);  
  45.     }  
  46. /** 
  47.  *方法说明:组建菜单 
  48.  *输入参数: 
  49.  *返回类型: 
  50.  */  
  51.     protected JMenuBar createMenuBar() {  
  52.         JMenuBar menuBar = new JMenuBar();  
  53.   
  54.         //定义一个菜单   
  55.         JMenu menu = new JMenu("文件");  
  56.         menu.setMnemonic(KeyEvent.VK_D);  
  57.         menuBar.add(menu);  
  58.   
  59.         //定义“新文档”菜单   
  60.         JMenuItem menuItem = new JMenuItem("新文档");  
  61.         menuItem.setMnemonic(KeyEvent.VK_N);  
  62.         menuItem.setAccelerator(KeyStroke.getKeyStroke(  
  63.                 KeyEvent.VK_N, ActionEvent.ALT_MASK));  
  64.         menuItem.setActionCommand("new");  
  65.         menuItem.addActionListener(this);  
  66.         menu.add(menuItem);  
  67.   
  68.         //定义“退出”菜单   
  69.         menuItem = new JMenuItem("退出");  
  70.         menuItem.setMnemonic(KeyEvent.VK_Q);  
  71.         menuItem.setAccelerator(KeyStroke.getKeyStroke(  
  72.                 KeyEvent.VK_Q, ActionEvent.ALT_MASK));  
  73.         menuItem.setActionCommand("quit");  
  74.         menuItem.addActionListener(this);  
  75.         menu.add(menuItem);  
  76.   
  77.         return menuBar;  
  78.     }  
  79. /** 
  80.  *方法说明:事件监听,对选择的菜单做出反映 
  81.  *输入参数:ActionEvent e 事件 
  82.  *返回类型: 
  83.  */  
  84.     public void actionPerformed(ActionEvent e) {  
  85.         if ("new".equals(e.getActionCommand())) { //新文档  
  86.             createFrame();  
  87.         } else { //退出  
  88.             quit();  
  89.         }  
  90.     }  
  91. /** 
  92.  *方法说明:调用MyInternalFrame类创建新的内部窗体, 
  93.  *输入参数: 
  94.  *返回类型: 
  95.  */  
  96.     protected void createFrame() {  
  97.         MyInternalFrame frame = new MyInternalFrame();  
  98.           
  99.         frame.setVisible(true);   
  100.         desktop.add(frame);  
  101.         try {  
  102.             frame.setSelected(true);  
  103.         } catch (java.beans.PropertyVetoException e) {}  
  104.     }  
  105. /** 
  106.  *方法说明:退出程序 
  107.  *输入参数: 
  108.  *返回类型: 
  109.  */  
  110.     protected void quit() {  
  111.         System.exit(0);  
  112.     }  
  113. /** 
  114.  *方法说明:主方法 
  115.  *输入参数: 
  116.  *返回类型: 
  117.  */  
  118.     public static void main(String[] args) {  
  119.         JFrame.setDefaultLookAndFeelDecorated(true);  
  120.   
  121.         //建立一个内部窗体   
  122.         InternalFrameDemo frame = new InternalFrameDemo();  
  123.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  124.   
  125.         //显示窗体   
  126.         frame.setVisible(true);  
  127.     }  
  128. }  

view plaincopy to clipboardprint?
  1. package test21;  
  2.   
  3. import javax.swing.JInternalFrame;  
  4. import javax.swing.JTextArea;  
  5.   
  6. /** 
  7.  * Title: 内部窗体 
  8.  * Description: 生成一个内部窗体,提供InternalFrameDemo类使用 
  9.  * Filename: MyInternalFrame.java 
  10.  */  
  11. public class MyInternalFrame extends JInternalFrame {  
  12.     
  13.     private static final long serialVersionUID = 1L;  
  14.     static int openFrameCount = 0;  
  15.     static final int xOffset = 30, yOffset = 30;  
  16.   
  17.     public MyInternalFrame() {  
  18.         super("文档 #" + (++openFrameCount),   
  19.               true//可变尺寸  
  20.               true//有关闭按钮  
  21.               true//有最大化按钮  
  22.               true);//最小化按钮  
  23.   
  24.         //给内部窗体添加一个文本域   
  25.         JTextArea j = new JTextArea(5,20);  
  26.         getContentPane().add(j);  
  27.         //设置内部窗体的大小   
  28.         setSize(300,300);  
  29.   
  30.         //设置内部窗体的显示位置   
  31.         setLocation(xOffset*openFrameCount, yOffset*openFrameCount);  
  32.     }  
  33. }  


view plaincopy to clipboardprint?
  1. package test22;  
  2.   
  3. import java.awt.*;  
  4. import javax.swing.*;  
  5. import javax.swing.event.*;  
  6.   
  7. /** 
  8.  * Title: 分割面板 
  9.  * Description: 演示将面板分割成左右两部分 
  10.  * Fiename:SplitPaneDemo.java  
  11.  */  
  12. public class SplitPaneDemo implements ListSelectionListener {  
  13.     private String[] imageNames={"Bird.gif","Cat.gif","Dog.gif","Pig.gif"};  
  14.     private JLabel picture;  
  15.     private JList list;  
  16.     private JSplitPane splitPane;  
  17. /** 
  18.  *方法说明:构造器,定义了所有要使用的构件 
  19.  *输入参数: 
  20.  *返回类型: 
  21.  */  
  22.     public SplitPaneDemo() {  
  23.           
  24.         //创建一个图像名称的列表,设置为单选方式   
  25.         list = new JList(imageNames);  
  26.         list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  
  27.         list.setSelectedIndex(0);  
  28.         list.addListSelectionListener(this);  
  29.         JScrollPane listScrollPane = new JScrollPane(list);  
  30.   
  31.         //获取默认的图片   
  32.         ImageIcon firstImage = createImageIcon("images/" +  
  33.                                      (String)imageNames[0]);  
  34.         if (firstImage != null) {  
  35.             picture = new JLabel(firstImage);  
  36.             picture.setPreferredSize(new Dimension(firstImage.getIconWidth(),  
  37.                                                    firstImage.getIconHeight()));  
  38.         } else {  
  39.             picture = new JLabel((String)imageNames[0]);  
  40.         }  
  41.         JScrollPane pictureScrollPane = new JScrollPane(picture);  
  42.   
  43.         //创建一个水平分割的面板,定义了两个面板的名字。  
  44.         splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,  
  45.                                    listScrollPane, pictureScrollPane);  
  46.         splitPane.setOneTouchExpandable(true);  
  47.         splitPane.setDividerLocation(150);  
  48.   
  49.         //定义面板的最小尺寸   
  50.         Dimension minimumSize = new Dimension(10050);  
  51.         listScrollPane.setMinimumSize(minimumSize);  
  52.         pictureScrollPane.setMinimumSize(minimumSize);  
  53.   
  54.         //定义初始尺寸   
  55.         splitPane.setPreferredSize(new Dimension(400200));  
  56.     }  
  57. /** 
  58.  *方法说明:获得这个分割的面板 
  59.  *输入参数: 
  60.  *返回类型:JSplitPane 对象 
  61.  */  
  62.     public JSplitPane getSplitPane() {  
  63.         return splitPane;  
  64.     }  
  65. /** 
  66.  *方法说明:列表监听事件处理 
  67.  *输入参数:ListSelectionEvent e 列表选择事件 
  68.  *返回类型: 
  69.  */  
  70.     public void valueChanged(ListSelectionEvent e) {  
  71.         if (e.getValueIsAdjusting())  
  72.             return;  
  73.   
  74.         JList theList = (JList)e.getSource();  
  75.         if (theList.isSelectionEmpty()) {  
  76.             picture.setIcon(null);  
  77.             picture.setText(null);  
  78.         } else {  
  79.             int index = theList.getSelectedIndex();  
  80.             ImageIcon newImage = createImageIcon("images/" +  
  81.                                      (String)imageNames[index]);  
  82.             picture.setIcon(newImage);  
  83.             if (newImage != null) {  
  84.                 picture.setText(null);  
  85.                 picture.setPreferredSize(new Dimension(newImage.getIconWidth(),  
  86.                                                        newImage.getIconHeight() ));  
  87.             } else {  
  88.                 picture.setText("Image not found: "  
  89.                                 + (String)imageNames[index]);  
  90.             }  
  91.             picture.revalidate();  
  92.         }  
  93.     }  
  94. /** 
  95.  *方法说明:根据路径获取图形对象 
  96.  *输入参数:String path 图片路径 
  97.  *返回类型:ImageIcon 图片对象 
  98.  */  
  99.     protected static ImageIcon createImageIcon(String path) {  
  100.         java.net.URL imgURL = SplitPaneDemo.class.getResource(path);  
  101.         if (imgURL != null) {  
  102.             return new ImageIcon(imgURL);  
  103.         } else {  
  104.             System.err.println("Couldn't find file: " + path);  
  105.             return null;  
  106.         }  
  107.     }  
  108. /** 
  109.  *方法说明:主方法 
  110.  *输入参数: 
  111.  *返回类型: 
  112.  */  
  113.     public static void main(String[] args) {  
  114.         JFrame.setDefaultLookAndFeelDecorated(true);  
  115.   
  116.         //定义窗体   
  117.         JFrame frame = new JFrame("SplitPaneDemo");  
  118.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  119.         SplitPaneDemo splitPaneDemo = new SplitPaneDemo();  
  120.         frame.getContentPane().add(splitPaneDemo.getSplitPane());  
  121.   
  122.         //显示窗体   
  123.         frame.pack();  
  124.         frame.setVisible(true);  
  125.     }  
  126. }  


view plaincopy to clipboardprint?
  1. package test23;  
  2.   
  3. import java.awt.*;  
  4. import java.awt.event.*;  
  5. import javax.swing.*;  
  6. import javax.swing.event.*;  
  7. /** 
  8.  * Title: 滑动杆演示 
  9.  * Description: 使用滑动杆控制定时器,来控制图片的播放速度 
  10.  * Filename: SliderDemo.java 
  11.  */  
  12. public class SliderDemo extends JPanel  
  13.                         implements ActionListener,  
  14.                                    WindowListener,  
  15.                                    ChangeListener {  
  16.   
  17.     private static final long serialVersionUID = 1L;  
  18.     //设置图片的参数   
  19.     static final int FPS_MIN = 0//设置最小值  
  20.     static final int FPS_MAX = 30//设置最大值  
  21.     static final int FPS_INIT = 15;  //初始数值  
  22.     int frameNumber = 0;  
  23.     int NUM_FRAMES = 14;  
  24.     ImageIcon[] images = new ImageIcon[NUM_FRAMES];  
  25.     int delay;  
  26.     Timer timer;  
  27.     boolean frozen = false;  
  28.   
  29.     //这个标签用来显示这只小狗   
  30.     JLabel picture;  
  31.   
  32.     public SliderDemo() {  
  33.         setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));  
  34.   
  35.         delay = 1000 / FPS_INIT;  
  36.   
  37.         //信息提示标签   
  38.         JLabel sliderLabel = new JLabel("调整滑动杆,改变播放速度!", JLabel.CENTER);  
  39.         sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);  
  40.   
  41.         //创建一个滑动杆,定义了最小值和最大值以及初始值  
  42.         JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL,  
  43.                                               FPS_MIN, FPS_MAX, FPS_INIT);  
  44.         framesPerSecond.addChangeListener(this);  
  45.   
  46.         //定义滑动杆参数   
  47.         framesPerSecond.setMajorTickSpacing(10);//每10刻度标注一次  
  48.         framesPerSecond.setMinorTickSpacing(1);//最小刻度为1  
  49.         framesPerSecond.setPaintTicks(true);//绘制滑动杆上的刻度  
  50.         framesPerSecond.setPaintLabels(true);//在滑动过程中绘制滑动块  
  51.         framesPerSecond.setBorder(  
  52.                 BorderFactory.createEmptyBorder(0,0,10,0));  
  53.   
  54.         //定义一个用来显示图片的标签   
  55.         picture = new JLabel();  
  56.         picture.setHorizontalAlignment(JLabel.CENTER);  
  57.         picture.setAlignmentX(Component.CENTER_ALIGNMENT);  
  58.         picture.setBorder(BorderFactory.createCompoundBorder(  
  59.                 BorderFactory.createLoweredBevelBorder(),  
  60.                 BorderFactory.createEmptyBorder(10,10,10,10)));  
  61.         updatePicture(0); //显示第一张图  
  62.   
  63.         //将成员添加到面板上   
  64.         add(sliderLabel);  
  65.         add(framesPerSecond);  
  66.         add(picture);  
  67.         setBorder(BorderFactory.createEmptyBorder(10,10,10,10));  
  68.   
  69.         //设置一个定时器来触发这个事件   
  70.         timer = new Timer(delay, this);  
  71.         timer.setInitialDelay(delay * 7); //在每轮循环停顿时间  
  72.         timer.setCoalesce(true);//设置重复循环  
  73.     }  
  74. /** 
  75.  *方法说明:添加一个窗体监听 
  76.  *输入参数: 
  77.  *返回类型: 
  78.  */  
  79.     void addWindowListener(Window w) {  
  80.         w.addWindowListener(this);  
  81.     }  
  82.     public void windowIconified(WindowEvent e) {  
  83.         stopAnimation();  
  84.     }  
  85.     public void windowDeiconified(WindowEvent e) {  
  86.         startAnimation();  
  87.     }  
  88.     public void windowOpened(WindowEvent e) {}  
  89.     public void windowClosing(WindowEvent e) {}  
  90.     public void windowClosed(WindowEvent e) {}  
  91.     public void windowActivated(WindowEvent e) {}  
  92.     public void windowDeactivated(WindowEvent e) {}  
  93. /** 
  94.  *方法说明:对滑动杆进行监听 
  95.  *输入参数:ChangeEvent e 滑动杆变动事件 
  96.  *返回类型: 
  97.  */  
  98.     public void stateChanged(ChangeEvent e) {  
  99.         JSlider source = (JSlider)e.getSource();  
  100.         if (!source.getValueIsAdjusting()) {  
  101.             int fps = (int)source.getValue();//获得滑动杆的值  
  102.             if (fps == 0) {  
  103.                 if (!frozen) stopAnimation();  
  104.             } else {  
  105.                 delay = 1000 / fps;  
  106.                 timer.setDelay(delay);  
  107.                 timer.setInitialDelay(delay * 10);  
  108.                 if (frozen) startAnimation();  
  109.             }  
  110.         }  
  111.     }  
  112. /** 
  113.  *方法说明:开始动画 
  114.  *输入参数: 
  115.  *返回类型: 
  116.  */  
  117.     public void startAnimation() {  
  118.         timer.start();  
  119.         frozen = false;  
  120.     }  
  121. /** 
  122.  *方法说明:停止动画 
  123.  *输入参数: 
  124.  *返回类型: 
  125.  */  
  126.     public void stopAnimation() {  
  127.         timer.stop();  
  128.         frozen = true;  
  129.     }  
  130. /** 
  131.  *方法说明:事件监听 
  132.  *输入参数: 
  133.  *返回类型: 
  134.  */  
  135.     public void actionPerformed(ActionEvent e) {  
  136.         //改变图片帧   
  137.         if (frameNumber == (NUM_FRAMES - 1)) {  
  138.             frameNumber = 0;  
  139.         } else {  
  140.             frameNumber++;  
  141.         }  
  142.   
  143.         updatePicture(frameNumber); //显示下张图  
  144.   
  145.         if ( frameNumber==(NUM_FRAMES - 1)  
  146.           || frameNumber==(NUM_FRAMES/2 - 1) ) {  
  147.             timer.restart();  
  148.         }  
  149.     }  
  150. /** 
  151.  *方法说明:绘制当前帧 
  152.  *输入参数:int frameNum 图片帧数数 
  153.  *返回类型: 
  154.  */  
  155.     protected void updatePicture(int frameNum) {  
  156.         if (images[frameNumber] == null) {  
  157.             images[frameNumber] = createImageIcon("images/doggy/T"  
  158.                                                   + frameNumber  
  159.                                                   + ".gif");  
  160.         }  
  161.   
  162.         //绘制图片   
  163.         if (images[frameNumber] != null) {  
  164.             picture.setIcon(images[frameNumber]);  
  165.         } else { //如果没有发现图片  
  166.             picture.setText("image #" + frameNumber + " not found");  
  167.         }  
  168.     }  
  169. /** 
  170.  *方法说明:获取图片 
  171.  *输入参数:String path 图片路径 
  172.  *返回类型:ImageIcon 图片对象 
  173.  */  
  174.     protected static ImageIcon createImageIcon(String path) {  
  175.         java.net.URL imgURL = SliderDemo.class.getResource(path);  
  176.         if (imgURL != null) {  
  177.             return new ImageIcon(imgURL);  
  178.         } else {  
  179.             System.err.println("Couldn't find file: " + path);  
  180.             return null;  
  181.         }  
  182.     }  
  183. /** 
  184.  *方法说明:主方法 
  185.  *输入参数: 
  186.  *返回类型: 
  187.  */  
  188.     public static void main(String[] args) {  
  189.         JFrame.setDefaultLookAndFeelDecorated(true);  
  190.   
  191.         //定义窗体   
  192.         JFrame frame = new JFrame("SliderDemo");  
  193.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  194.   
  195.         //实例化本类   
  196.         SliderDemo animator = new SliderDemo();  
  197.         animator.setOpaque(true);  
  198.         frame.setContentPane(animator);  
  199.   
  200.         //显示窗体   
  201.         frame.pack();  
  202.         frame.setVisible(true);  
  203.         animator.startAnimation();   
  204.     }  
  205. }  


view plaincopy to clipboardprint?
  1. package test24;  
  2.   
  3. import java.awt.*;  
  4. import javax.swing.*;  
  5. import javax.swing.event.*;  
  6.   
  7. /** 
  8.  * Title: 颜色选择器 
  9.  * Description: 演示一个颜色选择器,可以从样本中选择,可以使用HSB模式和RGB模式 
  10.  * Filename: ColorChooserDemo.java 
  11.  */  
  12.   
  13. public class ColorChooserDemo extends JPanel  
  14.                               implements ChangeListener {  
  15.   
  16.      
  17.     private static final long serialVersionUID = 1L;  
  18.     protected JColorChooser tcc;  
  19.     protected JLabel banner;  
  20.   
  21.     public ColorChooserDemo() {  
  22.         super(new BorderLayout());  
  23.   
  24.         //设置一个标签,做广告的。也用来显示用户选择的颜色。   
  25.         banner = new JLabel("欢迎使用颜色选择器!",  
  26.                             JLabel.CENTER);  
  27.         banner.setForeground(Color.yellow);  
  28.         banner.setBackground(Color.blue);  
  29.         banner.setOpaque(true);  
  30.         banner.setFont(new Font("SansSerif", Font.BOLD, 24));  
  31.         banner.setPreferredSize(new Dimension(10065));  
  32.   
  33.         JPanel bannerPanel = new JPanel(new BorderLayout());  
  34.         bannerPanel.add(banner, BorderLayout.CENTER);  
  35.         bannerPanel.setBorder(BorderFactory.createTitledBorder("广告"));  
  36.   
  37.         //设置选择颜色选择器   
  38.         tcc = new JColorChooser(banner.getForeground());//设置初始颜色  
  39.         tcc.getSelectionModel().addChangeListener(this);//给所有模式添加监听  
  40.         tcc.setBorder(BorderFactory.createTitledBorder("选择颜色"));  
  41.   
  42.         add(bannerPanel, BorderLayout.CENTER);  
  43.         add(tcc, BorderLayout.PAGE_END);  
  44.     }  
  45. /** 
  46.  *方法说明:事件监听。用户选择颜色触发 
  47.  *输入参数:ChangeEvent e 用户选择事件 
  48.  *返回类型: 
  49.  */  
  50.     public void stateChanged(ChangeEvent e) {  
  51.         Color newColor = tcc.getColor();//获取用户选择的颜色  
  52.         banner.setForeground(newColor);  
  53.     }  
  54. /** 
  55.  *方法说明:主方法 
  56.  *输入参数: 
  57.  *返回类型: 
  58.  */  
  59.     public static void main(String[] args) {  
  60.         JFrame.setDefaultLookAndFeelDecorated(true);  
  61.   
  62.         //创建窗体   
  63.         JFrame frame = new JFrame("ColorChooserDemo");  
  64.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  65.   
  66.         //创建面板容器   
  67.         JComponent newContentPane = new ColorChooserDemo();  
  68.         newContentPane.setOpaque(true);  
  69.         frame.setContentPane(newContentPane);  
  70.   
  71.         //显示窗体   
  72.         frame.pack();  
  73.         frame.setVisible(true);  
  74.     }  
  75. }  


view plaincopy to clipboardprint?
  1. package test25;  
  2.   
  3. import javax.swing.JTable;  
  4. import javax.swing.table.AbstractTableModel;  
  5.   
  6. import javax.swing.JScrollPane;  
  7. import javax.swing.JFrame;  
  8. import java.awt.*;  
  9. import java.awt.event.*;  
  10. /** 
  11.  * Title: 自己定义的表格 
  12.  * Description: 继承AbstractTableModel类,实现自己的表格 
  13.  * Flename: MyTableDemo.java 
  14.  */  
  15. public class MyTableDemo extends JFrame {  
  16.   
  17.     
  18.     private static final long serialVersionUID = 1L;  
  19.     public MyTableDemo() {  
  20.         super("MyTableDemo");  
  21.         //声明自己的表格,并添加到JTable中   
  22.         MyTableModel myModel = new MyTableModel();  
  23.         JTable table = new JTable(myModel);  
  24.         table.setPreferredScrollableViewportSize(new Dimension(50070));  
  25.   
  26.         //将表格添加到可滚动的面板   
  27.         JScrollPane scrollPane = new JScrollPane(table);  
  28.   
  29.         //将滚动面板添加到窗体   
  30.         getContentPane().add(scrollPane, BorderLayout.CENTER);  
  31.         //添加监听   
  32.         addWindowListener(new WindowAdapter() {  
  33.             public void windowClosing(WindowEvent e) {  
  34.                 System.exit(0);  
  35.             }  
  36.         });  
  37.     }  
  38. /** 
  39.  * Title: 定义自己的表格模式 
  40.  * Description: 通过继承AbstractTableModel类来定义自己的表格模式, 
  41.  *    这里使得第三个以后才可以编辑 
  42.  */  
  43.     class MyTableModel extends AbstractTableModel {  
  44.       
  45.     private static final long serialVersionUID = 1L;  
  46.         //定义表头   
  47.         final String[] columnNames = {"姓名",   
  48.                                       "性别",  
  49.                                       "学历",  
  50.                                       "年龄",  
  51.                                       "是否已婚"};  
  52.         //初始化表数据   
  53.         final Object[][] data = {  
  54.             {"张三""男",   
  55.              "大本"new Integer(25), new Boolean(false)},  
  56.             {"李四""男",   
  57.              "大本"new Integer(33), new Boolean(true)},  
  58.             {"王五""男",  
  59.              "高中"new Integer(20), new Boolean(false)},  
  60.             {"赵倩""女",  
  61.              "大专"new Integer(26), new Boolean(true)},  
  62.             {"周大""男",  
  63.              "大本"new Integer(24), new Boolean(false)}  
  64.         };  
  65. /** 
  66.  *方法说明:继承AbstractTableModel必须实现的方法 
  67.  *输入参数: 
  68.  *返回类型:int 列数 
  69.  */  
  70.         public int getColumnCount() {  
  71.             return columnNames.length;  
  72.         }  
  73. /** 
  74.  *方法说明:继承AbstractTableModel必须实现的方法 
  75.  *输入参数: 
  76.  *返回类型:int 列数 
  77.  */          
  78.         public int getRowCount() {  
  79.             return data.length;  
  80.         }  
  81. /** 
  82.  *方法说明:继承AbstractTableModel必须实现的方法 
  83.  *输入参数: 
  84.  *返回类型:String 列名 
  85.  */  
  86.         public String getColumnName(int col) {  
  87.             return columnNames[col];  
  88.         }  
  89. /** 
  90.  *方法说明:继承AbstractTableModel必须实现的方法,获取表格中的数据 
  91.  *输入参数:int row 行数 
  92.  *输入参数:int col 列数 
  93.  *返回类型:Object 数据对象 
  94.  */  
  95.         public Object getValueAt(int row, int col) {  
  96.             return data[row][col];  
  97.         }  
  98. /** 
  99.  *方法说明:实现这个方法使得最后一列不是显示true和false。而是使用检查盒 
  100.  *输入参数: 
  101.  *返回类型: 
  102.  */  
  103.         @SuppressWarnings("unchecked")  
  104.         public Class getColumnClass(int c) {  
  105.             return getValueAt(0, c).getClass();  
  106.         }  
  107. /** 
  108.  *方法说明:这个方法不一定需要实现。这里是为了定义可编辑的列 
  109.  *输入参数: 
  110.  *返回类型:boolean 是否可编辑 
  111.  */  
  112.         public boolean isCellEditable(int row, int col) {  
  113.             if (col < 2) {   
  114.                 return false;  
  115.             } else {  
  116.                 return true;  
  117.             }  
  118.         }  
  119. /** 
  120.  *方法说明:实现此方法,获得编辑数据。 
  121.  *输入参数: 
  122.  *返回类型: 
  123.  */  
  124.         public void setValueAt(Object value, int row, int col) {  
  125.                 System.out.println("修改数据位置: " + row + "," + col  
  126.                                    + " 新数据为: " + value);  
  127.   
  128.             data[row][col] = value;  
  129.             fireTableCellUpdated(row, col);  
  130.   
  131.                 System.out.println("表格新数据:");  
  132.                 printDebugData();  
  133.   
  134.         }  
  135. /** 
  136.  *方法说明:输出表格中的新数据 
  137.  *输入参数: 
  138.  *返回类型: 
  139.  */  
  140.         private void printDebugData() {  
  141.             int numRows = getRowCount();  
  142.             int numCols = getColumnCount();  
  143.   
  144.             for (int i=0; i < numRows; i++) {  
  145.                 System.out.print("    行 " + i + ":");  
  146.                 for (int j=0; j < numCols; j++) {  
  147.                     System.out.print("  " + data[i][j]);  
  148.                 }  
  149.                 System.out.println();  
  150.             }  
  151.             System.out.println("--------------------------");  
  152.         }  
  153.     }  
  154. /** 
  155.  *方法说明:主方法 
  156.  *输入参数: 
  157.  *返回类型: 
  158.  */  
  159.     public static void main(String[] args) {  
  160.         JFrame.setDefaultLookAndFeelDecorated(true);  
  161.         MyTableDemo frame = new MyTableDemo();  
  162.         frame.pack();  
  163.         frame.setVisible(true);  
  164.     }  
  165. }  


view plaincopy to clipboardprint?
  1. package test26;  
  2.   
  3. import java.awt.*;   
  4. import javax.swing.*;  
  5. /** 
  6.  * Title: 基本图形的绘制 
  7.  * Description: 本实例演示绘制四边型、圆角矩形、椭圆等基本的图形。  
  8.  * Filename: Sample.java 
  9.  */  
  10. public class Sample extends JFrame {   
  11.   
  12.     private static final long serialVersionUID = 1L;  
  13. /** 
  14.  *方法说明:主方法 
  15.  *输入参数: 
  16.  *返回类型: 
  17.  */    
  18.   public static void main(String[] args){  
  19.     Sample sl = new Sample();  
  20.     sl.update();  
  21.   }  
  22. /** 
  23.  *方法说明:构造器,显示窗体 
  24.  *输入参数: 
  25.  *返回类型: 
  26.  */    
  27.   @SuppressWarnings("deprecation")  
  28. Sample(){  
  29.     super("Sample");  
  30.     setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);  
  31.     setSize(310,160);  
  32.     show();  
  33.   }  
  34. /** 
  35.  *方法说明:更新画面 
  36.  *输入参数: 
  37.  *返回类型: 
  38.  */    
  39.   public void update(){  
  40.     repaint();  
  41.   }  
  42. /** 
  43.  *方法说明:绘制画面 
  44.  *输入参数: 
  45.  *返回类型: 
  46.  */    
  47.   public void paint(Graphics g) {   
  48.      int [] x={10,30,80,50,10};  
  49.      int [] y={90,140,120,100,90};  
  50.      g.setColor(Color.cyan);        
  51.      //绘制竖格线   
  52.      for (int i=0; i<=300; i+=10) {   
  53.         g.drawLine(i,0,i,150);      
  54.      }  
  55.      //绘制横格线    
  56.      for (int i=0; i<=150; i+=10) {   
  57.         g.drawLine(0,i,300,i);      
  58.      }  
  59.      g.setColor(Color.black);       
  60.      //有角矩形,起始点(10,30),宽80,高50   
  61.      g.drawRect(10,30,80,50);       
  62.      //圆角矩形,起始点(110,30),宽80,高50,角(a=20,b=10)  
  63.      g.drawRoundRect(110,30,80,50,20,10);  
  64.      //多角边   
  65.      g.drawPolygon(x,y,5);  
  66.      //椭圆,圆心(110,90)、a=80,b=50          
  67.      g.drawOval(110,90,80,50);   
  68.      //一条弧,圆心(219,30)、a=80,b=50 角度在0-90之间   
  69.      g.drawArc(210,30,80,50,0,90);  
  70.      //扇面,圆心(219,90)、a=80,b=50 角度在0-90之间   
  71.      g.fillArc(210,90,80,50,0,90);  
  72.   }  
  73. }   


view plaincopy to clipboardprint?
  1. package test27;  
  2.   
  3.  import java.awt.*;  
  4. import javax.swing.*;   
  5.    
  6.  public class Func extends JFrame{   
  7.   
  8.     private static final long serialVersionUID = 1L;  
  9. /** 
  10.  *方法说明:主方法 
  11.  *输入参数: 
  12.  *返回类型: 
  13.  */  
  14.   public static void main(String[] args){  
  15.     Func db = new Func();  
  16.     db.update();  
  17.   }  
  18. /** 
  19.  *方法说明:构造器,显示窗体 
  20.  *输入参数: 
  21.  *返回类型: 
  22.  */   
  23.   @SuppressWarnings("deprecation")  
  24. Func(){  
  25.     super("Function");  
  26.     setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);  
  27.     setSize(310,310);  
  28.     show();  
  29.   }  
  30. /** 
  31.  *方法说明:更新画面 
  32.  *输入参数: 
  33.  *返回类型: 
  34.  */   
  35.   public void update(){  
  36.      repaint();  
  37.   }  
  38. /** 
  39.  *方法说明:转换坐标点 
  40.  *输入参数: 
  41.  *返回类型: 
  42.  */  
  43.   double f(double x) {    
  44.        return (Math.sin(2*x)+Math.cos(3*x));   
  45.   }  
  46. /** 
  47.  *方法说明:绘制坐标图 
  48.  *输入参数: 
  49.  *返回类型: 
  50.  */    
  51.   public void paint(Graphics g) {   
  52.        double x0,x1,y0,y1,xd,yd;   
  53.        double max=5.0;   
  54.        int w,h,hw,hh;   
  55.        //获取屏幕的尺寸   
  56.        w=getSize().width;   
  57.        h=getSize().height;  
  58.        hw=w/2; hh=h/2;  
  59.        //在屏幕上输出字符   
  60.        g.drawString("Sin[2x]+Cos[3x]",10,40);  
  61.        g.setColor(Color.red);    
  62.        g.drawString("0",hw+5,hh+12);   
  63.        g.drawString(""+max,hw-20,40);  
  64.        g.drawString(""+max,w-20,hh+12);  
  65.        //绘制X轴坐标   
  66.        g.drawLine(0,hh,w,hh);  
  67.        //绘制Y轴坐标   
  68.        g.drawLine(hw,0,hw,h);  
  69.        xd=2*max/w;//计算X增量  
  70.        yd=hh/max; //计算y增量   
  71.        g.setColor(Color.blue);  
  72.        //使用增量绘制一小段线,最终组成曲线图形。    
  73.        for (int x=0 ; x<w-1; x++) {   
  74.           x0=-max+x*xd; y0=f(x0)*yd;   
  75.           x1=x0+xd;     y1=f(x1)*yd;   
  76.           g.drawLine(x,(int)(hh-y0),x+1,(int)(hh-y1));  
  77.        }   
  78.   }  
  79.  } //end  


view plaincopy to clipboardprint?
  1. package test28;  
  2.   
  3. import javax.swing.*;  
  4. import java.awt.*;  
  5. /** 
  6.  * Title: 图片的处理, 
  7.  * Description: 将图片放大和翻转显示 
  8.  * Filename: ImgDemo.java 
  9.  */  
  10. class ImgDemo extends JFrame {  
  11.   
  12.     private static final long serialVersionUID = 1L;  
  13. Image image;  
  14. /** 
  15.  *方法说明:构造器,显示窗体 
  16.  *输入参数: 
  17.  *返回类型: 
  18.  */  
  19. @SuppressWarnings("deprecation")  
  20. ImgDemo(String filename) {  
  21. setTitle("drawImage Example");  
  22. try {  
  23.   image = getToolkit().getImage(filename);  
  24.   setIconImage(image);  
  25. catch (Exception e) {  
  26.   e.printStackTrace();  
  27. }  
  28.   
  29. setSize(600250);  
  30. setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);  
  31. show();  
  32. }  
  33. /** 
  34.  *方法说明:绘制图像 
  35.  *输入参数: 
  36.  *返回类型: 
  37.  */  
  38. public void paint(Graphics g) {  
  39.   Insets insets = getInsets();  
  40.   int x = insets.left, y = insets.top;  
  41.   //获取图片尺寸   
  42.   int w = image.getWidth(this);  
  43.   int h = image.getHeight(this);  
  44.   //正常显示图片   
  45.   g.drawImage(image, x, y, this);   
  46.   //缩小图形   
  47.   g.drawRect(x, y, w/4+1, h/4+1);//画一个框  
  48.   g.drawImage(image, x+1, y+1, w/4, h/4this);  
  49.   //水平翻转   
  50.   g.drawImage(image, x+w, y, x+2*w, y+h, w, 00, h, this);  
  51. }  
  52. /** 
  53.  *方法说明:主方法,接受参数 
  54.  *输入参数: 
  55.  *返回类型: 
  56.  */  
  57. public static void main(String[] args) {  
  58.  if (args.length == 1) {  
  59.   new ImgDemo(args[0]);  
  60.  } else {  
  61.   System.err.println("usage: java ImgDemo images-name ");  
  62.  }  
  63. }  
  64. }  


view plaincopy to clipboardprint?
  1. package test29;  
  2.   
  3.  import java.awt.*;   
  4.  import java.awt.event.*;  
  5.  import java.util.*;  
  6.  import javax.swing.*;  
  7. import javax.swing.Timer;  
  8. /** 
  9.  * Title: 时钟 
  10.  * Description: 本实例演示使用图形绘制一个图形时钟 
  11.  * Filename: Clock.java 
  12.  */  
  13.  public class Clock extends JFrame implements ActionListener{   
  14.   
  15.     private static final long serialVersionUID = 1L;  
  16.     Timer timer;  
  17.     int x,y,old_X,old_Y, r,x0,y0,w,h,ang;   
  18.     int sdo,mdo,hdo,old_M,old_H;   
  19.     TimeZone tz =TimeZone.getTimeZone("JST");  
  20.     final double RAD=Math.PI/180.0;   
  21.   
  22.   public static void main(String[] args){  
  23.     @SuppressWarnings("unused")  
  24.     Clock cl = new Clock();  
  25.   }  
  26. /** 
  27.  *方法说明:实现ActionListener类必须过载的方法 
  28.  *输入参数: 
  29.  *返回类型: 
  30.  */   
  31.   public void actionPerformed(ActionEvent e) {  
  32.             timer.restart();  
  33.     }  
  34. /** 
  35.  *方法说明:构造器,显示窗体,并添加了一个秒表 
  36.  *输入参数: 
  37.  *返回类型: 
  38.  */   
  39.   @SuppressWarnings("deprecation")  
  40. Clock(){  
  41.     super("Clock");  
  42.     setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);  
  43.     setBackground(new Color(0,0,192));  
  44.     setSize(300,300);  
  45.     show();  
  46.     int delay = 1000;  
  47.     //窗体添加事件监听,监听秒表的触发   
  48.     ActionListener taskPerformer = new ActionListener() {  
  49.       public void actionPerformed(ActionEvent evt) {  
  50.          repaint();  
  51.       }  
  52.     };  
  53.     new Timer(delay, taskPerformer).start();  
  54.   }  
  55. /** 
  56.  *方法说明:绘制图形 
  57.  *输入参数: 
  58.  *返回类型: 
  59.  */  
  60.   public void paint( Graphics g ) {   
  61.      Insets insets = getInsets();  
  62.      int L0 = (insets.left)/2, T0 = (insets.top)/2;  
  63.      int hh,mm,ss;   
  64.      String st;   
  65.      h=getSize().height;  
  66.      //绘制圆形   
  67.      g.setColor(Color.white);   
  68.      g.drawOval(L0+30,T0+30,h-60,h-60);  
  69.      g.drawOval(L0+32,T0+32,h-64,h-64);  
  70.      r=h/2-30;  
  71.      x0=30+r-5+L0;  
  72.      y0=30+r-5-T0;  
  73.      ang=60;  
  74.      for (int i=1; i<=12; i++) {   
  75.         x=(int)((r+10)*Math.cos(RAD*ang)+x0);  
  76.         y=(int)((r+10)*Math.sin(RAD*ang)+y0);  
  77.         g.drawString(""+i,x,h-y);  
  78.         ang-=30;  
  79.      }   
  80.      x0=30+r+L0; y0=30+r+T0;  
  81.      //获取时间   
  82.      Calendar now=Calendar.getInstance();  
  83.      hh=now.get(Calendar.HOUR_OF_DAY);//小时  
  84.      mm=now.get(Calendar.MINUTE);//分钟   
  85.      ss=now.get(Calendar.SECOND);// 秒  
  86.      g.setColor(Color.pink);   
  87.      g.fillRect(L0,T0,60,28);//填充的矩形  
  88.      g.setColor(Color.blue);   
  89.      if (hh < 10) st="0"+hh;     else st=""+hh;   
  90.      if (mm < 10) st=st+":0"+mm; else st=st+":"+mm;   
  91.      if (ss < 10) st=st+":0"+ss; else st=st+":"+ss;   
  92.      g.drawString(st,L0,T0+25);  
  93.      //计算时间和图形的关系   
  94.      sdo=90-ss*6;  
  95.      mdo=90-mm*6;  
  96.      hdo=90-hh*30-mm/2;  
  97.      //擦除秒针   
  98.      if (old_X > 0) {  
  99.         g.setColor(getBackground());  
  100.         g.drawLine(x0,y0,old_X,(h-old_Y));  
  101.      } else {   
  102.         old_M=mdo;  
  103.         old_H=hdo;  
  104.      }   
  105.      //绘制秒针   
  106.      g.setColor(Color.yellow);   
  107.      x=(int)((r-8)*Math.cos(RAD*sdo)+x0);   
  108.      y=(int)((r-8)*Math.sin(RAD*sdo)+y0)-2*T0;   
  109.      g.drawLine(x0,y0,x,(h-y));  
  110.        
  111.      old_X=x;   
  112.      old_Y=y;   
  113.      //擦除分针和时针   
  114.      if (mdo != old_M) {  
  115.        line(g,old_M,(int)(r*0.7),getBackground());  
  116.        old_M=mdo;  
  117.      }   
  118.      if (hdo != old_H) {  
  119.        line(g,old_H,(int)(r*0.5),getBackground());  
  120.        old_H=hdo;  
  121.      }   
  122.      //绘制分针   
  123.      line(g,mdo,(int)(r*0.7),Color.green);  
  124.      //绘制时针   
  125.      line(g,hdo,(int)(r*0.5),Color.red);  
  126.   } // end paint    
  127. /** 
  128.  *方法说明:绘制线,用于绘制时针和分针 
  129.  *输入参数: 
  130.  *返回类型: 
  131.  */  
  132.    public void line(Graphics g, int t, int n, Color c) {   
  133.       int [] xp = new int[4];  
  134.       int [] yp = new int[4];   
  135.       xp[0]=x0;  
  136.       yp[0]=y0;  
  137.       xp[1]=  (int)((n-10)*Math.cos(RAD*(t-4))+x0);   
  138.       yp[1]=h-(int)((n-10)*Math.sin(RAD*(t-4))+y0);   
  139.       xp[2]=  (int)( n    *Math.cos(RAD* t   )+x0);   
  140.       yp[2]=h-(int)( n    *Math.sin(RAD* t   )+y0);   
  141.       xp[3]=  (int)((n-10)*Math.cos(RAD*(t+4))+x0);   
  142.       yp[3]=h-(int)((n-10)*Math.sin(RAD*(t+4))+y0);   
  143.       g.setColor(c);   
  144.       g.fillPolygon(xp,yp,4);  
  145.    }  
  146.  }  


view plaincopy to clipboardprint?
  1. package test30;  
  2.   
  3.   
  4.  import java.awt.*;   
  5.  import java.awt.event.*;   
  6.  import javax.swing.*;  
  7.  /** 
  8.  * Title: 正方体框图 
  9.  * Description: 绘制一个边框的正方体,获取鼠标事件根据鼠标的位置旋转方体。 
  10.  * Filename: Gr3d1m.java 
  11.  */  
  12.  public class Gr3d1m extends JFrame   
  13.      implements MouseListener,MouseMotionListener {   
  14.      int doX,doY;  
  15.      int angX=30,angY=30;  
  16.      Cube data = new Cube();  
  17.      Color [] Col={Color.gray,Color.cyan,Color.green,   
  18.                    Color.red,Color.white,Color.orange,   
  19.                    Color.magenta,Color.pink};   
  20. /** 
  21.  *方法说明:主方法 
  22.  *输入参数: 
  23.  *返回类型: 
  24.  */  
  25.   public static void main(String[] args){  
  26.      Gr3d1m G3 = new Gr3d1m();  
  27.   }  
  28. /** 
  29.  *方法说明:构造器 
  30.  *输入参数: 
  31.  *返回类型: 
  32.  */  
  33.   public  Gr3d1m() {  
  34.      setTitle("3D cube Frame");  
  35.      setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);  
  36.      addMouseListener(this);  
  37.      addMouseMotionListener(this);  
  38.      setBackground(new Color(128,128,255));  
  39.      setSize(350,350);  
  40.      show();  
  41.   }  
  42. /** 
  43.  *方法说明:鼠标按下事件,获取鼠标位置 
  44.  *输入参数: 
  45.  *返回类型: 
  46.  */  
  47.   public void mousePressed(MouseEvent e) {  
  48.      doX=e.getX();  
  49.      doY=e.getY();  
  50.   }  
  51. /** 
  52.  *方法说明:鼠标托拽事件,改变鼠标位置,重画屏幕 
  53.  *输入参数: 
  54.  *返回类型: 
  55.  */    
  56.   public void mouseDragged(MouseEvent e)  {  
  57.      angX=angX+e.getY()-doY;   
  58.      angY=angY+e.getX()-doX;  
  59.      doX=e.getX(); doY=e.getY();  
  60.      repaint();   
  61.   }  
  62. /* 以下是实现MouseListener和MouseMotionListener必须重载的方法*/  
  63.   public void mouseReleased(MouseEvent e) { }  
  64.   public void mouseClicked(MouseEvent e)  { }  
  65.   public void mouseEntered(MouseEvent e)  { }  
  66.   public void mouseExited(MouseEvent e)   { }  
  67.   public void mouseMoved(MouseEvent e)    { }   
  68. /** 
  69.  *方法说明:绘制图形 
  70.  *输入参数: 
  71.  *返回类型: 
  72.  */  
  73.   public void paint( Graphics g ) {  
  74.      delDeaw(g);  
  75.      for (int i=0; i<data.x.length; i++) {   
  76.         drawPG(g, data.x[i], data.y[i], data.z[i],   
  77.                150,150,Col[i]);   
  78.      }   
  79.      g.setColor(Color.yellow);   
  80.      g.drawString("X="+angX%360+" Y="+angY%360,   
  81.                   10,getSize().height-30);   
  82.   }  
  83. /** 
  84.  *方法说明:擦拭屏幕,使用背景色覆盖原来的图形 
  85.  *输入参数: 
  86.  *返回类型: 
  87.  */  
  88.   public void delDeaw(Graphics g){  
  89.      Insets insets = getInsets();  
  90.      int L0 = insets.left, T0 = insets.top;  
  91.     g.setColor(new Color(128,128,255));   
  92.     g.fillRect(L0,T0,L0+350,T0+350);  
  93.   }  
  94. /** 
  95.  *方法说明:绘制方体 
  96.  *输入参数: 
  97.  *返回类型: 
  98.  */  
  99.   public void drawPG(Graphics g,double []x,double []y,   
  100.                      double []z,int xp,int yp,Color co) {   
  101.      double x1,y1,z0;   
  102.      int len=x.length;   
  103.      int [] xx=new int [len];   
  104.      int [] yy=new int [len];   
  105.      final double RAD=Math.PI/180.0;  
  106.      double a=angX*RAD;  
  107.      double b=angY*RAD;   
  108.      double sinA=Math.sin(a),sinB=Math.sin(b);  
  109.      double cosA=Math.cos(a),cosB=Math.cos(b);  
  110.      for (int i=0; i<len; i++) {   
  111.         x1= x[i]*cosB+z[i]*sinB;  
  112.         z0=-x[i]*sinB+z[i]*cosB;   
  113.         y1= y[i]*cosA-  z0*sinA;  
  114.         xx[i]=xp+(int)Math.rint(x1);   
  115.         yy[i]=yp-(int)Math.rint(y1);   
  116.      }   
  117.      g.setColor(co);   
  118.      g.drawPolygon(xx,yy,len);//绘制多边形   
  119.   }  
  120.  }  


view plaincopy to clipboardprint?
  1. package test31;  
  2.   
  3.  import java.awt.*;   
  4.  import javax.swing.*;  
  5.  public class Gr3d4a extends Gr3d1m {  
  6.    
  7. /** 
  8.  *方法说明:主方法 
  9.  *输入参数: 
  10.  *返回类型: 
  11.  */  
  12.   public static void main(String[] args){  
  13.      Gr3d4a G3 = new Gr3d4a();  
  14.   }  
  15. /** 
  16.  *方法说明:构造器 
  17.  *输入参数: 
  18.  *返回类型: 
  19.  */  
  20.   public  Gr3d4a() {  
  21.      setTitle("3D cube box");  
  22.      setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);  
  23.      addMouseListener(this);  
  24.      addMouseMotionListener(this);  
  25.      setBackground(new Color(128,128,255));  
  26.      setSize(350,350);  
  27.      show();  
  28.   }  
  29. /** 
  30.  *方法说明:绘制正方体盒子,过载Gr3d1m中的方法 
  31.  *输入参数: 
  32.  *返回类型: 
  33.  */  
  34.   public void drawPG(Graphics g,double []x,double []y,   
  35.                      double []z,int xp,int yp,Color co) {   
  36.      double x1,y1,z0;   
  37.      int len=x.length;  
  38.      double [] xw=new double[len];  
  39.      double [] yw=new double[len];  
  40.      int    [] xx=new int   [len];   
  41.      int    [] yy=new int   [len];   
  42.      final double RAD=Math.PI/180.0;  
  43.      double a=angX*RAD;   
  44.      double b=angY*RAD;  
  45.      double sinA=Math.sin(a),sinB=Math.sin(b);  
  46.      double cosA=Math.cos(a),cosB=Math.cos(b);  
  47.      for (int i=0; i<len; i++) {   
  48.         x1= x[i]*cosB+z[i]*sinB;  
  49.         z0=-x[i]*sinB+z[i]*cosB;   
  50.         y1= y[i]*cosA-  z0*sinA;  
  51.         xx[i]=xp+(int)Math.rint(x1);  
  52.         yy[i]=yp-(int)Math.rint(y1);  
  53.         xw[i]=x1; yw[i]=y1;   
  54.      }   
  55.      if (Hvec(xw,yw) > 0) {  
  56.         g.setColor(co);  
  57.         g.fillPolygon(xx,yy,len);//填充的多边形  
  58.      }   
  59.   }  
  60. /** 
  61.  *方法说明:消影处理,如果平面被遮蔽将不被绘制 
  62.  *输入参数: 
  63.  *返回类型: 
  64.  */  
  65.   double Hvec(double []x,double []y) {   
  66.     return(x[0]*(y[1]-y[2])+x[1]*(y[2]-y[0])+x[2]*(y[0]-y[1]));   
  67.   }  
  68.  }  

view plaincopy to clipboardprint?
  1. package test32;  
  2.   
  3. import java.util.*;  
  4. import java.io.*;  
  5. /** 
  6.  * Title: 标注输入输出 
  7.  * Description: 接收标准的键盘输入,和输出到屏幕。 
  8.  * Filename: standerdIO.java 
  9.  */  
  10. public class standerdIO{  
  11. /** 
  12.  *方法说明:主方法 
  13.  *输入参数: 
  14.  *返回类型: 
  15.  */  
  16.  public static void main(String[] args){  
  17.    Vector<Object> vTemp = new Vector<Object>();  
  18.    boolean flag = true;  
  19.    while(flag){  
  20.      System.out.print("input>");  
  21.      String sTemp ="";    
  22.      //读取输入,System.in表示接收键盘输入流   
  23.      BufferedReader stdin  = new BufferedReader(new InputStreamReader(System.in));  
  24.      try{  
  25.      //读取一行输入   
  26.       sTemp = stdin.readLine();  
  27.      }catch(IOException ie){  
  28.        System.err.println("IO error!");  
  29.      }  
  30.      //解析输入命令   
  31.      String sCMD="";  
  32.      String sContext="";  
  33.      int point = sTemp.indexOf(":");  
  34.      if(point==-1){  
  35.          sCMD = sTemp.trim();  
  36.      }else{  
  37.        sCMD = sTemp.substring(0,point);  
  38.        sContext = sTemp.substring(point+1);  
  39.      }  
  40.      //添加数据   
  41.      if(sCMD.equalsIgnoreCase("in")){  
  42.        if(sContext.equals("")){  
  43.          System.err.println("this command format is errer!");  
  44.        }else{  
  45.          vTemp.addElement(sContext);  
  46.        }     
  47.      }//查看结果   
  48.      else if(sCMD.equalsIgnoreCase("out")){  
  49.        for(int i=0;i<vTemp.size();i++){  
  50.          System.out.println(i+":"+vTemp.elementAt(i));  
  51.        }  
  52.      }//结束   
  53.      else if(sCMD.equalsIgnoreCase("quit")){  
  54.        flag=false;  
  55.      }  
  56.      else{  
  57.        System.err.println("this command don't run!");  
  58.        System.out.print("use:   in:command");  
  59.        System.out.print("use:   out");  
  60.      }  
  61.    }  
  62.  }  
  63. }  


view plaincopy to clipboardprint?
  1. package test33;  
  2.   
  3. import java.io.*;  
  4. /** 
  5.  * Title: 读取和写入文件 
  6.  * Description: 使用字节流方式操作文件,读取和写入文件。 
  7.  * Filename: CopyBytes.java 
  8.  */  
  9. public class BAKCopyBytes {  
  10. /** 
  11.  *方法说明:主方法 
  12.  *输入参数: 
  13.  *返回类型: 
  14.  */  
  15.     public static void main(String[] args) throws IOException {  
  16.         String sFile;  
  17.         String oFile;  
  18.         if(args.length<2){  
  19.           System.out.println("USE:java CopyBytes source file | object file");  
  20.           return;  
  21.         }else{  
  22.           sFile = args[0];  
  23.           oFile = args[1];  
  24.         }  
  25.         try{  
  26.           File inputFile = new File(sFile);//定义读取源文件  
  27.           File outputFile = new File(oFile);//定义拷贝目标文件  
  28.           //定义输入文件流   
  29.           FileInputStream in = new FileInputStream(inputFile);  
  30.           //将文件输入流构造到缓存   
  31.           BufferedInputStream bin = new BufferedInputStream(in);  
  32.           //定义输出文件流   
  33.           FileOutputStream out = new FileOutputStream(outputFile);  
  34.           //将输出文件流构造到缓存   
  35.           BufferedOutputStream bout = new BufferedOutputStream(out);  
  36.           int c;  
  37.           //循环读取文件和写入文件   
  38.           while ((c = bin.read()) != -1)  
  39.              bout.write(c);  
  40.           //关闭输入输出流,释放资源   
  41.           bin.close();  
  42.           bout.close();  
  43.         }catch(IOException e){  
  44.           //文件操作,捕获IO异常。   
  45.           System.err.println(e);  
  46.         }  
  47.     }  
  48. }  


view plaincopy to clipboardprint?
  1. package test33;  
  2.   
  3. import java.io.*;  
  4. /** 
  5.  * Title: 读取和写入文件 
  6.  * Description: 使用字节流方式操作文件,读取和写入文件。 
  7.  * Filename: CopyBytes.java 
  8.  */  
  9. public class CopyBytes {  
  10. /** 
  11.  *方法说明:主方法 
  12.  *输入参数: 
  13.  *返回类型: 
  14.  */  
  15.     public static void main(String[] args) throws IOException {  
  16.         String sFile;  
  17.         String oFile;  
  18.         if(args.length<2){  
  19.           System.out.println("USE:java CopyBytes source file | object file");  
  20.           return;  
  21.         }else{  
  22.           sFile = args[0];  
  23.           oFile = args[1];  
  24.         }  
  25.         try{  
  26.           File inputFile = new File(sFile);//定义读取源文件  
  27.           File outputFile = new File(oFile);//定义拷贝目标文件  
  28.           //定义输入文件流   
  29.           FileInputStream in = new FileInputStream(inputFile);  
  30.           //将文件输入流构造到缓存   
  31.           BufferedInputStream bin = new BufferedInputStream(in);  
  32.           //定义输出文件流   
  33.           FileOutputStream out = new FileOutputStream(outputFile);  
  34.           //将输出文件流构造到缓存   
  35.           BufferedOutputStream bout = new BufferedOutputStream(out);  
  36.           int c;  
  37.           //循环读取文件和写入文件   
  38.           while ((c = bin.read()) != -1)  
  39.              bout.write(c);  
  40.           //关闭输入输出流,释放资源   
  41.           bin.close();  
  42.           bout.close();  
  43.         }catch(IOException e){  
  44.           //文件操作,捕获IO异常。   
  45.           System.err.println(e);  
  46.         }  
  47.     }  
  48. }  


view plaincopy to clipboardprint?
  1. package test34;  
  2.   
  3. import java.io.*;  
  4.   
  5. /** 
  6.  * Title: 文件的读取和写入(字符) 
  7.  * Description: 使用FileReader和FileWriter类,采用字符文件访问方式操作文件。 
  8.  * Filename:  
  9.  */  
  10. public class BAKCopyChar {  
  11. /** 
  12.  *方法说明:主方法 
  13.  *输入参数: 
  14.  *返回类型: 
  15.  */  
  16.     public static void main(String[] args) throws IOException {  
  17.         String sFile;  
  18.         String oFile;  
  19.         if(args.length<2){  
  20.           System.out.println("USE:java CopyChar source file | object file");  
  21.           return;  
  22.         }else{  
  23.           sFile = args[0];  
  24.           oFile = args[1];  
  25.         }  
  26.         try{  
  27.           File inputFile   = new File(sFile);//定义读取的文件源  
  28.           File outputFile = new File(oFile);//定义拷贝的目标文件  
  29.           //定义输入文件流   
  30.           FileReader in   = new FileReader(inputFile);  
  31.           //将文件输入流构造到缓存   
  32.           BufferedReader bin = new BufferedReader(in);  
  33.           //定义输出文件流   
  34.           FileWriter out  = new FileWriter(outputFile);  
  35.           //将输出文件流构造到缓存   
  36.           BufferedWriter bout = new BufferedWriter(out);  
  37.           int c;  
  38.           //循环读取和输入文件。   
  39.           while ((c = bin.read()) != -1)  
  40.              bout.write(c);  
  41.           bin.close();  
  42.           bout.close();  
  43.         }catch(IOException e){  
  44.           //文件操作,捕获IO异常。   
  45.           System.err.println(e);  
  46.         }  
  47.     }  
  48. }  


view plaincopy to clipboardprint?
  1. package test34;  
  2.   
  3. import java.io.*;  
  4.   
  5. /** 
  6.  * Title: 文件的读取和写入(字符) 
  7.  * Description: 使用FileReader和FileWriter类,采用字符文件访问方式操作文件。 
  8.  * Filename:  
  9.  */  
  10. public class CopyChar {  
  11. /** 
  12.  *方法说明:主方法 
  13.  *输入参数: 
  14.  *返回类型: 
  15.  */  
  16.     public static void main(String[] args) throws IOException {  
  17.         String sFile;  
  18.         String oFile;  
  19.         if(args.length<2){  
  20.           System.out.println("USE:java CopyChar source file | object file");  
  21.           return;  
  22.         }else{  
  23.           sFile = args[0];  
  24.           oFile = args[1];  
  25.         }  
  26.         try{  
  27.           File inputFile   = new File(sFile);//定义读取的文件源  
  28.           File outputFile = new File(oFile);//定义拷贝的目标文件  
  29.           //定义输入文件流   
  30.           FileReader in   = new FileReader(inputFile);  
  31.           //将文件输入流构造到缓存   
  32.           BufferedReader bin = new BufferedReader(in);  
  33.           //定义输出文件流   
  34.           FileWriter out  = new FileWriter(outputFile);  
  35.           //将输出文件流构造到缓存   
  36.           BufferedWriter bout = new BufferedWriter(out);  
  37.           int c;  
  38.           //循环读取和输入文件。   
  39.           while ((c = bin.read()) != -1)  
  40.              bout.write(c);  
  41.           bin.close();  
  42.           bout.close();  
  43.         }catch(IOException e){  
  44.           //文件操作,捕获IO异常。   
  45.           System.err.println(e);  
  46.         }  
  47.     }  
  48. }  


view plaincopy to clipboardprint?
  1. package test35;  
  2.   
  3. import java.io.*;  
  4. import java.util.*;  
  5. /** 
  6.  * Title: 文件操作 
  7.  * Description: 演示文件的删除和获取文件的信息 
  8.  * Filename:  
  9.  */  
  10. public class fileOperation{  
  11. /** 
  12.  *方法说明:删除文件 
  13.  *输入参数:String fileName 要删除的文件名 
  14.  *返回类型:boolean 成功为true 
  15.  */  
  16.   public boolean delFile(String fileName){  
  17.     try{  
  18.       //删除文件   
  19.       boolean success = (new File(fileName)).delete();  
  20.       if (!success) {  
  21.          System.out.println("delete file error!");  
  22.          return false;  
  23.       }else{  
  24.          return true;  
  25.       }  
  26.     }catch(Exception e){  
  27.       System.out.println(e);  
  28.       return false;  
  29.     }  
  30.   }  
  31. /** 
  32.  *方法说明:获取文件信息 
  33.  *输入参数:String Name 文件名 
  34.  *返回类型:String[] 文件信息数组 
  35.  */  
  36.   public String[] getFileInfo(String Name){  
  37.     try{  
  38.       File file = new File(Name);  
  39.       //获取文件修改日期(返回的是句)   
  40.       long modifiedTime = file.lastModified();  
  41.       //获取文件长度(单位:Bite)   
  42.       long filesize = file.length();  
  43.       //测试文件是否可读   
  44.       boolean cr = file.canRead();  
  45.       //测试文件是否可写   
  46.       boolean cw = file.canWrite();  
  47.       //测试文件是否隐藏   
  48.       boolean ih = file.isHidden();  
  49.         
  50.       String[] sTemp = new String[6];  
  51.       sTemp[0] = String.valueOf(filesize);  
  52.       sTemp[1] = getDateString(modifiedTime);  
  53.       sTemp[2] = String.valueOf(cr);  
  54.       sTemp[3] = String.valueOf(cw);  
  55.       sTemp[4] = String.valueOf(ih);  
  56.       sTemp[5] = String.valueOf(file.getCanonicalPath());  
  57.       return sTemp;  
  58.     }catch(Exception e){  
  59.       System.out.println(e);  
  60.       return null;  
  61.     }  
  62.   }  
  63.   
  64. /** 
  65.  *方法说明:将毫秒数字转换为日期 
  66.  *输入参数:mill    毫秒数 
  67.  *返回类型:String 字符 格式为:yyyy-mm-dd hh:mm 
  68.  */  
  69.   public static String getDateString(long mill)  
  70.   {  
  71.     if(mill < 0return  "";  
  72.       
  73.     Date date = new Date(mill);  
  74.     Calendar rightNow = Calendar.getInstance();  
  75.     rightNow.setTime(date);  
  76.     int year = rightNow.get(Calendar.YEAR);  
  77.     int month = rightNow.get(Calendar.MONTH);  
  78.     int day = rightNow.get(Calendar.DAY_OF_MONTH);  
  79.     int hour = rightNow.get(Calendar.HOUR_OF_DAY);  
  80.     int min = rightNow.get(Calendar.MINUTE);  
  81.   
  82.     return year + "-" + (month <10 ? "0" + month : "" + month) + "-"   
  83.            +  (day <10 ? "0" + day : "" + day)  
  84.            +  (hour <10 ? "0" + hour : "" + hour)+":"  
  85.            + (min <10 ? "0" + min : "" + min);  
  86.   }  
  87. /** 
  88.  *方法说明:主方法 
  89.  *输入参数: 
  90.  *返回类型: 
  91.  */  
  92.   public static void main(String[] args){  
  93.     try{  
  94.       fileOperation fo = new fileOperation();  
  95.       if(args.length==0){  
  96.         return;  
  97.       }else{  
  98.         String cmd = args[0];  
  99.         if(cmd.equals("del")){  
  100.           boolean bdel = fo.delFile(args[1]);  
  101.           System.out.println(bdel);  
  102.         }else if(cmd.equals("info")){  
  103.           String[] sTemp = fo.getFileInfo(args[1]);  
  104.           for(int i=0;i<sTemp.length;i++)  
  105.             System.out.println(sTemp[i]);  
  106.         }  
  107.         
  108.       }  
  109.     }catch(Exception e){  
  110.       return;  
  111.     }  
  112.   }  
  113. }  


view plaincopy to clipboardprint?
  1. package test36;  
  2.   
  3. /** 
  4.  * Title: 目录操作 
  5.  * Description: 演示列目录下的文件,和移动一个目录 
  6.  * Filename: Dir.java 
  7.  */  
  8. import java.io.*;  
  9. public class Dir{  
  10.  /** 
  11.  *方法说明:实现目录列表 
  12.  *输入参数: 
  13.  *返回类型: 
  14.  */   
  15.   public String[] DirList(String pathName){  
  16.     try{  
  17.       File path = null;  
  18.       String[] fileList;  
  19.       //如果没有指定目录,则列出当前目录。   
  20.       if(pathName.equals(""))  
  21.         path = new File(".");  
  22.       else  
  23.         path = new File(pathName);  
  24.       //获取目录文件列表   
  25.       if(path.isDirectory())  
  26.         fileList = path.list();  
  27.       else  
  28.         return null;  
  29.      return fileList;  
  30.     }catch(Exception e){  
  31.       System.err.println(e);  
  32.       return null;  
  33.     }  
  34.   }  
  35. /** 
  36.  *方法说明:移动一个目录 
  37.  *输入参数:String sou 源目录, String obj 新目录 
  38.  *返回类型: 
  39.  */  
  40.   public boolean DirMove(String sou, String obj){  
  41.     try{  
  42.      //检查源文件是否存在   
  43.       boolean sexists = (new File(sou)).isDirectory();  
  44.       if(!sexists) return false;  
  45.       boolean oexists = (new File(obj)).isDirectory();  
  46.       //目标目录不存在,建立一个   
  47.       if(!oexists){  
  48.         (new File(obj)).mkdirs();  
  49.       }  
  50.      
  51.         File file = new File(sou);  
  52.         File dir = new File(obj);  
  53.         //移动目录   
  54.         boolean success = file.renameTo(new File(dir, file.getName()));  
  55.         if (!success) {  
  56.          System.out.println("copy error!");  
  57.          return false;  
  58.         }  
  59.         else return true;  
  60.     }catch(Exception e){  
  61.         System.out.println(e);  
  62.         return false;  
  63.     }  
  64.       
  65.   }  
  66.   
  67. /** 
  68.  *方法说明:主方法 
  69.  *输入参数: 
  70.  *返回类型: 
  71.  */  
  72.   public static void main(String[] args){  
  73.      Dir d = new Dir();  
  74.     if(args.length==0){  
  75.       return;  
  76.     }else{  
  77.       String cmd = args[0];  
  78.       if(cmd.equals("list")){  
  79.         if(args.length!=2return;  
  80.         String[] sTemp = d.DirList(args[1]);  
  81.         for(int i=0;i<sTemp.length;i++)  
  82.           System.out.println(sTemp[i]);  
  83.       }else if(cmd.equals("move")){  
  84.         if(args.length!=3return;            
  85.         d.DirMove(args[1],args[2]);  
  86.       }  
  87.         
  88.     }  
  89.    }  
  90. }   


view plaincopy to clipboardprint?
  1. package test37;  
  2.   
  3. import java.io.*;  
  4. /** 
  5.  * Title: 读取随机文件 
  6.  * Description: 演示使用RandomAccessFile类读取文件。 
  7.  * Filename: RandFile.java 
  8.  */  
  9. public class RandFile{  
  10. /** 
  11.  *方法说明:主方法 
  12.  *输入参数: 
  13.  *返回类型: 
  14.  */  
  15.   public static void main(String[] args){  
  16.     String sFile;  
  17.     if(args.length<1){  
  18.       System.out.println("USE:java RandFile fileName");  
  19.       return;  
  20.     }else{  
  21.       sFile = args[0];  
  22.     }  
  23.     //接受IOException异常   
  24.     try{  
  25.       //构造随机访问文件,使用可读写方式。   
  26.       RandomAccessFile rf = new  RandomAccessFile(sFile, "rw");  
  27.       for(int i = 0; i < 10; i++)  
  28.         rf.writeDouble(i*1.414);  
  29.       rf.close();  
  30.       //构造一个随机访问文件,使用只读方式   
  31.       rf = new RandomAccessFile(sFile, "rw");  
  32.       rf.seek(5*8);  
  33.       rf.writeDouble(47.0001);  
  34.       rf.close();  
  35.       //构造一个随机文件访问文件,使用只读方式。   
  36.       rf = new RandomAccessFile(sFile, "r");  
  37.       for(int i = 0; i < 10; i++)  
  38.         System.out.println("Value " + i + ": " + rf.readDouble());  
  39.       rf.close();  
  40.      }catch(IOException e){  
  41.        System.out.println(e);  
  42.      }  
  43.   }  
  44. }  


view plaincopy to clipboardprint?
  1. package test38;  
  2.   
  3. import java.io.File;   
  4. import jxl.*;  
  5. import jxl.write.*;   
  6. /** 
  7.  * Title: 操作EXCEL文件 
  8.  * Description: 本实例演示使用jxl包实现对excel文件的操作 
  9.  * Filename: myExcel.java 
  10.  */  
  11. public class myExcel{  
  12.   Workbook workbook;  
  13.   Sheet sheet;  
  14. /** 
  15.  *方法说明:写入文件操作 
  16.  *输入参数: 
  17.  *返回类型: 
  18.  */  
  19.   public void write(){  
  20.     try{  
  21.         //创建一个可写入的excel文件对象   
  22.         WritableWorkbook workbook = Workbook.createWorkbook(new File("myfile.xls"));   
  23.         //使用第一张工作表,将其命名为“午餐记录”  
  24.         WritableSheet sheet = workbook.createSheet("午餐记录"0);   
  25.         //表头   
  26.         Label label0 = new Label(00"时间");   
  27.         sheet.addCell(label0);   
  28.         Label label1 = new Label(10"姓名");   
  29.         sheet.addCell(label1);   
  30.         Label label2 = new Label(20"午餐标准");   
  31.         sheet.addCell(label2);   
  32.         Label label3 = new Label(30"实际费用");   
  33.         sheet.addCell(label3);   
  34.         //格式化日期   
  35.         jxl.write.DateFormat df = new jxl.write.DateFormat("yyyy-dd-MM  hh:mm:ss");   
  36.         jxl.write.WritableCellFormat wcfDF = new jxl.write.WritableCellFormat(df);   
  37.         jxl.write.DateTime labelDTF = new jxl.write.DateTime(01new java.util.Date(), wcfDF);   
  38.         sheet.addCell(labelDTF);  
  39.         //普通字符   
  40.         Label labelCFC = new Label(11"riverwind");   
  41.         sheet.addCell(labelCFC);   
  42.          //格式化数字   
  43.         jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");   
  44.         WritableCellFormat wcfN = new WritableCellFormat(nf);   
  45.         jxl.write.Number labelNF = new jxl.write.Number(2113.1415926, wcfN);   
  46.         sheet.addCell(labelNF);   
  47.           
  48.            
  49.         jxl.write.Number labelNNF = new jxl.write.Number(3110.50001, wcfN);   
  50.         sheet.addCell(labelNNF);   
  51.         //关闭对象,释放资源   
  52.         workbook.write();   
  53.         workbook.close();   
  54.   
  55.     }catch(Exception e){  
  56.       System.out.println(e);  
  57.     }  
  58.   }  
  59. /** 
  60.  *方法说明:读取excel文件一行数据 
  61.  *输入参数:int row指定的行数 
  62.  *返回类型:String〔〕结果数组 
  63.  */    
  64.   public String[] readLine(int row){  
  65.     try{  
  66.       //获取数据表列数   
  67.       int colnum = sheet.getColumns();  
  68.       String[] rest = new String[colnum];  
  69.       for(int i = 0; i < colnum; i++){  
  70.         String sTemp = read(i,row);  
  71.         if(sTemp!=null)  
  72.          rest[i] = sTemp;  
  73.       }  
  74.       return rest;  
  75.     }catch(Exception e){  
  76.       System.out.println("readLine err:"+e);  
  77.       workbook.close();  
  78.       return null;  
  79.     }  
  80.   }  
  81. /** 
  82.  *方法说明:读取excel的指定单元数据 
  83.  *输入参数: 
  84.  *返回类型: 
  85.  */  
  86.   public String read(int col, int row){  
  87.     try{  
  88.       //获得单元数据   
  89.       Cell a2 = sheet.getCell(col,row);   
  90.       String rest = a2.getContents();  
  91.       return rest;  
  92.     }catch(Exception e){  
  93.       System.out.println("read err:"+e);  
  94.       workbook.close();  
  95.       return null;  
  96.     }  
  97.   }  
  98. /** 
  99.  *方法说明:主方法,演示程序用 
  100.  *输入参数: 
  101.  *返回类型: 
  102.  */  
  103.   public static void main(String[] arges){  
  104.     try{  
  105.       myExcel me = new myExcel();  
  106.       //生成一个可读取的excel文件对象   
  107.       me.workbook = Workbook.getWorkbook(new File("myfile.xls"));  
  108.       //使用第一个工作表   
  109.       me.sheet = me.workbook.getSheet(0);  
  110.       //读一行记录,并显示出来   
  111.       String[] ssTemp = me.readLine(1);  
  112.       for(int i=0;i<ssTemp.length;i++)  
  113.        System.out.println(ssTemp[i]);  
  114.       //写入数据   
  115.       me.write();  
  116.         
  117.       me.workbook.close();  
  118.     }catch(Exception e){  
  119.       System.out.println(e);  
  120.     }  
  121.   }  
  122.      
  123. }  


view plaincopy to clipboardprint?
  1. package test39;  
  2.   
  3. import com.lowagie.text.*;  
  4. import com.lowagie.text.pdf.*;  
  5. import java.io.*;  
  6. import java.awt.Color;  
  7.   
  8. /** 
  9.  * Title: 生成PDF文件 
  10.  * Description: 本实例通过使用iText包生成一个表格的PDF文件 
  11.  * Filename: myPDF.java 
  12.  */  
  13. public class myPDF{  
  14. /** 
  15.  *方法说明:写PDF文件 
  16.  *输入参数: 
  17.  *返回类型: 
  18.  */  
  19.   public void write(){  
  20.    try{  
  21.      Document document=new Document(PageSize.A4, 505010050);  
  22.      Rectangle pageRect=document.getPageSize();  
  23.      PdfWriter.getInstance(document, new FileOutputStream("tables.pdf"));  
  24.      //创建汉字字体   
  25.      BaseFont bfSong = BaseFont.createFont("STSong-Light""UniGB-UCS2-H"false);  
  26.      Font fontSong = new Font(bfSong, 10, Font.NORMAL);  
  27.      // 增加一个水印   
  28.      try {  
  29.          Watermark watermark = new Watermark(Image.getInstance("test.jpg"), pageRect.left()+50,pageRect.top()-85);  
  30.          watermark.scalePercent(50);  
  31.          document.add(watermark);  
  32.      }catch(Exception e) {  
  33.           System.err.println("请查看文件“test.jpg”是否在正确的位置?");  
  34.      }  
  35.        
  36.       // 为页增加页头信息   
  37.      HeaderFooter header = new HeaderFooter(new Phrase("Java实例一百例",fontSong), false);  
  38.      header.setBorder(2);  
  39.      header.setAlignment(Element.ALIGN_RIGHT);  
  40.      document.setHeader(header);  
  41.        
  42.       // 为页增加页脚信息   
  43.      HeaderFooter footer = new HeaderFooter(new Phrase("第 ",fontSong),new Phrase(" 页",fontSong));  
  44.      footer.setAlignment(Element.ALIGN_CENTER);  
  45.      footer.setBorder(1);  
  46.      document.setFooter(footer);  
  47.   
  48.       // 打开文档   
  49.      document.open();   
  50.      //构造表格   
  51.      Table table = new Table(4);  
  52.      table.setDefaultVerticalAlignment(Element.ALIGN_MIDDLE);  
  53.      table.setBorder(Rectangle.NO_BORDER);  
  54.      int hws[] = {10201020,};  
  55.      table.setWidths(hws);  
  56.      table.setWidth(100);  
  57.      //表头信息   
  58.      Cell cellmain = new Cell(new Phrase("用户信息",new Font(bfSong, 10, Font.BOLD,new Color(0,0,255))));  
  59.      cellmain.setHorizontalAlignment(Element.ALIGN_CENTER);  
  60.      cellmain.setColspan(4);  
  61.      cellmain.setBorder(Rectangle.NO_BORDER);  
  62.      cellmain.setBackgroundColor(new Color(0xC00xC00xC0));  
  63.      table.addCell(cellmain);  
  64.       //分表头信息   
  65.      Cell cellleft= new Cell(new Phrase("收货人信息",new Font(bfSong, 10, Font.ITALIC,new Color(0,0,255))));  
  66.      cellleft.setColspan(2);  
  67.      cellleft.setHorizontalAlignment(Element.ALIGN_CENTER);  
  68.      table.addCell(cellleft);  
  69.      Cell cellright= new Cell(new Phrase("订货人信息",new Font(bfSong, 10, Font.ITALIC,new Color(0,0,255))));  
  70.      cellright.setColspan(2);  
  71.      cellright.setHorizontalAlignment(Element.ALIGN_CENTER);  
  72.      table.addCell(cellright);  
  73.        
  74.      //收货和订货人信息,表体内容   
  75.      table.addCell(new Phrase("姓名",fontSong));  
  76.      table.addCell(new Phrase("张三",fontSong));  
  77.      table.addCell(new Phrase("姓名",fontSong));  
  78.      table.addCell(new Phrase("李四",fontSong));  
  79.   
  80.      table.addCell(new Phrase("电话",fontSong));  
  81.      table.addCell(new Phrase("23456789",fontSong));  
  82.      table.addCell(new Phrase("电话",fontSong));  
  83.      table.addCell(new Phrase("9876543",fontSong));  
  84.   
  85.      table.addCell(new Phrase("邮编",fontSong));  
  86.      table.addCell(new Phrase("100002",fontSong));  
  87.      table.addCell(new Phrase("邮编",fontSong));  
  88.      table.addCell(new Phrase("200001",fontSong));  
  89.   
  90.      table.addCell(new Phrase("地址",fontSong));  
  91.      table.addCell(new Phrase("北京西城区XX路XX号",fontSong));  
  92.      table.addCell(new Phrase("地址",fontSong));  
  93.      table.addCell(new Phrase("上海陆家嘴区XX路XX号",fontSong));  
  94.   
  95.      table.addCell(new Phrase("电子邮件",fontSong));  
  96.      table.addCell(new Phrase("zh_san@hotmail.com",fontSong));  
  97.      table.addCell(new Phrase("电子邮件",fontSong));  
  98.      table.addCell(new Phrase("li_si@hotmail.com",fontSong));  
  99.      //将表格添加到文本中   
  100.      document.add(table);  
  101.      //关闭文本,释放资源   
  102.      document.close();   
  103.        
  104.    }catch(Exception e){  
  105.      System.out.println(e);     
  106.    }  
  107.   }  
  108. /** 
  109.  *方法说明:主方法 
  110.  *输入参数: 
  111.  *返回类型: 
  112.  */  
  113.   public static void main(String[] arg){  
  114.     myPDF p = new myPDF();  
  115.     p.write();  
  116.   }  
  117. }  


view plaincopy to clipboardprint?
  1. package test40;  
  2.   
  3. //文件名:myZip.java   
  4. import java.io.*;  
  5. import java.util.*;  
  6. import java.util.zip.*;  
  7. /** 
  8.  * Title: 文件压缩和解压 
  9.  * Description: 使用ZipInputStream和ZipOutputStream对文件 
  10.  *                 和目录进行压缩和解压处理 
  11.  * Filename: myZip.java 
  12.  */  
  13. public class myZip{  
  14. /** 
  15.  *方法说明:实现文件的压缩处理 
  16.  *输入参数:String[] fs 压缩的文件数组 
  17.  *返回类型: 
  18.  */  
  19.   public void ZipFiles(String[] fs){  
  20.    try{  
  21.      String fileName = fs[0];  
  22.      FileOutputStream f =  
  23.        new FileOutputStream(fileName+".zip");  
  24.      //使用输出流检查   
  25.      CheckedOutputStream cs =   
  26.         new CheckedOutputStream(f,new Adler32());  
  27.       //声明输出zip流   
  28.       ZipOutputStream out =  
  29.         new ZipOutputStream(new BufferedOutputStream(cs));  
  30.       //写一个注释   
  31.       out.setComment("A test of Java Zipping");  
  32.       //对多文件进行压缩   
  33.       for(int i=1;i<fs.length;i++){  
  34.         System.out.println("Write file "+fs[i]);  
  35.         BufferedReader in =  
  36.            new BufferedReader(  
  37.              new FileReader(fs[i]));  
  38.          out.putNextEntry(new ZipEntry(fs[i]));  
  39.          int c;  
  40.          while((c=in.read())!=-1)  
  41.           out.write(c);  
  42.         in.close();  
  43.        }  
  44.        //关闭输出流   
  45.        out.close();  
  46.        System.out.println("Checksum::"+cs.getChecksum().getValue());  
  47.     }catch(Exception e){  
  48.        System.err.println(e);  
  49.     }  
  50.   }  
  51.   
  52. /** 
  53.  *方法说明:解压缩Zip文件 
  54.  *输入参数:String fileName 解压zip文件名 
  55.  *返回类型: 
  56.  */  
  57.   public void unZipFile(String fileName){  
  58.     try{  
  59.        System.out.println("读取ZIP文件........");  
  60.        //文件输入流   
  61.        FileInputStream fi =  
  62.          new FileInputStream(fileName+".zip");  
  63.        //输入流检查   
  64.        CheckedInputStream csi = new CheckedInputStream(fi,new Adler32());  
  65.        //输入流压缩   
  66.        ZipInputStream in2 =  
  67.          new ZipInputStream(  
  68.            new BufferedInputStream(csi));  
  69.        ZipEntry ze;  
  70.        System.out.println("Checksum::"+csi.getChecksum().getValue());  
  71.        //解压全部文件   
  72.        while((ze = in2.getNextEntry())!=null){  
  73.          System.out.println("Reading file "+ze);  
  74.          int x;  
  75.          while((x= in2.read())!=-1)  
  76.            //这里是写文件,write是以byte方式输出。   
  77.            System.out.write(x);  
  78.        }  
  79.        in2.close();  
  80.     }catch(Exception e){  
  81.       System.err.println(e);  
  82.     }  
  83.   }  
  84. /** 
  85.  *方法说明:读取Zip文件列表 
  86.  *输入参数:String fileName zip文件名 
  87.  *返回类型:Vector 文件列表 
  88.  */  
  89.   @SuppressWarnings("unchecked")  
  90. public Vector<Object> listFile(String fileName){  
  91.     try{  
  92.        @SuppressWarnings("unused")  
  93.     String[] aRst=null;  
  94.        Vector<Object> vTemp = new Vector<Object>();  
  95.        //zip文件对象   
  96.        ZipFile zf = new ZipFile(fileName+".zip");  
  97.        Enumeration e = zf.entries();  
  98.        while(e.hasMoreElements()){  
  99.          ZipEntry ze2 = (ZipEntry)e.nextElement();  
  100.          System.out.println("File: "+ze2);  
  101.          vTemp.addElement(ze2);  
  102.        }  
  103.        return  vTemp;  
  104.     }catch(Exception e){  
  105.       System.err.println(e);  
  106.       return null;  
  107.     }  
  108.   }  
  109. /** 
  110.  *方法说明:主方法 
  111.  *输入参数: 
  112.  *返回类型: 
  113.  */  
  114.   public static void main(String[] args){  
  115.     try{  
  116.      String fileName = args[0];  
  117.      myZip myZip = new myZip();  
  118.      myZip.ZipFiles(args);  
  119.      myZip.unZipFile(fileName);  
  120.      Vector<Object> dd = myZip.listFile(fileName);  
  121.      System.out.println("File List: "+dd);  
  122.     }catch(Exception e){  
  123.         e.printStackTrace();  
  124.     }  
  125.   }  
  126. }

 转自http://blog.csdn.net/fljxzxb

原创粉丝点击