按书的页码排列
如果代码有误,欢迎评论区指正!
p14简单招呼程序例程
public class J_HelloJava
{
public static void main(String args[ ])
{
System.out.println("Java语言,您好!");
System.out.println("我将成为优秀的Java程序员!");
} // 方法main结束
} // 类J_HelloJava结束
p18简单招呼小应用程序例程
import java.awt.Graphics;
import javax.swing.JApplet;
public class J_HelloApplet extends JApplet
{
public void paint(Graphics g)
{
g.clearRect(0, 0, getWidth( ), getHeight( )); // 清除背景
g.drawString("小应用程序,您好!", 10, 20);
} // 方法paint结束
} // 类J_HelloApplet结束
p25判断一个字符是否可以做Java标识符的起始字符或后续字符的例程
public class J_Identifier
{
public static void main(String args[ ])
{
char c = '猫';
if (Character.isJavaIdentifierStart(c))
System.out.println("字符'"+c+"'可以做标识符的首字符");
else
System.out.println("字符'"+c+"'不可以做标识符的首字符");
if (Character.isJavaIdentifierPart(c))
System.out.println("字符'"+c
+"'可以做标识符除首字符外的组成字符");
else
System.out.println("字符'"+c
+"'不可以做标识符除首字符外的组成字符");
} // 方法main结束
} // 类J_Identifier结束
p33数据类型转换例程
public class J_CastExample
{
public static void main(String args[ ])
{
short a= 100;
long b= a; // 隐式类型转换
System.out.println("类型转换: 短整数" + a + "变成长整数" + b);
b= 123456789L;
a= (short)b; // 显式类型转换,强制类型转换
System.out.println("类型转换: 长整数" + b + "变成短整数" + a);
} // 方法main结束
} // 类J_CastExample结束
p37布尔运算短路规则例程
public class J_Boolean
{
public static void main(String args[ ])
{
int month=8; // 定义变量month,并赋初值8
int day=1; // 定义变量day,并赋初值1
if ((month==8) || (++day<15))
System.out.println("Month=" + month + ", Day=" + day);
if ((month==8) | (++day<15))
System.out.println("Month=" + month + ", Day=" + day);
} // 方法main结束
} // 类J_Boolean结束
p41采用按位异或运算实现交换两个整数的例程
public class J_Swap
{
public static void main(String args[ ])
{
int a = 123;
int b = 321;
System.out.println("a=" + a + ", b=" + b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("a=" + a + ", b=" + b);
} // 方法main结束
} // 类J_Swap结束
p52带标点语句块和break语句例程
public class J_Break
{
public static void main(String args[ ])
{
int i = 0; // 定义变量i,并赋初值0
aBreakBlock:
{
System.out.println("在break语句之前");
if (i<=0)
break aBreakBlock; // 用来跳出aBreakBlock语句块
System.out.println("在if和break语句之后");
} // 语句块aBreakBlock结事
System.out.println("在aBreakBlock语句块之后");
} // 方法main结束
} // 类J_Break结束
p54在不含嵌套的循环语句中的continue语句例程
public class J_ContinueLoopSingle
{
public static void main(String args[ ])
{
for (int i=0; i< 10; i++)
{
if (1<i && i<8)
continue;
System.out.println("i=" + i);
} // for循环结束
} // 方法main结束
} // 类J_ContinueLoopSingle结束
p56在嵌套循环语句中的continue语句例程
public class J_ContinueLoopNested
{
public static void main(String args[ ])
{
aContinueBlock:
for (int i=0; i< 4; i++)
{
for (int j=0; j< 2; j++)
{
if (0<i && i<3)
continue aContinueBlock;
System.out.println("i=" + i + ", j=" +j);
} // 内层for循环结束
} // 语句块aContinueBlock结束, 外层for循环结束
} // 方法main结束
} // 类J_ContinueLoopNested结束
p57计算并输出10!例程
public class J_Factorial
{
public static void main(String args[ ])
{
int i; // 变量i将作为计数器
int result; // 用来存放计算结果
result= 1; // 初始化
for (i=1; i<= 10; i++)
result*=i;
System.out.println("10!=" + result);
} // 方法main结束
} // 类J_Factorial结束
p68实例对象生命周期的例程
class J_Book
{
public int m_id; // 书的编号
public J_Book( int i )
{
m_id = i;
} // J_Book构造方法结束
protected void finalize( )
{
switch (m_id)
{
case 1:
System.out.print( "《飘》" );
break;
case 2:
System.out.print( "《Java程序设计教程》" );
break;
case 3:
System.out.print( "《罗马假日》" );
break;
default:
System.out.print( "未知书籍" );
break;
} // switch语句结束
System.out.println( "所对应的实例对象存储单元被回收" );
} // 方法finalize结束
} // 类J_Book结束
public class J_Finalize
{
public static void main(String args[ ])
{
J_Book book1= new J_Book( 1 );
new J_Book( 2 );
new J_Book( 3 );
System.gc( ); // 申请立即回收垃圾
} // 方法main结束
} // 类J_Finalize结束
p71职工与教师之间的继承性例程
class J_Employee
{
public int m_workYear; // 工作的年限
public J_Employee( )
{
m_workYear = 1;
} // J_Employee构造方法结束
} // 类J_Employee结束
public class J_Teacher extends J_Employee
{
public int m_classHour; // 授课的课时
public J_Teacher( )
{
m_classHour = 96;
} // J_Teacher构造方法结束
public void mb_printInfo( )
{
System.out.println("该教师的工作年限为" + m_workYear);
System.out.println("该教师授课的课时为" + m_classHour);
} // 方法mb_printInfo结束
public static void main(String args[ ])
{
J_Teacher tom = new J_Teacher( );
tom.mb_printInfo( );
} // 方法main结束
} // 类J_Teacher结束
p75静态多态性例程
public class J_Student
{
public int m_id; // 学号
public int m_age; // 年龄
public J_Student( )
{
mb_setData(2008010400, 19);
} // J_Student构造方法结束
public J_Student( int id, int age )
{
mb_setData(id, age);
} // J_Student构造方法结束
public void mb_setData( int id, int age )
{
m_id = id;
m_age = age;
} // 方法mb_setData结束
public void mb_setData( int id )
{
m_id = id;
} // 方法mb_setData结束
public static void main(String args[ ])
{
J_Student jack = new J_Student( );
jack.mb_setData(2008010408);
J_Student lisa = new J_Student( );
lisa.mb_setData(2008010428, 18);
System.out.print("Jack的学号是" + jack.m_id);
System.out.println(",年龄是" + jack.m_age);
System.out.print("Lisa的学号是" + lisa.m_id);
System.out.println(",年龄是" + lisa.m_age);
} // 方法main结束
} // 类J_Student结束
p77职工与教师之间的动态多态性例程
class J_Employee
{
public int m_workYear; // 工作的年限
public J_Employee( )
{
m_workYear = 1;
} // J_Employee构造方法结束
public void mb_printInfo( )
{
System.out.println("该职工的工作年限为" + m_workYear);
} // 方法mb_printInfo结束
} // 类J_Employee结束
public class J_Teacher extends J_Employee
{
public int m_classHour; // 授课的课时
public J_Teacher( )
{
m_classHour = 96;
} // J_Teacher构造方法结束
public void mb_printInfo( )
{
System.out.println("该教师的工作年限为" + m_workYear);
System.out.println("该教师授课的课时为" + m_classHour);
} // 方法mb_printInfo结束
public static void main(String args[ ])
{
J_Employee a = new J_Employee( );
a.mb_printInfo( );
a = new J_Teacher( );
a.mb_printInfo( );
} // 方法main结束
} // 类J_Teacher结束
p82包例程——职工部分
package cn.edu.tsinghua.universityOrganization;
public class J_Employee
{
public int m_workYear; // 工作的年限
public J_Employee( )
{
m_workYear = 1;
} // J_Employee构造方法结束
public void mb_printInfo( )
{
System.out.println("该职工的工作年限为" + m_workYear);
} // 方法mb_printInfo结束
} // 类J_Employee结束
p83包例程——教师部分
package cn.edu.tsinghua.universityOrganization;
import cn.edu.tsinghua.universityOrganization.J_Employee;
public class J_Teacher extends J_Employee
{
public int m_classHour; // 授课的课时
public J_Teacher( )
{
m_classHour = 96;
} // J_Teacher构造方法结束
public void mb_printInfo( )
{
System.out.println("该教师的工作年限为" + m_workYear);
System.out.println("该教师授课的课时为" + m_classHour);
} // 方法mb_printInfo结束
} // 类J_Teacher结束
p83包例程——主程序部分
import cn.edu.tsinghua.universityOrganization.J_Employee;
import cn.edu.tsinghua.universityOrganization.J_Teacher;
public class J_University
{
public static void main(String args[ ])
{
J_Employee a = new J_Employee( );
a.mb_printInfo( );
a = new J_Teacher( );
a.mb_printInfo( );
} // 方法main结束
} // 类J_University结束
p90关于书的类的成员域和成员方法的静态属性与非静态属性历程
public class J_Book
{
public int m_id; // 书的编号
public static int m_bookNumber = 0; // 书的总数
public J_Book( )
{
m_bookNumber ++;
} // J_Book构造方法结束
public void mb_info( )
{
System.out.println( "当前书的编号是:" + m_id);
} // 方法mb_info结束
public static void mb_infoStatic( )
{
System.out.println( "书的总数是:" + m_bookNumber);
} // 方法mb_infoStatic结束
public static void main(String args[ ])
{
J_Book a = new J_Book( );
J_Book b = new J_Book( );
a.m_id = 1101;
b.m_id = 1234;
System.out.print( "变量a对应的");
a.mb_info( );
System.out.print( "变量b对应的");
b.mb_info( );
J_Book.mb_infoStatic( );
System.out.println( "比较(a.m_bookNumber==J_Book.m_bookNumber)"
+ "的结果是:" + (a.m_bookNumber==J_Book.m_bookNumber));
System.out.println( "比较(b.m_bookNumber==J_Book.m_bookNumber)"
+ "的结果是:" + (b.m_bookNumber==J_Book.m_bookNumber));
} // 方法main结束
} // 类J_Book结束
p98实名内部类例程
class J_Test
{
int m_dataOuter = 1;
static int m_dataOuterStatic = 2;
class J_Inner
{
int m_data;
static final int m_dataStatic = 4;
public J_Inner( )
{
m_data = 3;
} // J_Inner构造方法结束
public void mb_method( )
{
System.out.println( "m_dataOuter=" + m_dataOuter );
System.out.println( "m_dataOuterStatic="
+ m_dataOuterStatic );
System.out.println( "m_data=" + m_data );
System.out.println( "m_dataStatic=" + m_dataStatic );
mb_methodOuter( );
} // 方法mb_method结束
} // 内部类J_Inner结束
public void mb_methodOuter( )
{
System.out.println( "mb_methodOuter" );
} // 方法mb_methodOuter结束
} // 类J_Test结束
public class J_InnerTest
{
public static void main(String args[ ])
{
J_Test a = new J_Test( );
J_Test.J_Inner b = a.new J_Inner( );
b.mb_method( );
} // 方法main结束
} // 类J_InnerTest结束
p100父类型为类的匿名内部类例程
abstract class J_Class
{
int m_data;
public J_Class( int i )
{
m_data = i;
} // J_Class构造方法结束
public abstract void mb_method( );
} // 接口J_Class结束
public class J_InnerClass
{
public static void main(String args[ ])
{
J_Class b = new J_Class( 5 )
{
public void mb_method( )
{
System.out.println( "m_data=" + m_data );
} // 方法mb_method结束
}; // 父类型为类J_Class的匿名内部类结束
b.mb_method( );
} // 方法main结束
} // 类J_InnerClass结束
p101父类型为类的对照例程
abstract class J_Class
{
int m_data;
public J_Class( int i )
{
m_data = i;
} // J_Class构造方法结束
public abstract void mb_method( );
} // 类J_Class结束
class J_Anonymity extends J_Class
{
public J_Anonymity( int i )
{
super(i);
} // J_Anonymity构造方法结束
public void mb_method( )
{
System.out.println( "m_data=" + m_data );
} // 方法mb_method结束
} // 类J_Anonymity结束
public class J_InnerClass
{
public static void main(String args[ ])
{
J_Class b = new J_Anonymity( 5 );
b.mb_method( );
} // 方法main结束
} // 类J_InnerClass结束
p103父类型为接口的匿名内部类例程
interface J_Interface
{
public static int m_data = 5;
public abstract void mb_method( );
} // 接口J_Interface结束
public class J_InnerInterface
{
public static void main(String args[ ])
{
J_Interface b = new J_Interface( )
{
public void mb_method( )
{
System.out.println( "m_data=" + m_data );
} // 方法mb_method结束
}; // 实现接口J_Interface的匿名内部类结束
b.mb_method( );
} // 方法main结束
} // 类J_InnerInterface结束
p104父类型为接口的对照例程
interface J_Interface
{
public static int m_data = 5;
public abstract void mb_method( );
} // 接口J_Interface结束
class J_Anonymity implements J_Interface
{
public void mb_method( )
{
System.out.println( "m_data=" + m_data );
} // 方法mb_method结束
} // 类J_Anonymity结束
public class J_InnerInterface
{
public static void main(String args[ ])
{
J_Interface b = new J_Anonymity( );
b.mb_method( );
} // 方法main结束
} // 类J_InnerInterface结束
p107同名变量作用域范围重叠情况处理例程
class J_Time
{
public int data = 3;
// 这里省略类体的其他部分
} // 类J_Time结束
public class J_Scope extends J_Time
{
public int data = 2;
public void mb_method( )
{
int data = 1;
System.out.println("data=" + data);
System.out.println("this.data=" + this.data);
System.out.println("super.data=" + super.data);
} // 方法mb_method结束
public static void main(String args[ ])
{
J_Scope a = new J_Scope( );
a.mb_method( );
} // 方法main结束
} // 类J_Scope结束
p110基本数据类型值传递例程
public class J_Primitive
{
public static void mb_method( int a )
{
System.out.println("在a++之前方法参数a=" + a);
a++;
System.out.println("在a++之后方法参数a=" + a);
} // 方法mb_method结束
public static void main(String args[ ])
{
int i=0;
System.out.println("在方法调用之前变量i=" + i);
mb_method(i);
System.out.println("在方法调用之后变量i=" + i);
} // 方法main结束
} // 类J_Primitive结束
p111引用数据类型值传递例程
class J_Time
{
public int m_month = 1;
} // 类J_Time结束
public class J_Reference
{
public static void mb_method( J_Time t )
{
System.out.println("在t.m_month++之前t.m_month=" + t.m_month);
t.m_month++;
System.out.println("在t.m_month++之后t.m_month=" + t.m_month);
} // 方法mb_method结束
public static void main(String args[ ])
{
J_Time a = new J_Time( );
System.out.println("在方法调用之前a.m_month=" + a.m_month);
mb_method( a );
System.out.println("在方法调用之后a.m_month=" + a.m_month);
} // 方法main结束
} // 类J_Reference结束
p113形状接口例程
public interface J_Shape
{
public abstract double mb_getArea( ); // 计算并返回形状的面积
} // 接口J_Shape结束
p114圆例程
public class J_Circle implements J_Shape
{
public double m_x, m_y; // 圆心坐标
public double m_radius; // 半径
public J_Circle(double r)
{
m_x = 0;
m_y = 0;
m_radius = r;
} // J_Circle构造方法结束
public J_Circle(double x, double y, double r)
{
m_x = x;
m_y = y;
m_radius = r;
} // J_Circle构造方法结束
// 计算并返回形状的面积
public double mb_getArea( )
{
return (Math.PI*m_radius*m_radius);
} // 方法mb_getArea结束
} // 类J_Circle结束
p114矩形例程
public class J_Rectangle implements J_Shape
{
public double m_minX, m_minY; // 第一个角点坐标
public double m_maxX, m_maxY; // 另一个角点坐标
public J_Rectangle(double x1, double y1, double x2, double y2)
{
if (x1<x2)
{
m_minX = x1;
m_maxX = x2;
}
else
{
m_minX = x2;
m_maxX = x1;
} // if-else结构结束
if (y1<y2)
{
m_minY = y1;
m_maxY = y2;
}
else
{
m_minY = y2;
m_maxY = y1;
} // if-else结构结束
} // J_Rectangle构造方法结束
// 计算并返回形状的面积
public double mb_getArea( )
{
return ( (m_maxY-m_minY) * (m_maxX-m_minX) );
} // 方法mb_getArea结束
} // 类J_Rectangle结束
p115计算矩形和圆面积的例程
public class J_Area
{
public static void main(String args[ ])
{
J_Shape a = new J_Circle( 5 );
System.out.println("半径为5的圆的面积是" + a.mb_getArea( ));
a = new J_Rectangle(0 , 0, 3, 4);
System.out.println("给定的矩形面积是" + a.mb_getArea( ));
} // 方法main结束
} // 类J_Area结束
p125数组应用例程——求解和为15的棋盘游戏问题
public class J_Grid15
{
int [ ] [ ] m_board;
J_Grid15( )
{
m_board= new int[3][3];
} // J_Grid15构造方法结束
// 输出棋盘的格线行
private void mb_outputGridRowBoard( )
{
int i;
System.out.print("+");
for (i=0; i<5; i++)
System.out.print("-");
System.out.println("+");
} // 方法mb_outputGridRowBoard结束
// 输出棋盘的数据行(第i行, i只能为0, 1 或 2)
private void mb_outputGridRowBoard(int i)
{
int j;
for (j=0; j < m_board[i].length; j++)
System.out.print("|" + m_board[i][j]);
System.out.println("|");
} // 方法mb_outputGridRowBoard结束
// 输出棋盘
public void mb_outputGrid( )
{
int i;
mb_outputGridRowBoard( );
for (i=0; i < m_board.length; i++)
{
mb_outputGridRowBoard(i);
mb_outputGridRowBoard( );
} // for循环结束
} // 方法mb_outputGrid结束
// 初始化数据
private void mb_dataInit( )
{
int i, j, k;
for (i=0, k=1; i < m_board.length; i++)
for (j=0; j < m_board[i].length; j++, k++)
m_board[i][j]= k;
} // 方法mb_dataInit结束
// 数据结束检测
// 返回值说明: 当数据为最后一个数据时,返回true;否则,返回false
private boolean mb_dataEnd( )
{
int i, j, k;
for (i=0, k=9; i < m_board.length; i++)
for (j=0; j < m_board[i].length; j++, k--)
if (m_board[i][j]!= k)
return(false);
return(true);
} // 方法mb_dataEnd结束
// 取下一个数据
private void mb_dataNext( )
{
int i, j;
for (i= m_board.length-1; i>=0 ; i--)
for (j= m_board[i].length-1; j>=0 ; j--)
if (m_board[i][j]==9)
m_board[i][j]=1;
else
{
m_board[i][j]++;
return;
} // if-else结构结束
} // 方法mb_dataNext结束
// 数据检测: 判断数据中是否含有相同的数字
// 当数据中存在相同数字时,返回false; 否则,返回 true
private boolean mb_dataCheckDifferent( )
{
int i, j;
int [ ] digit= new int [10];
for (i=0; i < m_board.length; i++)
for (j=0; j < m_board[i].length; j++)
digit[m_board[i][j]]= 1;
for (i=1, j=0; i < digit.length; i++)
j+=digit[i];
if (j==9)
return(true);
return(false);
} // 方法mb_dataCheckDifferent结束
// 数据检测: 各行和是否为15
// 当各行和均为15时,返回true; 否则,返回false
private boolean mb_dataCheckSumRow( )
{
int i, j, k;
for (i=0; i < m_board.length; i++)
{
for (j=0, k=0; j < m_board[i].length; j++)
k+= m_board[i][j];
if (k!=15)
return(false);
} // for循环结束
return(true);
} // 方法mb_dataCheckSumRow结束
// 数据检测: 各列和是否为15
// 当各列和均为15时,返回true; 否则,返回false
private boolean mb_dataCheckSumColumn( )
{
int i, j, k;
for (i=0; i < m_board.length; i++)
{
for (j=0, k=0; j < m_board.length; j++)
k+= m_board[j][i];
if (k!=15)
return(false);
} // for循环结束
return(true);
} // 方法mb_dataCheckSumColumn结束
private boolean mb_dataCheck( )
{
if (!mb_dataCheckDifferent( ))
return(false);
if (!mb_dataCheckSumRow( ))
return(false);
if (!mb_dataCheckSumColumn( ))
return(false);
// 检测对角线之和是否为 15
if (m_board[0][0]+m_board[1][1]+m_board[2][2]!=15)
return(false);
// 检测对角线之和是否为 15
if (m_board[0][2]+m_board[1][1]+m_board[2][0]!=15)
return(false);
return(true);
} // 方法mb_dataCheck结束
// 求解并输出棋盘问题
public void mb_arrange( )
{
int n= 1;
for (mb_dataInit( ); !mb_dataEnd( ); mb_dataNext( ))
{
if (mb_dataCheck( ))
{
System.out.println("第" + n + "个结果:");
n++;
mb_outputGrid( );
} // if结构结束
} // for循环结束
} // 方法mb_arrange结束
public static void main(String args[ ])
{
J_Grid15 a= new J_Grid15( );
a.mb_arrange( );
} // 方法main结束
} // 类J_Grid15结束
p140字符串池例程
public class J_Intern
{
public static void main(String args[ ])
{
String s1 = "123456"; // 字符串直接量
String s2 = "123456"; // 字符串直接量
String s3 = "123" + "456"; // 这不是字符串直接量
String a0 = "123";
String s4 = a0 + "456"; // 这不是字符串直接量
String s5 = new String("123456"); // 这不是字符串直接量
String s6 = s5.intern( );
System.out.println("s2" + ((s2==s1) ? "==" : "!=") +"s1");
System.out.println("s3" + ((s3==s1) ? "==" : "!=") +"s1");
System.out.println("s4" + ((s4==s1) ? "==" : "!=") +"s1");
System.out.println("s5" + ((s5==s1) ? "==" : "!=") +"s1");
System.out.println("s6" + ((s6==s1) ? "==" : "!=") +"s1");
} // 方法main结束
} // 类J_Intern结束
p146字符串缓冲区例程
public class J_StringBuffer
{
public static void main(String args[ ])
{
StringBuffer b = new StringBuffer("0123");
System.out.println("字符串缓冲区的字符序列为"" + b + """);
System.out.println("字符串缓冲区的长度是" + b.length( ) );
System.out.println("字符串缓冲区的容量是" + b.capacity( ) );
b.ensureCapacity(25);
System.out.println( );
System.out.println("在调用"b.ensureCapacity(25)"之后");
System.out.println("字符串缓冲区的字符序列为"" + b + """);
System.out.println("字符串缓冲区的长度是" + b.length( ) );
System.out.println("字符串缓冲区的容量是" + b.capacity( ) );
} // 方法main结束
} // 类J_StringBuffer结束
p154通过哈希表形成数组下标与值之间的双向映射
import java.util.Hashtable;
public class J_Hashtable
{
public static void main(String args[ ])
{
String [ ] sa = {"Mary", "Tom", "John", "James", "Louis", "Jim",
"Rose", "Ann", "Liza", "Betty", "Henry", "Albert"};
Hashtable<String, Integer> ht = new Hashtable<String, Integer>( );
// 往哈希表中添加元素,并使得关键字与值之间建立起映射关系
int i;
for (i=0; i < sa.length; i++)
ht.put(sa[i], new Integer(i));
// 通过下标获得姓名(字符串值)
i=8;
System.out.println(
"在sa数组中,下标为" + i + "的字符串是"" + sa[i] + """);
// 通过哈希表,直接获得姓名(字符串值)的数组下标
String s=sa[i];
System.out.println("在sa数组中,"" + s + ""的下标是" + ht.get(s));
} // 方法main结束
} // 类J_Hashtable结束
p157WeakHashMap会自动去掉一些“不常用”元素(关键字及对应值)的历程
import java.util.WeakHashMap;
public class J_WeakHashMap
{
public static void main(String args[ ]) throws Exception
{
// 创建WeakHashMap实例对象
int s=800; // 将往WeakHashMap实例对象中添加的元素的个数
WeakHashMap<String, String> ht
= new WeakHashMap<String, String>(s*4/3, 0.75f);
// 给WeakHashMap实例对象添加元素(关键字及其值)
int i;
for (i=0; i<s; i++)
ht.put(("key"+i), ("value"+i));
System.out.println("在刚添加完数据时,弱哈希表元素个数是" + ht.size( ));
// 输出已经不在WeakHashMap实例对象中的元素;否则等待弱哈希表删除元素
for (i=0; i<s; )
{
if (!ht.containsKey("key"+i))
System.out.print("key" + i + "; ");
if (ht.size( )!=s)
i++;
} // for循环结束
System.out.println("");
System.out.println("一段时间之后,弱哈希表元素个数是" + ht.size( ));
} // 方法main结束
} // 类J_WeakHashMap结束
p164泛型例程
public class J_Add <T>
{
public String mb_sum(T a1, T a2, T a3)
{
return(a1.toString( ) + a2.toString( ) + a3.toString( ));
} // 方法mb_sum结束
public static void main(String args[ ])
{
J_Add<Integer> b = new J_Add<Integer>( );
Integer a1 = new Integer(1);
Integer a2 = new Integer(2);
Integer a3 = new Integer(3);
System.out.println( b.mb_sum(a1, a2, a3) );
} // 方法main结束
} // 类J_Add结束
p165泛型例程
interface J_Interface <T extends Number>
{
public int mb_sum(T a1, T a2, T a3);
} // 接口J_Interface结束
public class J_AddInterface <T extends Number>
implements J_Interface <T>
{
public int mb_sum(T a1, T a2, T a3)
{
int b1 = a1.intValue( );
int b2 = a2.intValue( );
int b3 = a3.intValue( );
return( b1 + b2 + b3 );
} // 方法mb_sum结束
public static void main(String args[ ])
{
J_AddInterface<Integer> b = new J_AddInterface<Integer>( );
Integer a1 = new Integer(1);
Integer a2 = new Integer(2);
Integer a3 = new Integer(3);
System.out.println( b.mb_sum(a1, a2, a3) );
} // 方法main结束
} // 类J_AddInterface结束
p167具有多父类型的类型变量泛型例程
class J_C1
{
public void mb_methodA( )
{
System.out.print("A");
} // 方法mb_methodA结束
} // 类J_C1结束
interface J_C2
{
public void mb_methodB( );
} // 接口J_C2结束
class J_C3 extends J_C1 implements J_C2
{
public void mb_methodB( )
{
System.out.print("B");
} // 方法mb_methodB结束
} // 类J_C3结束
class J_T <T extends J_C1 & J_C2>
{
public void mb_methodT( T t )
{
t.mb_methodA( );
t.mb_methodB( );
} // 方法mb_methodT结束
} // 类J_T结束
public class J_Genericity
{
public static void main(String args[ ])
{
J_T<J_C3> a = new J_T<J_C3>( );
a.mb_methodT( new J_C3( ) );
} // 方法main结束
} // 类J_Genericity结束
p170枚举例程
enum E_SEASON
{
春季, 夏季, 秋季, 冬季
} // 枚举E_SEASON结束
public class J_Enum
{
public static void main(String args[ ])
{
E_SEASON [ ] sa = E_SEASON.values( );
for ( int i=0; i< sa.length; i++ )
{
switch(sa[i])
{
case 春季:
System.out.println("春季花满天");
break;
case 夏季:
System.out.println("夏季热无边");
break;
case 秋季:
System.out.println("秋季果累累");
break;
case 冬季:
System.out.println("冬季雪皑皑");
break;
} // switch结构结束
} // for循环结束
} // 方法main结束
} // 类J_Enum结束
p173第一类for语句的简化写法例程
import java.util.Iterator;
import java.util.Vector;
public class J_VectorFor
{
public static void main(String args[ ])
{
Vector<String> a = new Vector<String>( );
a.add( "a" );
a.add( "b" );
a.add( "c" );
for ( String c : a)
System.out.print(c + ", ");
System.out.println( );
for ( Iterator<String> i=a.iterator( ); i.hasNext( ); )
{
String c = i.next( );
System.out.print(c + ", ");
} // for循环结束
System.out.println( );
} // 方法main结束
} // 类J_VectorFor结束
p174for语句的简化写法在枚举类型数组中的应用例程
enum E_SEASON
{
春季, 夏季, 秋季, 冬季
} // 枚举E_SEASON结束
public class J_EnumFor
{
public static void main(String args[ ])
{
for ( E_SEASON c : E_SEASON.values( ))
System.out.print(c + ", ");
System.out.println( );
E_SEASON [ ] ca = E_SEASON.values( );
for ( int i=0; i< ca.length; i++ )
{
E_SEASON c = ca[i];
System.out.print(c + ", ");
} // for循环结束
System.out.println( );
} // 方法main结束
} // 类J_EnumFor结束
p175for语句的简化写法在整数数组中的应用例程
public class J_Example
{
public static void main(String args[ ])
{
int [ ] a = {10, 20, 30, 40, 50};
int s = 0;
for ( int c : a)
s += c; // 这里需要注意c是数组的元素,而不是相应的下标
System.out.println("数组a的元素之和等于" + s);
s = 0;
for ( int i=1; i<=a.length; i++ )
s += i;
System.out.println("从1一直加到数组a的元素长度,结果等于" + s);
s = 0;
int [ ] ca = a;
for ( int i=0; i< ca.length; i++ )
{
int c = ca[i];
s += c;
} // for循环结束
System.out.println("数组a的元素之和等于" + s);
} // 方法main结束
} // 类J_Example结束
p179除数为0的异常例程
public class J_ExceptionByZero
{
public static void main(String args[ ])
{
int a= 10;
int b = 0;
System.out.println("a=" + a);
System.out.println("b=" + b);
System.out.println("a/b=" + a/b);
} // 方法main结束
} // 类J_ExceptionByZero结束
p182异常捕捉例程
public class J_ExceptionCatch
{
public static void main(String args[ ])
{
try
{
System.out.println("try语句块");
throw new Exception( );
}
catch(Exception e)
{
System.err.println("catch语句块");
e.printStackTrace( );
}
finally
{
System.out.println("finally语句块");
} // try-catch-finally结构结束
} // 方法main结束
} // 类J_ExceptionCatch结束
p184异常处理例程
public class J_Exception
{
public static void mb_throwException( )
{
System.out.println("产生并抛出ArithmeticException类型的异常");
throw new ArithmeticException( );
} // 方法mb_throwException结束
public static void mb_catchArrayException( )
{
try
{
mb_throwException( );
System.out.println("在try语句块中的多余语句");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.err.println("方法mb_catchArrayException捕捉到异常");
}
finally
{
System.out.println(
"方法mb_catchArrayException的finally语句块");
} // try-catch-finally结构结束
System.out.println("方法mb_catchArrayException运行结束");
} // 方法mb_catchArrayException结束
public static void main(String args[ ])
{
try
{
mb_catchArrayException( );
}
catch(ArithmeticException e)
{
System.err.println("方法main捕捉到异常");
}
finally
{
System.out.println("方法main的finally语句块");
} // try-catch-finally结构结束
System.out.println("异常处理结束");
} // 方法main结束
} // 类J_Exception结束
p186自定义异常例程
class J_ExceptionNew extends Exception
{
private static int m_number = 0;
public J_ExceptionNew( )
{
m_number ++;
} // J_ExceptionNew构造方法结束
public String toString( )
{
return("新异常出现" + m_number + "次");
} // 方法toString结束
} // 类J_ExceptionNew结束
public class J_ExceptionNewExample
{
public static void main(String args[ ])
{
try
{
throw new J_ExceptionNew( );
}
catch(J_ExceptionNew e)
{
System.err.println(e);
} // try-catch结构结束
} // 方法main结束
} // 类J_ExceptionNewExample结束
p189利用递归求解汉诺塔问题的例程
public class J_Hanoi
{
public static void mb_hanoi(int n, char start, char temp, char end)
{
if (n<=1)
System.out.println("将盘从" + start + "移到" + end);
else
{
mb_hanoi(n-1, start, end, temp);
System.out.println("将盘从" + start + "移到" + end);
mb_hanoi(n-1, temp, start, end);
} // if-else结构结束
} // 方法mb_hanoi结束
public static void main(String args[ ])
{
mb_hanoi(3, 'S', 'T', 'E');
} // 方法main结束
} // 类J_Hanoi结束
p190利用递归计算Fibonacci(30)的例程
public class J_Fibonacci
{
public static int mb_fibonacci(int n)
{
if (n< 1)
return(0);
else if (n==1 || n==2)
return(1);
return(mb_fibonacci(n-1)+mb_fibonacci(n-2));
} // 方法mb_fibonacci结束
public static void main(String args[ ])
{
int n = 30;
System.out.println("Fibonacci(" + n + ")=" + mb_fibonacci(n));
} // 方法main结束
} // 类J_Fibonacci结束
p191单体类实现例程
public class J_Singleton
{
private static J_Singleton m_object = new J_Singleton( );
// 定义构造方法: 不允许自行创建这个类的实例对象
private J_Singleton( )
{
} // J_Singleton构造方法结束
// 返回单体实例对象的引用
public static J_Singleton mb_getObject( )
{
return m_object;
} // 方法mb_getObject结束
} // 类J_Singleton结束
p192实用类J_Singleton的实例对象的例程
public class J_Example
{
public static void main(String args[ ])
{
J_Singleton a = J_Singleton.mb_getObject( );
J_Singleton b = J_Singleton.mb_getObject( );
if (a==b)
System.out.println("a和b指向同一个实例对象。");
else
System.out.println("a和b指向不同的实例对象。");
} // 方法main结束
} // 类J_Example结束
p193单体类实现例程
public class J_Singleton
{
private static J_Singleton m_object;
// 定义构造方法: 不允许自行创建这个类的实例对象
private J_Singleton( )
{
} // J_Singleton构造方法结束
// 返回单体实例对象的引用(如果还没有创建对象,则创建该对象)
public static J_Singleton mb_getObject( )
{
if (m_object == null)
m_object = new J_Singleton( );
return m_object;
} // 方法mb_getObject结束
} // 类J_Singleton结束
p196类java.lang.Runtime的应用例程
public class J_RuntimeExample
{
public static void main(String args[ ])
{
Runtime r = Runtime.getRuntime( );
System.out.println("处理器个数是" + r.availableProcessors( ));
try
{
r.exec("cmd /c start dir");
r.exec("notepad");
}
catch(Exception e)
{
System.err.println("命令运行不正常!");
e.printStackTrace( );
} // try-catch结构结束
System.out.println("可用的最大内存为: " + r.maxMemory( ));
System.out.println("现在的总内存为: " + r.totalMemory( ));
System.out.println("现在空闲内存为: " + r.freeMemory( ));
r.gc( );
System.out.println("现在空闲内存为: " + r.freeMemory( ));
} // 方法main结束
} // 类J_RuntimeExample结束
p201回显(echo)例程
import java.io.InputStream;
import java.io.IOException;
public class J_Echo
{
public static void mb_echo(InputStream in)
{
try
{
while (true) // 接受输入并回显
{
int i = in.read( );
if (i == -1) // 输入流结束
break;
char c = (char) i;
System.out.print(c);
} // while循环结束
}
catch (IOException e)
{
System.err.println("发生异常:" + e);
e.printStackTrace( );
} // try-catch结构结束
System.out.println( );
} // 方法mb_echo结束
public static void main(String args[ ])
{
mb_echo(System.in);
} // 方法main结束
} // 类J_Echo结束
p203读取文件“text.txt”内容的例程
import java.io.FileInputStream;
import java.io.IOException;
public class J_EchoFile
{
public static void main(String args[ ])
{
try
{
FileInputStream f =new FileInputStream("test.txt");
int i;
int b=f.read( );
for (i=0; b!=-1; i++)
{
System.out.print((char)b);
b=f.read( );
} // for循环结束
System.out.println( );
System.out.println("文件"test.txt"字节数为"+i);
f.close( );
}
catch (IOException e)
{
System.err.println("发生异常:" + e);
e.printStackTrace( );
} // try-catch结构结束
} // 方法main结束
} // 类J_EchoFile结束
p204输出流例程
import java.io.IOException;
import java.io.OutputStream;
public class J_Write
{
public static void mb_write(OutputStream out)
{
String s = "输出流例程";
byte[ ] b = s.getBytes( );
try
{
out.write(b);
out.flush( );
}
catch (IOException e)
{
System.err.println("发生异常:" + e);
e.printStackTrace( );
} // try-catch结构结束
} // 方法mb_write结束
public static void main(String args[ ])
{
mb_write(System.out);
} // 方法main结束
} // 类J_Write结束
p206文件输出流例程
import java.io.FileOutputStream;
import java.io.IOException;
public class J_WriteFile
{
public static void main(String args[ ])
{
String s = "文件输出流例程";
byte[ ] b = s.getBytes( );
try
{
FileOutputStream f = new FileOutputStream("out.txt");
f.write(b);
f.flush( );
f.close( );
}
catch (IOException e)
{
System.err.println("发生异常:" + e);
e.printStackTrace( );
} // try-catch结构结束
} // 方法main结束
} // 类J_WriteFile结束
p210PrintStream例程
import java.io.PrintStream;
import java.io.FileNotFoundException;
public class J_PrintStream
{
public static void main(String args[ ])
{
try
{
PrintStream f = new PrintStream("out.txt");
f.printf("%1$d+%2$d=%3$d", 1, 2, (1+2));
f.close( );
}
catch (FileNotFoundException e)
{
System.err.println("发生异常:" + e);
e.printStackTrace( );
} // try-catch结构结束
} // 方法main结束
} // 类J_PrintStream结束
p213数据输入流和数据输出流例程
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class J_Data
{
public static void main(String args[ ])
{
try
{
FileOutputStream fout = new FileOutputStream("out.txt");
DataOutputStream dfout =new DataOutputStream(fout);
int i;
for (i=0; i< 4; i++)
dfout.writeInt('0' + i);
dfout.close( );
FileInputStream fin= new FileInputStream("out.txt");
DataInputStream dfin= new DataInputStream(fin);
for (i=0; i< 4; i++)
System.out.print(dfin.readInt( ) + ", ");
dfin.close( );
}
catch (Exception e)
{
System.err.println("发生异常:" + e);
e.printStackTrace( );
} // try-catch结构结束
} // 方法main结束
} // 类J_Data结束
p215带与不带缓存在读取数据时的效率比较例程
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.Date;
public class J_BufferedInputStream
{
private static String m_fileName = "J_BufferedInputStream.class";
public static void main(String args[ ])
{
try
{
int i, ch;
i = 0;
Date d1= new Date( );
FileInputStream f = new FileInputStream(m_fileName);
while ((ch=f.read( )) != -1) // read entire file
i++;
f.close( );
Date d2= new Date( );
long t = d2.getTime( ) - d1.getTime( ); // 单位(毫秒)
System.out.printf("读取文件%1$s(共%2$d字节)%n",
m_fileName, i);
System.out.printf("不带缓存的方法需要%1$d毫秒%n", t);
i = 0;
d1= new Date( );
f = new FileInputStream(m_fileName);
BufferedInputStream fb = new BufferedInputStream(f);
while ((ch=fb.read( )) != -1) // read entire file
i++;
fb.close( );
d2= new Date( );
t = d2.getTime( ) - d1.getTime( ); // 单位(毫秒)
System.out.printf("带缓存的方法需要%1$d毫秒%n", t);
}
catch (Exception e)
{
System.err.println("发生异常:" + e);
e.printStackTrace( );
} // try-catch结构结束
} // 方法main结束
} // 类J_BufferedInputStream结束
p218重定向例程
import java.io.FileInputStream;
public class J_SetIn
{
public static void main(String args[ ])
{
try
{
System.setIn(new FileInputStream("test.txt"));
J_Echo.mb_echo(System.in);
}
catch (Exception e)
{
System.err.println("发生异常:" + e);
e.printStackTrace( );
} // try-catch结构结束
} // 方法main结束
} // 类J_SetIn结束
p221随机访问文件例程
import java.io.IOException;
import java.io.RandomAccessFile;
public class J_RandomAccessFile
{
public static void main(String args[ ])
{
try
{
RandomAccessFile f=new RandomAccessFile("test.txt", "rw");
int i;
double d;
for (i=0; i<10; i++)
f.writeDouble(Math.PI*i);
f.seek(16);
f.writeDouble(0);
f.seek(0);
for (i=0; i < 10; i++)
{
d=f.readDouble( );
System.out.println("[" + i + "]: " + d);
} // for循环结束
f.close( );
}
catch (IOException e)
{
System.err.println("发生异常:" + e);
e.printStackTrace( );
} // try-catch结构结束
} // 方法main结束
} // 类J_RandomAccessFile结束
p225文件读写器例程
import java.io.IOException;
import java.io.FileReader;
import java.io.FileWriter;
public class J_FileReaderWriter
{
public static void main(String args[ ])
{
try
{
FileWriter f_out= new FileWriter("test.txt");
f_out.write("有志者,事竞成");
f_out.close( );
FileReader f_in= new FileReader("test.txt");
for (int c=f_in.read( ); c!=-1; c=f_in.read( ))
System.out.print((char)c);
f_in.close( );
}
catch (IOException e)
{
System.err.println("发生异常:" + e);
e.printStackTrace( );
} // try-catch结构结束
} // 方法main结束
} // 类J_FileReaderWriter结束
p227带缓存读写器例程
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
public class J_BufferedReaderWriter
{
public static void main(String args[ ])
{
try
{
BufferedWriter bw = new BufferedWriter(
new FileWriter("test.txt"));
bw.write("有志者,事竞成");
bw.newLine( );
bw.write("苦心人,天不负");
bw.newLine( );
bw.close( );
LineNumberReader br = new LineNumberReader(
new FileReader("test.txt"));
String s;
for (s=br.readLine( ); s!=null; s=br.readLine( ))
System.out.println( br.getLineNumber( ) + ": " + s);
br.close( );
}
catch (IOException e)
{
System.err.println("发生异常:" + e);
e.printStackTrace( );
} // try-catch结构结束
} // 方法main结束
} // 类J_BufferedReaderWriter结束
p231PrintWriter例程
import java.io.PrintWriter;
import java.io.FileNotFoundException;
public class J_PrintWriter
{
public static void main(String args[ ])
{
try
{
PrintWriter f = new PrintWriter("out.txt");
f.println("莫等闲,白了少年头,空悲切");
f.close( );
}
catch (FileNotFoundException e)
{
System.err.println("发生异常:" + e);
e.printStackTrace( );
} // try-catch结构结束
} // 方法main结束
} // 类J_PrintWriter结束
p232从控制台窗口读入数据的例程
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class J_ReadData
{
// 输出提示信息
public static void mb_printIinfo( )
{
System.out.println("输入整数还是浮点数?");
System.out.println("t0: 退出; 1: 整数; 2: 浮点数");
} // 方法mb_printIinfo结束
// 接受整数的输入
public static int mb_getInt( BufferedReader f )
{
try
{
String s = f.readLine( );
int i = Integer.parseInt( s );
return i;
}
catch (Exception e)
{
return -1;
} // try-catch结构结束
} // 方法mb_getInt结束
// 接受浮点数的输入
public static double mb_getDouble( BufferedReader f )
{
try
{
String s = f.readLine( );
double d = Double.parseDouble( s );
return d;
}
catch (Exception e)
{
return 0d;
} // try-catch结构结束
} // 方法mb_getDouble结束
public static void main(String args[ ])
{
int i;
double d;
try
{
BufferedReader f =
new BufferedReader(new InputStreamReader( System.in ));
do
{
mb_printIinfo( );
i = mb_getInt( f );
if (i==0)
break;
else if (i==1)
{
System.out.print("t请输入整数: ");
i = mb_getInt( f );
System.out.println("t输入整数: " + i);
}
else if (i==2)
{
System.out.print("t请输入浮点数: ");
d = mb_getDouble( f );
System.out.println("t输入浮点数: " + d);
} // if-else结构结束
}
while (true); // do-while循环结束
f.close( );
}
catch (Exception e)
{
System.err.println("发生异常:" + e);
e.printStackTrace( );
} // try-catch结构结束
} // 方法main结束
} // 类J_ReadData结束
p237学生例程
import java.io.Serializable;
public class J_Student implements Serializable
{
static final long serialVersionUID = 123456L;
String m_name;
int m_id;
int m_height;
public J_Student( String name, int id, int h )
{
m_name = name;
m_id = id;
m_height = h;
} // J_Student构造方法结束
public void mb_output( )
{
System.out.println("姓名: " + m_name);
System.out.println("学号: " + m_id);
System.out.println("身高: " + m_height);
} // 方法mb_output结束
} // 类J_Student结束
p238对象输出例程
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class J_ObjectOutputStream
{
public static void main(String args[ ])
{
try
{
ObjectOutputStream f = new ObjectOutputStream(
new FileOutputStream("object.dat"));
J_Student s = new J_Student( "张三", 2003001, 172);
f.writeObject(s);
s.mb_output( );
f.close( );
}
catch (Exception e)
{
System.err.println("发生异常:" + e);
e.printStackTrace( );
} // try/catch结构结束
} // 方法main结束
} // 类J_ObjectOutputStream结束
p238读取对象例程
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class J_ObjectInputStream
{
public static void main(String args[ ])
{
try
{
ObjectInputStream f = new ObjectInputStream(
new FileInputStream("object.dat"));
J_Student s = (J_Student)(f.readObject( ));
s.mb_output( );
f.close( );
}
catch (Exception e)
{
System.err.println("发生异常:" + e);
e.printStackTrace( );
} // try-catch结构结束
} // 方法main结束
} // 类J_ObjectInputStream结束
p240学生例程
import java.io.Serializable;
public class J_Student implements Serializable
{
static final long serialVersionUID = 123456L;
String m_name;
int m_id;
int m_height;
int m_weight;
public J_Student( String name, int id, int h )
{
m_name = name;
m_id = id;
m_height = h;
} // J_Student构造方法结束
public void mb_output( )
{
System.out.println("姓名: " + m_name);
System.out.println("学号: " + m_id);
System.out.println("身高: " + m_height);
} // 方法mb_output结束
} // 类J_Student结束
p244文件例程
import java.io.File;
public class J_File
{
public static void main(String args[ ])
{
for (int i = 0; i < args.length; i++)
{
File f = new File(args[i]);
if (f.exists( ))
{
System.out.println("getName: " + f.getName( ));
System.out.println("getPath: " + f.getPath( ));
System.out.println("getParent: " + f.getParent( ));
System.out.println("length: " + f.length( ));
}
else System.out.printf("文件%1$s不存在%n", args[i]);
} // for循环结束
} // 方法main结束
} // 类J_File结束
p248在框架中添加标签的例程
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class J_LabelFrame extends JFrame
{
public J_LabelFrame( )
{
super( "框架和标签例程" );
String [ ] s = {"文本标签", "文字在图标的左侧", "文字在图标的下方"};
ImageIcon [ ] ic = {null, new ImageIcon( "img1.gif" ),
new ImageIcon( "img2.gif" )};
int [ ] ih = {0, JLabel.LEFT, JLabel.CENTER};
int [ ] iv = {0, JLabel.CENTER, JLabel.BOTTOM};
Container c = getContentPane( );
c.setLayout( new FlowLayout(FlowLayout.LEFT) );
for (int i=0; i<3; i++)
{
JLabel aLabel = new JLabel( s[i] , ic[i], JLabel.LEFT);
if (i>0)
{
aLabel.setHorizontalTextPosition(ih[i]);
aLabel.setVerticalTextPosition(iv[i]);
} // if结构结束
aLabel.setToolTipText( "第" + (i+1) + "个标签");
c.add( aLabel );
} // for循环结束
} // J_LabelFrame构造方法结束
public static void main(String args[ ])
{
J_LabelFrame app = new J_LabelFrame( );
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize( 360, 150 );
app.setVisible( true );
} // 方法main结束
} // 类J_LabelFrame结束
p253在对话框中添加标签的例程
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class J_FrameDialog
{
public static void main(String args[ ])
{
JFrame app = new JFrame( "框架" );
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize( 200, 100 );
app.setVisible( true );
JDialog d = new JDialog(app, "对话框", false);
Container c = d.getContentPane( );
c.setLayout( new FlowLayout(FlowLayout.LEFT) );
c.add(new JLabel("您好"));
d.setSize( 80, 80 );
d.setVisible(true);
} // 方法main结束
} // 类J_FrameDialog结束
p255标准对话框例程
import javax.swing.JOptionPane;
public class J_DialogMode
{
public static void main(String args[ ])
{
JOptionPane.showMessageDialog(null, "您好!");
JOptionPane.showConfirmDialog(null, "您现在还好吗?");
JOptionPane.showInputDialog(null, "您现在还好吗?");
String [ ] s = {"好", "不好"};
JOptionPane.showInputDialog(null, "您现在还好吗?", "输入",
JOptionPane.QUESTION_MESSAGE, null, s, s[0]);
} // 方法main结束
} // 类J_DialogMode结束
p257文本编辑框例程
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class J_Text
{
public static void main(String args[ ])
{
JFrame app = new JFrame( "文本编辑框例程" );
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize( 320, 120 );
Container c = app.getContentPane( );
c.setLayout( new FlowLayout( ) );
JTextField [ ] t = {
new JTextField("正常文本:", 8), new JTextField("显示", 15),
new JTextField("密码文本:", 8), new JPasswordField("隐藏", 15)};
t[0].setEditable( false );
t[2].setEditable( false );
for (int i=0; i<4; i++)
c.add( t[i] );
app.setVisible( true );
} // 方法main结束
} // 类J_Text结束
p259命令式按钮、复选框和单选按钮例程
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
public class J_Button extends JFrame
{
public J_Button( )
{
super( "按钮例程" );
Container c = getContentPane( );
c.setLayout( new FlowLayout( ) );
int i;
// 创建命令式按钮并添加到框架中
ImageIcon [ ] ic = {new ImageIcon("left.gif"),
new ImageIcon("right.gif")};
JButton [ ] b = {new JButton("左", ic[0]), new JButton("中间"),
new JButton("右", ic[1])};
for (i=0; i < b.length; i++)
c.add( b[i] );
// 创建复选框并添加到框架中
JCheckBox [ ] ck = {new JCheckBox("左"), new JCheckBox("右")};
for (i=0; i<ck.length; i++)
{
c.add( ck[i] );
ck[i].setSelected(true);
} // for循环结束
// 创建单选按钮并添加到框架中
JRadioButton[ ] r={new JRadioButton("左"), new JRadioButton("右")};
ButtonGroup rg = new ButtonGroup( );
for (i=0; i < r.length; i++)
{
c.add( r[i] );
rg.add( r[i] );
} // for循环结束
r[0].setSelected(true);
r[1].setSelected(false);
} // J_Button构造方法结束
public static void main(String args[ ])
{
J_Button app = new J_Button( );
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize( 250, 120 );
app.setVisible( true );
} // 方法main结束
} // 类J_Button结束
p263组合框、列表框、文本区域和滚动窗格例程
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class J_Lines extends JFrame
{
public J_Lines( )
{
super( "多行组件例程" );
Container c = getContentPane( );
c.setLayout( new FlowLayout( ) );
String [] s = {"选项1", "选项2", "选项3"};
JComboBox cb = new JComboBox( s );
JList t = new JList( s );
JTextArea ta = new JTextArea("1n2n3n4n5", 3, 10);
JScrollPane sta = new JScrollPane( ta );
c.add( cb );
c.add( t );
c.add( sta );
} // J_Lines构造方法结束
public static void main(String args[ ])
{
J_Lines app = new J_Lines( );
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize( 250, 120 );
app.setVisible( true );
} // 方法main结束
} // 类J_Lines结束
p267滑动条和面板例程
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
public class J_SliderAndPanel
{
public static void main(String args[ ])
{
JFrame app = new JFrame( "滑动条和面板例程" );
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize( 360, 120 );
Container c = app.getContentPane( );
c.setLayout( new FlowLayout( ) );
JSlider s = new JSlider(JSlider.HORIZONTAL, 0, 30, 10);
JPanel p = new JPanel( );
p.setPreferredSize( new Dimension(100, 60) );
p.setBackground(Color.green);
c.add( s );
c.add( p );
app.setVisible( true );
} // 方法main结束
} // 类J_SliderAndPanel结束
p270网格布局管理器例程
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class J_GridLayout
{
public static void main(String args[ ])
{
JFrame app = new JFrame( "网格布局管理器例程" );
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize( 520, 120 );
Container c = app.getContentPane( );
c.setLayout( new GridLayout(2, 5) );
String s;
JButton b;
for (int i=0; i<5; i++)
{
s = "按钮" + (i+1);
b = new JButton( s );
c.add( b );
} // for循环结束
app.setVisible( true );
} // 方法main结束
} // 类J_GridLayout结束
p271边界布局管理器例程
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
public class J_BorderLayout
{
public static void main(String args[ ])
{
JFrame app = new JFrame( "边界布局管理器例程" );
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize( 360, 130 );
Container c = app.getContentPane( );
c.setLayout( new BorderLayout( ) ); // 本语句可以删去
c.add(new JButton("东"), BorderLayout.EAST);
c.add(new JButton("西"), BorderLayout.WEST);
c.add(new JButton("南"), BorderLayout.SOUTH);
c.add(new JButton("北"), BorderLayout.NORTH);
c.add(new JButton("中"), BorderLayout.CENTER);
app.setVisible( true );
} // 方法main结束
} // 类J_BorderLayout结束
p273盒式布局管理器例程
import java.awt.Container;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class J_BoxLayout
{
public static void main(String args[ ])
{
JFrame app = new JFrame( "盒式布局管理器例程" );
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize( 220, 130 );
Container c = app.getContentPane( );
c.setLayout( new BoxLayout( c, BoxLayout.X_AXIS ) );
String s;
JButton b;
for (int i=0; i<3; i++)
{
s = "按钮" + (i+1);
b = new JButton( s );
c.add( b );
} // for循环结束
app.setVisible( true );
} // 方法main结束
} // 类J_BoxLayout结束
p275网格包布局管理器例程
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class J_GridBagLayout
{
public static void main(String args[ ])
{
JFrame app = new JFrame( "网格包布局管理器例程" );
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize( 320, 160 );
Container c = app.getContentPane( );
GridBagLayout gr = new GridBagLayout( );
c.setLayout( gr );
int [ ] gx = {0, 1, 2, 3, 1, 0, 0, 2};
int [ ] gy = {0, 0, 0, 0, 1, 2, 3, 2};
int [ ] gw = {1, 1, 1, 1, GridBagConstraints.REMAINDER, 2, 2, 2};
int [ ] gh = {2, 1, 1, 1, 1, 1, 1, 2};
GridBagConstraints gc = new GridBagConstraints( );
String s;
JButton b;
for (int i=0; i < gx.length; i++)
{
s = "按钮" + (i+1);
b = new JButton( s );
gc.gridx = gx[i];
gc.gridy = gy[i];
gc.gridwidth = gw[i];
gc.gridheight = gh[i];
gc.fill = GridBagConstraints.BOTH;
gr.setConstraints(b, gc);
c.add( b );
} // for循环结束
app.setVisible( true );
} // 方法main结束
} // 类J_GridBagLayout结束
p278卡片布局管理器例程
import java.awt.CardLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
public class J_CardLayout
{
public static void main(String args[ ])
{
JFrame app = new JFrame( "卡片布局管理器例程" );
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize( 180, 100 );
Container c = app.getContentPane( );
CardLayout card = new CardLayout( );
c.setLayout( card );
String s;
JButton b;
for (int i=0; i<5; i++)
{
s = "按钮" + (i+1);
b = new JButton( s );
c.add( b, s );
} // for循环结束
card.show(c, "按钮3");
card.next( c );
app.setVisible( true );
} // 方法main结束
} // 类J_CardLayout结束
p280组合布局方式例程
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class J_FlowBoxLayout
{
public static void main(String args[ ])
{
JFrame app = new JFrame( "组合布局方式例程" );
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize( 215, 150 );
Container c = app.getContentPane( );
c.setLayout(new FlowLayout( ));
JPanel [ ] p = new JPanel[3];
int i;
for (i=0; i<3; i++)
{
p[i]= new JPanel( );
p[i].setLayout(new BoxLayout(p[i], BoxLayout.X_AXIS));
c.add( p[i] );
} // for循环结束
String s;
JButton b;
int [ ] pj = {0, 1, 1, 2, 2, 2};
for (i=0; i<6; i++)
{
s = "按钮" + (i+1);
b = new JButton( s );
p[pj[i]].add( b );
} // for循环结束
app.setVisible( true );
} // 方法main结束
} // 类J_FlowBoxLayout结束
p283创建自定义的对角线布局管理器例程
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.LayoutManager;
public class J_DiagonalLayout implements LayoutManager
{
public void addLayoutComponent(String name, Component comp)
{
} // 方法addLayoutComponent结束
public void removeLayoutComponent(Component comp)
{
} // 方法removeLayoutComponent结束
public Dimension preferredLayoutSize(Container parent)
{
Dimension d = null;
Insets s = parent.getInsets( ); // 容器四条边框的尺寸
Dimension dp = new Dimension(s.left + s.right, s.top + s.bottom);
Component c;
int n = parent.getComponentCount( );
for (int i=0; i<n; i++)
{ // 计算组件及容器边框宽度之和及高度之和
c = parent.getComponent(i);
if (c.isVisible( ))
{
d = c.getPreferredSize( );
dp.width += d.width;
dp.height+= d.height;
} // if结构结束
} // for循环结束
return dp;
} // 方法preferredLayoutSize结束
public Dimension minimumLayoutSize(Container parent)
{
Dimension d = null;
Insets s = parent.getInsets( ); // 容器四条边框的尺寸
Dimension dp = new Dimension(0, 0);
Component c;
int n = parent.getComponentCount( );
for (int i =0; i<n; i++)
{ // 计算各个组件的最大宽度和最大高度
c = parent.getComponent(i);
if (c.isVisible( ))
{
d = c.getPreferredSize( );
if (d.width> dp.width)
dp.width= d.width;
if (d.height> dp.height)
dp.height= d.height;
} // if结构结束
} // for循环结束
dp.width += (s.left + s.right);
dp.height+= (s.top + s.bottom);
return dp;
} // 方法minimumLayoutSize结束
public void layoutContainer(Container parent)
{ // 当第一次显示指定容器或该容器的大小发生变化时调用本方法
int i;
int n = parent.getComponentCount( );
Component c;
Insets s = parent.getInsets( ); // 容器四条边框的尺寸
Dimension d;
Dimension dp = parent.getSize( ); // 容器本身的尺寸
Dimension dr = preferredLayoutSize(parent); // 容器的最佳尺寸
Dimension dc = new Dimension(s.left, s.top); // 组件的当前位置
Dimension dg
= new Dimension(dp.width-dr.width, dp.height-dr.height);
if (n>1)
{ // 计算组件之间的间隙
dg.width /= (n-1);
dg.height /= (n-1);
} // if结构结束
for (i=0 ; i<n ; i++)
{
c = parent.getComponent(i);
if (c.isVisible( ))
{
d = c.getPreferredSize( );
c.setBounds(dc.width, dc.height, d.width, d.height);
dc.width += (dg.width+d.width);
dc.height+= (dg.height+d.height);
} // if结构结束
} // for循环结束
} // 方法layoutContainer结束
} // 类J_DiagonalLayout结束
p286自定义对角线布局管理器应用例程
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
public class J_DiagonalLayoutExample
{
public static void main(String args[ ])
{
JFrame app = new JFrame( "自定义对角线布局管理器应用例程" );
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize( 300, 200 );
Container c = app.getContentPane( );
c.setLayout( new J_DiagonalLayout( ) );
String s;
JButton b;
for (int i=0; i<5; i++)
{
s = "按钮" + (i+1);
b = new JButton( s );
c.add( b );
} // for循环结束
app.setVisible( true );
} // 方法main结束
} // 类J_DiagonalLayoutExample结束
p289命令式按钮及其动作事件处理例程
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
class J_ActionListener implements ActionListener
{
int m_count = 0;
public void actionPerformed(ActionEvent e)
{
JButton b= (JButton)e.getSource( );
b.setText("单击" + (++m_count) + "次");
} // 方法actionPerformed结束
} // 类J_ActionListener结束
public class J_Button1 extends JFrame
{
public J_Button1( )
{
super( "动作事件例程" );
Container c = getContentPane( );
JButton b = new JButton("单击0次");
J_ActionListener a = new J_ActionListener( );
b.addActionListener(a);
c.add(b, BorderLayout.CENTER);
} // J_Button1构造方法结束
public static void main(String args[ ])
{
J_Button1 app = new J_Button1( );
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize( 100, 80 );
app.setVisible( true );
} // 方法main结束
} // 类J_Button1结束
p291命令式按钮及其动作事件处理例程
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class J_Button2 extends JFrame
{
public J_Button2( )
{
super( "动作事件例程" );
Container c = getContentPane( );
JButton b = new JButton("单击0次");
J_ActionListener a = new J_ActionListener( );
b.addActionListener(a);
b.addActionListener(new ActionListener( )
{
int m_count = 0;
public void actionPerformed(ActionEvent e)
{
JButton b= (JButton)e.getSource( );
b.setText("单击" + (++m_count) + "次");
} // 方法actionPerformed结束
} // 实现接口ActionListener的内部类结束
); // addActionListener方法调用结束
c.add(b, BorderLayout.CENTER);
} // J_Button2构造方法结束
public static void main(String args[ ])
{
J_Button2 app = new J_Button2( );
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize( 100, 80 );
app.setVisible( true );
} // 方法main结束
} // 类J_Button2结束
p298随手画板例程
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.Graphics;
import java.awt.Point;
import java.util.Vector;
import javax.swing.JPanel;
public class J_Panel extends JPanel
{
private Vector<Vector<Point>> m_vectorSet
= new Vector<Vector<Point>>( );
public J_Panel( )
{
addMouseListener( new MouseListener( )
{
public void mouseClicked(MouseEvent e)
{
} // 方法mouseClicked结束
public void mouseEntered(MouseEvent e)
{
} // 方法mouseEntered结束
public void mouseExited(MouseEvent e)
{
} // 方法mouseExited结束
public void mousePressed(MouseEvent e)
{
Point p= new Point(e.getX( ), e.getY( ));
Vector<Point> v= new Vector<Point>( ); // 新的笔划
v.add(p); // 添加笔划的起点
m_vectorSet.add(v);
} // 方法mousePressed结束
public void mouseReleased(MouseEvent e)
{
} // 方法mouseReleased结束
} // 实现接口MouseListener的内部类结束
); // addMouseListener方法调用结束
addMouseMotionListener( new MouseMotionListener( )
{
public void mouseMoved(MouseEvent e)
{
} // 方法mouseMoved结束
public void mouseDragged(MouseEvent e)
{
Point p= new Point(e.getX( ), e.getY( ));
int n= m_vectorSet.size( )-1;
Vector<Point> v= m_vectorSet.get(n);
v.add(p); // 添加笔划的中间点或终点
repaint( );
} // 方法mouseDragged结束
} // 实现接口MouseMotionListener的内部类结束
); // addMouseMotionListener方法调用结束
} // J_Panel构造方法结束
protected void paintComponent(Graphics g)
{
g.clearRect(0 , 0, getWidth( ), getHeight( )); // 清除背景
Vector<Point> v;
Point s, t;
int i, j, m;
int n= m_vectorSet.size( );
for (i=0; i<n; i++)
{
v= m_vectorSet.get(i);
m= v.size( )-1;
for (j=0; j<m; j++)
{
s= (Point)v.get(j);
t= (Point)v.get(j+1);
g.drawLine(s.x, s.y, t.x, t.y);
} // 内部for循环结束
} // 外部for循环结束
} // 方法paintComponent结束
public Dimension getPreferredSize( )
{
return new Dimension( 250, 120 );
} // 方法getPreferredSize结束
} // 类J_Panel结束
p300随手画例程
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
public class J_Draw extends JFrame
{
public J_Draw( )
{
super( "随手画例程" );
Container c = getContentPane( );
c.add( new J_Panel( ), BorderLayout.CENTER);
} // J_Draw构造方法结束
public static void main(String args[ ])
{
J_Draw app = new J_Draw( );
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize( 270, 150 );
app.setVisible( true );
} // 方法main结束
} // 类J_Draw结束