JAVA学习笔记2

2011.7.28              周四

 

1.泛型:<类型>    只能放一种类型

2.注意导包时有多个包的情况:如Date和List

3.ArrayList练习:

import java.util.Iterator;

import java.util.List;

import java.util.ArrayList;

public class ListTest {   

       publicstatic void main(String[] args) {

              //1 创建对象

              List<String> list = newArrayList<String>();

              //2添加元素(对象) add(E)  向列表的尾部添加指定的元素

              list.add("abc");

              list.add("abc");

              list.add("www");

              list.add("eee");

              list.add("rrr");       

              /**

               *add(int index, E element)

               * 在列表的指定位置插入指定元素(可选操作)。

               */

               list.add(3,"yyy");

              /**

               * remove(int index)移除列表中指定位置的元素(可选操作)。

               * remove(Object o)移除列表中元素

             */

                list.remove(3);                   

              //3.取某一索引对象

              System.out.println(list.get(3));

              System.out.println(list.get(4));            

              //循环

              for(String s:list){

                     System.out.println(s);

              }           

              /**

               * 集合迭代

               * 获得该集合对应的迭代器对象Iterator

               */

              Iterator<String> it =list.iterator();

              while(it.hasNext()){

                     Stringstr = it.next();

                     if(str.equals("eee")){

                     /*

                      *循环迭代集合过程中删除元素,不要使用集合对象删除

                      *应该使用迭代器删除 //list.remove(str);

                      */                       

                     it.remove();

                     continue;

                     }

                     System.out.println(str);

              }

              /**

               * 此时底层的指针指向最后一个元素  next已经没有元素

               *java.util.NoSuchElementException

               *String str2 = it.next();

               */         

       }

}

4.Vector和LinkedList练习

import java.util.Iterator;

import java.util.LinkedList;

import java.util.Vector;

public class VectorTest {

       publicstatic void main(String[] args) {

              Vector<Integer> v = newVector<Integer>();             

              v.add(1);

              v.add(1);

              v.add(2);

              v.add(3);       

              System.out.println(v.get(1));        

              v.remove(0);         

              v.size();         

              Iterator<Integer> it =v.iterator();

              while(it.hasNext()){

                     Integeri = it.next();

                     System.out.println(i);

              }                         

              LinkedList<String> list = new LinkedList<String>();         

              list.add("abc");

              list.add("abc");

              list.add("www");

              list.add("eee");

              list.add("rrr");       

              Iterator<String> it2 =list.iterator();

              while(it2.hasNext()){

                     Stringstr = it2.next();                                      

                     if(str.equals("eee")){

                            /*

                             *循环迭代集合过程中删除元素,不要使用集合对象删除

                             *应该使用迭代器删除

                             */

                            //list.remove(str);

                            it2.remove();

                            continue;

                     }

                     System.out.println(str);

              }

       }

}

5.HashSet练习

import java.util.HashSet;

import java.util.Iterator;

import java.util.Set;

public class SetTest {   

       publicstatic void main(String[] args) {

              Set<String> set = newHashSet<String>();         

              String str1 =new String("abc");//set不会出现相同元素

              String str2 =new String("abc");

              set.add(str1);

              set.add(str2);

              set.add("sdf");

              set.add("bsd");

              set.add("3432");

              set.add("rete");

              set.add("243");

              set.add("qwe");

              set.add("asdsad");         

              System.out.println(set.size());//长度           

               * 取某一个元素  没有   无法根据索引位置取对象

               * 因为set集合无序,没有确定的索引位置         

              /**

               * 集合无序,没有确定的索引   只能删除对象

               */

              set.remove("3432");             

              System.out.println(set.size());             

              Iterator<String> it =set.iterator();//迭代

              while(it.hasNext()){

                     Stringstr = it.next();

                     System.out.println(str);

              }                  

       }

}

import java.util.HashSet;

import java.util.Iterator;

import java.util.Set;

public class SetTest2 {  

       publicstatic void main(String[] args) {

              Set<Student> set = newHashSet<Student>();

              /**

               *Set 去除重复,如何判断两个对象相等?

               * 不是由equals()  而是hashCode码

               * 所以我们需要重新类的hashCode()方法

               */

              Student s1 = newStudent("zhangsan",20);

              Student s2 = new Student("zhangsan",20);

              Student s3 = newStudent("lisi",22);

              Student s4 = newStudent("wangwu",20);          

              set.add(s1);

              set.add(s2);

              set.add(s3);

              set.add(s4);

              Iterator<Student> it =set.iterator();//迭代

              while(it.hasNext()){

                     Studentstu = it.next();

                     System.out.println(stu);

              }

       }

}

6.TreeSetT练习

import java.util.Comparator;

import java.util.Iterator;

import java.util.TreeSet;

public class TreeSetTest {    

       publicstatic void main(String[] args) {

              TreeSet<Integer> set = newTreeSet<Integer>();

              /**

               * 不允许重复   排序功能   默认升序

               */

              set.add(5);

              set.add(5);

              set.add(2);

              set.add(7);

              set.add(0);            

              Iterator <Integer>it =set.iterator();

              while(it.hasNext()){

                     Integeri = it.next();

                     System.out.println(i);

              }           

              TreeSet<Student> set2 = new TreeSet<Student>();

              Student s1 = newStudent("zhangsan",20);

              Student s2 = newStudent("zhangsan",20);

              Student s3 = newStudent("lisi",22);

              Student s4 = newStudent("wangwu",20);

              set2.add(s1);

              set2.add(s2);

              set2.add(s3);

              set2.add(s4);         

              Iterator<Student> it2 =set2.iterator();

              while(it2.hasNext()){

                     Studentstu = it2.next();

                     System.out.println(stu);

              }

       }

}

注意: TreeSet 比较对象大小进行排序  两种方法:

《1》放入的对象对应的类 实现Comparable接口,让对象自身具有比较功能

     当我们使用TreeSet时,判断对象相等就不是hashCode而是比较大小时 compareTo()返回0  就认为是相等对象

public class Student implementsComparable<Student>{

       privateString name;

       privateint age;

       publicString getName() {

              return name;

       }

       publicvoid setName(String name) {

              this.name = name;

       }

       publicint getAge() {

              return age;

       }

       publicvoid setAge(int age) {

              this.age = age;

       }

       publicStudent(String name, int age) {

              super();

              this.name = name;

              this.age = age;

       }

       publicStudent(){}

      

       @Override

       publicString toString() {

              return this.name+"  "+this.age;

       }

       @Override

       publicboolean equals(Object obj) {

              Student s = (Student)obj;

              if(this.name.equals(s.getName())&&this.age==s.getAge())

                     returntrue;

              return false;

       }

       @Override

       publicint hashCode() {        

              return this.name.hashCode()+this.age;

       }

        // 按照学生年龄升序排列  如果年龄相同  按照名字降序

        // 小心返回值0

       /*@Override

       publicint compareTo(Student o) {

              if(this.age!=o.getAge()){

                     returnthis.age-o.getAge();

              }else{

                     return-this.name.compareTo(o.getName());

              }

       }

}

 

  《2》放入的对象对应类不需要实现Comparable接口,我们创建TreeSet集合时,使用TreeSet(Comparator<? super E> comparator)构造方法,让集合本身具有比较器,进行添加元素的比较大小

              TreeSet<Student> set2 = newTreeSet<Student>(new Comparator<Student>(){

                     @Override

                     publicint compare(Student o1, Student o2) {                          

                            if(o1.getAge()!=o2.getAge()){

                                   returno1.getAge()-o2.getAge();

                            }else{

                                   return-o1.getName().compareTo(o2.getName());

                            }

                     }                  

              });         

              Student s1 = newStudent("zhangsan",20);

              Student s2 = newStudent("zhangsan",20);

              Student s3 = newStudent("lisi",22);

              Student s4 = newStudent("wangwu",20);

              set2.add(s1);

              set2.add(s2);

              set2.add(s3);

              set2.add(s4);         

              Iterator<Student> it2 =set2.iterator();

              while(it2.hasNext()){

                     Studentstu = it2.next();

                     System.out.println(stu);

              }

       }

 

}

7.HashMap练习

import java.util.*;

public class MapTest {

       publicstatic void main(String[] args) {

              //创建对象

              HashMap<Integer,String> map = newHashMap<Integer,String>();

               * 添加元素   put(E key , E value)

               *map中添加元素   key唯一  如果出现相同,后放入的value会覆盖先放入的

              map.put(1, "1");

              map.put(1, "111");

              map.put(3, "333");

              map.put(6, "666");

              map.put(2, "222");

              System.out.println(map.size());//获得集合长度         

              /**

               * 取元素 根据key 获取value    value get(E key)

               */

              String str = map.get(3);

              System.out.println(str);        

              /**

               * 删除元素 remove(E key)

               */

              map.remove(1);

              /**

               * 如果get(E key)  传入的key不存在呢?不会抛异常,返回null

               */

              String str2 = map.get(1);

              System.out.println(str2);             

              /**

               *map清空  clear()

               * 判断集合中是否有数据?

               * 《1》先判断集合对象是否==null 

               * 《2》如果集合!=null, 判断.size()>0

              map.clear();

              System.out.println(map.size());                  

              if(map.size()<=0){

                     System.out.println("没有东西");

              }else{

                     System.out.println("有东西");

              }

               *boolean containsKey(key)

               * 判断集合中是否存在相应的key

               * 如果存在 返回true

               * 否则     返回false

              if(!map.containsKey(1)){

                     map.put(1,"111");

              }                         

       }

}

import java.util.*;

public class MapTest2 {

       publicstatic void main(String[] args) {

              HashMap<Integer,String> map = newHashMap<Integer,String>();          

              map.put(1, "1");

              map.put(1, "111");

              map.put(3, "333");

              map.put(6, "666");

              map.put(2, "222");        

              /**

               *map如何迭代? map本身没有迭代器,实现相对麻烦

               * 实现方式三种

               * 《1》获得所有的value 集合

               *Collection<V> values()返回此映射中包含的值的 Collection 视图

               * 优点:最简单

               * 缺点:无法获得key             

              Collection<String> coll =map.values();

              Iterator <String> it =coll.iterator();

              while(it.hasNext()){

                     Stringvalue = it.next();

                     System.out.println(value);

              }           

              /**

               * 《2》获得所有的key的集合   然后迭代,分别取value

               *Set<K> keySet()返回此映射中包含的键的 Set 视图

               *key和value都可以获得

               */

              Set<Integer> keys = map.keySet();

              Iterator<Integer> it =keys.iterator();

              while(it.hasNext()){

                     Integerkey = it.next();

                     Stringvalue = map.get(key);

                     System.out.println("key:"+key+"  value:"+value);

              }           

