Java2实用教程(第3版)课后答案

更新时间:2024-05-27 05:14:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

第1章 Java入门

1. 开发与运行Java程序需要经过哪些主要步骤和过程?

答:(1)编写Java源文件:使用文本编辑器(Edit或记事本),拓展名为.java (2)编译Java源文件:使用Java编译器(javac.exe)。得到字节码文件*.class (3)运行Java程序:Java应用程序使用Java解释器(java.exe)执行字节码文件; Java小应用程序使用支持Java标准的浏览器来执行。

2. 怎样区分应用程序和小应用程序?应用程序的主类或小应用程序的主类必须用public修饰吗? 答: ①应用程序必须有main方法,这个方法是程序执行的入口。 小应用程序没有main方法。

②应用程序的主类不一定用public修饰;小应用程序的主类必须用public修饰。

3. Java程序是由什么组成的?一个程序中必须要有public类吗?Java源文件的命名规则是怎样的? 答: ①Java程序由类组成。

②应用程序可以没有public类;小应用程序一定有一个类是public类(主类)。 ③应用程序:如果只有一个类,源文件名与该类的类名相同,拓展名为.java; 有多个类时,如果有public类(最多一个),源文件名与public类的类 名相同,拓展名是.java;没有public类,源文件名与任何一个类的类名 相同即可,拓展名为.java。

小应用程序:源文件名与主类的类名相同,拓展名是.java。

4. 在运行小程序的HTML文件中可以使用codebase属性指定小程序的字节码所驻留的目录。如果不使用codebase属性,小程序的字节码文件必须和运行它的HTML文件在同一目录中。编写一个小程序并将小程序的字节码存放在某个目录中,比如C:\\5000;把运行该小程序的HTML文件(注意其中的codebase属性):

存放在另一个目录中。

答: 以书中小应用程序为例进行说明: ①编写Java小应用程序源代码 import java.applet.*; import java.awt.*;

