自定义博客皮肤VIP专享

*博客头图:

格式为PNG、JPG,宽度*高度大于1920*100像素,不超过2MB,主视觉建议放在右侧,请参照线上博客头图

请上传大于1920*100像素的图片!

博客底图:

图片格式为PNG、JPG,不超过1MB,可上下左右平铺至整个背景

栏目图:

图片格式为PNG、JPG,图片宽度*高度为300*38像素,不超过0.5MB

主标题颜色:

RGB颜色,例如:#AFAFAF

Hover:

RGB颜色,例如:#AFAFAF

副标题颜色:

RGB颜色,例如:#AFAFAF

自定义博客皮肤

-+
  • 博客(0)
  • 资源 (4)
  • 收藏
  • 关注

空空如也

Java 2实用教程第三版实验指导与习题解答

Java 2实用教程(第三版)实验指导与习题解答 清华大学出版社 (编著 耿祥义 张跃平) 实验模版代码 建议使用文档结构图 (选择Word菜单→视图→文档结构图) 上机实践1 初识Java 4 实验1 一个简单的应用程序 4 实验2 一个简单的Java Applet程序 4 实验3 联合编译 5 上机实践2 基本数据类型与控制语句 6 实验1 输出希腊字母表 6 实验2 回文数 6 实验3 猜数字游戏 8 上机实践3 类与对象 9 实验1 三角形、梯形和圆形的类封装 9 实验2 实例成员与类成员 12 实验3 使用package语句与import语句 13 上机实践4 继承与接口 15 实验1 继承 15 实验2 上转型对象 17 实验3 接口回调 18 上机实践5 字符串、时间与数字 19 实验1 String类的常用方法 19 实验2 比较日期的大小 21 实验3 处理大整数 22 上机实践6 组件及事件处理 23 实验1 算术测试 23 实验2 信号灯 25 实验3 布局与日历 28 上机实践7 组件及事件处理2 31 实验1 方程求根 31 实验2 字体对话框 34 实验3 英语单词拼写训练 37 上机实践8 多线程 41 实验1 汉字打字练习 41 实验2 旋转的行星 43 实验3 双线程接力 47 上机实践9 输入输出流 50 实验1 学读汉字 50 实验2 统计英文单词字 53 实验2 读取Zip文件 56 上机实践10 Java 中的网络编程 57 实验1 读取服务器端文件 57 实验2 使用套接字读取服务器端对象 59 实验3 基于UDP的图像传输 62 上机实践11 数据结构 66 实验1 扫雷小游戏 66 实验2 排序与查找 70 实验3 使用TreeSet排序 72 上机实践12 java Swing 74 实验1 JLayeredPane分层窗格 74 实验2 使用表格显示日历 75 实验3 多文档界面(MDI) 78 上机实践1 初识Java 实验1 一个简单的应用程序 2.模板代码 Hello.java package 实验一; public class Hello { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("你好,很高兴学习Java"); //命令行窗口输出"你好,很高兴学习Java" A a=new A(); a.fA(); } } class A { void fA() {System.out.println("we are student"); } } 实验2 一个简单的Java Applet程序 2.模板代码 FirstApplet.java import java.applet.*; import java.awt.*; public class FirstApplet extends Applet { public void paint(Graphics g) { g.setColor(Color.blue); g.drawString("这是一个Java Applet 程序",10,30);//在Java Applet中绘制一行文字:“这是一个Java Applet 程序” g.setColor(Color.red); g.setFont(new Font("宋体",Font.BOLD,36)); g.drawString("我改变了字体",20,50);//在Java Applet中绘制一行文字:“我改变了字体” } }实验3 联合编译 2.模板代码 public class MainClass { public static void main (String args[ ]) { System.out.println("你好,只需编译我") ; //命令行窗口输出"你好,只需编译我" A a=new A(); a.fA(); B b=new B(); b.fB(); } } public class A { void fA() { System.out.println("I am A") ; //命令行窗口输出"I am A" } } public class B { void fB() { System.out.println("I am B") ; //命令行窗口输出"I am B" } } public class C { void fC() { System.out.println("I am c") ; //命令行窗口输出"I am C" } } 上机实践2 基本数据类型与控制语句 实验1 输出希腊字母表 2.模板代码 GreekAlphabet.java public class GreekAlphabet { public static void main (String args[ ]) { int startPosition=0,endPosition=0; char cStart='α',cEnd='ω'; startPosition=(int)cStart; //cStart做int型转换据运算,并将结果赋值给startPosition endPosition=(int)cEnd ; //cEnd做int型转换运算,并将结果赋值给endPosition System.out.println("希腊字母\'α\'在unicode表中的顺序位置:"+(int)cStart); System.out.println("希腊字母表:"); for(int i=startPosition;i<=endPosition;i++) { char c='\\0'; c=(char)i ; //i做char型转换运算,并将结果赋值给c System.out.print(" "+c); if((i-startPosition+1)==0) System.out.println(""); } } } 实验2 回文数 2.模板代码 Number.java import javax.swing.JOptionPane; public class Number { public static void main(String args[]) { int number=0,d5,d4,d3,d2,d1; String str=JOptionPane.showInputDialog("输入一个1至99999之间的数"); number=Integer.parseInt(str); if(number>=1&&number;<=99999) //判断number在1至99999之间的条件 { d5=number0000/10000; //计算number的最高位(万位)d5 d4=number000/1000; //计算number的千位d4 d3=number00/100; //计算number的百位d3 d2=number0/10; d1=number; if(number>9999) //判断number是5位数的条件 { System.out.println(number+"是5位数"); if(d5==d1&&d4;==d2) //判断number是回文数的条件 { System.out.println(number+"是回文数"); } else { System.out.println(number+"不是回文数"); } } else if(number>999) //判断number是4位数的条件 { System.out.println(number+"是4位数"); if(d4==d1&&d2;==d3) //判断number是回文数的条件码 { System.out.println(number+"是回文数"); } else { System.out.println(number+"不是回文数"); } } else if(number>99) //判断number是3位数的条件 { System.out.println(number+"是3位数"); if(d1==d3) //判断number是回文数的条件 { System.out.println(number+"是回文数"); } else { System.out.println(number+"不是回文数"); } } else if(d2!=0) { System.out.println(number+"是2位数"); if(d1==d2) { System.out.println(number+"是回文数"); } else { System.out.println(number+"不是回文数"); } } else if(d1!=0) { System.out.println(number+"是1位数"); System.out.println(number+"是回文数"); } } else { System.out.printf("\n%d不在1至99999之间",number); } } } 实验3 猜数字游戏 2.模板代码 GuessNumber.java import javax.swing.JOptionPane; public class GuessNumber { public static void main (String args[ ]) { System.out.println("给你一个1至100之间的整数,请猜测这个数"); int realNumber=(int)(Math.random()*100)+1; int yourGuess=0; String str=JOptionPane.showInputDialog("输入您的猜测:"); yourGuess=Integer.parseInt(str); while(yourGuess!=realNumber) //循环条件 { if(yourGuess>realNumber) //条件代码 { str=JOptionPane.showInputDialog("猜大了,再输入你的猜测:"); yourGuess=Integer.parseInt(str); } else if(yourGuess<realNumber) //条件代码 { str=JOptionPane.showInputDialog("猜小了,再输入你的猜测:"); yourGuess=Integer.parseInt(str); } } System.out.println("猜对了!"); } } 上机实践3 类与对象 实验1 三角形、梯形和圆形的类封装 2.模板代码 AreaAndLength.java class Trangle { double sideA,sideB,sideC,area,length; boolean boo; public Trangle(double a,double b,double c) { sideA=a; sideB=b; sideC=c; //参数a,b,c分别赋值给sideA,sideB,sideC if(a<(b+c)&&b<(a+c)&&c<(a+b)) //a,b,c构成三角形的条件表达式 { boo=true; //给boo赋值。 } else { boo=false;//给boo赋值。 } } double getLength() { if(boo) { length=sideA+sideB+sideC; return length; } else{ System.out.println("这个不是三角形,不能计算周长"); return 0; } //方法体,要求计算出length的值并返回 } public double getArea() { if(boo) { double p=(sideA+sideB+sideC)/2.0; area=Math.sqrt(p*(p-sideA)*(p-sideB)*(p-sideC)) ; return area; } else { System.out.println("不是一个三角形,不能计算面积"); return 0; } } public void setABC(double a,double b,double c) { sideA=a; sideB=b; sideC=c;//参数a,b,c分别赋值给sideA,sideB,sideC if(a+c>b&&a+b>c&&b+c>a) //a,b,c构成三角形的条件表达式 { boo=true; //给boo赋值。 } else { boo=false; //给boo赋值。 } } } class Lader { double above,bottom,height,area; Lader(double a,double b,double h) { above=a; bottom=b; height=h;//方法体,将参数a,b,h分别赋值给above,bottom,height } double getArea() { area=(above+bottom)/2*height; return area;//方法体,,要求计算出area返回 } } class Circle { double radius,area; Circle(double r) { radius=r; //方法体 } double getArea() { area=3.14*radius*radius; return area;//方法体,要求计算出area返回 } double getLength() { return 2*3.14*radius; //getArea方法体的代码,要求计算出length返回 } void setRadius(double newRadius) { radius=newRadius; } double getRadius() { return radius; } } public class AreaAndLength { public static void main(String args[]) { double length,area; Circle circle=null; Trangle trangle; Lader lader; circle=new Circle(10) ;//创建对象circle trangle=new Trangle(3,4,5); //创建对象trangle。 lader=new Lader(3,4,10); //创建对象lader length=trangle.getLength(); // 调用getLength()方法返回周长并赋值给length System.out.println("圆的周长:"+length); area=circle.getArea(); // 调用getArea()方法返回面积并赋值给area System.out.println("圆的面积:"+area); length=trangle.getLength(); // 调用getLength()方法返回周长并赋值给length System.out.println("三角形的周长:"+length); area=trangle.getArea(); // 调用getArea()方法返回面积并赋值给area System.out.println("三角形的面积:"+area); area=lader.getArea();// 调用getArea()方法返回面积并赋值给area System.out.println("梯形的面积:"+area); trangle.setABC(12,34,1); // trangle调用setABC()方法设置三个边,要求将三个边修改为12,34,1。 area=trangle.getArea(); // trangle调用getArea()方法返回面积并赋值给area System.out.println("三角形的面积:"+area); length=trangle.getLength(); // trangle调用getLength()方法返回周长并赋值给length System.out.println("三角形的周长:"+length); } } 实验2 实例成员与类成员 2.模板代码 Example.java class A { float a; //声明一个float型实例变量a static float b; //声明一个float型类变量b,即static变量b void setA(float a) { this.a=a; //将参数a的值赋值给成员变量a } void setB(float b) { this.b=b; //将参数b的值赋值给成员变量b } float getA() { return a; } float getB() { return b; } void inputA() { System.out.println(a); } static void inputB() { System.out.println(b); } } public class Example { public static void main(String args[]) { A.b=100; //通过类名操作类变量b,并赋值100 A.inputB(); //通过类名调用方法inputB() A cat=new A(); A dog=new A(); cat.setA(200); //cat对象调用方法setA(int a)将cat的成员a的值设置为200 cat.setB(400); //cat调用方法setB(int b)将cat的成员b的值设置为400 dog.setA(150); //dog调用方法setA(int a)将dog的成员a的值设置为150 dog.setB(300); //dog调用方法setB(int b)将dog的成员b的值设置为300 cat.inputA(); //cat调用inputA()。 cat.inputB(); //cat调用inputB()。 dog.inputA(); //dog调用inputA()。 dog.inputB(); //dog调用inputB()。 } } 实验3 使用package语句与import语句 2.模板代码 SquareEquation.java package tom.jiafei; public class SquareEquation { double a,b,c; double root1,root2; boolean boo; public SquareEquation(double a,double b,double c) { this.a=a; this.b=b; this.c=c; if(a!=0) { boo=true; } else { boo=false; } } public void getRoots() { if(boo) { System.out.println("是一元2次方程"); double disk=b*b-4*a*c; if(disk>=0) { root1=(-b+Math.sqrt(disk))/(2*a); root2=(-b-Math.sqrt(disk))/(2*a); System.out.printf("方程的根:%f,%f\n",root1,root2); } else { System.out.printf("方程没有实根\n"); } } else { System.out.println("不是一元2次方程"); } } public void setCoefficient(double a,double b,double c) { this.a=a; this.b=b; this.c=c; if(a!=0) { boo=true; } else { boo=false; } } } SunRise.java import tom.jiafei.*; class SunRise { public static void main(String args[ ]) { SquareEquation equation=new SquareEquation(4,5,1); equation.getRoots(); equation.setCoefficient(-3,4,5); equation.getRoots(); } } 上机实践4 继承与接口 实验1 继承 2.模板代码 Example.java package ll; class People { protected double weight,height; public void speakHello() { System.out.println("yayawawa"); } public void averageHeight() { height=173; System.out.println("average height:"+height); } public void averageWeight() { weight=70; System.out.println("average weight:"+weight); } } class ChinaPeople extends People { public void speakHello() { System.out.println("你好,吃了吗"); } //重写public void speakHello()方法,要求输出类似“你好,吃了吗”这样的 //汉语信息 public void averageHeight() { height=168.78; System.out.println("中国人的平均身高:"+height+"厘米"); } //重写public void averageHeight()方法,要求输出类似 //“中国人的平均身高:168.78厘米”这样的汉语信息 public void averageWeight() { weight=65; System.out.println("中国人的平均体重: "+weight+"公斤"); } //重写public void averageWeight()方法, //要求输出类似“中国人的平均体重:65公斤”这样的汉语信息 public void chinaGongfu() { System.out.println("坐如钟,站如松,睡如弓 "); //输出中国武术的信息,例如:"坐如钟,站如松,睡如弓"等 } } class AmericanPeople extends People { public void speakHello() { System.out.println("How do you do"); } //重写public void speakHello()方法,要求输出类似 //“How do you do”这样的英语信息。 public void averageHeight() { height=188.0; System.out.println("美国人的平均身高:"+height+"厘米"); } //重写public void averageHeight()方法 public void averageWeight() { weight=80.23; System.out.println("美国人的平均体重: "+weight+"公斤"); } //重写public void averageWeight()方法 public void americanBoxing() { System.out.println("直拳”、钩拳");//输出拳击的信息,例如,“直拳”、“钩拳”等 } } class BeijingPeople extends ChinaPeople { public void speakHello() { System.out.println("您好"); } //重写public void speakHello()方法,要求输出类似“您好”这样的汉语信息 public void averageHeight() { height=167.0; System.out.println("北京人的平均身高:"+height+"厘米"); } //重写public void averageHeight()方法 public void averageWeight() { weight=68.5; System.out.println("北京人的平均体重: "+weight+"公斤"); } //重写public void averageWeight()方法 public void beijingOpera() { System.out.println("京剧术语");//输出京剧的信息 } } public class Example { public static void main(String args[]) { ChinaPeople chinaPeople=new ChinaPeople(); AmericanPeople americanPeople=new AmericanPeople(); BeijingPeople beijingPeople=new BeijingPeople(); chinaPeople.speakHello(); americanPeople.speakHello(); beijingPeople.speakHello(); chinaPeople.averageHeight(); americanPeople.averageHeight(); beijingPeople.averageHeight(); chinaPeople.averageWeight(); americanPeople.averageWeight(); beijingPeople.averageWeight(); chinaPeople.chinaGongfu(); americanPeople.americanBoxing(); beijingPeople.beijingOpera() ; beijingPeople.chinaGongfu(); } } 实验2 上转型对象 2.模板代码 HardWork.java package 上机实践4; abstract class Employee { public abstract double earnings(); } class YearWorker extends Employee { public double earnings() { return 50.456; }//重写earnings()方法 } class MonthWorker extends Employee { public double earnings() { return 12*23; } //重写earnings()方法。 } class WeekWorker extends Employee { public double earnings() { return 52*23; } //重写earnings()方法。 } class Company { Employee[] employee; double salaries=0; Company(Employee[] employee) { this.employee=employee; } public double salariesPay() { salaries=0; for(int i=0;i<employee.length;i++) { salaries=salaries+employee[i].earnings(); } //计算salaries。 return salaries; } } public class HardWork { public static void main(String args[]) { Employee[] employee=new Employee[20]; for(int i=0;i<employee.length;i++) { if(i%3==0) employee[i]=new WeekWorker(); else if(i%3==1) employee[i]=new MonthWorker(); else if(i%3==2) employee[i]=new YearWorker(); } Company company=new Company(employee); System.out.println("公司年工资总额:"+company.salariesPay()); } } 实验3 接口回调 2.模板代码 Road.java package 上机实践4; interface ComputerWeight { public double computeWeight(); } class Television implements ComputerWeight { public double computeWeight() { return 45.5; }//实现computeWeight()方法。 } class Computer implements ComputerWeight { public double computeWeight() { return 65.5; } //实现computeWeight()方法。 } class WashMachine implements ComputerWeight { public double computeWeight() { return 145; }//实现computeWeight()方法。 } class Car { ComputerWeight[] goods; double totalWeights=0; Car(ComputerWeight[] goods) { this.goods=goods; } public double getTotalWeights() { totalWeights=0; for(int k=0;k<goods.length;k++) { totalWeights=totalWeights+goods[k].computeWeight(); } //计算totalWeights return totalWeights; } } public class Road { public static void main(String args[]) { ComputerWeight[] goodsOne=new ComputerWeight[50], goodsTwo=new ComputerWeight[22] ; for(int i=0;i<goodsOne.length;i++) { if(i%3==0) goodsOne[i]=new Television(); else if(i%3==1) goodsOne[i]=new Computer(); else if(i%3==2) goodsOne[i]=new WashMachine(); } for(int i=0;i<goodsTwo.length;i++) { if(i%3==0) goodsTwo[i]=new Television(); else if(i%3==1) goodsTwo[i]=new Computer(); else if(i%3==2) goodsTwo[i]=new WashMachine(); } Car 大货车=new Car(goodsOne); System.out.println("大货车装载的货物重量:"+大货车.getTotalWeights()); Car 小货车=new Car(goodsTwo); System.out.println("小货车装载的货物重量:"+小货车.getTotalWeights()); } } 上机实践5 字符串、时间与数字 实验1 String类的常用方法 模板代码 StringExample.java package 上机实践5; class StringExample { public static void main(String args[]) { String s1=new String("you are a student"), s2=new String("how are you"); if(s1.equals(s2)) // 使用equals方法判断s1与s2是否相同 { System.out.println("s1与s2相同"); } else { System.out.println("s1与s2不相同"); } String s3=new String("22030219851022024"); if(s3.startsWith("220302",0)) //判断s3的前缀是否是“220302”。 { System.out.println("吉林省的身份证"); } String s4=new String("你"), s5=new String("我"); if(s4.compareTo(s5)>0)//按着字典序s4大于s5的表达式。 { System.out.println("按字典序s4大于s5"); } else { System.out.println("按字典序s4小于s5"); } int position=0; String path="c:\\\\java\\\\jsp\\\\A.java"; position=path.lastIndexOf("\\"); //获取path中最后出现目录分隔符号的位置 System.out.println("c:\\java\\jsp\\A.java中最后出现\\的位置:"+position); String fileName=path.substring(position+1);//获取path中“A.java”子字符串。 System.out.println("c:\\java\\jsp\\A.java中含有的文件名:"+fileName); String s6=new String("100"), s7=new String("123.678"); int n1=Integer.parseInt(s6); //将s6转化成int型数据。 double n2=Double.parseDouble(s7); //将s7转化成double型数据。 double m=n1+n2; System.out.println(m); String s8=String.valueOf(m); //String调用valuOf(int n)方法将m转化为字符串对象 position=s8.indexOf("."); String temp=s8.substring(position+1); System.out.println("数字"+m+"有"+temp.length()+"位小数") ; String s9=new String("ABCDEF"); char a[]= s9.toCharArray(); //将s9存放到数组a for(int i=a.length-1;i>=0;i--) { System.out.print(" "+a[i]); } } }} 实验2 比较日期的大小 模板代码 DateExample import java.util.*; import javax.swing.JOptionPane; public class DateExample { public static void main(String args[ ]) { String str=JOptionPane.showInputDialog("输入第一个日期的年份:"); int yearOne=Integer.parseInt(str); str=JOptionPane.showInputDialog("输入该年的月份:"); int monthOne=Integer.parseInt(str); str=JOptionPane.showInputDialog("输入该月份的日期:"); int dayOne=Integer.parseInt(str); str=JOptionPane.showInputDialog("输入第二个日期的年份:"); int yearTwo=Integer.parseInt(str); str=JOptionPane.showInputDialog("输入该年的月份:"); int monthTwo=Integer.parseInt(str); str=JOptionPane.showInputDialog("输入该月份的日期:"); int dayTwo=Integer.parseInt(str); Calendar calendar= Calendar.getInstance(); //初始化日历对象 calendar.set(yearOne, monthOne, dayOne); //将calendar的时间设置为yearOne年monthOne月dayOne日 long timeOne= calendar.getTimeInMillis(); //calendar表示的时间转换成毫秒 calendar.set(yearTwo, monthTwo, dayTwo); //将calendar的时间设置为yearTwo年monthTwo月dayTwo日 long timeTwo= calendar.getTimeInMillis(); //calendar表示的时间转换成毫秒。 Date date1= new Date(timeOne); // 用timeOne做参数构造date1 Date date2= new Date(timeTwo); // 用timeTwo做参数构造date2 if(date2.equals(date1)) { System.out.println("两个日期的年、月、日完全相同"); } else if(date2.after(date1)) { System.out.println("您输入的第二个日期大于第一个日期"); } else if(date2.before(date1)) { System.out.println("您输入的第二个日期小于第一个日期"); } long days= (timeOne-timeTwo)/(1000*60*60*24);//计算两个日期相隔天数 System.out.println(yearOne+"年"+monthOne+"月"+dayOne+"日和" +yearTwo+"年"+monthTwo+"月"+dayTwo+"相隔"+days+"天"); } } 实验3 处理大整数 模板代码 BigintegerExample import java.math.*; class BigIntegerExample { public static void main(String args[]) { BigInteger n1=new BigInteger("987654321987654321987654321"), n2=new BigInteger("123456789123456789123456789"), result=null; result= n1.add(n2);//n1和n2做加法运算 System.out.println("和:"+result.toString()); result= n1.subtract(n2);//n1和n2做减法运算 System.out.println("差:"+result.toString()); result= n1.multiply(n2);//n1和n2做乘法运算 System.out.println("积:"+result.toString()); result= n1.divide(n2);//n1和n2做除法运算 System.out.println("商:"+result.toString()); BigInteger m=new BigInteger("1968957"), COUNT=new BigInteger("0"), ONE=new BigInteger("1"), TWO=new BigInteger("2"); System.out.println(m.toString()+"的因子有:"); for(BigInteger i=TWO;i.compareTo(m)<0;i=i.add(ONE)) { if((m.remainder(i).compareTo(BigInteger.ZERO))==0) { COUNT=COUNT.add(ONE); System.out.print(" "+i.toString()); } } System.out.println(""); System.out.println(m.toString()+"一共有"+COUNT.toString()+"个因子"); } } 上机实践6 组件及事件处理 实验1 算术测试 模板代码 Teacher.java public class Teacher { int numberOne,numberTwo; String operator=""; boolean right; public int giveNumberOne(int n) { numberOne=(int)(Math.random()*n)+1; return numberOne; } public int giveNumberTwo(int n) { numberTwo=(int)(Math.random()*n)+1; return numberTwo; } public String giveOperator() { double d=Math.random(); if(d>=0.5) operator="+"; else operator="-"; return operator; } public boolean getRight(int answer) { if(operator.equals("+")) { if(answer==numberOne+numberTwo) right=true; else right=false; } else if(operator.equals("-")) { if(answer==numberOne-numberTwo) right=true; else right=false; } return right; } } ComputerFrame.java import java.awt.*; import java.awt.event.*; public class ComputerFrame extends Frame implements ActionListener { TextField textOne,textTwo,textResult; Button getProblem,giveAnwser; Label operatorLabel,message; Teacher teacher; ComputerFrame(String s) { super(s); teacher=new Teacher(); setLayout(new FlowLayout()); textOne= new TextField(10); //创建textOne,其可见字符长是10 textTwo= new TextField(10); //创建textTwo,其可见字符长是10 textResult= new TextField(10); //创建textResult,其可见字符长是10 operatorLabel=new Label("+"); message=new Label("你还没有回答呢"); getProblem=new Button("获取题目"); giveAnwser=new Button("确认答案"); add(getProblem); add(textOne); add(operatorLabel); add(textTwo); add(new Label("=")); add(textResult); add(giveAnwser); add(message); textResult.requestFocus(); textOne.setEditable(false); textTwo.setEditable(false); getProblem.addActionListener(this);//将当前窗口注册为getProblem的ActionEvent事件监视器 giveAnwser.addActionListener(this);//将当前窗口注册为giveAnwser的ActionEvent事件监视器 textResult.addActionListener(this);//将当前窗口注册为textResult的ActionEvent事件监视器 setBounds(100,100,450,100); setVisible(true); validate(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } public void actionPerformed(ActionEvent e) { if(e.getSource()==getProblem) //判断事件源是否是getProblem { int number1=teacher.giveNumberOne(100); int number2=teacher.giveNumberTwo(100); String operator=teacher.givetOperator(); textOne.setText(""+number1); textTwo.setText(""+number2); operatorLabel.setText(operator); message.setText("请回答"); textResult.setText(null); } if(e.getSource()==giveAnwser) //判断事件源是否是giveAnwser { String answer=textResult.getText(); try{ int result=Integer.parseInt(answer); if(teacher.getRight(result)==true) { message.setText("你回答正确"); } else { message.setText("你回答错误"); } } catch(NumberFormatException ex) { message.setText("请输入数字字符"); } } textResult.requestFocus(); validate(); } } MainClass.java public class MainClass { public static void main(String args[]) { ComputerFrame frame; frame= new ComputerFrame("算术测试");//创建窗口,其标题为:算术测试 } } 实验2 信号灯 2.模板代码 SignalCanvas.java import java.awt.*; public class SignalCanvas extends Canvas { int red,green,yellow,x,y,r; SignalCanvas() { setBackground(Color.white); } public void setRed(int r) { red=r; } public void setGreen(int g) { green=g; } public void setYellow(int y) { yellow=y; } public void setPosition(int x,int y) { this.x=x; this.y=y; } public void setRadius(int r) { this.r=r; } public void paint(Graphics g) { if(red==1) { g.setColor(Color.red); } else if(green==1) { g.setColor(Color.green); } else if(yellow==1) { g.setColor(Color.yellow); } g.fillOval(x,y,2*r,2*r); } } SignalFrame.java import java.awt.*; import java.applet.*; import java.awt.event.*; public class SignalFrame extends Frame implements ItemListener { Choice choice; SignalCanvas signal=null; String itemRed="红灯",itemYellow="黄灯",itemGreen="绿灯"; public SignalFrame() { choice=new Choice(); //创建choice choice.add(itemRed); //创建choice添加itemRed choice.add(itemYellow); //创建choice添加itemYellow choice.add(itemGreen); //创建choice添加itemGreen choice.addItemListener(this); //将当前窗口注册为choice的ItemEvent事件监视器 add(choice,BorderLayout.NORTH); try{ Class cs=Class.forName("SignalCanvas"); signal=(SignalCanvas)cs.newInstance(); add(signal,BorderLayout.CENTER); } catch(Exception e) { add(new Label("您还没有编写SignalCanvas类"),BorderLayout.CENTER); } setBounds(100,100,360,300); setVisible(true); validate(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } public void itemStateChanged(ItemEvent e) { String item= choice.getSelectedItem(); // choice返回被选中的条目 int w=signal.getBounds().width; int h=signal.getBounds().height; int m=Math.min(w,h); signal.setRadius(m/6); if(item.equals(itemRed)) { if(signal!=null) { signal.setRed(1); signal.setYellow(0); signal.setGreen(0); signal.setPosition(w/3,0); signal.repaint(); } } else if(item.equals(itemYellow)) { if(signal!=null) { signal.setRed(0); signal.setYellow(1); signal.setGreen(0); signal.setPosition(w/3,h/3); signal.repaint(); } } else if(item.equals(itemGreen)) { if(signal!=null) { signal.setRed(0); signal.setYellow(0); signal.setGreen(1); signal.setPosition(w/3,2*h/3); signal.repaint(); } } } } SignalMainClass.java public class SignalMainClass { public static void main(String args[]) { SignalFrame frame; frame=new SignalFrame() ; frame.setTitle("信号灯"); } } 实验3 布局与日历 2.模板代码 CalendarBean.java import java.util.Calendar; public class CalendarBean { String day[]; int year=2005,month=0; public void setYear(int year) { this.year=year; } public int getYear() { return year; } public void setMonth(int month) { this.month=month; } public int getMonth() { return month; } public String[] getCalendar() { String a[]=new String[42]; Calendar 日历=Calendar.getInstance(); 日历.set(year,month-1,1); int 星期几=日历.get(Calendar.DAY_OF_WEEK)-1; int day=0; if(month==1||month==3||month==5||month==7||month==8||month==10||month==12) { day=31; } if(month==4||month==6||month==9||month==11) { day=30; } if(month==2) { if(((year%4==0)&&(year0!=0))||(year@0==0)) { day=29; } else { day=28; } } for(int i=星期几,n=1;i<星期几+day;i++) { a[i]=String.valueOf(n) ; n++; } return a; } } CalendarFrame.java import java.util.*; import java.awt.*; import java.awt.event.*; import java.applet.*; public class CalendarFrame extends Frame implements ActionListener { Label labelDay[]=new Label[42]; Button titleName[]=new Button[7]; String name[]={"日","一","二","三", "四","五","六"}; Button nextMonth,previousMonth; int year=2006,month=10; CalendarBean calendar; Label showMessage=new Label("",Label.CENTER); public CalendarFrame() { Panel pCenter=new Panel(); pCenter.setLayout(new GridLayout(7,7));//将pCenter的布局设置为7行7列的GridLayout 布局。 for(int i=0;i<7;i++) { titleName[i]=new Button(name[i]); pCenter.add(titleName[i]);//pCenter添加组件titleName[i]。 } for(int i=0;i<42;i++) { labelDay[i]=new Label("",Label.CENTER); pCenter.add(labelDay[i]);//pCenter添加组件labelDay[i]。 } calendar=new CalendarBean(); calendar.setYear(year); calendar.setMonth(month); String day[]=calendar.getCalendar(); for(int i=0;i<42;i++) { labelDay[i].setText(day[i]); } nextMonth=new Button("下月"); previousMonth=new Button("上月"); nextMonth.addActionListener(this); previousMonth.addActionListener(this); Panel pNorth=new Panel(), pSouth=new Panel(); pNorth.add(previousMonth); pNorth.add(nextMonth); pSouth.add(showMessage); showMessage.setText("日历:"+calendar.getYear()+"年"+ calendar.getMonth()+"月" ); ScrollPane scrollPane=new ScrollPane(); scrollPane.add(pCenter); add(scrollPane,BorderLayout.CENTER);// 窗口添加scrollPane在中心区域 add(pNorth,BorderLayout.NORTH);// 窗口添加pNorth 在北面区域 add(pSouth,BorderLayout.SOUTH);// 窗口添加pSouth 在南区域。 } public void actionPerformed(ActionEvent e) { if(e.getSource()==nextMonth) { month=month+1; if(month>12) month=1; calendar.setMonth(month); String day[]=calendar.getCalendar(); for(int i=0;i<42;i++) { labelDay[i].setText(day[i]); } } else if(e.getSource()==previousMonth) { month=month-1; if(month<1) month=12; calendar.setMonth(month); String day[]=calendar.getCalendar(); for(int i=0;i<42;i++) { labelDay[i].setText(day[i]); } } showMessage.setText("日历:"+calendar.getYear()+"年"+calendar.getMonth()+"月" ); } }CalendarMainClass.java public class CalendarMainClass { public static void main(String args[]) { CalendarFrame frame=new CalendarFrame(); frame.setBounds(100,100,360,300); frame.setVisible(true); frame.validate(); frame.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } } ); } } 上机实践7 组件及事件处理2 实验1 方程求根 2.模板代码 SquareEquation.java public class SquareEquation { double a,b,c; double root1,root2; public void setA(double a) { this.a=a; } public void setB(double b) { this.b=b; } public void setC(double c) { this.c=c; } public double getRootOne() throws NoRealRootException,NoSquareEquationException { if(a!=0) { double disk=b*b-4*a*c; if(disk>=0) { root1=(-b+Math.sqrt(disk))/(2*a); } else { throw new NoRealRootException("没有实根"); } } else { throw new NoRealRootException("不是二次方程"); } return root1; } public double getRootTwo() throws NoRealRootException,NoSquareEquationException { if(a!=0) { double disk=b*b-4*a*c; if(disk>=0) { root2=(-b-Math.sqrt(disk))/(2*a); } else { throw new NoRealRootException("没有实根"); } } else { throw new NoRealRootException("不是二次方程"); } return root2; } } class NoRealRootException extends Exception { String message; NoRealRootException(String s) { message=s; } public String getMessage() { return message; } } class NoSquareEquationException extends Exception { String message; NoSquareEquationException(String s) { message=s; } public String getMessage() { return message; } } EquationFrame.java import java.awt.*; import java.awt.event.*; public class EquationFrame extends Frame implements ActionListener { SquareEquation equation; TextField textA,textB,textC; TextArea showRoots; Button controlButton; public EquationFrame() { equation=new SquareEquation(); textA=new TextField(8); textB=new TextField(8); textC=new TextField(8); showRoots=new TextArea(); controlButton=new Button("确定"); Panel pNorth=new Panel(); pNorth.add(new Label("二次项系数:")); pNorth.add(textA); pNorth.add(new Label("一次项系数:")); pNorth.add(textB); pNorth.add(new Label("常数项系数:")); pNorth.add(textC); pNorth.add(controlButton); 【代码1】 //当前窗口作为controlButton的ActionEvent事件的监视器 add(pNorth,BorderLayout.NORTH); add(showRoots,BorderLayout.CENTER); setBounds(100,100,630,160); setVisible(true); validate(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } public void actionPerformed(ActionEvent e) { try{ double a=Double.parseDouble(【代码2】); //textA调用方法获取其中的文本 double b=Double.parseDouble(【代码3】); //textB调用方法获取其中的文本 double c=Double.parseDouble(【代码4】); // textC调用方法获取其中的文本 equation.setA(a); equation.setB(b); equation.setC(c); textA.setText(""+a); textB.setText(""+b); textC.setText(""+c); showRoots.append("\n 根:"+equation.getRootOne()); showRoots.append(" 根:"+equation.getRootTwo()); } catch(Exception ex) { showRoots.append("\n"+ex+"\n"); } } } EquationMainClass.java public class EquationMainClass { public static void main(String args[]) { EquationFrame frame=new EquationFrame(); } } 实验2 字体对话框 2.模板代码 FontFamilyNames.java import java.awt.GraphicsEnvironment; public class FontFamilyNames { String fontName[]; public String [] getFontName() { GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment(); fontName=ge.getAvailableFontFamilyNames(); return fontName; } } FontDialog.java import java.awt.event.*; import java.awt.*; import javax.swing.JLabel; public class FontDialog extends Dialog implements ItemListener,ActionListener { FontFamilyNames fontFamilyNames; int fontSize=38; String fontName; Choice fontNameList; JLabel label; Font font; Button yes,cancel; static int YES=1,NO=0; int state=-1; FontDialog(Frame f) { super(f); fontFamilyNames=new FontFamilyNames(); 【代码1】 //对话框设置为有模式 yes=new Button("Yes"); cancel=new Button("cancel"); yes.addActionListener(this); cancel.addActionListener(this); label=new JLabel("hello,奥运",JLabel.CENTER); fontNameList=new Choice(); String name[]=fontFamilyNames.getFontName(); for(int k=0;k<name.length;k++) { fontNameList.add(name[k]); } fontNameList.addItemListener(this); add(fontNameList,BorderLayout.NORTH); add(label,BorderLayout.CENTER); Panel pSouth=new Panel(); pSouth.add(yes); pSouth.add(cancel); add(pSouth,BorderLayout.SOUTH); setBounds(100,100,280,170); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { state=NO; setVisible(false); } } ); validate(); } public void itemStateChanged(ItemEvent e) { fontName=(String)fontNameList.getSelectedItem(); font=new Font(fontName,Font.BOLD,fontSize); label.setFont(font); label.repaint(); validate(); } public void actionPerformed(ActionEvent e) { if(e.getSource()==yes) { state=YES; 【代码2】 //对话框设置为不可见 } else if(e.getSource()==cancel) { state=NO; 【代码3】 //对话框设置为不可见 } } public int getState() { return state; } public Font getFont() { return font; } } FrameHaveDialog.java import java.awt.event.*; import java.awt.*; import javax.swing.JTextArea; public class FrameHaveDialog extends Frame implements ActionListener { JTextArea text; Button buttonFont; FrameHaveDialog() { buttonFont=new Button("设置字体"); text=new JTextArea("Java 2实用教程(第三版)"); buttonFont.addActionListener(this); add(buttonFont,BorderLayout.NORTH); add(text); setBounds(60,60,300,300); setVisible(true); validate(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } public void actionPerformed(ActionEvent e) { if(e.getSource()==buttonFont) { FontDialog dialog=【代码4】 //创建对话框 【代码5】 //对话框设置为可见 【代码6】 //对话框设置设置标题为“字体对话框” if(dialog.getState()==FontDialog.YES) { text.setFont(dialog.getFont()); text.repaint(); } if(dialog.getState()==FontDialog.NO) { text.repaint(); } } } } FontDialogMainClass.java public class FontDialogMainClass { public static void main(String args[]) { new FrameHaveDialog(); } } 实验3 英语单词拼写训练 2.模板代码 RondomString.java public class RondomString { String str=""; public String getRondomString(String s) { StringBuffer strBuffer=new StringBuffer(s); int m=strBuffer.length(); for(int k=0;k<m;k++) { int index=(int)(Math.random()*strBuffer.length()); char c=strBuffer.charAt(index); str=str+c; strBuffer=strBuffer.deleteCharAt(index); } return str; } } LetterLabel.java import java.awt.*; import java.awt.event.*; public class LetterLabel extends Button implements FocusListener,MouseListener { LetterLabel() { 【代码1】 //将当前对象注册为自身的焦点视器 【代码2】 //将当前对象注册为自身的标监视器 setBackground(Color.cyan); setFont(new Font("",Font.BOLD,30)); } public static LetterLabel[] getLetterLabel(int n) { LetterLabel a[]=new LetterLabel[n]; for(int k=0;k<a.length;k++) { a[k]=new LetterLabel(); } return a; } public void focusGained(FocusEvent e) { setBackground(Color.red); } public void focusLost(FocusEvent e) { setBackground(Color.cyan); } public void mousePressed(MouseEvent e) { requestFocus(); } public void setText(char c) { setLabel(""+c); } public void mouseReleased(MouseEvent e){} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseClicked(MouseEvent e){} } SpellingWordFrame.java import java.awt.*; import java.awt.event.*; import javax.swing.Box; public class SpellingWordFrame extends Frame implements KeyListener,ActionListener { TextField inputWord; Button button; LetterLabel label[]; Panel northP,centerP; Box wordBox; String hintMessage="用鼠标单击字母,按左右箭头交换字母,将其排列成所输入的单词"; Label messaageLabel=new Label(hintMessage); String word=""; SpellingWordFrame() { inputWord=new TextField(12); button=new Button("确定"); button.addActionListener(this); inputWord.addActionListener(this); northP=new Panel(); northP.add(new Label("输入一个英文单词:")); northP.add(inputWord); northP.add(button); centerP=new Panel(); wordBox=Box.createHorizontalBox(); centerP.add(wordBox); add(northP,BorderLayout.NORTH); add(centerP,BorderLayout.CENTER); add(messaageLabel,BorderLayout.SOUTH); setBounds(100,100,350,180); setVisible(true); validate(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } public void actionPerformed(ActionEvent e) { word=inputWord.getText(); int n=word.length(); RondomString rondom=new RondomString(); String randomWord=rondom.getRondomString(word); wordBox.removeAll(); messaageLabel.setText(hintMessage); if(n>0) { label=LetterLabel.getLetterLabel(n); for(int k=0;k<label.length;k++) { 【代码3】 //将当前窗口注册为label[k]的键盘监视器 label[k].setText(""+randomWord.charAt(k)); wordBox.add(label[k]); } validate(); inputWord.setText(null); label[0].requestFocus(); } } public void keyPressed(KeyEvent e) { LetterLabel sourceLabel=(LetterLabel)e.getSource(); int index=-1; if(【代码4】) //判断按下的是否是←键) { for(int k=0;k<label.length;k++) { if(label[k]==sourceLabel) { index=k; break; } } if(index!=0) { String temp=label[index].getText(); label[index].setText(label[index-1].getText()); label[index-1].setText(temp); label[index-1].requestFocus(); } } else if(【代码5】) //判断按下的是否是→键 { for(int k=0;k<label.length;k++) { if(label[k]==sourceLabel) { index=k; break; } } if(index!=label.length-1) { String temp=label[index].getText(); label[index].setText(label[index+1].getText()); label[index+1].setText(temp); label[index+1].requestFocus(); } } validate(); } public void keyTyped(KeyEvent e){} public void keyReleased(KeyEvent e) { String success=""; for(int k=0;k<label.length;k++) { String str=label[k].getText(); success=success+str; } if(success.equals(word)) { messaageLabel.setText("恭喜你,你成功了"); for(int k=0;k<label.length;k++) { label[k].removeKeyListener(this); label[k].removeFocusListener(label[k]); label[k].setBackground(Color.green); } inputWord.requestFocus(); } } } WordMainClass.java public class WordMainClass { public static void main(String args[]) { new SpellingWordFrame(); } } 上机实践8 多线程 实验1 汉字打字练习 2.模板代码 WordThread.java import java.awt.*; public class WordThread extends Thread { char word; int k=19968; Label com; WordThread(Label com) { this.com=com; } public void run() { k=19968; while(true) { word=(char)k; com.setText(""+word); try{ sleep(6000);//调用sleep方法使得线程中断6000豪秒 } catch(InterruptedException e){} k++; if(k>=29968) k=19968; } } } ThreadFrame.java import java.awt.*; import java.awt.event.*; public class ThreadFrame extends Frame implements ActionListener { Label wordLabel; Button button; TextField inputText,scoreText; WordThread giveWord;//用WordThread声明一个giveWord对象 int score=0; ThreadFrame() { wordLabel=new Label(" ",Label.CENTER); wordLabel.setFont(new Font("",Font.BOLD,72)); button=new Button("开始"); inputText=new TextField(3); scoreText=new TextField(5); scoreText.setEditable(false); giveWord=new WordThread(wordLabel);//创建giveWord,将wordLabel传递给WordThread构造方法的参数 button.addActionListener(this); inputText.addActionListener(this); add(button,BorderLayout.NORTH); add(wordLabel,BorderLayout.CENTER); Panel southP=new Panel(); southP.add(new Label("输入标签所显示的汉字后回车:")); southP.add(inputText); southP.add(scoreText); add(southP,BorderLayout.SOUTH); setBounds(100,100,350,180); setVisible(true); validate(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } public void actionPerformed(ActionEvent e) { if(e.getSource()==button) { if(!(giveWord.isAlive())) //giveWord调用方法isAlive() { giveWord=new WordThread(wordLabel); } try { giveWord.start();//giveWord调用方法start() } catch(Exception exe){} } else if(e.getSource()==inputText) { if(inputText.getText().equals(wordLabel.getText())) { score++; } scoreText.setText("得分:"+score); inputText.setText(null); } } } WordThread.java public class ThreadWordMainClass { public static void main(String args[]) { new ThreadFrame(); } 实验2 旋转的行星 2.模板代码 Mycanvas.java import java.awt.*; public class Mycanvas extends Canvas { int r; Color c; public void setColor(Color c) { this.c=c; } public void setR(int r) { this.r=r; } public void paint(Graphics g) { g.setColor(c); g.fillOval(0,0,2*r,2*r); } public int getR() { return r; } } Planet.java import java.awt.*; public class Planet extends Panel implements Runnable { Thread moon; //用Thread类声明一个moon对象 Mycanvas yellowBall; double pointX[]=new double[360], pointY[]=new double[360]; //用来表示画布左上角端点坐标的数组 int w=100,h=100; int radius=30; Planet() { setSize(w,h); setLayout(null); yellowBall=new Mycanvas(); yellowBall.setColor(Color.yellow); add(yellowBall); yellowBall.setSize(12,12); yellowBall.setR(12/2); pointX[0]=0; pointY[0]=-radius; double angle=1*Math.PI/180; //刻度为1度 for(int i=0;i<359;i++) //计算出数组中各个元素的值 { pointX[i+1]=pointX[i]*Math.cos(angle)-Math.sin(angle)*pointY[i]; pointY[i+1]=pointY[i]*Math.cos(angle)+pointX[i]*Math.sin(angle); } for(int i=0;i<360;i++) { pointX[i]=pointX[i]+w/2; //坐标平移 pointY[i]=pointY[i]+h/2; } yellowBall.setLocation((int)pointX[0]-yellowBall.getR(), (int)pointY[0]-yellowBall.getR()); Thread moon =new Thread(this); //创建 moon线程,当前面板做为该线程的目标对象 } public void start() { try{ moon .start(); } catch(Exception exe){} } public void paint(Graphics g) { g.setColor(Color.blue); g.fillOval(w/2-9,h/2-9,18,18); } public void run() { int i=0; while(true) { i=(i+1)60; yellowBall.setLocation((int)pointX[i]-yellowBall.getR(), (int)pointY[i]-yellowBall.getR()); try{ Thread.sleep(10); // Thread类调用类方法sleep使得线程中断10豪秒 } catch(InterruptedException e){} } } } HaveThreadFrame.java import java.awt.*; import java.awt.event.*; public class HaveThreadFrame extends Frame implements Runnable { Thread rotate; //用Thread类声明一个rotate对象 Planet earth; double pointX[]=new double[360], pointY[]=new double[360]; int width,height; int radius=120; HaveThreadFrame() { rotate=new Thread(this); earth=new Planet(); setBounds(0,0,360,400); width=getBounds().width; height=getBounds().height; pointX[0]=0; pointY[0]=-radius; double angle=1*Math.PI/180; for(int i=0;i<359;i++) { pointX[i+1]=pointX[i]*Math.cos(angle)-Math.sin(angle)*pointY[i]; pointY[i+1]=pointY[i]*Math.cos(angle)+pointX[i]*Math.sin(angle); } for(int i=0;i<360;i++) { pointX[i]=pointX[i]+width/2; pointY[i]=pointY[i]+height/2; } setLayout(null); setVisible(true); validate(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); add(earth); earth.setLocation((int)pointX[0]-earth.getSize().width/2, (int)pointY[0]-earth.getSize().height/2); earth.start(); rotate.start(); //用rotate调用start方法 } public void run() { int i=0; while(true) { i=(i+1)60; earth.setLocation((int)pointX[i]-earth.getSize().width/2, (int)pointY[i]-earth.getSize().height/2); try{ Thread.sleep(100); } catch(InterruptedException e){} } } public void paint(Graphics g) { g.setColor(Color.red); g.fillOval(width/2-15,height/2-15,30,30); } } HaveThreadFrame.java public class ThreadRotateMainClass { public static void main(String args[]) { new HaveThreadFrame(); } } 实验3 双线程接力 2.模板代码 MoveButton.java import java.awt.*; import java.awt.event.*; public class MoveButton extends Frame implements Runnable,ActionListener { Thread first,second;//用Thread类声明first,second两个线程对象 Button redButton,greenButton,startButton; int distance=10; MoveButton() { first=new Thread(this); //创建first线程,当前窗口做为该线程的目标对象 second=new Thread(this); //创建first线程,当前窗口做为该线程的目标对象 redButton=new Button(); greenButton=new Button(); redButton.setBackground(Color.red); greenButton.setBackground(Color.green); startButton=new Button("start"); startButton.addActionListener(this); setLayout(null); add(redButton); redButton.setBounds(10,60,15,15); add(greenButton); greenButton.setBounds(100,60,15,15); add(startButton); startButton.setBounds(10,100,30,30); setBounds(0,0,300,200); setVisible(true); validate(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } public void actionPerformed(ActionEvent e) { try{ first.start(); second.start(); } catch(Exception exp){} } public void run() { while(true) { if(Thread.currentThread()==first) //判断当前占有CPU资源的线程是否是first { moveComponent(redButton); try{ Thread.sleep(20); } catch(Exception exp){} } if(Thread.currentThread()==second) //判断当前占有CPU资源的线程是否是second { moveComponent(greenButton); try{ Thread.sleep(10); } catch(Exception exp){} } } } public synchronized void moveComponent(Component b) { if(Thread.currentThread()==first) { while(distance>100&&distance;<=200) try{ wait(); } catch(Exception exp){} distance=distance+1; b.setLocation(distance,60); if(distance>=100) { b.setLocation(10,60); notifyAll(); } } if(Thread.currentThread()==second) { while(distance>=10&&distance;<100) try{ wait(); } catch(Exception exp){} distance=distance+1; b.setLocation(distance,60); if(distance>200) { distance=10; b.setLocation(100,60); notifyAll(); } } } }MoveButtonMainClass.java public class MoveButtonMainClass { public static void main(String args[]) { new MoveButton(); } } 上机实践9 输入输出流 实验1 学读汉字 2.模板代码 ChineseCharacters.java import java.io.*; import java.util.StringTokenizer; public class ChineseCharacters { public StringBuffer getChinesecharacters(File file) { StringBuffer hanzi=new StringBuffer(); try{ FileReader inOne=new FileReader(file); //创建指向文件f的inOne 的对象 BufferedReader inTwo= new BufferedReader(inOne); //创建指向文件inOne的inTwo 的对象 String s=null; int i=0; while((s=inTwo.readLine())!=null) //inTwo读取一行 { StringTokenizer tokenizer=new StringTokenizer(s," ,'\n' "); while(tokenizer.hasMoreTokens()) { hanzi.append(tokenizer.nextToken()); } } } catch(Exception e) {} return hanzi; } } StudyFrame.java import java.awt.*; import java.awt.event.*; import java.io.*; import javax.sound.sampled.*; public class StudyFrame extends Frame implements ItemListener,ActionListener,Runnable { ChineseCharacters chinese; Choice choice; Button getCharacters,voiceCharacters; Label showCharacters; StringBuffer trainedChinese=null; Clip clip=null; Thread voiceThread; int k=0; Panel pCenter; CardLayout mycard; TextArea textHelp; MenuBar menubar; Menu menu; MenuItem help; public StudyFrame() { chinese=new ChineseCharacters(); choice=new Choice(); choice.add("training1.txt"); choice.add("training2.txt"); choice.add("training3.txt"); showCharacters=new Label("",Label.CENTER); showCharacters.setFont(new Font("宋体",Font.BOLD,72)); showCharacters.setBackground(Color.green); getCharacters=new Button("下一个汉字"); voiceCharacters=new Button("发音"); voiceThread=new Thread(this); choice.addItemListener(this); voiceCharacters.addActionListener(this); getCharacters.addActionListener(this); Panel pNorth=new Panel(); pNorth.add(new Label("选择一个汉字字符组成的文件")); pNorth.add(choice); add(pNorth,BorderLayout.NORTH); Panel pSouth=new Panel(); pSouth.add(getCharacters); pSouth.add(voiceCharacters); add(pSouth,BorderLayout.SOUTH); pCenter=new Panel(); mycard=new CardLayout(); pCenter.setLayout(mycard); textHelp=new TextArea(); pCenter.add("hanzi",showCharacters); pCenter.add("help",textHelp); add(pCenter,BorderLayout.CENTER); menubar=new MenuBar(); menu=new Menu("帮助"); help=new MenuItem("关于学汉字"); help.addActionListener(this); menu.add(help); menubar.add(menu); setMenuBar(menubar); setSize(350,220); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); validate(); } public void itemStateChanged(ItemEvent e) { String fileName=choice.getSelectedItem(); File file=new File&#40;fileName&#41;; trainedChinese=chinese.getChinesecharacters(file); k=0; mycard.show(pCenter,"hanzi") ; } public void actionPerformed(ActionEvent e) { if(e.getSource()==getCharacters) { if(trainedChinese!=null) { char c=trainedChinese.charAt(k); k++; if(k>=trainedChinese.length()) k=0; showCharacters.setText(""+c); } else { showCharacters.setText("请选择一个汉字字符文件"); } } if(e.getSource()==voiceCharacters) { if(!(voiceThread.isAlive())) { voiceThread=new Thread(this); } try{ voiceThread.start(); } catch(Exception exp){} } if(e.getSource

2012-06-28

Java 2实用教程(第三版)实验指导与习题解答

Java 2实用教程(第三版)实验指导与习题解答 清华大学出版社 (编著 耿祥义 张跃平) 实验模版代码 建议使用文档结构图 (选择Word菜单→视图→文档结构图) 上机实践1 初识Java 4 实验1 一个简单的应用程序 4 实验2 一个简单的Java Applet程序 4 实验3 联合编译 5 上机实践2 基本数据类型与控制语句 6 实验1 输出希腊字母表 6 实验2 回文数 6 实验3 猜数字游戏 8 上机实践3 类与对象 9 实验1 三角形、梯形和圆形的类封装 9 实验2 实例成员与类成员 12 实验3 使用package语句与import语句 13 上机实践4 继承与接口 15 实验1 继承 15 实验2 上转型对象 17 实验3 接口回调 18 上机实践5 字符串、时间与数字 19 实验1 String类的常用方法 19 实验2 比较日期的大小 21 实验3 处理大整数 22 上机实践6 组件及事件处理 23 实验1 算术测试 23 实验2 信号灯 25 实验3 布局与日历 28 上机实践7 组件及事件处理2 31 实验1 方程求根 31 实验2 字体对话框 34 实验3 英语单词拼写训练 37 上机实践8 多线程 41 实验1 汉字打字练习 41 实验2 旋转的行星 43 实验3 双线程接力 47 上机实践9 输入输出流 50 实验1 学读汉字 50 实验2 统计英文单词字 53 实验2 读取Zip文件 56 上机实践10 Java 中的网络编程 57 实验1 读取服务器端文件 57 实验2 使用套接字读取服务器端对象 59 实验3 基于UDP的图像传输 62 上机实践11 数据结构 66 实验1 扫雷小游戏 66 实验2 排序与查找 70 实验3 使用TreeSet排序 72 上机实践12 java Swing 74 实验1 JLayeredPane分层窗格 74 实验2 使用表格显示日历 75 实验3 多文档界面(MDI) 78 上机实践1 初识Java 实验1 一个简单的应用程序 2.模板代码 Hello.java package 实验一; public class Hello { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("你好,很高兴学习Java"); //命令行窗口输出"你好,很高兴学习Java" A a=new A(); a.fA(); } } class A { void fA() {System.out.println("we are student"); } } 实验2 一个简单的Java Applet程序 2.模板代码 FirstApplet.java import java.applet.*; import java.awt.*; public class FirstApplet extends Applet { public void paint(Graphics g) { g.setColor(Color.blue); g.drawString("这是一个Java Applet 程序",10,30);//在Java Applet中绘制一行文字:“这是一个Java Applet 程序” g.setColor(Color.red); g.setFont(new Font("宋体",Font.BOLD,36)); g.drawString("我改变了字体",20,50);//在Java Applet中绘制一行文字:“我改变了字体” } }实验3 联合编译 2.模板代码 public class MainClass { public static void main (String args[ ]) { System.out.println("你好,只需编译我") ; //命令行窗口输出"你好,只需编译我" A a=new A(); a.fA(); B b=new B(); b.fB(); } } public class A { void fA() {

2012-06-28

需求分析需求分析(UML图)

软件工程课程设计实验报告 —网上选课系统 《软件工程》课程设计任务书

2012-06-26

软件工程学生成绩管理系统

软件工程学生成绩管理系统及代码 学生成绩管理系统E-R图等

2012-06-25

空空如也

TA创建的收藏夹 TA关注的收藏夹

TA关注的人

提示
确定要删除当前文章?
取消 删除