              /**

               * 《3》可以获得key-value 键值对  的集合

               *key-value--->Map.Entry

               *Set<Map.Entry<K,V>> entrySet()返回此映射中包含的映射关系的 Set 视图

              Set<Map.Entry<Integer,String>> entrys = map.entrySet();

              Iterator <Map.Entry<Integer,String>> it = entrys.iterator();

              while(it.hasNext()){

                     Map.Entry<Integer,String> entry= it.next();

                     Integerkey = entry.getKey();

                     Stringvalue = entry.getValue();

                     System.out.println("key:"+key+"  value:"+value);

              }

       }

}

8.重点是TreeSet排序的实现 TreeSet(Comparator<E> comparator) 采用静态、成员、匿名三种内部类实现

import java.util.*;

public class TreeSetTest {

              //静态内部类

              static class MComparator implementsComparator<Student>{

                     @Override

                     publicint compare(Student arg0, Student arg1) {

                            if(!(arg0.getAge()==(arg1.getAge())))

                                   returnarg0.getAge()-arg1.getAge();

                            else

                                   returnarg0.getSName().compareTo(arg1.getSName());

                     }

              }           

              //成员内部类        

              public class MyCom implementsComparator<Student>{

                     @Override

                     publicint compare(Student arg0, Student arg1) {

                            if(!(arg0.getAge()==(arg1.getAge())))

                                   returnarg0.getAge()-arg1.getAge();

                            else

                                   returnarg0.getSName().compareTo(arg1.getSName());

                     }

              }

              public static void main(String[] args) {

                      //TreeSet排序的实现 --匿名内部类

                     Students1=new Student(" 张三",12);

                     Students2=new Student(" 历史",43);

                     Students3=new Student(" 玩个",32);

                     Students4=new Student(" 张三",54);

                     TreeSet<Student>ts=new TreeSet<Student>(new Comparator<Student>(){

                            @Override                                 

                            public int compare(Student arg0, Studentarg1) {

                                   if(!(arg0.getAge()==(arg1.getAge())))

                                          return arg0.getAge()-arg1.getAge();

                                   else

                                          returnarg0.getSName().compareTo(arg1.getSName());

                            }

                     });                

                     ts.add(s4);

                     ts.add(s3);

                     ts.add(s2);

                     ts.add(s1);

                     Iterator<Student>it5 =ts.iterator();

                     while(it5.hasNext()){

                            Student s11 = it5.next();

                            System.out.println(s11);

                     }

                     //TreeSet排序的实现--静态内部类

                     TreeSet<Student>ts1=new TreeSet<Student>(new ListTest.MComparator());

                     ts1.add(s4);                 

                     ts1.add(s3);

                     ts1.add(s2);

                     ts1.add(s1);

                     Iterator<Student>it6 =ts1.iterator();

                     while(it6.hasNext()){

                            Student s11 = it6.next();

                            System.out.println(s11);

                     }

                     //TreeSet排序的实现--成员内部类

                     TreeSet<Student>ts2=new TreeSet<Student>(new ListTest().new MyCom());

                     ts2.add(s1);

                     ts2.add(s4);

                     ts2.add(s3);

                     ts2.add(s2);

                     ts2.add(s1);

                     Iterator<Student>it7 =ts1.iterator();

                     while(it7.hasNext()){

                            Student s11 = it7.next();

                            System.out.println(s11);

                     }

              }

       }

public class Student {

       privateString sName;

       privateint age;

       publicString getSName() {

              return sName;

       }

       publicvoid setSName(String name) {

              sName = name;

       }

       publicint getAge() {

              return age;

       }

       publicvoid setAge(int age) {

              this.age = age;

       }

       publicStudent(String name, int age) {

              super();

              sName = name;

              this.age = age;

       }

       publicStudent() {}

       @Override

       publicString toString() {             

              return "学生姓名:"+sName+" 年龄:"+age;

       }

}

9.编写

       时间Duration类:int hours ; int minutes; intseconds;

       歌曲Track类:String title ; Duration duration

       CD抽象类Recording:String title;doubleprice;String category;String imageName;

       音乐专辑MusicRecording extends Recording

                     Stringsinger;Vector<Track> tracks;

       合理编写每个类的属性对应的setter和getter方法 

       类的构造方法  toString方法

       编写SuperVCDTest测试类 测试这些类是否正确

 

public class Duration {

              private int hours;

              private int minutes;

              private int seconds;

              public Duration(int hours,int minutes){

                     this.hours=hours;

                     this.minutes=minutes;

              }

              public Duration(int seconds){

                     this.hours=seconds/ 3600;

                     this.minutes=seconds% 3600 / 60;

                     this.seconds=seconds% 60;

              }

              public Duration(){}

              public void setHours(int hours){

                     this.hours=hours;

              }

              public void setMinutes(int minutes){

                     this.minutes=minutes;

              }

              public void setSeconds(int seconds){

                     this.seconds=seconds;

              }

              public int getHours(){

                     returnhours;

              }

              public int getMinutes(){

                     returnminutes;      

 

              }

              public int getSeconds(){

                     returnseconds;

              }

              //格式转化

              public String format(int x){

                     Stringy;

                     if(x<10){

                            return y="0"+x;

                     }

                     else{

                            return y=x+"";

                     }

              }

              //重写toString方法,使得时间输出格式是hh:mm:ss

              public String toString(){

                     if(this.hours==0){

                            returnformat(minutes)+":"+this.seconds;

                     }

                     else{

                            returnformat(this.hours)+":"+format(this.minutes)+":"+this.seconds;

                     }

              }           

              //把时间转化成秒数,以便计算

               public int toSeconds(){

                   return  hours*3600+minutes*60+seconds;

               }

              //两个时间相加

              public Duration Durationadd(Duration d1){

                     intt=this.toSeconds()+d1.toSeconds();

                     returnnew Duration(t);

              }

              //两个时间相减

              public Duration Durationdec(Duration d2){

                     intt=Math.abs(this.toSeconds()-d2.toSeconds());

                     returnnew Duration(t);

              }    

  }

 

public class Track {

       privateString title;

       privateDuration d;

       publicString getTitle() {

              return title;

       }

       publicvoid setTitle(String title) {

              this.title = title;

       }

       publicDuration getD() {

              return d;

       }

       publicvoid setD(Duration d) {

              this.d = d;

       }

       publicTrack() {}

       publicTrack(String title, Duration d) {

              super();

              this.title = title;

              this.d = d;

       }

       publicString toString(){

              return "歌曲名: "+title+"  时长: "+d+"\n";

       }

}

public class Recording {

       privateString title;

       privatedouble price;

       privateString category;

       privateString imageName;

       publicString getTitle() {

              return title;

       }

       publicvoid setTitle(String title) {

              this.title = title;

       }

       publicdouble getPrice() {

              return price;

       }

       publicvoid setPrice(double price) {

              this.price = price;

       }

       publicString getCategory() {

              return category;

       }

       publicvoid setCategory(String category) {

              this.category = category;

       }

       publicString getImageName() {

              return imageName;

       }

       publicvoid setImageName(String imageName) {

              this.imageName = imageName;

       }

       publicRecording(String title, double price, String category,

                     StringimageName) {

              super();

              this.title = title;

              this.price = price;

              this.category = category;

              this.imageName = imageName;

       }

       publicRecording() {}

       @Override

       publicString toString() {

       return"专辑名:"+title+"   价格:"+price+"  地区:"+category+"  图片名:"+imageName;

       }

}

import java.util.*;

public class MusicRecoding extendsRecording {

       privateString singer;

       privateVector<Track> tracks;

       publicString getSinger() {

              return singer;

       }

       publicvoid setSinger(String singer) {

              this.singer = singer;

       }

       publicVector<Track> getTracks() {

              return tracks;

       }

       publicvoid setTracks(Vector<Track> tracks) {

              this.tracks = tracks;

       }

      

       publicMusicRecoding(String title, double price, String category,

                     StringimageName, String singer, Vector<Track> tracks) {

              super(title, price, category, imageName);

              this.singer = singer;

              this.tracks = tracks;

      

       }

       publicMusicRecoding(String title, double price, String category,

                     StringimageName) {}

       @Override

       publicString toString() {

             

              return super.toString()+"  歌手:"+singer+"   "+tracks.size()+"\n"+tracks;

       }

}

import java.util.Iterator;

import java.util.Vector;

public class SuperVCDTest {

       publicstatic void main(String[] args) {

              Track t1=new Track("很受伤",new Duration(1423));

              Track t2=new Track("不是我",new Duration(253));

              Track t3=new Track("就是你",new Duration(644));

              Track t4=new Track("爱大了",new Duration(234));

              Track t5=new Track("寂寞哥",new Duration(2343));

              Track t6=new Track("可惜不是你",new Duration(625));

              Track t7=new Track("其实我很在乎你",new Duration(456));

              Track t8=new Track("未来的你",new Duration(987));

              Vector<Track> tracks=newVector<Track>();

              tracks.add(t1);

              tracks.add(t2);

              tracks.add(t3);

              tracks.add(t4);

              tracks.add(t5);

              tracks.add(t6);

              tracks.add(t7);

              tracks.add(t8);

              tracks.size();                

              MusicRecording mr=newMusicRecording("专辑1",35.12,"大陆地区","小刚.jpg","成龙",tracks);

              System.out.println(mr);

       }

}

10.阅读ShoppingCart类,改进功能方法并编写测试类测试

 public class Book {

       privateString name;

       privatedouble price;

       privateString author;

       privateint quantity;

       publicString getName() {

              return name;

       }

       publicvoid setName(String name) {

              this.name = name;

       }

       publicdouble getPrice() {

              return price;

       }

       publicvoid setPrice(double price) {

              this.price = price;

       }

       publicString getAuthor() {

              return author;

       }

       publicvoid setAuthor(String author) {

              this.author = author;

       }

       publicint getQuantity() {

              return quantity;

       }

       publicvoid setQuantity(int quantity) {

              this.quantity = quantity;

       }

       publicBook(String name, double price, String author, int quantity) {

              this.name = name;

              this.price = price;

              this.author = author;

              this.quantity = quantity;

       }

       publicBook(){}    

       @Override

       publicString toString() {

              return this.name+"  "+this.price+"  "+this.author+"  "+this.quantity;

       }

 }

import java.util.*;

public class ShoppingCart {

private Map<String,Book> cart;

       publicMap<String, Book> getCart() {

              return cart;

       }

       publicvoid setCart(Map<String, Book> cart) {

              this.cart = cart;

       }

       publicShoppingCart(){

              cart = new HashMap<String,Book>();

       }

       /**

        * 购物车功能方法

        * 添加商品方法

        * 改进:添加时,如果商品存在,数量+1

        *            不存在,添加商品,数量为1

        */

       publicvoid addBook(Book b){

              Set<String> keyset=cart.keySet();

              Iterator<String>it=keyset.iterator();

              while(it.hasNext()){

                     Stringstr=it.next();

                     inti=b.getQuantity();

                     if(str.equals(b.getName())){

                            b.setQuantity(i++);

                     }

                     else{

                            i=1;

                            cart.put(b.getName(), b);

                     }    

              }

       }

       /**

        * 删除商品

        * 改进:删除时,如果数量》1  数量-1

        *                   如果数量=1  删除商品

        */

       publicvoid delBook(String name){

              Book b=cart.get(name);

              int i=b.getQuantity();

              if(i==1)

                     cart.remove(name);

              else

              {

                     i-=1;

                     b.setQuantity(i);

              }    

       }

       /**

        * 清空购物车

        */

       publicvoid clearCart(){

              cart.clear();

       }

       /**

        * 获得总价

        * 每本书price*quantity 累加

        */

       publicdouble totalPrice(){

              Collection<Book>book=cart.values();

              Iterator<Book> it=book.iterator();

              double t=0;

              while(it.hasNext()){

                     Bookb=it.next();

                     t+=b.getPrice()*b.getQuantity();

              }

              return t;

       }    

}

 

 

import java.util.*;

public class ShoppingCartTest {

       publicstatic void main(String[] args) {

              Book b1=new Book("C语言",27.6,"三毛",1);

              Book b2=new Book("JAVA面向对象程序设计",45.9,"耿祥义",39);

              Book b3=new Book("很纯很暧昧",71,"老鱼",6);

              Map<String,Book> cart=newHashMap<String,Book>();

              cart.put(b1.getName(), b1);

              cart.put(b2.getName(), b2);

              cart.put(b3.getName(), b3);

              cart.put(b4.getName(), b4);         

              Set<Map.Entry<String, Book>>entrys= cart.entrySet();

              Iterator<Map.Entry<String,Book>> it=entrys.iterator();

              while(it.hasNext()){

                     Map.Entry<String,Book> entry=it.next();

                     Stringkey=entry.getKey();

                     Bookvalue=entry.getValue();

                     System.out.println(key+"  " +value);

              }           

       }

}

集合接口:

 

 

 


                      t

 

 

 

 

 

集合类:

 

 

 

 

 

 

 

 

 

 

 

 

 


2011.7.29              周五

1.类的反射:

确定一个对象的类

可以获得类的修饰符、属性、字段、方法、构造方法以及父类

找出一个属于一个接口的常量和在接口中声明的方法

在没有运行之前可以创建一个类的未知名称的对象

在没有运行之前,可以给未知属性设置值和得到该属性的值,叫动态访问

在没有运行之前,可以访问未知名称的方法并调用它,叫动态调用。

在没有运行之前,可以创建一个尺寸和类型都未知的数组,在运行的时候,动态修改数组的组件。

 Java反射机制实例类:

Class: 每个类在JVM中都拥有一个对应的java.lang.Class对象,它提供了类结构信息的描述。

Class反射对象描述类的结构信息,所以我们可以从Class对象中获取这些信息,

比如:

 构造方法、成员变量、方法等元素的反射对象,并以编程的方式通过这些反射对象对目标类对象进行操作。这些反射对象类在java.reflect包中定义。

 Constructor:类的构造方法的反射对象。可以通过Class#getDeclaredConstructors()方法获取类的所有构造方法反射对象数组Constructor[]。还可以通过Class#getDeclaredConstructor(Class...parameterTypes)获取指定特定参数的构造方法反射对象。Constructor的一个主要方法是newInstance(Object...initargs),通过该方法可以创建一个对象类的实例,相当于new关键字作用。

Method:类方法的反射类。通过Class#getDeclaredMethods()方法可以获得类的所有方法反射类对象数组Method[].

可以通过getDeclaredMethod(Stringname,Class... parameterTypes)获取特定的方法,name为 方法名,Class...为方法参数类型列表。

Method有个主要的方法invoke(Object obj,Object... args),obj表示操作的目标对象,args为设置参数

此外还有其他方法:ClassgetReturnType()获取方法返回类型方法

                             Class[] getParameterTypes():获取方法参数类型数组方法。

                             Class[] getExceptionTypes():获取方法异常类型数组方法。

Field:类成员变量的反射类。通过Class#getDeclearedFields()方法可以获得类的成员变量反射类对象数组。

通过Class#getDeclearedField(Stringname)可以获得某个特定名称的成员变量对应的反射对象。

Field类主要的方法是set(Object obj,Object value),obj表示操作的目标对象,value为给目标对象obj付的值。如果成员变量为原始类型,可以通过提供的带类型名的方法,

例如:setBoolean(Objectobj,boolean value)   setInt(Objectobj,int value)

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

public class ReflectTest1 {   