public class Boy extends Applet {

public void paint(Graphics g) {

g.setColor(Color.red);

g.drawString(\我一边喝着咖啡,一边学Java呢\g.setColor(Color.blue);

g.drawString(\我学得很认真\} }

②将上述代码命名为Boy.java并进行编译得到Boy.class字节码文件;将得到的字节码文件存放在

C:\\5000文件夹下;

③编写小应用程序的HTML源文件:

④将上述编写好的代码命名为Boy.html;并将此文件存放在C:\\5000文件夹以外的任意一个文件夹中(如C:\\1000); ⑤运行Boy.html。

第2章 标识符、关键字和数据类型

1. 什么叫标识符?标识符的规则是什么?

答:①用来标识类名、变量名、、方法名、类型名、数组名、文件名的有效字符序列。

②由字母、下划线、美元符号和数字组成,并且第一个字符不能是数字字符,而且关键字不能作为标识符。 2. 什么叫关键字?请说出5个关键字。

答:①Java语言中已经被赋予特定意义的一些单词。 ②class break public return static extends等。 3. Java的基本数据类型都是什么?

答:boolean(逻辑型) char(字符型) float、double(浮点型) byte、short、int、long(整型)。 4. 下列哪些语句是错误的: int x = 8; byte b = 127; b = x;

答:b=x语句错误;原因是高级别的变量赋值给低级别的变量时,一定要用显式转换即b=(byte)x; 。 5. 下列程序的输出结果是什么? public class E {

public static void main(String args[]) {

long[] a={1,2,3,4};

long[] b={100,200,300,400,500}; b=a;

System.out.println(\数组b的长度:\System.out.println(\} }

答: 数组b的长度:4 b[0]=1

6. 上机运行下列程序,注意观察输出结果。 public class E {

public static void main(String args[]) {

for(int i=20302;i<20322;i++) {

System.out.println((char)i); } }

}

答: 低住佐佑佒体佔何佖佗佘余佚佛作佝佞佟你佡

7. System.out.println(“你好”);可输出字符串,也可以使用System.out.println( )输出变量或表达式的值,只需使用并置符号“+”将变量、表达式或一个常数值与一个字符串并置即可,如:

System.out.println(“ ”+x);System.out.println(“:”+123+“大于”+122);等。上机调试下列程序,注意观察结果,特别注意System.out.print( )和System.out.println( )的区别。 public class OutputData {

public static void main(String args[]) {

int x=234,y=432;

System.out.println(x+\System.out.print(\我输出结果后不回车\

System.out.println(\我输出结果后自动回车到下一行\System.out.println(\System.out.println(\} }

答: 234<468

我输出结果后不回车我输出结果后自动回车到下一行 x+y= 666 234432=234432

8. 编写一个Java应用程序,输出全部的希腊字母。 答:

public class a {

public static void main(String args[]) {System .out .println(\这是我的第一个程序\}

第3章 运算符、表达式和语句

1. 下列程序的输出结果是什么? public class E {

public static void main(String args[]) {

char x='你',y='e',z='吃'; if(x>'A') { y='爱'; z='情'; } else y='我'; z='她';

System.out.println(\} }

答: 你爱她

2. 下列程序的输出结果是什么? public class E3 {

public static void main(String args[]) {

char c='\\0';

for(int i=1;i<=4;i++) { switch(i) {

case 1:c='b'; System.out.print(c); case 2:c='e'; System.out.print(c); break; case 3:c='p'; System.out.print(c); default:

System.out.print(\} } } }

答:beep!!

3. 编写应用程序,求1!+2!+?+10!。 答: class Fact {

public static void main(String args[]) {

int fact,sum=0; for(int i=1;i<=10;i++) { fact=1;

for(int j=1;j<=i;j++) fact*=j; sum+=fact; }

System.out.println(\到10的阶乘之和是:\}

}

4. 编写一个应用程序,求100以内的全部素数。 答:

class Primes {

public static void main(String args[]) { int w=1;

for(int i=2;i<=100;i++) {

for(int j=2;j

System.out.println(i+\是素数\} } }

5. 分别用do―while和for循环计算1+1/2!+1/3!+1/4!+?的前20项和。 答: ①for循环 class Sum {

public static void main(String args[]) { int fact; double sum=0;

for(int i=1;i<=20;i++) { fact=1;

for(int j=1;j<=i;j++) fact*=j; sum+=1.0/fact; }

System.out.println(sum); } }

②do―while循环 class Sum {

public static void main(String args[]) {

int i=1; int fact; double sum=0; do { fact=1; int j=0; while(++j<=i) fact*=j; sum+=1.0/fact; }

while(++i<=20);

System.out.println(sum); } }

6. 一个数如果恰好等于它的因子之和,这个数就称为“完数”。编写应用程序,求1000之内的所有完数。 答:

class Wanshu {

public static void main(String args[]) {

int x,i,sum;

for(x=1;x<=1000;x++) {

sum=0;

for(i=1;i

if(x%i==0) sum+=i; }

if(x==sum)

System.out.println(x+\是完数\} } }

7. 编写应用程序,分别使用while和for循环计算8+88+888+?前10项之和。 答: ①for循环 class TheSum {

public static void main(String args[]) {

long sum=0,data=8; for(int i=1;i<=10;i++) {

sum=sum+data; data=data*10+8; }

System.out.println(sum); } }

②while循环 class TheSum {

public static void main(String args[]) {

long sum=0,data=8,i=0; while(++i<=10) {

sum=sum+data; data=data*10+8; }

System.out.println(sum); } }

8. 编写应用程序,输出满足1+2+3+?+n<8888的最大正整数n。 答: class Maxn { {

int k=1,sum=0; while((sum+=k)<8888) k++; k--;

System.out.println(\最大能取到:\} }

public static void main(String args[])

第4章 类、对象和接口

1. 类中的实例变量在什么时候会被分配内存空间?

答: 当该类创建对象之后,实例变量才会被分配相应的内存空间。 2. 什么叫方法的重载?构造方法可以重载吗?

答:①一个类中可以有多个方法具有相同的名字,但这些方法的参数必须不同,即或者是参数的个数不同,或者是参数的类型不同(方法的重载体现了多态性,即功能多态性)。 ②构造方法可以重载。

3. 类中的实例方法可以操作类变量(static变量)吗?类方法(static方法)可以操作实例变量吗? 答:①类中的实例方法可以操作类变量。 ②类方法不可以操作实例变量

4. 类中的实例方法可以用类名直接调用吗? 答: 类中的实例方法不可以用类名直接调用。 5. 举例说明protected方法和友好方法的区别。

答: 当子类与父类不在同一个包中时,子类可以继承父类的protected方法;而友好方法此时则不能被子类继承。

6. 举例说明类变量和实例变量的区别。

答:⑴书写: 定义成员变量时,类变量有static修饰;实例变量没有static修饰。 例: class A {

int x; //实例变量 static int y; //类变量 }

⑵内存: 不创建对象,类的实例变量不会被分配内存空间;类变量被分配相应的内存空间。 不同对象的实例变量被分配不同的内存空间;不同对象的类变量被分配相同的内存空间。 任何一个对象改变类变量,其他对象的相应类变量也发生相应变化。 一个对象的实例变量发生改变,不影响其他对象的相应实例变量。 例: 执行语句: A1.x=10; A1.y=20;

这时A2.x的值也是10;而A2.y的值保持原来的初值。

⑶使用: 类变量可以被类方法操作;而实例变量不能被类方法操作。 例: class A { int x; static int y; static void func() {

b=10; //合法 a=20; //非法 } }

类变量可以通过类名访问;实例变量不能通过类名访问。 例: class A { int x; static int y; } class B {

public void func(); {

A.x=10; //非法 A.y=20; //合法

} }

7. 子类将继承父类的哪些成员变量和方法?子类在什么情况下隐藏父类的成员变量和方法?在子类中是否允许有一个方法和父类的方法名字相同,而类型不同?

答:①子类和父类在同一个包中时,子类可以继承父类的除private属性的所有方法和成员变量,当子类与 父类不在同一个包中时,子类只能继承父类的protected和public属性的成员变量和方法。

②子类中定义的成员变量和父类中的成员变量同名时,子类就隐藏了继承的成员变量;子类中定义一个方法,并且这个方法的名字、返回类型、参数个数和类型与从父类继承的方法完全相同,子类就隐藏从父类继承来的方法(方法的重写)。

③在子类中允许有一个方法和父类的方法名字相同而类型不同。 8. 父类的final方法可以被子类重写吗? 答: 父类的final方法不能被子类重写。 9. 什么类中可以有abstract方法? 答: abstract类中可以有abstract方法。 10.什么叫对象的上转型对象?

答: B类是A类的子类或间接子类,当用子类B创建一个对象b并把这个对象的引用放到A类的对象a中时,称A类对象a是子类对象b的上转型对象。 11.什么叫接口的回调?

答: 可以把实现某一接口的类创建的对象的引用赋给该接口声明的接口变量中。 12.下列程序有什么错误? public class Takecare

{ int a=90;

static float b=10.98f;

public static void main(String args[]) {

float c=a+b;

System.out.println(\} }

答: 语句float c=a+b;错误。原因是类方法main操作了实例变量a。 13. 请写出下列程序的输出结果。 class A {

public int f(int x) {

return x+1; } }

class B extends A {

public int f(int x) {

return x*x; } }

public class E {

public static void main(String args[]) {

A a=new B(); int m=a.f(10);

System.out.println(m); } } 答: 100

14. 请写出下列程序的输出结果。 class A { int x;

public void setX(int x) { this.x=x; }

int getX()

{ return x; } } class B {

public void f(A a) {

a.setX(100); } }

public class E {

public static void main(String args[]) {

A a=new A(); a.setX(8);

System.out.println(a.getX()); B b=new B(); b.f(a);

System.out.println(a.getX()); } } 答: 8 100

15.使用接口有哪些注意事项?模仿例子4.27,编写一个类实现两个接口的程序。

答:①一个类使用接口时,要有implements关键字,当一个类使用多个接口时,接口名要用逗号“,”隔开;使用接口的类除abstract类外,必须实现接口的所有方法,并且实现接口的方法时,方法名字、返回类型、参数个数及类型必须与接口中的完全一致;类在实现接口时,方法体一定要用public修饰,如果接口方法的返回类型不是void型,在类中实现接口时,方法体至少有一个return语句。 ② interface 表面积 {

double allArea(double r); }

interface 体积 {

double volu(double r); }

class Sph implements 表面积,体积 {

double PI=3.14159;

public double allArea(double r) {

return 4*PI*r*r;

}

public double volu(double r) {

return 4.0/3*PI*r*r*r; } }

public class Test {

public static void main(String args[]) {

double r=5.0; Sph a=new Sph();

System.out.println(\半径为5的球的表面积是:\System.out.println(\半径为5的球的体积是:\

} }

16.编写一个类A,该类创建的对象可以调用方法f输出英文字母表,然后再编写一个该类的子类B,要求子类B必须继承A类的方法f(不允许重写),子类创建的对象不仅可以调用方法f输出英文字母表,而且调用子类新增的方法g输出希腊字母表。 答: class A { int m; void f() {

for(m=65;m<91;m++)

System.out.print((char)m+\for(m=97;m<123;m++)

System.out.print((char)m+\System.out.println(\} }

class B extends A { int i; void g() {

for(i=913;i<930;i++)

System.out.print((char)i+\for(i=931;i<938;i++)

System.out.print((char)i+\for(i=945;i<962;i++)

System.out.print((char)i+\for(i=963;i<970;i++)

System.out.print((char)i+\

System.out.println(\} }

public class Test {

public static void main(String args[]) {

B b=new B();

System.out.println(\我调用方法f输出英文字母表:\b.f();

System.out.println(\我调用方法g输出希腊字母表:\

b.g(); } }

17.编写一个异常类MyException,再编写一个类Student,该类有一个产生异常的方法public void speak(int m) throws MyException,要求参数m的值大于1000时,方法抛出一个MyException对象。最后编写主类,在主类的main方法中用Student创建一个对象,让该对象调用speak方法。 答: class MyException extends Exception {

String str1; MyException(int m) {

str1=m+\出现错误 可能造成的原因是取值大于1000\}

public void showStr1() {

System.out.println(str1); } }

class Student {

public void speak(int m) throws MyException {

if(m>1000) {

MyException exception=new MyException(m); throw exception; } else

System.out.println(m); } }

public class Test {

public static void main(String agrs[]) { int m;

Student stu1=new Student(); m=987; try {

stu1.speak(m);

m=1234; stu1.speak(m); }

catch(MyException e) {

e.showStr1(); } } }

18.编写一个类,该类有一个方法public int f(int a,int b),该方法返回a和b的最大公约数。然后再编写一个该类的子类,要求子类重写方法f,而且重写的方法将返回a和b的最小公倍数。要求在重写的方法的方法体中首先调用被隐藏的方法返回a和b的最大公约数m,然后将乘积(a*b)/m返回。要求在应用程序的主类中分别使用父类和子类创建对象,并分别调用方法f计算两个正整数的最大公约数和最小公倍数。 答: class A {

public int f(int a,int b) { if(a

int temp=0; temp=a; a=b; b=temp; }

int r=a%b; while(r!=0) { a=b; b=r; r=a%b; } return b; } }

class B extends A

{

public int f(int a,int b) { int m;

m=super.f(a,b); return (a*b)/m;

} }

public class Test {

public static void main(String args[]) {

A a=new A();

System.out.println(\和102的最大公约数是:\B b=new B();

System.out.println(\和102的最小公倍数是:\} }

第5章 字符串

1. 使用String类的public String toUpperCase()方法可以将一个字符串中的小写字母变成大写字母,使用public String toLowerCase()方法可以将一个字符串中的大写字母变成小写字母。编写一个程序,使用这两个方法实现大小写的转换。 答: class Test {

public static void main(String args[]) {

String str=\

System.out.println(\要转换的字符串是:\String s=str.toUpperCase();

System.out.println(\转换成大写字符串是:\s=str.toLowerCase();

System.out.println(\转换成小写字符串是:\} }

2. 使用String类的public String concat(String str)方法可以把调用该方法的字符串与参数指定的字符串连接,把str指定的串连接到当前串的尾部获得一个新的串。编写一个程序通过连接两个串得到一个新串,并输出这个新串。 答: class Test {

public static void main(String args[]) {

String str1=\String str2=\

String s=str1.concat(str2);

System.out.println(\将字符串\与字符串\连接后得到的新字符串是:\System.out.println(s);

} }

3. String类的public char charAt(int index)方法可以得到当前字符串index位置上的一个字符。说出下列程序的输出结果。 public class E3 {

public static void main(String args[]) {

String s=\中国科学技术大学\char a=s.charAt(2),b=s.charAt(6); System.out.print(a); System.out.println(b); } } 答: 科大

4. 使用java.util包中的Arrays类的静态方法public static void sort(double a[])可以把参数a指定的double型数组按升序排序,使用java.util包中的Arrays类的静态方法public static void sort(double a[],int start,int end)可以把参数a指定的double型数组中从位置start到end-1位置的数按升序排序。写出下列程序的输出结果。 import java.util.*; public class E4 {

public static void main(String args[]) {

int a[]={23,67,89,90,-987};

double b[]={12.89,90.87,34,678.987,-98.78,0.89}; Arrays.sort(a); Arrays.sort(b,1,4); for(int i=0;i<=4;i++) {

System.out.print(a[i]+\}

for(int i=0;i

System.out.print(b[i]+\} } }

答: -987,23,67,89,90,12.89,34.0,90.87,678.987,-98.78,0.89,

5. 使用java.lang包中System类的静态方法arraycopy可以实现数组的快速复制,上机实习下列程序,并总结出arraycopy方法参数的使用规则。 public class ArrayCopy {

public static void main(String args[])

{

char a1[]={'a','b','c','d','e','f'},b1[]={'1','2','3','4','5','6'}; System.arraycopy(a1,0,b1,1,a1.length-1); System.out.println(new String(a1)); System.out.println(new String(b1));

byte a2[]={97,98,99,100,101,102},b2[]={65,67,68,69,70,71}; System.arraycopy(b2,0,a2,3,b2.length-3); System.out.println(new String(a2)); System.out.println(new String(b2)); } }

答:①运行结果:abcdef 1abcde abcACD ACDEFG

②arraycopy的方法是public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)。其中五个参数分别表示: src - 被复制的数组

srcPos - 从第几个元素开始复制 dest - 要复制到的数组

destPos - 从第几个元素开始粘贴 length - 一共需要复制的元素个数

第6章 时间、日期和数字

1. 用Data类不带参数的构造方法创建日期,要求日期的输出格式是:星期 小时 分 秒。 答: import java.util.*; import java.text.*; class Test {

public static void main(String args[]) {

Date 时间=new Date();

SimpleDateFormat s=new SimpleDateFormat(\时 mm分 ss秒\System.out.println(s.format(时间)); } }

2. 输出2006年2月的日历页,程序需处理闰年问题。 答: import java.util.*; class Test {

public static void main(String args[])

{

int year=2006,month=2; int allDay;

if((year%4==0&&year0!=0)||(year@0==0)) allDay=29; else allDay=28;

Calendar feb=Calendar.getInstance(); feb.set(2006,1,1);

int dat=feb.get(Calendar.DAY_OF_WEEK)-1; String a[]=new String[dat+allDay]; for(int i=0;i

for(int i=dat,n=1;i<(dat+allDay);i++) { if(n<=9)

a[i]=String.valueOf(n)+\else

a[i]=String.valueOf(n)+\n++; }

System.out.println(\年 \月\System.out.println(\日 一 二 三 四 五 六\for(int j=0;j

if(j%7==0) {

System.out.println(\}

System.out.print(a[j]); } } }

3. 计算某年、某月、某日和某年、某月、某日之间的天数间隔。要求年、月、日通过main方法的参数传递到程序中。

答: import java.util.*; class Test {

public static void main(String args[]) {

Calendar c=Calendar.getInstance(); c.set(2000,0,1);

long time1=c.getTimeInMillis(); c.set(2008,7,8);

long time2=c.getTimeInMillis();

long dayCous=(time2-time1)/(1000*60*60*24);

System.out.println(\年8月8日和2000年1月1日相隔\天\} }

4. 编程练习 Math类的常用方法。 答: import java.text.*; public class Test {

public static void main(String args[]) {

double a=Math.abs(-10);

System.out.println(\的绝对值是:\double maxNum=Math.max(123.456,-5.4321);

System.out.println(\与-5.4321中的最大值是:\double minNum=Math.min(123.456,-5.4321);

System.out.println(\与-5.4321中的最小值是:\int randomNum=(int)(Math.random()*10)+1;

System.out.println(\输出一个1到10的随机数是:\double powNum=Math.pow(2,10);

System.out.println(\的10次幂是:\double sqrtNum=Math.sqrt(10);

System.out.println(\的平方根是:\double logNum=Math.log(2);

System.out.println(\的对数是:\double sinNum=Math.sin(-10);

System.out.println(\的正弦值是:\double asinNum=Math.asin(0.5);

System.out.println(\的反正弦值是:\System.out.println(\格式化之前的数是:\NumberFormat f=NumberFormat.getInstance(); f.setMaximumFractionDigits(10); f.setMinimumIntegerDigits(4); String s=f.format(sqrtNum); System.out.println(\格式化后:\} }

5. 使用BigInteger类计算1!+3!+5!+7!+?的前30项的和。 答: import java.math.*;

public class Test {

public static void main(String args[])

{

BigInteger sum=new BigInteger(\jieCheng=new BigInteger(\ONE=new BigInteger(\i=ONE; int k=0; while(++k<=30) {

sum=sum.add(jieCheng); i=i.add(ONE);

jieCheng=jieCheng.multiply(i); i=i.add(ONE);

jieCheng=jieCheng.multiply(i); }

System.out.println(sum); } }

第7章 AWT组件及事件处理

1. Frame类对象的默认布局是什么布局?和Panel类对象的默认布局相同吗? 答:①Frame类对象的默认布局是BorderLayout布局; ②不相同,Panel类对象的默认布局是FlowLayout布局。 2. 一个容器对象是否可以使用add方法添加一个Frame窗口? 答: 不可以。

3. Checkbox对象可以触发ItemEvent事件吗? 答: 可以。

4. 编写应用程序,有一个标题为“计算的窗口”的窗口,窗口的布局为FlowLayout布局。窗口中添加两个文本区,当我们在一个文本区中输入若干个数时,另一个文本区,同时对输入的数进行求和运算并求出平均值,也就是说随着输入的变化,另一个文本区不断地更新求和及平均值。 答: import java.awt.*; import java.awt.event.*; import java.util.*;

class Calculated extends Frame implements TextListener {

TextArea text1,text2; //定义了2个文本区

Calculated(String s) //标题为“计算的窗口”的窗口 { super(s);

setLayout(new FlowLayout()); //窗口布局为FlowLayout text1=new TextArea(5,23); text2=new TextArea(5,23); add(text1); add(text2);

text2.setEditable(false); //显示求和结果和平均值的文本区禁止编辑

text1.addTextListener(this);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0); } } );

setBounds(100,100,400,160); setVisible(true); validate(); }

public void textValueChanged(TextEvent e) {

String s=text1.getText();

StringTokenizer geshu=new StringTokenizer(s); int n=geshu.countTokens(); double a[]=new double[n]; for(int i=0;i

String temp=geshu.nextToken(); double date=Double.parseDouble(temp); a[i]=date; }

double sum=0,average; for(int i=0;i

sum=sum+a[i]; }

average=sum/n; text2.setText(null);

text2.append(\和:\平均数:\} }

public class Test {

public static void main(String args[]) {

Calculated calc=new Calculated(\计算的窗口\} }

5. 文本区可以使用getSelectedText()方法获取该文本区通过拖动鼠标选中的文件。编写应用程序,有一个标题为“挑单词”的窗口,窗口的布局为BorderLayout布局。窗口中添加两个文本去和一个按钮组

件,要求文本区分别添加到窗口的东部区域和西部区域;按钮添加到窗口的南部区域,当单击按钮时,程序将东部区域的文本区中鼠标选中的内容尾加到西部区域的文本区中。 答: import java.awt.*; import java.awt.event.*;

class WindowSelectedText extends Frame implements ActionListener {

TextArea text1,text2; //定义2个文本区 Button button; //定义一个按钮

WindowSelectedText(String s) //窗口名字为“挑单词” { super(s);

setLayout(new BorderLayout()); //窗口布局是BorderLayout布局 text1=new TextArea(6,15); text2=new TextArea(6,15); button=new Button(\确定\add(text1,BorderLayout.EAST); add(text2,BorderLayout.WEST); add(button,BorderLayout.SOUTH); button.addActionListener(this); addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0); } } );

text2.setEditable(false); setBounds(100,100,350,200); setVisible(true); validate(); }

public void actionPerformed(ActionEvent e) {

if(e.getSource()==button) {

String s=text1.getSelectedText()+\String str=text2.getText(); text2.setText(str+s); } } }

public class Test {

public static void main(String args[]) {

new WindowSelectedText(\挑单词\} }

6. 编写一个应用程序,有一个标题为“计算”的窗口,窗口的布局为FlowLayout布局。设计4个按钮,分别命名为“加”、“差”、“积”、“除”,另外,窗口中还有3个文本框。单击相应的按钮,将两个文本框的数字做运算,在第三个文本框中显示结果。要求处理NumberFormatException。 答: import java.awt.*; import java.awt.event.*;

class Calculated extends Frame implements ActionListener {

TextField text1,text2,text3; //3个文本框

Button buttonH,buttonC,buttonJ,buttonS; //4个按钮 Calculated(String s) { super(s);

setLayout(new FlowLayout()); //FlowLayout布局 text1=new TextField(10); text2=new TextField(10); text3=new TextField(17); buttonH=new Button(\加\buttonC=new Button(\差\buttonJ=new Button(\积\buttonS=new Button(\除\add(text1); add(text2); add(text3);

text3.setEditable(false);

add(buttonH); add(buttonC); add(buttonJ); add(buttonS);

buttonH.addActionListener(this); buttonC.addActionListener(this); buttonJ.addActionListener(this); buttonS.addActionListener(this); addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0); } }

);

setBounds(100,100,160,180); setVisible(true); validate(); }

public void actionPerformed(ActionEvent e) {

double num1=0,num2=0,totle=0; try {

num1= Double.parseDouble(text1.getText()); num2= Double.parseDouble(text2.getText()); if(e.getSource()==buttonH) {

totle=num1+num2;

text3.setText(\和\}

else if(e.getSource()==buttonC) {

totle=num1-num2;

text3.setText(\差\}

else if(e.getSource()==buttonJ) {

totle=num1*num2;

text3.setText(\积\}

else if(e.getSource()==buttonS) {

totle=num1/num2;

text3.setText(\商\} }

catch(NumberFormatException event) {

text3.setText(\请输入数字字符!\} } }

public class Test {

public static void main(String args[]) {

Calculated calc=new Calculated(\计算\标题为“计算”的窗口

} }

7. 改进例子7.16,在程序中增加一个名称为“确定”的按钮和一个文本区。当单击按钮时,程序验证用户是否输入了合法的E-mail地址格式,如果合法就将用户输入的姓名、E-mail和职业尾加到文本区中,否则在输入E-mail的文本框中提示用户输入了非法格式的E-mail地址。 答: import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.awt.event.*;

class WindowBox extends Frame implements ActionListener {

TextField text1,text2,text3; TextArea textarea; Box baseBox,boxV1,boxV2; Button button; WindowBox() {

button=new Button(\确定\textarea=new TextArea(6,12); text1=new TextField(12); text2=new TextField(12); text3=new TextField(12); boxV1=Box.createVerticalBox(); boxV1.add(new Label(\姓名\

boxV1.add(Box.createVerticalStrut(8)); boxV1.add(new Label(\

boxV1.add(Box.createVerticalStrut(8)); boxV1.add(new Label(\职业\boxV2=Box.createVerticalBox(); boxV2.add(text1);

boxV2.add(Box.createVerticalStrut(8)); boxV2.add(text2);

boxV2.add(Box.createVerticalStrut(8)); boxV2.add(text3);

baseBox=Box.createHorizontalBox(); baseBox.add(boxV1);

baseBox.add(Box.createHorizontalStrut(10)); baseBox.add(boxV2);

setLayout(new FlowLayout()); add(baseBox); add(button); add(textarea);

addWindowListener(new WindowAdapter() { {

System.exit(0); } } );

textarea.setEditable(false); button.addActionListener(this); setBounds(100,100,210,250); setVisible(true); validate(); }

public void actionPerformed(ActionEvent e) {

boolean a; int b; String s;

if(e.getSource()==button) {

s=text2.getText(); a=s.endsWith(\b=s.indexOf(\if(a&&b>0) {

String str1=text1.getText()+\String str2=textarea.getText();

public void windowClosing(WindowEvent e)

textarea.setText(str2+str1); } else {

text2.setText(\输入了非法格式的E-mail地址\} } } }

public class Test {

public static void main(String args[]) {

new WindowBox(); } }

8. 写一个应用程序,要求编写一个Panel的子类MyPanel,MyPanel中有一个文本框和一个按钮,要求MyPanel的实例作为其按钮的ActionEvent事件的监视器,当单击按钮时,程序获取文本框中的文本,

并将该文本作为按钮的名称。然后在编写一个Frame的子类,即窗口。窗口的布局为BorderLayout布局。窗口中添加两个MyPanel面板,分别添加到窗口的东部区域和西部区域。 答: import java.awt.*; import java.awt.event.*;

class MyPanel extends Panel implements ActionListener {

String name; TextField text; Button button; MyPanel() {

text=new TextField(10); button=new Button(\确定\add(text); add(button);

button.addActionListener(this); addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0); } }

); }

public void actionPerformed(ActionEvent e) {

if(e.getSource()==button) {

name=text.getText(); button.setLabel(name); } } }

class MyFrame extends Frame {

MyPanel panel1,panel2; MyFrame() {

panel1=new MyPanel(); panel2=new MyPanel();

add(panel1,BorderLayout.EAST); add(panel2,BorderLayout.WEST); setBounds(100,100,400,100);

setVisible(true); validate(); } }

public class Test {

public static void main(String args[]) {

MyFrame win=new MyFrame(); } }

9. 参照例子7.18编写一个应用程序,要求有一个画布,在画布上绘制一个矩形,用户通过文本框输入矩形的宽和高以及矩形左上角的位置坐标。 答: import java.awt.*; import java.awt.event.*; class Mycanvas extends Canvas {

int x,y,w,h; Mycanvas() {

setBackground(Color.cyan); }

public void setX(int x) { this.x=x; }

public void setY(int y) { this.y=y; }

public void setW(int w) { this.w=w; }

public void setH(int h) { this.h=h; }

public void paint(Graphics g) {

g.drawRect(x,y,w,h); } }

class WindowCanvas extends Frame implements ActionListener

{

Mycanvas canvas;

TextField text1,text2,text3,text4; Button button; WindowCanvas() {

canvas=new Mycanvas(); text1=new TextField(4); text2=new TextField(4); text3=new TextField(5); text4=new TextField(5);

Panel pNorth=new Panel(),pSouth=new Panel(); button=new Button(\确定\button.addActionListener(this); pNorth.add(new Label(\矩形的宽: \pNorth.add(text3);

pNorth.add(new Label(\矩形的高: \

pNorth.add(text4);

pSouth.add(new Label(\左上角位置坐标:\pSouth.add(text1); pSouth.add(text2); pSouth.add(button);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0); } } );

add(canvas,BorderLayout.CENTER); add(pNorth,BorderLayout.NORTH); add(pSouth,BorderLayout.SOUTH); setBounds(100,100,500,500); setVisible(true); validate(); }

public void actionPerformed(ActionEvent e) {

int x,y,w,h; try {

x=Integer.parseInt(text1.getText()); y=Integer.parseInt(text2.getText());

w=Integer.parseInt(text3.getText()); h=Integer.parseInt(text4.getText()); canvas.setX(x); canvas.setY(y); canvas.setW(w); canvas.setH(h); canvas.repaint(); }

catch(NumberFormatException ee) {

x=0;y=0;w=0;h=0; } } }

public class Test {

public static void main(String args[]) {

new WindowCanvas(); } }

10.编写应用程序,有一个窗口对象,该窗口取它的默认布局: BorderLayout布局,北面添加一个List组件,该组件有四个商品名称的选项。中心添加一个文本区,当选择List组件中的某个选项后,文本区显示对该商品的价格和产地:当双击List组件中的某个选项后,文本区显示该商品的详细广告。 答: import java.awt.*; import java.awt.event.*;

class WindowGoods extends Frame implements ActionListener,ItemListener {

String s[]={\产地:北京\产地:上海\产地:沈阳\产地:广东\String p[]={\价格:3200\价格:158\价格:13.2\价格:320/打\

String a[]={\本商品****\本商品*****\本商品******\本商品*******\List list; TextArea text; WindowGoods() {

list=new List(3,false); text=new TextArea(6,20); text.setEditable(false); list.add(\商品1\list.add(\商品2\list.add(\商品3\list.add(\商品4\

add(list,BorderLayout.NORTH); add(text,BorderLayout.CENTER);

list.addItemListener(this); list.addActionListener(this);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0); } } );

setBounds(100,100,300,300);

setVisible(true); validate(); }

public void itemStateChanged(ItemEvent e) {

if(e.getItemSelectable()==list) {

int m=list.getSelectedIndex(); text.setText(p[m]+'\\n'+s[m]); } }

public void actionPerformed(ActionEvent e) {

int n=list.getSelectedIndex(); text.setText(a[n]); } }

public class Test {

public static void main(String args[]) {

new WindowGoods(); } }

11.编写程序,观察各种组件设置背景色和前景色的情况。 答: import java.awt.*; import java.awt.event.*;

class WindowColor extends Frame implements ActionListener {

Button button; //按钮 TextField textfield; //文本框 TextArea textarea; //文本区 Mypanel panel; //面板

Checkbox box; //选择框 Choice choice; //下拉列表 List list; //滚动列表 Label label; //标签 Mycanvas can; //画布

Button buttonBackColor,buttonForeColor; WindowColor() {

button=new Button(\我是按钮\

textfield=new TextField(\我是文本框\textarea=new TextArea(6,15); textarea.setText(\我是文本区\textfield.setEditable(false); textarea.setEditable(false); panel=new Mypanel();

box=new Checkbox(\我是选择框\choice=new Choice(); choice.add(\我是下拉列表\list=new List(3,false); list.add(\我是滚动列表\label=new Label(\我是标签\can=new Mycanvas();

buttonBackColor=new Button(\背景色\buttonForeColor=new Button(\前景色\setLayout(new FlowLayout()); add(button); add(textfield); add(textarea); add(panel); add(box); add(choice); add(list); add(label); add(can);

add(buttonBackColor); add(buttonForeColor);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0); } } );

buttonBackColor.addActionListener(this); buttonForeColor.addActionListener(this); setBounds(100,100,300,300); setVisible(true); validate();

}

public void actionPerformed(ActionEvent e) {

if(e.getSource()==buttonBackColor) {

button.setBackground(Color.yellow); textfield.setBackground(Color.yellow); textarea.setBackground(Color.yellow); panel.setBackground(Color.yellow); box.setBackground(Color.yellow); choice.setBackground(Color.yellow); list.setBackground(Color.yellow); label.setBackground(Color.yellow); can.setBackground(Color.yellow); }

else if(e.getSource()==buttonForeColor) {

button.setForeground(Color.blue); textfield.setForeground(Color.blue); textarea.setForeground(Color.blue); panel.setForeground(Color.blue); box.setForeground(Color.blue); choice.setForeground(Color.blue); list.setForeground(Color.blue); label.setForeground(Color.blue); can.setForeground(Color.blue); } } }

class Mycanvas extends Canvas {

Mycanvas(){ }

public void paint(Graphics g) {

g.drawString(\我是画布\} }

class Mypanel extends Panel {

Button button1; Mypanel()

{

button1=new Button(\我是面板\add(button1); } }

public class Test {

public static void main(String args[]) { new WindowColor(); } }

12.编写应用程序,有一个标题为“移动”的窗口,窗口的布局为null,在窗口中有两个按钮,单击一个按钮让另一个按钮移动。 答: import java.awt.*; import java.awt.event.*;

class WindowMove extends Frame implements ActionListener {

Button button1,button2; WindowMove(String s) { super(s); setLayout(null);

button1=new Button(\我让它横向走动\button2=new Button(\我让它纵向走动\button1.setBackground(Color.blue); button2.setBackground(Color.green); button1.addActionListener(this); button2.addActionListener(this);

button1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); button2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); add(button1); add(button2);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0); } } );

button1.setBounds(20,80,100,30); button2.setBounds(100,180,100,30);

setBounds(100,100,500,500); setVisible(true); validate(); }

public void actionPerformed(ActionEvent e) {

Rectangle rect1=button1.getBounds(); int x1=(int)rect1.getX(); int y1=(int)rect1.getY();

Rectangle rect2=button2.getBounds(); int x2=(int)rect2.getX(); int y2=(int)rect2.getY(); if(e.getSource()==button1) { x2=x2+5;

button2.setLocation(x2,y2); }

else if(e.getSource()==button2) { y1=y1+5;

button1.setLocation(x1,y1); } } }

public class Test {

public static void main(String args[]) {

new WindowMove(\移动\} }

13.编写应用程序,有一个标题为“改变颜色”的窗口,窗口的布局为null,在窗口中有3个按钮和一个画布,3个按钮的颜色分别是红、绿、蓝。单击相应的按钮,画布绘制相应颜色的圆。 答: import java.awt.*; import java.awt.event.*;

class WindowChangeColor extends Frame implements ActionListener {

Button buttonRed,buttonGreen,buttonBlue; Mycanvas canvas;

WindowChangeColor(String s) { super(s); setLayout(null);

buttonRed=new Button(\红色\

buttonGreen=new Button(\绿色\buttonBlue=new Button(\蓝色\canvas=new Mycanvas();

buttonRed.setBackground(Color.red); buttonGreen.setBackground(Color.green); buttonBlue.setBackground(Color.blue); add(canvas);

canvas.setBounds(10,10,150,150); add(buttonRed);

buttonRed.setBounds(10,170,50,30); add(buttonGreen);

buttonGreen.setBounds(70,170,50,30); add(buttonBlue);

buttonBlue.setBounds(130,170,50,30); buttonRed.addActionListener(this); buttonGreen.addActionListener(this); buttonBlue.addActionListener(this); addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0); } } );

setBounds(100,100,200,250); setVisible(true); validate(); }

public void actionPerformed(ActionEvent e) {

if(e.getSource()==buttonRed) {

canvas.setX(1); canvas.repaint(); }

else if(e.getSource()==buttonGreen) {

canvas.setX(2); canvas.repaint(); }

else if(e.getSource()==buttonBlue) {

canvas.setX(3);

canvas.repaint(); } } }

class Mycanvas extends Canvas { int x=0; Mycanvas() {

setBackground(Color.white); }

public void setX(int y) { x=y; }

public void paint(Graphics g) {

switch(x){ case 1:

g.setColor(Color.red); break; case 2:

g.setColor(Color.green); break; case 3:

g.setColor(Color.blue); break; default:

g.setColor(Color.white); }

g.drawOval(65,65,50,50); } }

public class Test {

public static void main(String args[]) {

new WindowChangeColor(\改变颜色\

} }

14.编写应用程序,测试Cursor类中表示鼠标形状的静态常量。 答: import java.awt.*; import java.awt.event.*;

class WindowCursor extends Frame implements ActionListener

{

Button button,button1; TextField text; int n=-1; WindowCursor() {

button=new Button(\单击我\

text=new TextField(\将鼠标放在上面的按钮上看形状\button1=new Button(\看看你鼠标的形状\add(button,BorderLayout.NORTH); add(button1,BorderLayout.CENTER); add(text,BorderLayout.SOUTH); button.setBackground(Color.cyan); button1.setBackground(Color.pink); button.addActionListener(this); addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0); } } );

setBounds(100,100,190,150); setVisible(true); validate(); }

public void actionPerformed(ActionEvent e) {

n=(n+1); switch(n) { case 0:

button1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); break;

case 1:

button1.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); break; case 2:

button1.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); break; case 3:

button1.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); break;

case 4:

button1.setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR)); break; case 5:

button1.setCursor(Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR)); break; case 6:

button1.setCursor(Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR)); break; case 7:

button1.setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR)); break; case 8:

button1.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); break; case 9:

button1.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); break; } } }

public class Test {

public static void main(String args[]) {

new WindowCursor(); } }

15.改进本章例子7.30,当释放鼠标键时,如果当前组件和其他组件相交,就将其他组件设置为不可见状态。 答: import java.awt.*; import java.awt.event.*;

import javax.swing.SwingUtilities;

本文来源:https://www.bwwdw.com/article/f9g7.html

Top