       publicstatic void main(String[] args) {

              //Student.class

              Class<?> classType = null;

              if(args.length<1){

                     System.out.println("请在运行时输入参数");

              }else{

                     try{

                            classType = Class.forName(args[0]);                       

                            /**

                             * 获得类定义的属性

                             */

                            Field [] fields =classType.getDeclaredFields();

                            System.out.println("类定义的属性为:");

                            for(int i=0;i<fields.length;i++){

                                   System.out.println(fields[i]);

                            }                         

                            //获得类的定义的所有方法

                            Method []methods =classType.getDeclaredMethods();

                            System.out.println("类定义的方法为:");

                            for(int i=0;i<methods.length;i++){

                                   System.out.println(methods[i]);

                            }                         

                            //获得类定义的构造方法

                            Constructor[] constructors=classType.getDeclaredConstructors();

                            System.out.println("类定义的构造方法为:");

                            for(inti=0;i<constructors.length;i++){

                                   System.out.println(constructors[i]);

                            }                                                     

                     }catch (ClassNotFoundException e) {

                            //e.printStackTrace();

                            System.out.println("您输入的类没有,请重新输入");

                     }                                                            

              }

       }

}

public class ReflectTest2 {   

       publicstatic void main(String[] args) throws Exception {

              //根据当前类的线程获得类的加载器

              ClassLoader loader =Thread.currentThread().getContextClassLoader();

              //使用类加载器根据类名加载该类的反射类Class

              Class clazz=loader.loadClass("sample.Student");

              //获取类的一个指定构造方法      方法中可以不写参数或 null来指明无参数

              Constructor cons =clazz.getDeclaredConstructor(String.class,int.class);

              //Constructor cons =clazz.getDeclaredConstructor(null);

             

              //使用构造方法的反射类间接的构造一个对象    方法中可以不写参数或null来指明无参数

              Student stu =(Student)cons.newInstance("zhangsan",20);

              //Student stu =(Student)cons.newInstance(null);

              System.out.println(stu);

              /*//获得方法的反射对象

              Method setName =clazz.getDeclaredMethod("setName", String.class);

              //间接的执行目标对象的方法

              setName.invoke(stu,"lisi");   //等价于stu.setName("lisi");

              Method setAge =clazz.getDeclaredMethod("setAge", int.class);

              setAge.invoke(stu, 30);//等价于 stu.setAge(30);

             

              System.out.println(stu);*/

       }

}

 *Java反射机制实例类

 * 我们可以使用java反射机制,间接的操作类的对象,并可以提供间接的访问私有及保护的成员变量和方法

public class ReflectTest3 {   

       publicstatic void main(String[] args) throws Exception {

              //根据当前类的线程获得类的加载器

              ClassLoader loader =Thread.currentThread().getContextClassLoader();

              //使用类加载器根据类名加载该类的反射类Class

              Class clazz=loader.loadClass("sample.Student");       

              //获取类的一个指定构造方法      方法中可以不写参数或 null来指明无参数

              //Constructor cons =clazz.getDeclaredConstructor(String.class,int.class);

              Constructor cons =clazz.getDeclaredConstructor(null);

              //使用构造方法的反射类间接的构造一个对象    方法中可以不写参数或null来指明无参数

              //Student stu =(Student)cons.newInstance("zhangsan",20);

              Student stu =(Student)cons.newInstance(null);         

              //获得对应属性变量的反射对象

              Field nameField =clazz.getDeclaredField("name");

              Field ageField =clazz.getDeclaredField("age");

              //清除java语言访问检查 以访问私有的变量

              nameField.setAccessible(true);

              ageField.setAccessible(true);

              //以访问目标对象stu 私有变量方式给私有变量赋值

              nameField.set(stu,"zhangsan");//等价于 stu.name ="zhangsan";

              ageField.setInt(stu, 30);//等价于stu.age =30;

              //获得print方法的反射对象    null代表方法无参数   null可以省略

              Method printMethod =clazz.getDeclaredMethod("print",null);

              //设置清除java语言检查  以访问私有的方法

              printMethod.setAccessible(true);

//使用反射机制间接执行目标对象stu的print方法     null代表方法无参数,可以省略

              printMethod.invoke(stu,null);//等价于stu.print();

       }

}

2.正则表达式:

java.util.regex

类 Pattern

指定为字符串的正则表达式必须首先被编译为此类的实例。然后,可将得到的模式用于创建 Matcher 对象,依照正则表达式,该对象可以与任意字符序列匹配。

执行匹配所涉及的所有状态都驻留在匹配器中,所以多个匹配器可以共享同一模式。

x 字符 x

\\ 反斜线字符

\0n 带有八进制值 0 的字符 n (0 <=n <= 7)

\0nn 带有八进制值 0 的字符 nn (0<= n <= 7)

\0mnn 带有八进制值 0 的字符 mnn(0 <= m <= 3、0 <= n <= 7)

\xhh 带有十六进制值 0x 的字符 hh

\uhhhh 带有十六进制值 0x 的字符 hhhh

\t 制表符 ('\u0009')

\n 新行(换行)符 ('\u000A')

\r 回车符 ('\u000D')

\f 换页符 ('\u000C')

\a 报警 (bell) 符 ('\u0007')

\e 转义符 ('\u001B')

\cx 对应于 x 的控制符

字符类

[abc] a、b 或 c(简单类)

[^abc] 任何字符,除了 a、b 或 c(否定)

[a-zA-Z] a 到 z 或 A 到 Z,两头的字母包括在内(范围)

[a-d[m-p]] a 到 d 或 m 到 p:[a-dm-p](并集)

[a-z&&[def]] d、e 或 f(交集)

[a-z&&[^bc]] a 到 z,除了 b 和 c:[ad-z](减去)

[a-z&&[^m-p]] a 到 z,而非 m 到 p:[a-lq-z](减去)

预定义字符类

. 任何字符(与行结束符可能匹配也可能不匹配)

\d 数字:[0-9]

\D 非数字: [^0-9]

\s 空白字符:[ \t\n\x0B\f\r]

\S 非空白字符:[^\s]

\w 单词字符:[a-zA-Z_0-9]

\W 非单词字符:[^\w]

边界匹配器

^ 行的开头

$ 行的结尾

\b 单词边界

\B 非单词边界

\A 输入的开头

\G 上一个匹配的结尾

\Z 输入的结尾,仅用于最后的结束符(如果有的话)

\z 输入的结尾

Greedy 数量词

X? X,一次或一次也没有

X* X,零次或多次

X+ X,一次或多次

X{n} X,恰好 n 次

X{n,} X,至少 n 次

X{n,m} X,至少 n 次,但是不超过 m 次

Reluctant 数量词

X?? X,一次或一次也没有

X*? X,零次或多次

X+? X,一次或多次

X{n}? X,恰好 n 次

X{n,}? X,至少 n 次

X{n,m}? X,至少 n 次,但是不超过 m 次

Possessive 数量词

X?+ X,一次或一次也没有

X*+ X,零次或多次

X++ X,一次或多次

X{n}+ X,恰好 n 次

X{n,}+ X,至少 n 次

X{n,m}+ X,至少 n 次,但是不超过 m 次

反斜线字符 ('\') 用于引用转义构造,同时还用于引用其他将被解释为非转义构造的字符。因此,表达式 \\ 与单个反斜线匹配,而 \{ 与左括号匹配。

(1)matches  public static boolean matches(Stringregex,CharSequence input)编译给定正则表达式并尝试将给定输入与其匹配。

(2)split     public String[] split(CharSequence input,intlimit)围绕此模式的匹配拆分给定输入序列。

      如果限制 n 大于零,那么模式至多应用 n> - 1 次,数组的长度不大于 n,并且数组的最后条目将包含除最后的匹配定界符之外的所有输入。

      如果 n 非正,那么将应用模式的次数不受限制,并且数组可以为任意长度。

      如果 n 为零,那么应用模式的次数不受限制,数组可以为任意长度,并且将丢弃尾部空字符串。

      例如,输入"boo:and:foo" 将产生以下结果及参数:

       Regex    Limit              Result    

        :         2           { "boo","and:foo" }

        :         5           { "boo", "and","foo" }

        :         -2          { "boo", "and","foo" }

        o         5           { "b", "",":and:f", "", "" }

        o        -2           { "b", "",":and:f", "", "" }

        o         0           { "b", "",":and:f" }

(3)split   public String[] split(CharSequence input)围绕此模式的匹配拆分给定输入序列。 得到的数组中不包括尾部空字符串。

    例如,输入 "boo:and:foo" 将产生以下结果及表达式:

    Regex        Result

      :         { "boo", "and", "foo" }

     o          { "b","", ":and:f" }

实例:

public class Reg1 {

       publicstatic void main(String[] args) {

              /**

               * 判断字符串都有数字组成

               */

              String str ="123a567890";

              char[] chs = str.toCharArray();

              boolean flag = true;//是否完全是数字组成的标志    true是  false不是

              for(int i=0;i<chs.length;i++){

                     if(!(chs[i]>='0'&&chs[i]<='9')){

                            flag = false;

                            break;

                     }

              }

              if(flag)

                     System.out.println("该字符串完全有数字组成");

              else

                     System.out.println("该字符串不是完全有数字组成");

             

              /**

               * 使用正则表达式

               *\\d+  就是“正则表达式”

               *\d 数字:[0-9] 

               */

              if(str.matches("\\d+")){

                     System.out.println("字符串是全部由数字组成");

              }else{

                     System.out.println("字符串不是全部由数字组成");

              }

              /**

               * 字符串使用正则表达式的应用场合:

               * 《1》比较字符串是否匹配某个规则 

                           booleanmatches(String regex)

               * 《2》按照某规则切割字符串

                           String[]split(String regex)

               * 《3》按照某规则替换字符串

                           Stringreplace(CharSequence target, CharSequence replacement)

                           StringreplaceAll(String regex, String replacement)

                           StringreplaceFirst(String regex, String replacement)

               */         

              String str2 ="a1bb222cccc34";

              //a bb - cccc

              String [] str2s =str2.split("\\d",0);

              System.out.println(str2s.length);

              for(String s:str2s){

                     System.out.println(s+"&");

              }

       }

}

public class Reg2 {

       publicstatic void main(String[] args) {       

              /**

               * 思考实例:

              《1》验证如下格式xxx-xx-xxxx   x代表数字,正则表达式?

                     \\d{3}-\\d{2}-\\d{4}

              《2》验证字符串是字符、数字、_组成,首个为字母,正则表达式?

                     [a-zA-Z]{1}\\w+

              《3》验证字符串格式为email, 正则表达式?  

                     正则:\\w+@\\w+.\\w+

              《4》验证字符串格式为手机号,要求13xxxxxxxxx或15xxxxxxxxx,正则表达式?

              《5》给定一个ip地址 例如192.168.20.100,完成按照.分割字符,然后获得数字的和?

               */

              String ip ="192.168.20.100";

              String []ips = ip.split("\\.");//容易出错

              int result = 0;

              for(String s:ips){

                     result+=Integer.parseInt(s);

              }

              System.out.println(result);

       }

}   

3.异常:

java.lang

类 Exception

结构如下:

 *try{

      异常源

             ------第一行出现异常   后面不会执行直接进入catch 从而改变代码流程

             ------

 

 *}catch(异常类型){

             发生异常,捕获后处理代码

   }

 *finally{

             最终代码 一定会执行的代码块

  }

* 出现异常后就会改变正常的程序流程

* 异常处理 try catch finally 可以嵌套

* 还可以  一个try 多个catch,

* 但是注意:多个catch必须从小到大  如果异常类型没有大小关系,上下无所谓

* 通常的习惯是:上面写具体的异常类型,最后放一个Exception

public class Exception1 {

       publicstatic int div(int a,int b){

              int result = 0;

              try{

                     result=  a/b;

              }catch(ArithmeticException e){

                     //e.getMessage()获得异常信息

                     System.out.println("发生了异常:"+e.getMessage());

                     //e.printStackTrace();//打印异常栈轨迹

                     result= -1;

                     returnresult;

                     //会先检查有没有finally 如果有先执行完finally,再返回来执行return

              }finally{

                     System.out.println("finally一定执行");

              }           

              return result;

       }    

       publicstatic void main(String[] args) {

              int result = Exception1.div(10, 0);

              System.out.println(result);

       }

}

public class Exception2 {

       publicstatic int div(int a,int b) throws Exception{

              int result = 0;

              try{

                     result=  a/b;

              }catch(NullPointerException e){

                    

              }catch(ArithmeticException e){

                     //如果发生异常  我们不处理,就要往外抛异常

                     //在catch中抛异常,通常是   throw 异常对象

                     thrownew Exception();              

                     //如果处理时抛的是受查型异常   必须处理  或者方法定义上使用

                     //throws异常类型, 将来谁调用该方法,就处理异常

              }catch (Exception e){

                    

              }

              finally{

                     System.out.println("finally一定执行");

              }

             

              return result;

       }    

       publicstatic void main(String[] args) throws Exception {

              int result=0;

              result = Exception2.div(10, 0);

              System.out.println(result);

       }

常见异常:

(1)类 ClassNotFoundException     当应用程序试图使用以下方法通过字符串名加载类时,抛出该异常:

(2)类 DataFormatException        当数据格式发生错误时,抛出此异常。

(3)类 InstantiationException     当应用程序试图使用 Class 类中的 newInstance 方法创建一个类的实例,而指定的类对象无法被实例化时,抛出该异常。

                                实例化失败有很多原因,包括但不仅限于以下原因:

                                  类对象表示一个抽象类、接口、数组类、基本类型、void

                                  类没有非 null 构造方法

(4)类 NoSuchAttributeException   尝试访问不存在的属性时,抛出此异常。

(5)类 NoSuchMethodException      无法找到某一特定方法时,抛出该异常。

(6)类 SQLException       提供关于数据库访问错误或其他错误信息的异常。

(7)类 TransformerException      此类指定了转换过程中发生的异常条件。

(8)类 RuntimeException      那些可能在 Java 虚拟机正常运行期间抛出的异常的超类。

    可能在执行方法期间抛出但未被捕获的 RuntimeException 的任何子类都无需在 throws 子句中进行声明

   运行时异常包含:

 (a)类 ArithmeticException       当出现异常的运算条件时,抛出此异常。例如,一个整数“除以零”时,抛出此类的一个实例。

 (b)类 ArrayStoreException    试图将错误类型的对象存储到一个对象数组时抛出的异常

 (c)类 ClassCastException     当试图将对象强制转换为不是实例的子类时,抛出该异常。

 (d)类 EmptyStackException    该异常由 Stack 类中的方法抛出,以表明堆栈为空。

 (e)类 IllegalArgumentException抛出的异常表明向方法传递了一个不合法或不正确的参数。

 (f)类 IndexOutOfBoundsException 指示某排序索引(例如对数组、字符串或向量的排序)超出范围时抛出。

     越界异常包含:

       类ArrayIndexOutOfBoundsException  用非法索引访问数组时抛出的异常。如果索引为负或大于等于数组大小,则该索引为非法索引。

       类 StringIndexOutOfBoundsException 此异常由 String 方法抛出,指示索引或者为负,或者超出字符串的大小。

              对诸如 charAt 的一些方法,当索引等于字符串的大小时,也会抛出该异常。

 (g)类 JMRuntimeException       由 JMX 实现所发出的运行时异常。

 (h)类 NegativeArraySizeException如果应用程序试图创建大小为负的数组,则抛出该异常。

  (i)类 NullPointerException      当应用程序试图在需要对象的地方使用 null 时,抛出该异常。

     这种情况包括:

       调用 null 对象的实例方法。

       访问或修改 null 对象的字段。

       将 null 作为一个数组,获得其长度。

       将 null 作为一个数组,访问或修改其时间片。

       将 null 作为 Throwable 值抛出。

     应用程序应该抛出该类的实例,指示其他对 null 对象的非法使用。

  (j)类SystemException     SystemException 扩展了 java.lang.RuntimeException,

考题:异常(Exception )和错误(Error)区别:

     exception 表示一种设计或实现问题。也就是说,它表示如果程序运行正常,从不会发生的情况。

     error 表示恢复不是不可能但很困难的情况下的一种严重问题。比如说内存溢出。不可能指望程序能处理这样的情况

 

考题:final、finally{}、finalize()区别:

     Final 用于声明属性,方法和类,分别表示属性不可变,方法不可覆盖,类不可继承。

           内部类要访问局部变量,局部变量必须定义成final类型,  

    finally是异常处理语句结构的一部分,表示一定会执行。

    finalize是Object类的一个方法,当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。子类重写 finalize 方法,以配置系统资源或执行其他清除。

考题:throw 和 throws 区别

 throw通常在代码中抛异常对象 

 throws是在方法定义后抛异常类型

  当一个方法抛出了受查型异常,必须捕获或者方法往外throws 异常类型

 

考题:请写出你最常见到的5个runtime exception。

     NullPointerException、ArrayIndexOutOfBoundsException、ClassCastException、ArithmeticException、SystemException

 

考题:运行时异常与一般异常有何异同?

     异常表示程序运行过程中可能出现的非正常状态,运行时异常表示虚拟机的通常操作中可能遇到的异常,是一种常见运行错误。

     java编译器要求方法必须声明抛出可能发生的非运行时异常,但是并不要求必须声明抛出未被捕获的运行时异常。

 

4..开发supervcd项目

   开发一个DataAccess类  

   编写一个方法使用Map封装多个专辑

  DataAccess类   中增加一个根据地区类别查询专辑方法

   测试类测试

import java.util.*;

public class DataAccess {

       protectedHashMap<String,MusicRecording> map;

      

       publicHashMap<String, MusicRecording> getMap() {

              return map;

       }

       publicvoid setMap(HashMap<String, MusicRecording> map) {

              this.map = map;

       }

       publicDataAccess(HashMap<String, MusicRecording> map) {

              super();

              this.map = map;

       }

       publicDataAccess(){

              map=newHashMap<String,MusicRecording>();

       }

       publicHashMap<String,MusicRecording> getMap(MusicRecording mr){

              map=newHashMap<String,MusicRecording>();

              map.put(mr.getCategory(), mr);

              return map;

       }

       publicVector<MusicRecording> selectTrack (String str){        

              Vector<MusicRecording> vp=newVector<MusicRecording>();

              MusicRecording v=map.get(str);

              vp.add(v);

              return vp;

       }    

}

 

 

 

 

 

 

 

 

 

 

2011.8.1         周一

1.异常类:

  (1)异常的传播:如果产生异常不起捕获,异常将会导致应用程序中断。

package sample;

public class ExceptionStackTest {

       publicvoid a() throws Exception{            

b();

       }

       publicvoid b() throws Exception{

              c();

       }

       publicvoid c() throws Exception{

       throw new Exception();   //往外抛异常,Main函数处理

       }

       publicstatic void main(String[] args) {

                ExceptionStackTest est = new ExceptionStackTest();

                  try{                   //必须有异常处理,否则程序瘫痪

                       est.a();

              }catch(Exception e){

                      e.printStackTrace();

              }

   }

(2)异常的层次:

       Error一般由类产生,表示类的状态不正常。

       应用程序不能不从Error中恢复

       所有的java异常型来自于Exception类

  (3)     运行时异常也叫非受查型异常

           一个非受查异常不必必须捕获

  (4)普通受查异常:

              java.lang.ArithmeticException  

              java.lang.NullPointerException 

              java.lang.ArrayIndexOutofBoundsException       

       java.lang.SecurityException     / /安全异常

              java.lang.NegativeArraySizeException

2.写一个类DivisionByZero,该类中有个division()方法,在division()方法中实现除法运算,用异常处理的概念来处理产生的异常

编写测试类测试

 public class DivisionByZero {

       publicstatic int divisio(int a,int b){

              int result = 0;

              try{

                     result=  a/b;

              }catch(ArithmeticException  e){

                     System.out.println("发生了异常:"+e.getMessage());       

                     result= -1;

              }

              catch(Exceptione){

                     System.out.println("发生了异常:"+e.getMessage());       

                     result= -2;           

              }finally{

                     System.out.println("执行了finally");

              }           

              return result;  

       }

 }

 public class DivisionByZeroTest {     

       publicstatic void main(String[] args) {

              int result=DivisionByZero.divisio(45, 0);

              System.out.println(result);

       }

 }  

3.自定义异常类:

  开发步骤

 《1》受查型异常继承Exception   

     非受查型异常继承RuntimeException

      受查型异常,捕获时,代码必须有抛出该类异常

4.写三个类:

       OwnException自定义异常类

       OwnExceptionSource异常源类

       OwnExcpeitonHandler异常处理类 可以直接写测试方法

       OwnExceptonSource中有个方法a(),在a()中抛出一个异常OwnException,然后在OwnExceptionHandler中调用a()并且要处理异常

 

 public class OwnExceptionextends RuntimeException  {

   publicOwnException(String message){ //构造函数调用父类的构造函数,给message传值

              super(message);   //调用父类用super()

       }    

       publicOwnException(){

              this("数组索引越界了");    //同类构造函数调用用this

       }

}

 

 public class OwnExceptionSource{   

       publicstatic void a()throws OwnException{   

              String str="abc123";

              char [] ch=str.toCharArray();

              try {

                     for(inti=0;i<=ch.length;i++){

                            System.out.println(ch[i]);

                     }

              } catch (Exception e) {

                     throw new OwnException();

              }

       }    

 }

 public class OwnExcpeitonHandler {

       publicstatic void main(String[] args)  {

              try {

                     OwnExceptionSource.a();

              } catch (OwnException e) {

                     System.out.println(e.getMessage());

              }

       }

 }

 

5.AWT:Abstract Window Toolkit 抽象窗口工具

     提供了一组对象用来创建图形用户界面(GUI)

     在java.awt包中有主要的三种类型的类

       (1)组件:AWT中基础类包括容器

       (2)容器:一个能容纳其它组件的特殊化的组件

       (3)布局管理器:负责在一个容器内管理组件尺寸,位置信息的一个接口

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


6.流程:

       1选择一个容器(组件可以添加到容器中)  通常是窗体(通常要先选择一个顶级容器)

               * 常用容器    Frame Panel  Dialog(FileDialog) Applet

               * 顶级容器:自己可以直接存在,然后盛放其他组件 Frame Dialog

               * 二级容器:自己不能直接存在,必须放在某个顶级容器中存在Panel  Applet

               * 容器可以被继承>组件都可以被继承

               * Frame  继承Window  的顶级容器

                  * 有标题、边框和菜单条MenuBar

                   * 默认的布局方式是BorderLayout管理器

                  * 用setLayout()方法改变布局管理器

 

 

 

 

 

 

 

 

 

 

 

 


        2.设置布局管理器

               * 使用容器的setLayout(new Borderlayout())方法设置一个布局管理器

               * 作用:

                 * 在容器中限制组件的尺寸和位置

                 * 调用组件的setLocation(),setSize(),setBounds()方法来规定组件的尺寸和位置

       注意:有的布局管理器,组件就按照自己的方法设置大小,只能适应布局管理器的大小

               * Window类型下的容器默认的布局方式是BorderLayout

               * Panel类型下的容器默认的布局方式是FlowLayout

        3 创建组件  添加组件到容器

        4.创建事件处理器   给组件添加事件监听器

        5.设置位置大小  可见

例:public classAWT1 {

       publicstatic void main(String[] args) {

              Frame f = new Frame("标题");      //1.选择容器

            //f.setTitle("标题");

              f.setLayout(new BorderLayout());   //2.设置布局管理器

 

              Button b1 = new Button("北丐");   //3.创建组件

              //b1.setLabel("北丐");

              Button b2 = new Button("南帝");

              Button b3 = new Button("东邪");

              Button b4 = new Button("西毒");

              Button b5 = new Button("中神通");

              f.add(b1,BorderLayout.NORTH);    //3.添加组件到容器

              f.add(b2,BorderLayout.SOUTH);

              f.add(b3,BorderLayout.EAST);

              f.add(b4,BorderLayout.WEST);

              //f.add(b5,BorderLayout.CENTER);

              f.add(b5);//BorderLayout默认放Center

              f.setLocation(200, 300);          //5.设置位置大小可见

              f.setSize(400, 300);             

              //f.setBounds(200, 300, 300, 300);

              //f.show();//show()方法过时

              f.setVisible(true);

       }

    }

  组件可以被继承:

import java.awt.BorderLayout;

import java.awt.Button;

import java.awt.Frame;

public class AWT2 extends Frame{

       publicAWT2(){}

       publicAWT2(String title){

              super(title);    //调用父类Frame的构造函数

       }

       privateButton b ;

       publicvoid init(){

              //this.setTitle("标题");          

              //设置布局

              this.setLayout(new BorderLayout());          

              //创建组件  添加组件

              b = new Button("按钮");

              this.add(b,BorderLayout.SOUTH);             

              //事件                         

       }

       publicstatic void main(String[] args) {

              AWT2 f = new AWT2("标题");//创建一个窗体

              //f.setTitle("标题");       

              f.init();

              f.setBounds(200, 200, 300, 200);

              f.setVisible(true);

       }

}

public class AWT3 extends Frame{

       privateButton b ;

       publicAWT3(){ }

       publicAWT3(String title){

              super(title);

              //this.setTitle("标题");          

              //设置布局

              this.setLayout(new BorderLayout());          

              //创建组件  添加组件

              b = new Button("按钮");

              this.add(b,BorderLayout.SOUTH);             

              //事件           

       }                  

       publicstatic void main(String[] args) {

              AWT3 f = new AWT3("标题");//创建一个窗体         

              f.setBounds(200, 200, 300, 200);

              f.setVisible(true);

       }

}

7.Panel 二级容器  需要放在顶级容器中使用

        * 作用:放组件

        * 默认布局管理器 FlowLayout

* BorderLayout

               * 东西南北中五部分,每部分只能直接放一个组件,

               * 如果某一个部分放多个,后放入的会覆盖先放入的组件

               * 当某个部分需要放入多个组件时,我们需要使用Panel面板包装几个组件,

               * 然后将一个panel放入到BorderLayout的某部分

import java.awt.BorderLayout;

import java.awt.Button;

import java.awt.Frame;

import java.awt.Label;

import java.awt.Panel;

 

public class PanelTest {

       publicstatic void main(String[] args) {

              Frame f = new Frame("Panel");          

              f.setLayout(new BorderLayout());       

              //北部

              Label l = new Label();

              l.setText("显示信息");   //给标签设置标题

              f.add(l,BorderLayout.NORTH);           

              //南部           

              Button b1 = new Button("OK按钮");

              Button b2 = new Button("NO");   

              Panel p = new Panel();   //也需要根据需求设置布局管理器  默认FlowLayout

              p.add(b1);

              p.add(b2);

              f.add(p,BorderLayout.SOUTH);          

              f.setBounds(200, 200, 300, 200);

              f.setVisible(true);

       }

}

容器的布局:

Flow Layout:流式布局管理器

Border Layout:边框布局管理器

Grid Layout:网格布局管理器

Card Layout:卡片布局管理器

GridBag Layout:网格包布局管理器

 

8.public class FlowLayoutTest {

       publicstatic void main(String[] args) {

              Frame f = newFrame("FlowLayout");

              /**

               * 流式布局  默认对其方式  居中

               */

              f.setLayout(new FlowLayout(FlowLayout.LEFT,20,30));   //设置对齐    

              Button b1 = new Button("按钮1");

              Button b2 = new Button("按钮2");

              Button b3 = new Button("按钮3");

              Button b4 = new Button("按钮4");             

              f.add(b1);f.add(b2);f.add(b3);f.add(b4);             //按序放置

              f.setBounds(200, 200, 300, 200);

              f.setVisible(true);

       }

 }

 

9.public class GridLayoutTest {

       /**

        * 网格式布局管理器

        * 组件不会是最佳大小

        * 单元格都大小相同

       publicstatic void main(String[] args) {

              Frame f = newFrame("GridLayout");

              f.setLayout(new GridLayout(2,2,10,20));

              Button b1 = new Button("按钮1");

              Button b2 = new Button("按钮2");

              Button b3 = new Button("按钮3");

              Button b4 = new Button("按钮4");             

              f.add(b1);f.add(b3);    //按序放置

              f.add(b4);f.add(b2);             

              f.setBounds(200, 200, 300, 200);

              f.setVisible(true);          

       }

 }

10.public class CardLayoutTest {

       publicstatic void main(String[] args) {

              Frame f = new Frame("CardLayout练习");

              f.setLayout(new CardLayout());   

              Button b1 = new Button("按钮1");

              Button b2 = new Button("按钮2");

              Button b3 = new Button("按钮3");

              Button b4 = new Button("按钮4");

              f.add(b1,"b1"); //CardLayout添加组件必须有个String约束名,不要重复

              f.add(b2,"b2");

              f.add(b3,"b3");

              f.add(b4,"b4");      

              f.setBounds(200, 200, 300, 200);

              f.setVisible(true);

       }

 }

1.编写如下图形界面:

public class PanelTest {

       publicstatic void main(String[] args) {

              Frame f=new Frame("PanelTest");             

              f.setLayout(new BorderLayout());       

              Label l=new Label();

              l.setText("显示信息的标签");

              f.add(l,BorderLayout.NORTH);                  

              Panel p=new Panel();           

              p.setLayout(new FlowLayout());         

              Button b1=new Button();

              b1.setLabel("OK");       

              Button b2=new Button("Panic");

              p.add(b1,"B1");

              p.add(b2, "B2");           

              f.add(p,BorderLayout.SOUTH);                 

              f.setBounds(200, 300, 400, 200);

              f.setResizable(false);   //设置边框大小不可改变

              f.setVisible(true);          

       }

}

4、分析模拟supervcd主界面的布局设置

 

import java.awt.*;

public class StoneForest {

    public static void main(String[] args) {

        Frame f = new Frame("欢迎使用StoneForest应用!"); 

        //菜单

        MenuBar menu=new MenuBar();

        menu.add(new Menu("文件"));

        menu.add(new Menu("选项"));

        menu.add(new Menu("帮助"));

        f.setMenuBar(menu);

        //中间的

        Label l1=new Label("音乐");

        Panel p2=new Panel(new FlowLayout(FlowLayout.LEFT));

        Label l2=new Label("选择音乐目录");

        Choice chooser = new Choice(); //下拉列表框

        chooser.add("-----");

        chooser.add("大陆");

        chooser.add("港台");

        chooser.add("新加坡");

        chooser.add("欧美");

        TextArea t=new TextArea(13,45);  //多行文本域

        p2.add(l2);

        p2.add(chooser);

        p2.add(t);

        f.add(l1);

        f.add(p2);

        //底部的

        Button b1=new Button("详细…");

        Button b2=new Button("清空");

        Button b3=new Button("退出");

        Panel p=new Panel();

        p.add(b1);

        p.add(b2);

        p.add(b3);

        f.add(p,BorderLayout.SOUTH);   

        f.setBounds(200, 200,350, 350);

        f.setVisible(true);

    }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

2011.8.3     周三

1.Component Methods 组件的方法

setForeground()、getForeground()    前景色(放的东西的颜色)

setBackground() 、getBackground()   背景色

setEnabled() getEnabled()  可见性(可以看见但不能操纵,显示灰色)

setVisible() 、getVisible()    可见性

setFont() 、getFont()   字体

setSize() 、getSize()   大小

getPreferredSize()   获取最佳大小

setLocation() 、getLocation()   位置

setBounds() 、getBounds()   大小及位置

paint()    画

repaint()   重新画

update()  更新

实例

class AWTTest extends Frame {    

       publicAWTTest() {

                     super("Components Test");

                     this.addWindowListener(new WindowAdapter() {   //匿名内部类

                          public voidwindowClosing(WindowEvent evt) {

                              setVisible(false);

                              dispose();        //Frame窗体的关闭步骤                                                                   System.exit(0);

                          }

                     });

                     this.setSize(300,300);

                     this.setLayout(new FlowLayout());

                     this.add(new Button("Button"));  //按钮

                     this.add(new Checkbox("CheckBox", true));  //复选框默认选中             

                     Choice ch = new Choice();    //下拉列表框

                     ch.add("Choice1");

                     ch.add("Choice2");

                     this.add(ch);          

                     this.add(new Label("Label"));    //标签

                     class MyCanvas extends Canvas {   //画布

                        public void paint(Graphics g) {

                            g.drawString("Canvas",10,10);    //不是实心的

                                    g.fillString("Canvas",10,10);      //是实心的

                        }

                     }

                     Canvas c = new MyCanvas();

                     c.setBackground(Color.black);

                     c.setForeground(Color.white);

                     c.setSize(60, 50);

                     this.add(c);                            

                     List l = new List(4, false);    //列表框

                     l.add("List item 1");

                     l.add("List item 2");

                     this.add(l);  

                     this.add(new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0, 255));   //滚动条

                     this.add(new TextArea("TextArea", 5, 40));      //文本编辑区域

                     this.add(new TextField("TextField"));           //单行文本

                  }   

                  public static void main (String [] args) {

                     new AWTTest().setVisible(true);

                  }

                }

 

2.Button 按钮

 是一个能够当用户产生点击时能产生一个动作的组件

构造方法:

Button()  

Button(String label)

其它方法:

setActionCommand() andgetActionCommand()   

setLabel() and getLabel() 

addActionListener() andremoveActionListener()

getActionListeners()

3.Canvas 画布

  用于显示图形

  在画布上可以用各种颜色描绘几何图形,像素,文本

构造方法:

Canvas()  

Canvas(GraphicsConfiguration conf)

其它方法:

paint()  / /repaint()默认调用paint()方法

update()

requestFocus()   //获得焦点

实例

public class CanvasTest extends Canvasimplements KeyListener {

   int index;

   Color[] colors= {Color.red, Color.green, Color.blue };  

   public CanvasTest() {

       addKeyListener(this);

   }      

   public void paint(Graphics g) {

       g.setColor(colors[index]);

       g.fillRect(0,0,getSize().width,getSize().height);

       g.drawRect(0,0,getSize().width,getSize().height);

       if(index==colors.length-1){

              index=0;

       }

       g.setColor(colors[index+1]);

       g.fillOval(100, 100, 100, 100);

    }

   public static void main(String args[]) {

       final Frame f = new Frame("Canvas");

       f.addWindowListener(new WindowAdapter() {

           public void windowClosing(WindowEvent evt) {

               f.setVisible(false);

                f.dispose();

                System.exit(0);

           }

       });

       CanvasTest mc = new CanvasTest();

       f.add(mc,BorderLayout.CENTER);

       f.setSize(150, 150);

       mc.requestFocus();

       f.setVisible(true);

    }

   public void keyTyped(KeyEvent ev) {

       index++;

       if (index == colors.length) {

           index =0;

       }

       repaint(); //默认调用paint()方法

    }

   public void keyPressed(KeyEvent ev) {

    }

 

   public void keyReleased(KeyEvent ev) {

    }

}

4.Checkbox 复选框

  单独使用,显示一个复选框或者是选中,或者是没选中

  也checkboxgroup中的一部分,显示为单选按钮

构造方法:

Checkbox()  

checkbox(String label) 

checkbox(String label, boolean state)  //默认状态是否选中   

checkbox(String label, boolean state,CheckboxGroup group)   //分组

checkbox(String label,CheckboxGroup group,boolean state)

其他方法:

addItemListener() andremoveItemListener()  

setState() and getState() 

setLabel() and getLabel()

如果变成单选按钮组,必须使用同一个CheckboxGroup封装

CheckboxGroup方法:

getSelectedCheckbox() andsetSelectedCheckbox()

实例:

public class CheckboxTest {

       publicstatic void main(String[] args) {

              Frame f = newFrame("CheckboxTest");

              f.setLayout(newFlowLayout(FlowLayout.LEFT));   //居左对齐

              Checkbox cb1 = new Checkbox();

              cb1.setLabel("足球");

              Checkbox cb2 = new Checkbox("篮球",true);

              f.add(cb1);

              f.add(cb2);

              CheckboxGroup group = newCheckboxGroup();

              Checkbox cb3 = new Checkbox();

              cb3.setLabel("男");

              cb3.setCheckboxGroup(group);

              Checkbox cb4 = new Checkbox("女",true,group);

              f.add(cb3);

              f.add(cb4);

              f.setBounds(300, 300, 400, 300);

              f.setVisible(true);

       }

}

实例

class CheckboxTest extends Frame implementsItemListener {

    Label l = new Label("Record the state");    

    public CheckboxTest() {

       super("Checkboxes and Radio buttons");

       this.addWindowListener(new WindowHandler());

       this.setSize(300,200);

       this.setLayout(new FlowLayout()); 

       Checkbox[] cb = new Checkbox[6];

       this.add(cb[0] = new Checkbox("Watermelons", true));

       this.add(cb[1] = new Checkbox("Kiwis", true));

       this.add(cb[2] = new Checkbox("Apples", true));

       CheckboxGroup group = new CheckboxGroup();

       this.add(cb[3] = new Checkbox("Windows", group, true));

       this.add(cb[4] = new Checkbox("Linux", group, false));

       this.add(cb[5] = new Checkbox("Macintosh", group,false)); 

       for(int i = 0; i < cb.length; i++)

           cb[i].addItemListener(this);

       l.setBackground(Color.black);

       l.setForeground(Color.green);

       l.setSize(300, 40);

       this.add(l);

    }    

    public static void main (String [] args) {

        new CheckboxTest().setVisible(true);

     }   

     public void itemStateChanged(java.awt.event.ItemEvent itemEvent) {

         String state = "deselected";

        if(itemEvent.getStateChange() == itemEvent.SELECTED)

            state = "selected";

        Checkbox cb = (Checkbox)itemEvent.getSource();

        l.setText(cb.getLabel() + " is " +  state);

     }     

      class WindowHandler extends WindowAdapter {

         public void windowClosing(java.awt.event.WindowEvent windowEvent) {

            CheckboxTest.this.setVisible(false);

            CheckboxTest.this.dispose();

            System.exit(0);

         }

    }

}

5.Choice 下拉选择框

  带有选择项的下拉菜单

  只有当前被选中的项目能显示在屏幕上

构造方法:

Choice()

其它方法:

add() and insert()   

getSelectedItem(), getSelectedIndex() andgetItem()

addItemListener() and removeItemListener()

实例:

public class ChoiceTest {

       publicstatic void main(String[] args) {

              Frame f = newFrame("ChoiceTest");

              f.setLayout(new FlowLayout());  //默认居中对齐

              final Choice ch = new Choice();

              ch.add("-----------");

              ch.add("大陆");

              ch.add("港台");

              ch.add("欧美");

              ch.add("新加坡");

              ch.insert(其它, 5);

              f.add(ch);

              f.setBounds(300, 300, 400, 300);

              f.setVisible(true);

       }

}

6.Label 标签

  用于在屏幕上显示文本内容

  Label不能直接同用户产生交互动作,没有事件

构造方法:

Label()     

Label(String text)     

Label(String text, int alignment)其他方法:

setText() and getText()

实例:

public class LabelTest {

       publicstatic void main(String[] args) {

              Frame f = newFrame("LabelTest");

              f.setLayout(new BorderLayout());                     

Label l = new Label("选择音乐目录:");

              f.add(l);

              f.setBounds(300, 300, 400, 300);

              f.setVisible(true);

       }

}

7.List 列表框

  在屏幕上显示字符串列表  有滚动条

  允许用户在列表框中选择一个或多个选项

  AWT List组件放的内容是String字符串

  将来使用SwingJList组件  放的内容是Object对象

  * List组件清空removeAll()

  * 将来使用SwingJList组件时,清空使用removeAll()无效

构造方法:

List()   

List(int rows)   

List(int rows, boolean multipleMode)   //支持多选

其它方法:

add() and remove(), removeAll()   //add是字符串

addActionListener() andremoveActionListener()   

getSelectedItem(), getSelectedItems(),getSelectedIndex()

getSelectedIndexes(), getItem(), getItems()

实例:

public class ListTest {

       publicstatic void main(String[] args) {

              Frame f = new Frame("ListTest");

              f.setLayout(new BorderLayout());

              List l=new List(10,true); //支持多选

              l.add("真的,用了心");

              l.add("真的英雄");

              l.add("你给我一片天");

              l.add("明明白白我的心");

              l.add("在我生命中的每一天");

              l.add("问心无愧");

              l.add("对不起自己");

              l.add("壮志在我胸");           

              f.add(l,BorderLayout.CENTER);

              f.setBounds(300, 300, 400, 300);

              f.setVisible(true);

       }

}

8.Textfield 单行文本输入框

  可以输入单行文本并可以编辑

  AWT中没有单独的密码输入框,使用文本输入框,然后设置它的回显字符为*

构造方法:

Textfield()     

Textfield(int columns)    //显示几列   

Textfield(String text)     //指明文本,默认有值  

Textfield(String text, int columns)

其它方法:

setText() and getText()    

addActionListener() andremoveActionListener()   

setEditable() andisEditable()   //是否可以编辑

setEchoChar() andgetEchoChar()    //设置回滚字符 

实例:

public class TextfieldTest {

       publicstatic void main(String[] args) {

              Frame f = newFrame("TextfieldTest");

              f.setLayout(new BorderLayout());       

              Label name = new Label("账户:");

              Label password = new Label("密码:");

              TextField tf1 = newTextField("",10);

              TextField tf2 = newTextField("",10);

              tf.setEditable(false);//设置是否可编辑

              tf2.setEchoChar('*');//设置回显字符

              f.add(name);

              f.add(tf1);

              f.add(password);

              f.add(tf2);

              f.setBounds(300, 300, 400, 300);

              f.setVisible(true);

       }

}

9.TextArea 多行文本编辑区

  可以进行多行文本输入和编辑

  含有滚动条

构造方法:

TextArea()   

TextArea(int rows , intcols )  

TextArea(String text)   

TextArea(String text, int rows, intcols)   

TextArea(String text, int rows, int cols,int scrollbars)

其它方法:

getText() and setText(),

append(), insert(), replaceRange()   

addTextListener() and removeTextListener()

实例:

public class TextAreaTest {

       publicstatic void main(String[] args) {

              Frame f = newFrame("TextAreaTest");

              f.setLayout(new BorderLayout());

              TextArea ta = new TextArea(10,50);

              f.add(ta);                     

              f.setBounds(300, 300, 400, 300);

              f.setVisible(true);

       }

}

10.Dialog 对话框

  是一个含有Titleborder的顶级Window

  默认的布局方式是BorderLayout

  对话框必须要有主容器

  可以是非模态和模态的

构造方法:

Dialog(Dialog owner), 

Dialog(Dialog owner, String title),     

Dialog(Dialog owner, String title, booleanmodal),    

Dialog(Dialog owner, String title, booleanmodal, GraphicsConfiguration gc),     

Dialog(Frame owner),

Dialog(Frame owner, boolean modal),  

Dialog(Frame owner, String title),

Dialog(Frame owner, String title, booleanmodal)   

Dialog(Frame owner, String title, booleanmodal, GraphicsConfiguration gc)

其它方法:

setModal() and isModal()   

setTitle() and getTitle()   

setResizable() andisResizable()     //设置可拉伸性

show() and hide()   

dispose()   //释放对象

实例:

public class DialogTest {

       publicstatic void main(String[] args) {

              Frame f = new Frame("Dialog练习");        

              Dialog d = new Dialog(f,"对话框");

               //model true 有模式的   对话框打开,owner不能操作(无法获得焦点)

              //Dialog d = new Dialog(f,"对话框",true);

              //d.setTitle("对话框");

              d.setBounds(200, 200, 300, 250);

              d.setResizable(false);

              f.setBounds(300, 300, 400, 300);

              f.setResizable(false);    //设置大小可变

              f.setVisible(true);

              d.setVisible(true);

       }

}

11.FileDialog 文件对话框

  模态的对话框  用于选择文件

构造方法:

FileDialog(Frame parent)   

FileDialog(Frame parent, String title)   

FileDialog(Frame parent, String title, intmode)

其他方法:

setFile() and getFile() 

setMode() and getMode()   

setDirectory() and getDirectory()

setFilenameFilter() and getFilenameFilter()

实例:

public class FileDialogTest {

   public static void main(String[] args) {

       FileDialog fd = new FileDialog(new Frame(), "Choose a file",FileDialog.LOAD);

       FilenameFilter ff = new MyFilenameChooser();

       fd.setFilenameFilter(ff);

       fd.setVisible(true);

       String name = fd.getFile();

       System.out.println("You chose the file: " + name);

       System.exit(0);

    }

}

class MyFilenameChooser implementsFilenameFilter{

   public boolean accept(File dir, String name) {

       return name.endsWith("java");

    }

}

12.ScrollPane  可滚动区

  是个容器

  为单个的内部组件自动添加水平或者垂直滚动条

构造方法:

ScrollPane() 

ScrollPane(int scrollbarDisplayPolicy)其他方法:

setLayout()  

setScrollPosition() and getScrollPosition()、

13.菜单的层次关系

 

 

 

 

 

 

 

 

 

 

 


至少有三种类型的菜单 菜单条、菜单、菜单项

 MenuBar:紧靠着Window顶部的一个横条

 Menus:包含在MenuBar中

 MenuItems:包含在Menu中

菜单类的方法:

getFont() and setFont()

getName() and setName()

getParent() 

(1)MenuBar 菜单条

     在紧靠Frame顶部创建的一个包含Menu的一个横条

     使用Frame类的setMenuBar()方法添加MenuBar

    构造方法:

           MenuBar()   

    其它方法:

         add() and remove()

           getMenu() and getMenuCount() 

(2)Menu 菜单

     主要功能是包含MenuItem

     继承于MenuItem类,当然可以包含其他的Menu

   构造方法:

       Menu() 

       Menu(Stringlabel)  

       Menu(Stringlabel, boolean tearOff)  

  其他方法:

       add(),insert(),

       addSeparator() //添加分割符

       remove(),

       removeAll()

  getItem(), getItemCount() 

(3)MenuItem 菜单项

     可以选择的一种菜单的标签

   构造方法:

       MenuItem() 

       MenuItem(Stringlabel)

       MenuItem(Stringlabel, MenuShortcut s)

   其他方法:

       addActionListener()and removeActionListener()

   setActionCommand() and getActionCommand()

       setLabel()and getLabel()

       setEnable()and isEnable() 

(4)PopupMenu 弹出菜单

     在组件的内部和相应的位置上动态弹出

   构造方法:

       PopupMenu()

       PopupMenu(Stringlabel)  

   其他方法:

      methods inherited from Menu

       show()

实例:

public class MenuTest {

       publicstatic void main(String[] args) {

              Frame f = new Frame("SuperVCD 菜单练习");

              //菜单条

              MenuBar bar = new MenuBar();          

              //三个主菜单

              Menu file = new Menu("文件");

              Menu option = new Menu("选项");

              Menu help = new Menu("帮助");        

              //添加file菜单项

              Menu open = new Menu("打开");

                     MenuItemop1 = new MenuItem("本地...");

                     MenuItemop2 = new MenuItem("局域网...");

                     MenuItemop3 = new MenuItem("互联网...");

                     open.add(op1);open.add(op2);open.add(op3);

              MenuItem save = new MenuItem("保存");

              MenuItem exit = new MenuItem("退出");

              file.add(open);

              file.add(save);

              file.addSeparator();//添加分割线    在哪里调用,就再哪添加

              file.add(exit);        

              //添加option菜单项

              MenuItem option1 = new MenuItem("选项1");

              MenuItem option2 = new MenuItem("保存2");

              MenuItem option3 = new MenuItem("保存3");

              option.add(option1);option.add(option2);option.add(option3);           

              //添加help菜单项

              MenuItem about = new MenuItem("关于...");

              help.add(about);           

              //将三个菜单添加到菜单条

              bar.add(file);bar.add(option);bar.add(help);         

              //给主窗体设置菜单条

              f.setMenuBar(bar);              

              f.setBounds(300, 300, 400, 300);

              f.setResizable(false);

              f.setVisible(true);

       }

}  实例:

class MenuTest extends Frame {

    PopupMenu pop;

    public MenuTest() {

       super("Golf Caddy");

       addWindowListener(new WindowAdapter() {

           public void windowClosing(WindowEvent evt) {

                setVisible(false);

                dispose();

                System.exit(0);

           }

       });

       this.setSize(300,300);

       this.add(new Label("Choose club."), BorderLayout.NORTH);     

       Menu woods = new Menu("Woods");

       woods.add("1 W");

       woods.add("3 W");

       woods.add("5 W");

       Menu irons = new Menu("Irons");

       irons.add("3 iron");

       irons.add("4 iron");

       irons.add("5 iron");

       irons.add("7 iron");

       irons.add("8 iron");

       irons.add("9 iron");

       irons.addSeparator();

       irons.add("PW");

       irons.insert("6 iron", 3);      

       MenuBar mb = new MenuBar();

       mb.add(woods);

       mb.add(irons);

       this.setMenuBar(mb);     

       pop = new PopupMenu("Woods");

        pop.add("1 W");

       pop.add("3 W");

       pop.add("5 W");    

       final TextArea p = new TextArea(100, 100);

       p.setBackground(Color.green);

       this.addMouseListener(new MouseAdapter() {

           public void mouseReleased(java.awt.event.MouseEvent evt) {

                if(evt.isPopupTrigger()) {

                       System.out.println("popup trigger");

                       System.out.println(evt.getComponent());

                       System.out.println("" + evt.getX()+ " " +evt.getY());

                       pop.show(evt.getComponent(), evt.getX(), evt.getY());

                    }

                }

       });

       this.add(p, BorderLayout.CENTER);

    }

    

    public static void main (String [] args) {

        new MenuTest().setVisible(true);

    }

}

 

14.写个类ResumeFrame         自己分析布局设计

Choice -- 求职目标、自我技能、工作经验、教育经历、证书。

TextArea 创建5个TextArea对象,每个对象中对应保存上诉项目所要描述的详细信息

public class ResumeFrame {

       publicstatic void main(String[] args) {

              Frame f=new Frame("简历信息");             

              f.setLayout(new BorderLayout());       

              Panel p1=new Panel();         

              Label l=new Label("简历信息选项");

              Choice ch = new Choice();

              ch.add("");

              ch.add("求职目标");

              ch.add("自我技能");

              ch.add("工作经历");

              ch.add("教育经历");

              ch.add("证书");

              p1.add(l);

              p1.add(ch);           

              f.add(p1,BorderLayout.WEST);          

             

              Panel p2=new Panel();

              p2.setLayout(new CardLayout());

             

              TextArea ta1=new TextArea(30,40);

              ta1.setText("寻找一份java开发类工作,要求工作时间8小时,周末不加班,工资最少3000元");

              p2.add(ta1,"t1");

             

              TextArea ta2=new TextArea(30,40);

              ta2.setText("本人熟悉J2SE和J2EE开发,善于网络编程");

              p2.add(ta2,"t2");

             

              TextArea ta3=new TextArea(30,40);

              ta3.setText("2011.7.13-2011.11.13期间在北京亚思晟培训,培训期间参与开发过SuperVCD等项目");

              p2.add(ta3,"t3");

             

              TextArea ta4=new TextArea(30,40);

              ta4.setText("1996-2001年富坑小学,2001-2004年仙下中学,2004-2007年于都中学,2008-2012年东华理工大学");

              p2.add(ta4,"t4");

             

              TextArea ta5=new TextArea(30,40);

              ta5.setText("软件资格水平考试——中级电子商务设计师,计算机等级考试四级数据库系统工程师");

              p2.add(ta5,"t5");

             

              f.add(p2,BorderLayout.EAST);

             

              f.setBounds(200, 300, 500, 400);

              f.setResizable(false);

              f.setVisible(true);          

       }    

}

 

15.SuperVCD主窗体

public class StoneForest {

       publicstatic void main(String[] args) {

              Frame f = new Frame("欢迎使用StoneForest应用!");          

              //菜单                  

              MenuBar bar = new MenuBar();          

              //三个主菜单

              Menu file = new Menu("文件");

              Menu option = new Menu("选项");

              Menu help = new Menu("帮助");        

              //添加file菜单项

              Menu open = new Menu("打开");

                     MenuItemop1 = new MenuItem("本地...");

                     MenuItemop2 = new MenuItem("局域网...");

                     MenuItemop3 = new MenuItem("互联网...");

                     open.add(op1);open.add(op2);open.add(op3);

              MenuItem save = new MenuItem("保存");

              MenuItem exit = new MenuItem("退出");

              file.add(open);

              file.add(save);

              file.addSeparator();

              file.add(exit);        

              //添加option菜单项

              MenuItem option1 = new MenuItem("复制");

              MenuItem option2 = new MenuItem("剪切");

              MenuItem option3 = new MenuItem("粘贴");

              option.add(option1);option.add(option2);option.add(option3);           

              //添加help菜单项

              MenuItem about = new MenuItem("关于...");

              help.add(about);           

              //将三个菜单添加到菜单条

              bar.add(file);bar.add(option);bar.add(help);

             

              //给主窗体设置菜单条

              f.setMenuBar(bar);

             

              //上部

              Panel p2=new Panel();

              p2.setLayout(newFlowLayout(FlowLayout.LEFT));         

              Label l2=new Label("选择音乐目录");

              Choice chooser = new Choice();

              chooser.add("-----");

              chooser.add("大陆");

              chooser.add("新加坡");

              chooser.add("欧美");

              chooser.add("港台");    

              p2.add(l2);

              p2.add(chooser);          

              f.add(p2,BorderLayout.NORTH);

             

              //中部

              List l=new List(10,true);

              f.add(l,BorderLayout.CENTER);

                           

              //底部的

              Button b1=new Button("详细…");

              b1.setEnabled(false);

              Button b2=new Button("清空");

              b2.setEnabled(false);

              Button b3=new Button("退出");

              b3.setEnabled(true);

              Panel p=new Panel();

              p.add(b1);

              p.add(b2);

              p.add(b3);

              f.add(p,BorderLayout.SOUTH);

                           

              f.setBounds(200, 200, 350, 350);

              f.setResizable(false);

              f.setVisible(true);

       }

}

 

16.展示唱片窗体

public class ShowSongs {

       publicstatic void main(String[] args) {

              Frame f=new Frame("展现唱片");             

              //北部

              Panel p1=new Panel();

              p1.setLayout(new GridLayout(1,2));

             

              Panel p2=new Panel();

              p2.setLayout(newBoxLayout(p2,BoxLayout.Y_AXIS));

              Label l1=new Label("专辑名:真的用了心");

              Label l2=new Label("歌手名:成龙");

              Label l3=new Label("地区名:港台");

              p2.add(l1);

              p2.add(l2);

              p2.add(l3);            

              p1.add(p2);           

              Panel p4=new Panel();

              p4.setLayout(new BorderLayout());

              //Label l4=new Label("图片");

              Button b2=new Button("图片");

              p4.add(b2);

              p1.add(p4);

             

              f.add(p1,BorderLayout.NORTH);        

             

              //中部

              List l=new List(10);

              l.add("真的,用了心");

              l.add("真的英雄");

              l.add("你给我一片天");

              l.add("明明白白我的心");

              l.add("在我生命中的每一天");

              l.add("问心无愧");

              l.add("对不起自己");

              l.add("壮志在我胸");           

              f.add(l,BorderLayout.CENTER);

 

              //南部

              Panel p3=new Panel();

              p3.setLayout(newFlowLayout(FlowLayout.CENTER));

              Button b=new Button("确定");

              p3.add(b);

              f.add(p3,BorderLayout.SOUTH);

      

              f.setBounds(100, 200, 300, 400);

              f.setVisible(true);

       }

}

 

 

 

 

 

 

 

 

 

2011.8.4         周四

1.概念

Event Sources事件源—产生事件

Event Objects事件对象—描述事件

Event Listeners事件监听器—监听事件并调用相应的处理方法

2.事件对象 Event Objects

   一个包含与特定类型的事件相关信息的对象

   一个事件对象至少要包含一个引起事件的这个对象的引用  public ObjectgetSource()

   所有的事件都是Event Objects类的子类

3.事件源  Event Sources

  事件源就是引发事件的组件或者对象

  提供方法允许其他的方法来增加或删除事件监听器

  维护事件监听器的列表

  包含向所有的事件监听器创建和传递事件对象的业务逻辑代码

4.开发流程

 * 《1》确定事件源 

 * 《2》实现对应的事件监听器  XXXListener (接口)

 * 《3》给事件源注册事件监听器  事件源对象.addXXXListener(XXXListener l)

     如果使用匿名内部类实现事件监听器,《2》《3》合二为一

 ActionEvent -->监听器ActionListener-->添加监听器方法addActionListener(ActionListenera)

实例:

public class ActionEventTest {

       publicstatic void main(String[] args) {

              Frame f = new Frame("Event Test!");        

              final Label l = new Label("显示信息");

              Button b1 = new Button("OK");

              Button b2 = new Button("NO");

              Panel p = new Panel();

              p.add(b1);p.add(b2);

              f.add(p,BorderLayout.SOUTH);          

              //3 事件源注册(添加)事件监听器

              MyActionListener listener = newMyActionListener(l);

              b1.addActionListener(listener);

              b2.addActionListener(listener);

              /*b1.addActionListener(newActionListener(){

                     @Override

                     publicvoid actionPerformed(ActionEvent e) {

                            //System.out.println("OK 点击了");

                            l.setText("OK 点击了");

                     }                  

              });

              b2.addActionListener(newActionListener(){

                     @Override

                     publicvoid actionPerformed(ActionEvent e) {

                            //System.out.println("OK 点击了");

                            l.setText("NO 点击了");

                     }

                    

              });*/

              f.add(l,BorderLayout.NORTH);           

              f.setBounds(400, 300, 300, 300);

              f.setVisible(true);

       }

 

}

class MyActionListener implementsActionListener{  // 开发一个事件监听器

       privateLabel l;

       publicMyActionListener(Label l){

              this.l = l;

       }

       @Override

       publicvoid actionPerformed(ActionEvent e) {

              //System.out.println("OK 点击了");           

              //获得事件源

              Button b = (Button)e.getSource();

              if(b.getLabel().equals("OK"))

                     l.setText("OK点击了");

              else

                     l.setText("NO点击了");             

       }    

}

5.事件监听器 Event Listeners

  通知一个对象产生了事件

  必须实现适当的事件监听器

 

6.事件类型

 

 

 

 

 

 

 

 

 

 

 

 

7.动作事件ActionEvent

   双击List组件中选项

   选择一个按钮

   选择MenuItem

   在文本框组件中按回车(Enter)键

public class ActionEventTest2 {

                      publicstatic void main(String[] args) {

                            Frame f = new Frame("Event Test!");

                            f.setLayout(new FlowLayout());

                            final Label l = new Label("显示信息");

                            f.add(l);         

                            //List 双击时触击动作事件

                            final List list = new List(10);

                            list.add("aaaaaaaaaaaaa");

                            list.add("bbbbbbbbbbbbb");

                            list.add("ccccccccccccc");

                            list.add("ddddddddddddddd");

                            f.add(list);            

                            list.addActionListener(newActionListener(){

                                   @Override

                                   publicvoid actionPerformed(ActionEvent e) {

                                          String item = list.getSelectedItem();

                                          l.setText(item);

                                   }

                                  

                            });

                            //TextField按回车(Enter)键事件

                            final TextField tf = new TextField(10);

                            f.add(tf);

                            tf.addActionListener(new ActionListener(){

                                   @Override

                                   publicvoid actionPerformed(ActionEvent e) {

                                          String value = tf.getText();

                                          list.add(value);

                                          tf.setText("");

                                   }                  

                            });         

                            f.setBounds(400, 300, 300, 300);

                            f.setVisible(true);

                      }

}

8.文本事件  TextEvent

  文本框中文本发生改变

  TextArea组件中的文本发生改变

实例:

public class TextEventTest {

                      publicstatic void main(String[] args) {

                            Frame f = new Frame("Event Test!");

                            f.setLayout(new FlowLayout());

                            final Label l = new Label("显示信息");

                            f.add(l);         

                            //文本事件

                            final TextField tf = new TextField(10);

                            f.add(tf);

                            tf.addTextListener(new TextListener(){

                                   @Override

                                   publicvoid textValueChanged(TextEvent e) {

                                          String value = tf.getText();

                                          l.setText(value);                         

                                   }                  

                            });         

                            final TextArea ta = new TextArea(10,50);

                            f.add(ta);

                            ta.addTextListener(new TextListener(){

                                   @Override

                                   publicvoid textValueChanged(TextEvent e) {

                                          String value = ta.getText();

                                          l.setText(value);                         

                                   }                  

                            });         

                            f.setBounds(400, 300, 300, 300);

                            f.setVisible(true);

                      }

}

9.选项事件 ItemEvent

  选择和取消选择Checkbox

  选择和取消选择CheckboxMenuItem

  选择Choice中的选项

  选择一个或多个List组件中的选项

实例:

public class ItemEventTest {

                      publicstatic void main(String[] args) {

                            Frame f = new Frame("Event Test!");        

                            SuperVCDMenuBar bar = newSuperVCDMenuBar();

                            f.setMenuBar(bar);       

                            Label l = new Label("选择音乐目录:");

                            final Choice ch = new Choice();

                            ch.add("------------");

                            ch.add("大陆");

                            ch.add("港台");

                            ch.add("欧美");

                            ch.add("新加坡");

                            Panel p = new Panel();

                            p.setLayout(newFlowLayout(FlowLayout.LEFT));

                            p.add(l);p.add(ch);

                            f.add(p,BorderLayout.NORTH);          

                            final List list = new List();

                            f.add(list);     

                            final Button b1 = new Button("详细");

                            final Button b2 = new Button("清空");

                            Button b3 = new Button("退出");

                            b1.setEnabled(false);

                            b2.setEnabled(false);            

                            Panel p2 = new Panel();

                            p2.add(b1);p2.add(b2);p2.add(b3);

                            f.add(p2,BorderLayout.SOUTH); 

                            ch.addItemListener(new ItemListener(){           //给ch下拉框加事件

                                   @Override

                                   publicvoid itemStateChanged(ItemEvent e) {

                                          list.removeAll();

                                          if(ch.getSelectedIndex()==0){//========                             

                                                 b1.setEnabled(false);

                                                 b2.setEnabled(false);

                                          }else{

                                                 Stringitem = ch.getSelectedItem();

                                                 list.add(item);

                                                 b1.setEnabled(false);

                                                 b2.setEnabled(true);

                                          }

                                   }

                                  

                            });         

                            list.addItemListener(new ItemListener(){  //List 添加选项事件

                                   @Override

                                   publicvoid itemStateChanged(ItemEvent e) {

                                          b1.setEnabled(true);

                                   }                  

                            });         

                            f.setBounds(400, 300, 300, 300);

                            f.setVisible(true);

                      }

}

 

10.事件监听器

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


11.事件适配器 EventAdapters

   一个事件适配器实现了一个特定的事件监听器

   只能够继承适配器并且重写他的方法

public class WindowEventTest {

                      publicstatic void main(String[] args) {

                            final Frame f = new Frame("WindowEvent Test !");

                            /**

                             * 关闭窗口WindowListener

                             */

                                   f.addWindowListener(newWindowAdapter(){

                                   @Override

                                   publicvoid windowClosing(WindowEvent e){

                                          f.setVisible(false);

                                          f.dispose();

                                          System.exit(0);

                                   }

                            });         

                            f.setBounds(400, 300, 300, 300);

                            f.setVisible(true);

                      }

}

 

事件监听器(续)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


2011.8.6  周六

1.Applets小应用程序

  一个Applet是一个小的程序,通过嵌入到别的应用程序来运行

  Applet不能独立运行,必须放在浏览器中使用,其父类是Panel,二级容器 Applet也是二级容器,可以放组件

  使用AWT组件必须继承Java.applet.Applet

  使用Swing组件必须继承Javax.swing.JApplet

  JApplet是Applet的子类

  Applets嵌入到HTML页面中

  在浏览器或者Applet viewers中运行

  类的层次关系:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

实例:

importjava.applet.Applet;

importjava.awt.*;

importjava.awt.event.ActionEvent;

importjava.awt.event.ActionListener;

publicclass MyApplet extends Applet{

       private Button b1;

       private Button b2;

       private Panel p;

       private Label l;

       @Override

       public void destroy() {

              System.out.println("--------destroy");

       }

       @Override

       public void init() {

              System.out.println("--------init初始化");

              b1= new Button("OK");

              b2= new Button("Panic");

              p= new Panel();

              l= new Label("显示信息");

       }

       @Override

       public void start() {

              System.out.println("----------start");

              this.setLayout(newBorderLayout());          

              this.add(l,BorderLayout.NORTH);

              p.add(b1);p.add(b2);

              this.add(p,BorderLayout.SOUTH);             

              b1.addActionListener(newActionListener(){

                     @Override

                     public void actionPerformed(ActionEvente) {

                            l.setText("OK按钮点击了");

                     }           

              });

              b2.addActionListener(newActionListener(){

                     @Override

                     public void actionPerformed(ActionEvente) {

                            l.setText("Panic按钮点击了");

                     }           

              });                       

       }

       @Override

       public void stop() {

              System.out.println("------------stop-----");

       }    

       public void a(){   //不运行

              System.out.println("-----------------aaaa");

       }    

}

2.嵌入到页面中的Applet

  <html>

       <head>

              <title>AppletTest</title>

       </head>

       <body>

              <h3><hr>我的第一个Applet<hr></h3>            

              <appletcodebase="." code="sample.MyApplet" width="300"height="200">

              </applet>

       </body>

</html>

 

3.Applet没有main()方法、默认只会调用自己的4个方法其它方法必须放到4个方法内调用。

  Applet4个生命周期

  初始化:init()  每次装在Applet的时候都调用init()初始化方法   只运行一次

  运行:Start()   启动Applet执行Applet代码       可以运行多次

  停止:Stop()    停止Applet运行                 可以运行多次

  销毁:destroy()  在卸载之前做的最后的请理性工作              只运行一次

publicvoid init() { . . . }     

publicvoid start() { . . .}    

publicvoid stop() { . . . }  

publicvoid destroy() { . . .}

4.绘图及事件处理的方法:

publicvoid paint(Graphics g){...} 

publicvoid update(Graphics g){…}

paint(Graphicsg):绘图的基本方法

update(Graphicsg):同paint方法配合使用,提高绘图效率的重绘的方法

如果Applet继承了Japplet,则需要在ContentPane中添加组件

Applet程序从Componet类继承了一组事件处理的方法

5.安全限制

Applet不能够导入库或者定义的本地方法

通常情况下它不能够读或写执行它的主机的文件

不能够创建其他的网络,除了Applet所在的主机

不能够在运行它的主机上运行任何程序

不能读取特定系统信息

带有Applet的窗口看起来和带有应用程序的窗口不一样

6.在Applet和Browser之间通信

getParameter(Stringname)

showStatus(Stringmsg)

getCodeBase()

getDocumentBase()

在Applet之间进行通信

InterfaceAppletContext 

publicinterface AppletContext {       

publicApplet getApplet(String name);      

publicEnumeration getApplets();       

 … 

}

Applet中的方法

getAppletContext()

Applet 标签

<applet 

[archive=archiveList]  code= appletFile.class   width= pixels height= pixels    

[codebase=codebaseURL ]     [alt= alternateText]  

[name=appletInstanceName ]     [align=alignment ]  

[vspace= pixels ] [hspace= pixels ] >  

[<paramname= appletAttribute1 value= value >] 

[<paramname= appletAttribute2 value= value >]

.......

[alternateHTML]

</applet>

实例:

importjava.applet.Applet;

importjava.awt.Graphics;

publicclass SimpleApplet extends java.applet.Applet {  

  StringBuffer buffer;

    public void init() {

       buffer = new StringBuffer();

        addItem("initializing... ");

    }

    public void start() {

        addItem("starting... ");

    }

    public void stop() {

        addItem("stopping... ");

    }

    public void destroy() {

        addItem("preparing forunloading...");

    }

    void addItem(String newWord) {

        System.out.println(newWord);

        buffer.append(newWord);

        repaint();

    }

    public void paint(Graphics g) {

        g.drawRect(0, 0, size().width - 1,size().height - 1);

        g.drawString(buffer.toString(), 5, 15);

    }

}

7.输入输出流和文件系统(Stream I/O and Files)

  流:字节流的源和目的地

  2种流:字节输入流和字节输出流

  流的分类:

 (1)输入流:InputStream  读入内存 read   参照物:针对内存 抽象类不能new对象

      输出流:OutputStream 写出内存 write  参照物:针对内存 抽象类不能new对象

  (2) 字节流:.......Stream

      字符流:.....Read()、......Write

  (3) 处理流:构造方法无法直接与文件对接(必须通过节点流嵌入) BufferedInputStream

      节点流:构造方法可以直接与文件对接

 

 

 

 

 

 

 

 

 


8.字节流:以字节形式Byte(8位 -128—127)

  (1)字节输入流:ObjectInputStream、FileInputStream、DataInputStream、BufferedInputStream

  (2)字节输出流:ObjectOutputStream、FileOutputStream、DataOutputStream、BufferedOutputStream、PrintStream

9.(1)字节输入流:

构造方法:

intread()                

intread(byte[])               

intread(byte[], int, int)

其它方法:

voidclose()                

intavailable()                

skip(long)               

booleanmarkSupported()               

voidmark(int)               

voidreset(int)

 (2)字节输出流:

构造方法:

intwrite(int)                            

intwrite(byte[])                            

intwrite(byte[], int, int)

其它方法:

voidclose()                            

voidflush()

缓存刷新

实例:public class FileInputStreamTest {   

       public static void main(String[] args) {

              Filef1 = new File("1.txt");            //源文件  必须事先存在    

              Filef2 = new File("2.txt");         //目的地文件   一般不存在      

              try{ 

                     FileInputStream fis = newFileInputStream(f1); //和源文件对接的读的流对象      

                     FileOutputStream fos = newFileOutputStream(f2);//和目的地文件对接的流对象                

                     int b =0;

                     while(( b=fis.read())!=-1){     //读出文件

                            fos.write(b);           //写入文件

                     }                  

                     fos.close();   //关闭

                     fis.close();                   

              }catch (FileNotFoundException e) {

                     e.printStackTrace();

              }catch (IOException e) {

                     e.printStackTrace();

              }           

       }

 

1.txt

 

 

目的地

2.txt

 
}

 

 

 

 


10.文件体系

   一个文件对象就代表一个文件或者目录

   File处理各种磁盘操作

构造函数:

File(Fileparent, String child)

  根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例   

File(Stringpathname)

   通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例  

File(Stringparent, String child)

    根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例 

File(URIuri)  通过将给定的 file: URI 转换为一个抽象路径名来创建一个新的 File 实例

目录分隔符:

File.separator  (Window系统\\ 、Linux系统/)动态获取

File类的方法:

booleancreateNewFile() 创建新文件(只能创建文件、不能创建目录)

booleandelete()    删除文件或目录

booleanmkdir()   只能创建一层文件夹

booleanmkdirs()  可以创建多层文件夹  

booleanrenameTo(File destination)   重命名(参数是文件目的地)

booleancanRead()    测试应用程序是否可以读取此抽象路径名表示的文件

booleancanWrite()   测试应用程序是否可以修改此抽象路径名表示的文件

booleanexists()    测试文件或目录是否存在

String[]list()     获得文件目录、直接包含的文件名数组(只有一层)

longlastModified()  返回此抽象路径名表示的文件最后一次被修改的时间

StringgetPath()     将此抽象路径名转换为一个路径名字符串(相对路径)

getAbsolutePath()    返回此抽象路径名的绝对路径名字符串

StringgetParent()   返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回null

getName()返回由此抽象路径名表示的文件或目录的名称

实例:

importjava.io.File;

importjava.io.IOException;

publicclass FileTest {

       public static void main(String[] args) {

              //File对象 可以代表具体文件或目录

              Filef1 = new File("E:\\");

              Filef2 = new File("D:\\a.txt");

              Filef3 = new File("D:/d/a.txt");

              Filef4 = new File("D:"+File.separator+"a.txt");

              //目录分隔符  根据系统产生分隔符  window \   Linux /

              System.out.println(File.separator);       

              Filef5= new File("D:/","a.txt");

              Filef6 = new File(f1,"a.txt");                     

              try{

                     /**

                      * 创建新文件  只能创建文件,不能创建目录 

                      */

                     f2.createNewFile();

                     //f3.createNewFile(); 找不到D:/d目录  但不会自动创建                  

                     /**

                      * 创建目录mkdir() 注意:只能创建一层文件夹

                      */

                     File f7 = new File("D:/d");

                     f7.mkdir();

                     File f8 = new File("D:/e/e");

                     System.out.println(f8.mkdir());                  

                     /**

                      * 创建多层目录mkdirs()

                      */

                     f8.mkdirs();          

                     /**

                      * 重命名

                      */

                     File f9 = new File("a.txt");

                     f9.createNewFile();                    

                     f9.renameTo(new File("b.txt"));                 

                     System.out.println(f3.exists());                  

                     /**

                      * 获得文件目录 直接包含文件名数组  list()

                      */                

                     String [] names = f1.list();

                     for(String name:names){

                            System.out.println(name);

                     }                  

                     /**

                      * 路径

                      */

                     System.out.println(f9.getPath());

                     System.out.println(f9.getAbsolutePath());                                      

              }catch (IOException e) {

                     e.printStackTrace();

              }                                

       }

}

11.(1)文件字节输入输出流:

    当创建一个文件输入流时源文件必须存在且能被读

FileInputStream(Filefile)   

FileInputStream(Stringname)

    当创建文件输出流时,若文件不存在则创建文件,否则覆盖文件

FileOutputStream(Filefile)   

FileOutputStream(Filefile, boolean append)  

FileOutputStream(Stringname)    

FileOutputStream(Stringname, boolean append)

 (2)文件字符输入输出流:

     方便了字符文件的读/写

FileReader(Filefile)  

FileReader(Stringname) 

FileWriter(Filefile)  

FileWriter(Stringfilename)

12.带有缓冲区的字节输入输出流

对输入输出流进行缓冲,从而提高性能

BufferedInputStream(InputStreamin)  

BufferedInputStream(InputStreamin, int size)

BufferedOutputStream(OutputStreamout) 

BufferedOutputStream(OutputStreamout, int size)

实例:

publicclass BufferedStreamTest {

       public static void main(String[] args) {

              Filef1 = new File("1.txt");

              Filef2 = new File("3.txt");           

              FileInputStreamfis;

              try{

                     fis = new FileInputStream(f1);

                     BufferedInputStream bis = newBufferedInputStream(fis);                             

                     FileOutputStream fos = newFileOutputStream(f2);

                     BufferedOutputStream bos = newBufferedOutputStream(fos);               

                     int b =0;

                     while((b=bis.read())!=-1){

                            bos.write(b);                       

                     }

                     bos.flush();

 

                     bos.close();

                     bis.close();

                     fos.close();

                     fis.close();                                 

              }catch (FileNotFoundException e) {

                     e.printStackTrace();

              }catch (IOException e) {

                     e.printStackTrace();

              }           

       }

}

 

 

 

 

 

 

 

 

 

 

 

 

 


综合实例:

importjava.io.File;

importjava.io.IOException;

publicclass FileTest2 {

       public static void printFile(File f){

              System.out.println(f.getName());

              if(f.isDirectory()){

                     String [] names = f.list();

                     for(String name:names){

                            printFile(newFile(f,name));

                     }

              }

       }

       public static void main(String[] args) {

              if(args.length==0){

                     System.out.println("请在运行时输入一个文件目录");

              }else{

                     File f = new File(args[0]);

                     printFile(f);

              }           

       }

}

12.完成一个图片的拷贝

  import java.io.File;

importjava.io.FileInputStream;

importjava.io.FileNotFoundException;

importjava.io.FileOutputStream;

importjava.io.IOException;

publicclass ImageCopy {

       /**

        * 图片的拷贝

        *@param args

        */

       public static void main(String[] args) {

              Filef1=new File("1.jpg");

              Filef2=new File("2.jpg");

              try{

                     FileInputStream fis = newFileInputStream(f1);         

                     FileOutputStream fos = newFileOutputStream(f2);           

                     int b =0;

                     while(( b=fis.read())!=-1){

                            fos.write(b);

                     }                  

                     fos.close();

                     fis.close();            

              }catch (FileNotFoundException e) {

                     e.printStackTrace();

              }catch (IOException e) {                  

                     e.printStackTrace();

              }

       }

}

13.读取一个文件内容,读取过程中打印每个字节,如果是q,后面不再读取打印

14.尝试打印某File目录对象下所有文件名,并尝试打印出层次关系

public class FileNavTest {

    File root;

    public FileNavTest(StringrootName){

        root = new File(rootName);

    }

    //展现指定根路径的所有文件方法

    public void showFilesList(File root,int level){

        if(!root.isDirectory()){//如果不是路径 就不再展现,结束该方法

            return;

        }else{//是路径  就展现

            level++;//标示是根路径的第几级

            String [] fileNames = root.list();

        for(int i=0;i<fileNames.length;i++){//打印文件夹下的所有文件名

                for(int j=0;j<level;j++){//输出展现级别的空格

                    System.out.print("    ");

                }      

                //当前展现文件名

                String fileName =fileNames[i];

                System.out.println(fileName);

                //还得判断并输出此文件下的文件名

                File f = new File(root,fileName);

                if(f.isDirectory()){

                    showFilesList(f,level);

                }

            }

        }

    }

    public static void main(String[] args) {

        FileNavTest fnt = new FileNavTest("E:/a");

        System.out.println(fnt.root.getPath());

        fnt.showFilesList(fnt.root, 0);

    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值