AWK是一种优良的文本处理工具。它不仅是 Linux 中也是任何环境中现有的功能最强大的数据处理发动机之一。这种编程及数据操作语言(其名称得自于它的创始人 Alfred Aho 、Peter Weinberger 和 Brian Kernighan 姓氏的首个字母)的最大功能取决于一个人所拥有的知识。 AWK 提供了极其强大的功能:可以进行样式装入、流控制、数学运算符、进程控制语句甚至于内置的变量和函数。它具备了一个完整的语言所应具有的几乎所有精美特性。实际上 AWK 的确拥有自己的语言: AWK 程序设计语言,三位创建者已将它正式定义为“样式扫描和处理语言”。它允许您创建简短的程序,这些程序读取输入文件、为数据排序、处理数据、对输入执行计算以及生成报表,还有无数其他的功能。
你可能对UNIX比较熟悉,但你可能对awk很陌生,这一点也不奇怪,的确,与其优秀的功能相比,awk还远没达到它应有的知名度。awk是什么?与其它大多数UNIX命令不同的是,从名字上看,我们不可能知道awk的功能:它既不是具有独立意义的英文单词,也不是几个相关单词的缩写。事实上,awk是三个人名的缩写,他们是:Aho、(Peter)Weinberg和 (Brain)Kernighan。正是这三个人创造了awk---一个优秀的样式扫描与处理工具。
最简单地说, AWK 是一种用于处理文本的编程语言工具。AWK 在很多方面类似于 shell 编程语言,尽管 AWK 具有完全属于其本身的语法。它的设计思想来源于 SNOBOL4 、sed 、Marc Rochkind设计的有效性语言、语言工具 yacc 和 lex ,当然还从 C 语言中获取了一些优秀的思想。在最初创造 AWK 时,其目的是用于文本处理,并且这种语言的基础是,只要在输入数据中有模式匹配,就执行一系列指令。该实用工具扫描文件中的每一行,查找与命令行中所给定内容相匹配的模式。如果发现匹配内容,则进行下一个编程步骤。如果找不到匹配内容,则继续处理下一行。
尽管操作可能会很复杂,但命令的语法始终是:
awk '{pattern + action}' {filenames}
其中 pattern 表示 AWK 在数据中查找的内容,而 action 是在找到匹配内容时所执行的一系列命令。花括号 ({}) 不需要在程序中始终出现,但它们用于根据特定的模式对一系列指令进行分组。
gawk 是 AWK 的 GNU 版本。
一、AWK的功能是什么?
与sed和 grep很相似,awk是一种样式扫描与处理工具。但其功能却大大强于sed和grep。awk提供了极其强大的功能:它几乎可以完成grep和sed所能完成的全部工作,同时,它还可以可以进行样式装入、流控制、数学运算符、进程控制语句甚至于内置的变量和函数。它具备了一个完整的语言所应具有的几乎所有精美特性。实际上,awk的确拥有自己的语言:awk程序设计语言,awk的三位创建者已将它正式定义为:样式扫描和处理语言。
二、为什么使用awk?
即使如此,你也许仍然会问,我为什么要使用awk?
使用awk的第一个理由是基于文本的样式扫描和处理是我们经常做的工作,awk所做的工作有些象数据库,但与数据库不同的是,它处理的是文本文件,这些文件没有专门的存储格式,普通的人们就能编辑、阅读、理解和处理它们。而数据库文件往往具有特殊的存储格式,这使得它们必须用数据库处理程序来处理它们。既然这种类似于数据库的处理工作我们经常会遇到,我们就应当找到处理它们的简便易行的方法,UNIX有很多这方面的工具,例如sed 、grep、sort以及find等等,awk是其中十分优秀的一种。
使用awk的第二个理由是awk是一个简单的工具,当然这是相对于其强大的功能来说的。的确,UNIX有许嘤判愕墓ぞ撸鏤NIX天然的开发工具C语言及其延续C++就非常的优秀。但相对于它们来说,awk完成同样的功能要方便和简捷得多。这首先是因为awk提供了适应多种需要的解决方案:从解决简单问题的awk命令行到复杂而精巧的awk程序设计语言,这样做的好处是,你可以不必用复杂的方法去解决本来很简单的问题。例如,你可以用一个命令行解决简单的问题,而C不行,即使一个再简单的程序,C语言也必须经过编写、编译的全过程。其次,awk本身是解释执行的,这就使得awk程序不必经过编译的过程,同时,这也使得它与shell script程序能够很好的契合。最后,awk本身较C语言简单,虽然awk吸收了C语言很多优秀的成分,熟悉C语言会对学习awk有很大的帮助,但 awk本身不须要会使用C语言——一种功能强大但需要大量时间学习才能掌握其技巧的开发工具。
使用awk的第三个理由是awk是一个容易获得的工具。与C和C++语言不同,awk只有一个文件(/bin/awk),而且几乎每个版本的UNIX都提供各自版本的awk,你完全不必费心去想如何获得awk。但C语言却不是这样,虽然C语言是UNIX天然的开发工具,但这个开发工具却是单独发行的,换言之,你必须为你的UNIX版本的C语言开发工具单独付费(当然使用D版者除外),获得并安装它,然后你才可以使用它。
基于以上理由,再加上awk强大的功能,我们有理由说,如果你要处理与文本样式扫描相关的工作,awk应该是你的第一选择。在这里有一个可遵循的一般原则:如果你用普通的shell工具或shell script有困难的话,试试awk,如果awk仍不能解决问题,则便用C语言,如果C语言仍然失败,则移至C++。
三、awk的调用方式
前面曾经说过,awk提供了适应多种需要的不同解决方案,它们是:
1、 awk命令行,你可以象使用普通UNIX命令一样使用awk,在命令行中你也可以使用awk程序设计语言,虽然awk支持多行的录入,但是录入长长的命令行并保证其正确无误却是一件令人头疼的事,因此,这种方法一般只用于解决简单的问题。当然,你也可以在shell script程序中引用awk命令行甚至awk程序脚本。
2、使用-f选项调用awk程序。awk允许将一段awk程序写入一个文本文件,然后在awk命令行中用-f选项调用并执行这段程序。具体的方法我们将在后面的awk语法中讲到。
3、利用命令解释器调用awk程序:利用UNIX支持的命令解释器功能,我们可以将一段awk程序写入文本文件,然后在它的第一行加上:
#!/bin/awk -f
并赋予这个文本文件以执行的权限。这样做之后,你就可以在命令行中用类似于下面这样的方式调用并执行这段awk程序了。
$awk脚本文本名 待处理文件
awk的语法:
与其它UNIX命令一样,awk拥有自己的语法:
awk [ -F re] [parameter...] ['prog'] [-f progfile][in_file...]
参数说明:
-F re:允许awk更改其字段分隔符。
parameter: 该参数帮助为不同的变量赋值。
'prog': awk的程序语句段。这个语句段必须用单拓号:'和'括起,以防被shell解释。这个程序语句段的标准形式为:
'pattern {action}'
其中pattern参数可以是egrep正则表达式中的任何一个,它可以使用语法/re/再加上一些样式匹配技巧构成。与sed类似,你也可以使用","分开两样式以选择某个范围。关于匹配的细节,你可以参考附录,如果仍不懂的话,找本UNIX书学学grep和sed(本人是在学习ed时掌握匹配技术的)。 action参数总是被大括号包围,它由一系统awk语句组成,各语句之间用";"分隔。awk解释它们,并在pattern给定的样式匹配的记录上执行其操作。与shell类似,你也可以使用“#”作为注释符,它使“#”到行尾的内容成为注释,在解释执行时,它们将被忽略。你可以省略pattern和 action之一,但不能两者同时省略,当省略pattern时没有样式匹配,表示对所有行(记录)均执行操作,省略action时执行缺省的操作——在标准输出上显示。
-f progfile:允许awk调用并执行progfile指定有程序文件。progfile是一个文本文件,他必须符合awk的语法。
in_file:awk的输入文件,awk允许对多个输入文件进行处理。值得注意的是awk不修改输入文件。如果未指定输入文件,awk将接受标准输入,并将结果显示在标准输出上。awk支持输入输出重定向。
awk的记录、字段与内置变量:
前面说过,awk处理的工作与数据库的处理方式有相同之处,其相同处之一就是awk支持对记录和字段的处理,其中对字段的处理是grep和sed不能实现的,这也是awk优于二者的原因之一。在awk中,缺省的情况下总是将文本文件中的一行视为一个记录,而将一行中的某一部分作为记录中的一个字段。为了操作这些不同的字段,awk借用shell的方法,用$1,$2,$3...这样的方式来顺序地表示行(记录)中的不同字段。特殊地,awk用$0表示整个行(记录)。不同的字段之间是用称作分隔符的字符分隔开的。系统默认的分隔符是空格。awk允许在命令行中用-F re的形式来改变这个分隔符。事实上,awk用一个内置的变量FS来记忆这个分隔符。awk中有好几个这样的内置变量,例如,记录分隔符变量RS、当前工作的记录数NR等等,本文后面的附表列出了全部的内置变量。这些内置的变量可以在awk程序中引用或修改,例如,你可以利用NR变量在模式匹配中指定工作范围,也可以通过修改记录分隔符RS让一个特殊字符而不是换行符作为记录的分隔符。
例:显示文本文件myfile中第七行到第十五行中以字符%分隔的第一字段,第三字段和第七字段:
awk -F % 'NR==7,NR==15 {printf $1 $3 $7}'
四、awk的内置函数
awk 之所以成为一种优秀的程序设计语言的原因之一是它吸收了某些优秀的程序设计语言(例如C)语言的许多优点。这些优点之一就是内置函数的使用,awk定义并支持了一系列的内置函数,由于这些函数的使用,使得awk提供的功能更为完善和强大,例如,awk使用了一系列的字符串处理内置函数(这些函数看起来与C 语言的字符串处理函数相似,其使用方式与C语言中的函数也相差无几),正是由于这些内置函数的使用,使awk处理字符串的功能更加强大。本文后面的附录中列有一般的awk所提供的内置函数,这些内置函数也许与你的awk版本有些出入,因此,在使用之前,最好参考一下你的系统中的联机帮助。
作为内置函数的一个例子,我们将在这里介绍awk的printf函数,这个函数使得awk与c语言的输出相一致。实际上,awk中有许多引用形式都是从C语言借用过来的。如果你熟悉C语言,你也许会记得其中的printf函数,它提供的强大格式输出功能曾经带我们许多的方便。幸运的是,我们在awk中又和它重逢了。awk中printf几乎与C语言中一模一样,如果你熟悉C语言的话,你完全可以照C语言的模式使用awk中的printf。因此在这里,我们只给出一个例子,如果你不熟悉的话,请随便找一本C语言的入门书翻翻。
例:显示文件myfile中的行号和第3字段:
$awk '{printf"%03d%sn",NR,$1}' myfile
五、在命令行使用awk
按照顺序,我们应当讲解awk程序设计的内容了,但在讲解之前,我们将用一些例子来对前面的知识进行回顾,这些例子都是在命令行中使用的,由此我们可以知道在命令行中使用awk是多么的方便。这样做的原因一方面是为下面的内容作铺垫,另一方面是介绍一些解决简单问题的方法,我们完全没有必要用复杂的方法来解决简单的问题----既然awk提供了较为简单的方法的话。
例:显示文本文件mydoc匹配(含有)字符串"sun"的所有行。
$awk '/sun/{print}' mydoc
由于显示整个记录(全行)是awk的缺省动作,因此可以省略action项。
$awk '/sun/' mydoc
例:下面是一个较为复杂的匹配的示例:
$awk '/[Ss]un/,/[Mm]oon/ {print}' myfile
它将显示第一个匹配Sun或sun的行与第一个匹配Moon或moon的行之间的行,并显示到标准输出上。
例:下面的示例显示了内置变量和内置函数length()的使用:
$awk 'length($0)>80 {print NR}' myfile
该命令行将显示文本myfile中所有超过80个字符的行号,在这里,用$0表示整个记录(行),同时,内置变量NR不使用标志符'$'。
例:作为一个较为实际的例子,我们假设要对UNIX中的用户进行安全性检查,方法是考察/etc下的passwd文件,检查其中的passwd字段(第二字段)是否为"*",如不为"*",则表示该用户没有设置密码,显示出这些用户名(第一字段)。我们可以用如下语句实现:
#awk -F: '$2=="" {printf("%s no password!n",$1' /etc/passwd
在这个示例中,passwd文件的字段分隔符是“:”,因此,必须用-F:来更改默认的字段分隔符,这个示例中也涉及到了内置函数printf的使用。
六、awk的变量
如同其它程序设计语言一样,awk允许在程序语言中设置变量,事实上,提供变量的功能是程序设计语言的其本要求,不提供变量的程序设计语言本人还从未见过。
awk 提供两种变量,一种是awk内置的变量,这前面我们已经讲过,需要着重指出的是,与后面提到的其它变量不同的是,在awk程序中引用内置变量不需要使用标志符"$"(回忆一下前面讲过的NR的使用)。awk提供的另一种变量是自定义变量。awk允许用户在awk程序语句中定义并调用自已的变量。当然这种变量不能与内置变量及其它awk保留字相同,在awk中引用自定义变量必须在它前面加上标志符"$"。与C语言不同的是,awk中不需要对变量进行初始化, awk根据其在awk中第一次出现的形式和上下文确定其具体的数据类型。当变量类型不确定时,awk默认其为字符串类型。这里有一个技巧:如果你要让你的 awk程序知道你所使用的变量的明确类型,你应当在在程序中给它赋初值。在后面的实例中,我们将用到这一技巧。
七、运算与判断
作为一种程序设计语言所应具有的特点之一,awk支持多种运算,这些运算与C语言提供的几本相同:如+、-、*、/、%等等,同时,awk也支持C语言中类似++、--、+=、-=、=+、=-之类的功能,这给熟悉C语言的使用者编写awk程序带来了极大的方便。作为对运算功能的一种扩展,awk还提供了一系列内置的运算函数(如log、sqr、cos、sin等等)和一些用于对字符串进行操作(运算)的函数(如length、substr等等)。这些函数的引用大大的提高了awk的运算功能。
作为对条件转移指令的一部分,关系判断是每种程序设计语言都具备的功能,awk也不例外。 awk中允许进行多种测试,如常用的==(等于)、!=(不等于)、>(大于)、<(小于)、>=(大于等于)、>=(小于等于)等等,同时,作为样式匹配,还提供了~(匹配于)和!~(不匹配于)判断。
作为对测试的一种扩充,awk也支持用逻辑运算符:!(非)、&&(与)、||(或)和括号()进行多重判断,这大大增强了awk的功能。本文的附录中列出了awk所允许的运算、判断以及操作符的优先级。
八、awk的流程控制
流程控制语句是任何程序设计语言都不能缺少的部分。任何好的语言都有一些执行流程控制的语句。awk提供的完备的流程控制语句类似于C语言,这给我们编程带来了极大的方便。
1、BEGIN和END:
在awk 中两个特别的表达式,BEGIN和END,这两者都可用于pattern中(参考前面的awk语法),提供BEGIN和END的作用是给程序赋予初始状态和在程序结束之后执行一些扫尾的工作。任何在BEGIN之后列出的操作(在{}内)将在awk开始扫描输入之前执行,而END之后列出的操作将在扫描完全部的输入之后执行。因此,通常使用BEGIN来显示变量和预置(初始化)变量,使用END来输出最终结果。
例:累计销售文件xs中的销售金额(假设销售金额在记录的第三字段):
$awk
>'BEGIN { FS=":";print "统计销售金额";total=0}
>{print $3;total=total+$3;}
>END {printf "销售金额总计:%.2f",total}' sx
(注:>是shell提供的第二提示符,如要在shell程序awk语句和awk语言中换行,则需在行尾加反斜杠)
在这里,BEGIN预置了内部变量FS(字段分隔符)和自定义变量total,同时在扫描之前显示出输出行头。而END则在扫描完成后打印出总合计。
2、流程控制语句
awk提供了完备的流程控制语句,其用法与C语言类似。下面我们一一加以说明:
2.1、if...else语句:
格式:
if(表达式)
语句1
else
语句2
格式中"语句1"可以是多个语句,如果你为了方便awk判断也方便你自已阅读,你最好将多个语句用{}括起来。awk分枝结构允许嵌套,其格式为:
if(表达式1)
{if(表达式2)
语句1
else
语句2
}
语句3
else {if(表达式3)
语句4
else
语句5
}
语句6
当然实际操作过程中你可能不会用到如此复杂的分枝结构,这里只是为了给出其样式罢了。
2.2、while语句
格式为:
while(表达式)
语句
2.3、do-while语句
格式为:
do
{
语句
}while(条件判断语句)
2.4、for语句
格式为:
for(初始表达式;终止条件;步长表达式)
{语句}
在awk 的 while、do-while和for语句中允许使用break,continue语句来控制流程走向,也允许使用exit这样的语句来退出。break 中断当前正在执行的循环并跳到循环外执行下一条语句。continue从当前位置跳到循环开始处执行。对于exit的执行有两种情况:当exit语句不在 END中时,任何操作中的exit命令表现得如同到了文件尾,所有模式或操作执行将停止,END模式中的操作被执行。而出现在END中的exit将导致程序终止。
例:为了
九、awk中的自定义函数
定义和调用用户自己的函数是几乎每个高级语言都具有的功能,awk也不例外,但原始的awk并不提供函数功能,只有在nawk或较新的awk版本中才可以增加函数。
函数的使用包含两部分:函数的定义与函数调用。其中函数定义又包括要执行的代码(函数本身)和从主程序代码传递到该函数的临时调用。
awk函数的定义方法如下:
function 函数名(参数表){
函数体
}
在gawk中允许将function省略为func,但其它版本的awk不允许。函数名必须是一个合法的标志符,参数表中可以不提供参数(但在调用函数时函数名后的一对括号仍然是不可缺少的),也可以提供一个或多个参数。与C语言相似,awk的参数也是通过值来传递的。
在awk 中调用函数比较简单,其方法与C语言相似,但awk比C语言更为灵活,它不执行参数有效性检查。换句话说,在你调用函数时,可以列出比函数预计(函数定义中规定)的多或少的参数,多余的参数会被awk所忽略,而不足的参数,awk将它们置为缺省值0或空字符串,具体置为何值,将取决于参数的使用方式。
awk函数有两种返回方式:隐式返回和显式返回。当awk执行到函数的结尾时,它自动地返回到调用程序,这是函数是隐式返回的。如果需要在结束之前退出函数,可以明确地使用返回语句提前退出。方法是在函数中使用形如:return 返回值 格式的语句。
例:下面的例子演示了函数的使用。在这个示例中,定义了一个名为print_header的函数,该函数调用了两个参数FileName和PageNum, FileName参数传给函数当前使用的文件名,PageNum参数是当前页的页号。这个函数的功能是打印(显示)出当前文件的文件名,和当前页的页号。完成这个功能后,这个函数将返回下一页的页号。
nawk
>'BEGIN{pageno=1;file=FILENAME
>pageno=print_header(file,pageno);#调用函数print_header
>printf("当前页页号是:%dn",pageno);
>}
>#定义函数print_header
>function print_header(FileName,PageNum){
>printf("%s %dn",FileName,PageNum); >PageNum++;return PageNUm;
>}
>}' myfile
执行这个程序将显示如下内容:
myfile 1
当前页页号是:2
十、awk高级输入输出
1.读取下一条记录:
awk的next语句导致awk读取下一个记录并完成模式匹配,然后立即执行相应的操作。通常它用匹配的模式执行操作中的代码。next导致这个记录的任何额外匹配模式被忽略。
2.简单地读取一条记录
awk 的 getline语句用于简单地读取一条记录。如果用户有一个数据记录类似两个物理记录,那么getline将尤其有用。它完成一般字段的分离(设置字段变量$0 FNR NF NR)。如果成功则返回1,失败则返回0(到达文件尾)。如果需简单地读取一个文件,则可以编写以下代码:
例:示例getline的使用
{while(getline==1)
{
#process the inputted fields
}
}
也可以使getline保存输入数据在一个字段中,而不是通过使用getline variable的形式处理一般字段。当使用这种方式时,NF被置成0,FNR和NR被增值。
用户也可以使用getline<"filename"方式从一个给定的文件中输入数据,而不是从命令行所列内容输入数据。此时,getline将完成一般字段分离(设置字段变量$0和NF)。如果文件不存在,返回-1,成功,返回1,返回0表示失败。用户可以从给定文件中读取数据到一个变量中,也可以用stdin(标准输入设备)或一个包含这个文件名的变量代替filename。值得注意的是当使用这种方式时不修改FNR和NR。
另一种使用getline语句的方法是从UNIX命令接受输入,例如下面的例子:
例:示例从UNIX命令接受输入
{while("who -u"|getline)
{
#process each line from the who command
}
}
当然,也可以使用如下形式:
"command" | getline variable
3.关闭文件:
awk中允许在程序中关闭一个输入或输出文件,方法是使用awk的close语句。
close("filename"t
filename可以是getline打开的文件(也可以是stdin,包含文件名的变量或者getline使用的确切命令)。或一个输出文件(可以是stdout,包含文件名的变量或使用管道的确忻睿?
4.输出到一个文件:
awk中允许用如下方式将结果输出到一个文件:
printf("hello word!n"t>"datafile"
或
printf("hello word!n"t>>"datafile"
5.输出到一个命令
awk中允许用如下方式将结果输出到一个命令:
printf("hello word!n"t|"sort-t','"
十一、awk与shell script混合编程
因为awk可以作为一个shell命令使用,因此awk能与shell批处理程序很好的融合在一起,这给实现awk与shell程序的混合编程提供了可能。实现混合编程的关键是awk与shell script之间的对话,换言之,就是awk与shell script之间的信息交流:awk从shell script中获取所需的信息(通常是变量的值)、在awk中执行shell命令行、shell script将命令执行的结果送给awk处理以及shell script读取awk的执行结果等等。
1.awk读取Shell script程序变量
在awk中我们可以通过“'$变量名'”的方式读取sell scrpit程序中的变量。
例:在下面的示例中,我们将读取sell scrpit程序中的变量Name,该变量存放的是文本myfile的撰写者,awk将打印出这个人名。
$cat writename
:
# @(#)
#
.
.
.
Name="张三" nawk 'BEGIN {name="'Name'"; printf("t%st撰写者%sn",FILENAME,name"t;}
{...}END{...}' myfile
.
.
.
2.将shell命令的执行结果送给awk处理
作为信息传送的一种方法,我们可以将一条shell命令的结果通过管道线(|)传递给awk处理:
例:示例awk处理shell命令的执行结果
$who -u | awk '{printf("%s正在执行%sn",$2,$1)}'
该命令将打印出注册终端正在执行的程序名。
3.shell script程序读awk的执行结果
为了实现shell script程序读取awk执行的结果,我们可以采取一些特殊的方法,例如我们可以用变量名=`awk语句`的形式将awk执行的结果存放入一个 shell script变量。当然也可以用管道线的方法将awk执行结果传递给shell script程序处理。
例:作为传送消息的机制之一,UNIX提供了一个向其所有用户传送消息的命令wall(意思是write to all写给所有用户),该命令允许向所有工作中的用户(终端)发送消息。为此,我们可以通过一段shell批处理程序wall.shell来模拟这一程序(事实上比较老的版本中wall就是一段shell批处理程序:
$cat wall.shell
:
# @(#) wall.shell:发送消息给每个已注册终端
#
cat >/tmp/$$
#用户录入消息文本 who -u | awk '{print $2}' | while read tty
do
cat /tmp/$$>$tty
done
在这个程序里,awk接受who -u命令的执行结果,该命令打印出所有已注册终端的信息,其中第二个字段是已注册终端的设备名,因此用awk命令析出该设备名,然后用while read tty语句循环读出这些文件名到变量(shell script变量)tty中,作为信息传送的终结地址。
4.在awk中执行shell命令行----嵌入函数system()
system()是一个不适合字符或数字类型的嵌入函数,该函数的功能是处理作为参数传递给它的字符串。system对这个参数的处理就是将其作为命令处理,也就是说将其当作命令行一样加以执行。这使得用户在自己的awk程序需要时可以灵活地执行命令或脚本。
例:下面的程序将使用system嵌入函数打印用户编制好的报表文件,这个文件存放在名为myreport.txt的文件中。为简约起见,我们只列出了其END部分:
.
.
.
END {close("myreport.txt"t;system("lp myreport.txt"t;}
在这个示例中,我们首先使用close语句关闭了文件myreport.txt文件,然后使用system嵌入函数将myreport.txt送入打印机打印。
写到这里,我不得不跟朋友们说再见了,实在地说,这些内容仍然是awk的初步知识,电脑永远是前进的科学,awk也不例外,本篇所能做的只是在你前行的漫漫长途中铺平一段小小开端,剩下的路还得靠你自己去走。老实说,如果本文真能给你前行的路上带来些许的方便,那本人就知足了!
如对本篇有任何疑问,请E-mail To:Chizlong@yeah.net或到主页http://chizling.yeah.net中留言。
附录:
1.awk的常规表达式元字符
换码序列
^ 在字符串的开头开始匹配
$ 在字符串的结尾开始匹配
. 与任何单个字符串匹配
[ABC] 与[]内的任一字符匹配
[A-Ca-c] 与A-C及a-c范围内的字符匹配(按字母表顺序)
[^ABC] 与除[]内的所有字符以外的任一字符匹配
Desk|Chair 与Desk和Chair中的任一个匹配
[ABC][DEF] 关联。与A、B、C中的任一字符匹配,且其后要跟D、E、F中的任一个字符。
* 与A、B或C中任一个出现0次或多次的字符相匹配
+ 与A、B或C中任何一个出现1次或多次的字符相匹配
? 与一个空串或A、B或C在任何一个字符相匹配
(Blue|Black)berry 合并常规表达式,与Blueberry或Blackberry相匹配
2.awk算术运算符
运算符 用途
------------------
x^y x的y次幂
x**y 同上
x%y 计算x/y的余数(求模)
x+y x加y
x-y x减y
x*y x乘y
x/y x除y
-y 负y(y的开关符号);也称一目减
++y y加1后使用y(前置加)
y++ 使用y值后加1(后缀加)
--y y减1后使用y(前置减)
y-- 使用后y减1(后缀减)
x=y 将y的值赋给x
x+=y 将x+y的值赋给x
x-=y 将x-y的值赋给x
x*=y 将x*y的值赋给x
x/=y 将x/y的值赋给x x%=y 将x%y的值赋给x
x^=y 将x^y的值赋给x
x**=y 将x**y的值赋给x
3.awk允许的测试:
操作符 含义
x==y x等于y
x!=y x不等于y
x>y x大于y
x>=y x大于或等于y
xx<=y x小于或等于y?
x~re x匹配正则表达式re?
x!~re x不匹配正则表达式re?
4.awk的操作符(按优先级升序排列)
= 、+=、 -=、 *= 、/= 、 %=
||
&&
> >= < <= == != ~ !~
xy (字符串连结,'x''y'变成"xy")
+ -
* / %
++ --
5.awk内置变量(预定义变量)
说明:表中v项表示第一个支持变量的工具(下同):A=awk,N=nawk,P=POSIX awk,G=gawk
V 变量 含义 缺省值
--------------------------------------------------------
N ARGC 命令行参数个数
G ARGIND 当前被处理文件的ARGV标志符
N ARGV 命令行参数数组
G CONVFMT 数字转换格式 %.6g
P ENVIRON UNIX环境变量
N ERRNO UNIX系统错误消息
G FIELDWIDTHS 输入字段宽度的空白分隔字符串
A FILENAME 当前输入文件的名字
P FNR 当前记录数
A FS 输入字段分隔符 空格
G IGNORECASE 控制大小写敏感0(大小写敏感)
A NF 当前记录中的字段个数
A NR 已经读出的记录数
A OFMT 数字的输出格式 %.6g
A OFS 输出字段分隔符 空格
A ORS 输出的记录分隔符 新行
A RS 输入的记录他隔符 新行
N RSTART 被匹配函数匹配的字符串首
N RLENGTH 被匹配函数匹配的字符串长度
N SUBSEP 下标分隔符 "34"
6.awk的内置函数
V 函数 用途或返回值
------------------------------------------------
N gsub(reg,string,target) 每次常规表达式reg匹配时替换target中的string
N index(search,string) 返回string中search串的位置
A length(string) 求串string中的字符个数
N match(string,reg) 返回常规表达式reg匹配的string中的位置
N printf(format,variable) 格式化输出,按format提供的格式输出变量variable。
N split(string,store,delim) 根据分界符delim,分解string为store的数组元素
N sprintf(format,variable) 返回一个包含基于format的格式化数据,variables是要放到串中的数据
G strftime(format,timestamp) 返回一个基于format的日期或者时间串,timestmp是systime()函数返回的时间
N sub(reg,string,target) 第一次当常规表达式reg匹配,替换target串中的字符串
A substr(string,position,len) 返回一个以position开始len个字符的子串
P totower(string) 返回string中对应的小写字符
P toupper(string) 返回string中对应的大写字符
A atan(x,y) x的余切(弧度)
N cos(x) x的余弦(弧度)
A exp(x) e的x幂
A int(x) x的整数部分
A log(x) x的自然对数值
N rand() 0-1之间的随机数
N sin(x) x的正弦(弧度)
A sqrt(x) x的平方根
A srand(x) 初始化随机数发生器。如果忽略x,则使用system()
G system() 返回自1970年1月1日以来经过的时间(按秒计算
Friday, 11 May 2007
Thursday, 10 May 2007
Border;Comb_box;Menu
Use Borders
Every JComponent can have one or more borders.
To put a border around a JComponent, you use its setBorder method. You can use the BorderFactory class to create most of the borders that Swing provides.
Here is an example of code that creates a bordered container:
JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createLineBorder(Color.black));
titled borders. Using a titled border, you can convert any border into one that displays a text description.
Use Combo Boxes
A JComboBox, which lets the user choose one of several choices, can have two very different forms. The default form is the uneditable combo box, which features a button and a drop-down list of values. The second form, called the editable combo box, features a text field with a small button abutting it. The user can type a value in the text field or click the button to display a drop-down list.
or
Use Menus
Every JComponent can have one or more borders.
To put a border around a JComponent, you use its setBorder method. You can use the BorderFactory class to create most of the borders that Swing provides.
Here is an example of code that creates a bordered container:
JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createLineBorder(Color.black));
titled borders. Using a titled border, you can convert any border into one that displays a text description.
Border blackline;
blackline = BorderFactory.createLineBorder(Color.black);
jComp1.setBorder(blackline);
TitledBorder title;
title = BorderFactory.createTitledBorder("title");
jComp8.setBorder(title);
Use Combo Boxes
A JComboBox, which lets the user choose one of several choices, can have two very different forms. The default form is the uneditable combo box, which features a button and a drop-down list of values. The second form, called the editable combo box, features a text field with a small button abutting it. The user can type a value in the text field or click the button to display a drop-down list.
String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
//Create the combo box, select item at index 4.
//Indices start at 0, so 4 specifies the pig.
JComboBox petList = new JComboBox(petStrings);
petList.setSelectedIndex(4);
petList.addActionListener(this);
or
String[] patternExamples = {
"dd MMMMM yyyy",
"dd.MM.yy",
"MM/dd/yy",
"yyyy.MM.dd G 'at' hh:mm:ss z",
"EEE, MMM d, ''yy",
"h:mm a",
"H:mm:ss:SSS",
"K:mm a,z",
"yyyy.MMMMM.dd GGG hh:mm aaa"
};
. . .
JComboBox patternList = new JComboBox(patternExamples);
patternList.setEditable(true);
patternList.addActionListener(this);
Use Menus
//Where the GUI is created:
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JRadioButtonMenuItem rbMenuItem;
JCheckBoxMenuItem cbMenuItem;
//Create the menu bar.
menuBar = new JMenuBar();
//Build the first menu.
menu = new JMenu("A Menu");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription(
"The only menu in this program that has menu items");
menuBar.add(menu);
//a group of JMenuItems
menuItem = new JMenuItem("A text-only menu item",
KeyEvent.VK_T);
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"This doesn't really do anything");
menu.add(menuItem);
menuItem = new JMenuItem("Both text and icon",
new ImageIcon("images/middle.gif"));
menuItem.setMnemonic(KeyEvent.VK_B);
menu.add(menuItem);
menuItem = new JMenuItem(new ImageIcon("images/middle.gif"));
menuItem.setMnemonic(KeyEvent.VK_D);
menu.add(menuItem);
//a group of radio button menu items
menu.addSeparator();
ButtonGroup group = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
rbMenuItem.setSelected(true);
rbMenuItem.setMnemonic(KeyEvent.VK_R);
group.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem("Another one");
rbMenuItem.setMnemonic(KeyEvent.VK_O);
group.add(rbMenuItem);
menu.add(rbMenuItem);
//a group of check box menu items
menu.addSeparator();
cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
cbMenuItem.setMnemonic(KeyEvent.VK_C);
menu.add(cbMenuItem);
cbMenuItem = new JCheckBoxMenuItem("Another one");
cbMenuItem.setMnemonic(KeyEvent.VK_H);
menu.add(cbMenuItem);
//a submenu
menu.addSeparator();
submenu = new JMenu("A submenu");
submenu.setMnemonic(KeyEvent.VK_S);
menuItem = new JMenuItem("An item in the submenu");
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_2, ActionEvent.ALT_MASK));
submenu.add(menuItem);
menuItem = new JMenuItem("Another item");
submenu.add(menuItem);
menu.add(submenu);
//Build second menu in the menu bar.
menu = new JMenu("Another Menu");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"This menu does nothing");
menuBar.add(menu);
...
frame.setJMenuBar(theJMenuBar);
Use Borders
Every JComponent can have one or more borders.
To put a border around a JComponent, you use its setBorder method. You can use the BorderFactory class to create most of the borders that Swing provides.
Here is an example of code that creates a bordered container:
JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createLineBorder(Color.black));
titled borders. Using a titled border, you can convert any border into one that displays a text description.
Use Combo Boxes
Every JComponent can have one or more borders.
To put a border around a JComponent, you use its setBorder method. You can use the BorderFactory class to create most of the borders that Swing provides.
Here is an example of code that creates a bordered container:
JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createLineBorder(Color.black));
titled borders. Using a titled border, you can convert any border into one that displays a text description.
Border blackline;
blackline = BorderFactory.createLineBorder(Color.black);
jComp1.setBorder(blackline);
TitledBorder title;
title = BorderFactory.createTitledBorder("title");
jComp8.setBorder(title);
Use Combo Boxes
Wednesday, 9 May 2007
normalization
update anomalies:
insertion anomalies
deletion anomalies
modification anomalize
functional dependency: describles the relationship between attributes in a relation. for example, if A and B are attribute of reltion R, B is functionally dependent on A (denoted A->B), if each value of A is associated with eactly one value of B (A and B may each consist of one or more attributes.)
B is functionally dependent on B
A functionally determines B
functional dependency is specified as a constraint between the attributes.
determinant: refers to the attribute, or group of attributes, on the left_hand side of the arrow of a functional dependency.
full functional dependency: indicates that if A and B are attributes of a relation, B is fully functionally dependent on A if B is functionally dependent on A, but not on any proper subset of A.
partially dependency: if there is some attribute that can be removed from A and yet the dependency still holds.
there are two kind of functional dependency:
one-to-one relationship: full functional dependency
many-to-one relationship: partially dependecy
transitive dependency: a condition where A, B and C are attributes of a relation such that if A->B and B->C, then C is transitively dependent on A via B
the main purpose of identifying a set of functional dependencies for a relation is to specify the set of intergrity constraints that must hold on a relation.
hence, we see that an essential characteristic for a candidate key of relation is that the attribute of a determinant either individually or working together must be able to functionally determine all the other attribute in the relation.
the concepts of functional dependencies and keys are central to the process of normalization.
normalization is a formal technique for analyzing relations based on their primary key(or candidate keys) and functional dependencies.
UNF: a table that contains one or more repeating groups
1NF: a relation in which the intersection of each row and column contains one and only one value.
2NF: a relation that is in 1NF and every non_cabdidate_key attribute is fully functionally dependent on the candidate key.
if a partial dependency exists, we remove the partially dependent attributes from the relation by placing them in a new relation along with a copy of their determinant.
3NF: a relation that is in 1NF and 2NF and in which no non-candidate-key attribute is candidate dependent on the primary key.
if a transitive dependency exists, we remove the transitively dependent attributes from the relation by placing the attributes in a new relation along with a copy of the determinant.
redendancy is often caused by a functional dependency. each normal form has fewer FDs than the last. since FDs represent redundancy, each normal form has less redundancy than the last.
properties of FDs
the primary key FDs any set of attributes in that relation. same for candidate key.
any set of attributes is FD on itself.
relues for FDs
reflexivity: if B is a subset of A then: A->B
augmentation: if A->B then: A U C -> B U C
transitivity: if A->B and B->C then A->C
removing FDs:
suppose we have a relation R with scheme S and the FD A->B where A^B ={}
let C = S - (A U B): all other attributes not in A and B
it turns out that we can split R into two parts: R1, with scheme C U A ; R2, with scheme A U B
the orginal relation can be recovered as the natural join of R1 and R2: R=R1 NATURAL JOIN R2.
self-determination: A->A
Decomposition: if A->B,C, then A->B and A->C
Union: if A->B and A->C, then A->B,C
Composition: if A->B and C->D then A,C->B,D
a set of functional dependency X is minimal if it satisfy the following conditions:
every dependency in X has a single attribute on its right-hand side.
We can not replace any dependency A->B in X with dependency C->B, where C is a proper subset of A, and still have a set of dependencies that is equivalent to X
we cannot remove any dependency from X and still have a set of dependencies that is equivalent to x.
transitive FDs
a FD, A->C is a transitive FD, if there is some set B such that A->B and B->C are non-trivial FDs.
A->B non-trivial means: B is not a subset of A
to normalise a relation, we used projection. if R(A,B,C) satisfies A->B then we can project it on A,B and A,C without losing information.
when is decomposition is not lossless: no FD
BCNF: a relation in BCNF if for every FD A->B either B is contained in A(the FD is trivial), or A contains a candidate key of the relation. in other words: every determinant in a non-trivial dependency is a (super) key. If there is only one cadidate key then 3NF and BCNF are the same one.
normalisation to 3NF is always lossless and dependency preserving.
normalisation to BCNF is lossless, may not preserve dependency.
insertion anomalies
deletion anomalies
modification anomalize
functional dependency: describles the relationship between attributes in a relation. for example, if A and B are attribute of reltion R, B is functionally dependent on A (denoted A->B), if each value of A is associated with eactly one value of B (A and B may each consist of one or more attributes.)
B is functionally dependent on B
A functionally determines B
functional dependency is specified as a constraint between the attributes.
determinant: refers to the attribute, or group of attributes, on the left_hand side of the arrow of a functional dependency.
full functional dependency: indicates that if A and B are attributes of a relation, B is fully functionally dependent on A if B is functionally dependent on A, but not on any proper subset of A.
partially dependency: if there is some attribute that can be removed from A and yet the dependency still holds.
there are two kind of functional dependency:
one-to-one relationship: full functional dependency
many-to-one relationship: partially dependecy
transitive dependency: a condition where A, B and C are attributes of a relation such that if A->B and B->C, then C is transitively dependent on A via B
the main purpose of identifying a set of functional dependencies for a relation is to specify the set of intergrity constraints that must hold on a relation.
hence, we see that an essential characteristic for a candidate key of relation is that the attribute of a determinant either individually or working together must be able to functionally determine all the other attribute in the relation.
the concepts of functional dependencies and keys are central to the process of normalization.
normalization is a formal technique for analyzing relations based on their primary key(or candidate keys) and functional dependencies.
UNF: a table that contains one or more repeating groups
1NF: a relation in which the intersection of each row and column contains one and only one value.
2NF: a relation that is in 1NF and every non_cabdidate_key attribute is fully functionally dependent on the candidate key.
if a partial dependency exists, we remove the partially dependent attributes from the relation by placing them in a new relation along with a copy of their determinant.
3NF: a relation that is in 1NF and 2NF and in which no non-candidate-key attribute is candidate dependent on the primary key.
if a transitive dependency exists, we remove the transitively dependent attributes from the relation by placing the attributes in a new relation along with a copy of the determinant.
redendancy is often caused by a functional dependency. each normal form has fewer FDs than the last. since FDs represent redundancy, each normal form has less redundancy than the last.
properties of FDs
the primary key FDs any set of attributes in that relation. same for candidate key.
any set of attributes is FD on itself.
relues for FDs
reflexivity: if B is a subset of A then: A->B
augmentation: if A->B then: A U C -> B U C
transitivity: if A->B and B->C then A->C
removing FDs:
suppose we have a relation R with scheme S and the FD A->B where A^B ={}
let C = S - (A U B): all other attributes not in A and B
it turns out that we can split R into two parts: R1, with scheme C U A ; R2, with scheme A U B
the orginal relation can be recovered as the natural join of R1 and R2: R=R1 NATURAL JOIN R2.
self-determination: A->A
Decomposition: if A->B,C, then A->B and A->C
Union: if A->B and A->C, then A->B,C
Composition: if A->B and C->D then A,C->B,D
a set of functional dependency X is minimal if it satisfy the following conditions:
every dependency in X has a single attribute on its right-hand side.
We can not replace any dependency A->B in X with dependency C->B, where C is a proper subset of A, and still have a set of dependencies that is equivalent to X
we cannot remove any dependency from X and still have a set of dependencies that is equivalent to x.
transitive FDs
a FD, A->C is a transitive FD, if there is some set B such that A->B and B->C are non-trivial FDs.
A->B non-trivial means: B is not a subset of A
to normalise a relation, we used projection. if R(A,B,C) satisfies A->B then we can project it on A,B and A,C without losing information.
when is decomposition is not lossless: no FD
BCNF: a relation in BCNF if for every FD A->B either B is contained in A(the FD is trivial), or A contains a candidate key of the relation. in other words: every determinant in a non-trivial dependency is a (super) key. If there is only one cadidate key then 3NF and BCNF are the same one.
normalisation to 3NF is always lossless and dependency preserving.
normalisation to BCNF is lossless, may not preserve dependency.
Physical DB Issues
LECTURE_13
E/R modelling helps find the requirements of a database
Normalisation helps to refine a design by removing data redundancy
Physical design Concerned with storing and accessing the data
RAID - redundant array of independent (inexpensive) disks
Storing information across more than one physical disk
Speed - can access more than one disk
Robustness - if one disk fails it is OK
RAID Level 0 : Files are split across several disks
For a system with n disks, each file is split into n parts, one part stored on each disk
Improves speed, but no redundancy
RAID Level 1: As RAID 0 but with redundancy
Files are split over multiple disks
Each disk is mirrored
For n disks, split files into n/2 parts, each stored on 2 disks
Improves speed, has redundancy(in two disks), but needs lots of disks
Parity Checking: for a set of data in binary form we count the number of 1s for each bit across the data. If this is even the parity is 0, if odd then it is 1. We can use parity checking to reduce the number of disks ---------????????how to reduce the number of disk
Recovery With Parity: If one of our pieces of data is lost we can recover it.
RAID Level 3: Data is striped over disks, and a parity disk for redundancy
For n disks, we split the data in n-1 parts
Each part is stored on a disk
The final disk stores parity information for recovery
Indexes:
Types of indexes
Primary or clustered indexes affect the order that the data is stored in a file
Secondary indexes give a look-up table into the file
Only one primary index, but many secondary ones
Choosing Indexes: only have one primary index. The most frequently looked-up value is often the best choice. Some DBMSs assume the primary key is the primary index, as it is usually used to refer to rows
Don’t create too many indexes: They can speed up queries, but they slow down inserts, updates and deletes. Whenever the data is changed, the index may need to change
Creating Indexes:
Query Processing:
Three main stages
Parsing and translation - the query is put into an internal form
relational operators: PRODUCT,SELECTION, PROJECTION,
Optimisation - changes are made for efficiency
Evaluation - the optimised query is applied to the DB
----------P31??????????????????, why 15 operantions
E/R modelling helps find the requirements of a database
Normalisation helps to refine a design by removing data redundancy
Physical design Concerned with storing and accessing the data
RAID - redundant array of independent (inexpensive) disks
Storing information across more than one physical disk
Speed - can access more than one disk
Robustness - if one disk fails it is OK
RAID Level 0 : Files are split across several disks
For a system with n disks, each file is split into n parts, one part stored on each disk
Improves speed, but no redundancy
RAID Level 1: As RAID 0 but with redundancy
Files are split over multiple disks
Each disk is mirrored
For n disks, split files into n/2 parts, each stored on 2 disks
Improves speed, has redundancy(in two disks), but needs lots of disks
Parity Checking: for a set of data in binary form we count the number of 1s for each bit across the data. If this is even the parity is 0, if odd then it is 1. We can use parity checking to reduce the number of disks ---------????????how to reduce the number of disk
Recovery With Parity: If one of our pieces of data is lost we can recover it.
RAID Level 3: Data is striped over disks, and a parity disk for redundancy
For n disks, we split the data in n-1 parts
Each part is stored on a disk
The final disk stores parity information for recovery
Indexes:
Types of indexes
Primary or clustered indexes affect the order that the data is stored in a file
Secondary indexes give a look-up table into the file
Only one primary index, but many secondary ones
Choosing Indexes: only have one primary index. The most frequently looked-up value is often the best choice. Some DBMSs assume the primary key is the primary index, as it is usually used to refer to rows
Don’t create too many indexes: They can speed up queries, but they slow down inserts, updates and deletes. Whenever the data is changed, the index may need to change
Creating Indexes:
Query Processing:
Three main stages
Parsing and translation - the query is put into an internal form
relational operators: PRODUCT,SELECTION, PROJECTION,
Optimisation - changes are made for efficiency
Evaluation - the optimised query is applied to the DB
----------P31??????????????????, why 15 operantions
Monday, 7 May 2007
When There Was Me And You
lyric:
It's funny when you find yourself
Looking from the outside
I'm standing here but all I want
Is to be over there
Why did I let myself believe
Miracles could happen
Cause now I have to pretend
That I don't really care
I thought you were my fairytale
A dream when I'm not sleeping
A wish upon a star
Thats coming true
But everybody else could tell
That I confused my feelings with the truth
When there was me and you
I swore I knew the melody
That I heard you singing
And when you smiled
You made me feel
Like I could sing along
But then you went and changed the words
Now my heart is empty
I'm only left with used-to-be's
Once upon a song
Now I know your not a fairytale
And dreams were meant for sleeping
And wishes on a star
Just don't come true
Cause now even I tell
That I confused my feelings with the truth
Cause I liked the view
When there was me and you
I can't believe that
I could be so blind
It's like you were floating
While I was falling
And I didn't mind
Cause I liked the view
Thought you felt it too
When there was me and you
It's funny when you find yourself
Looking from the outside
I'm standing here but all I want
Is to be over there
Why did I let myself believe
Miracles could happen
Cause now I have to pretend
That I don't really care
I thought you were my fairytale
A dream when I'm not sleeping
A wish upon a star
Thats coming true
But everybody else could tell
That I confused my feelings with the truth
When there was me and you
I swore I knew the melody
That I heard you singing
And when you smiled
You made me feel
Like I could sing along
But then you went and changed the words
Now my heart is empty
I'm only left with used-to-be's
Once upon a song
Now I know your not a fairytale
And dreams were meant for sleeping
And wishes on a star
Just don't come true
Cause now even I tell
That I confused my feelings with the truth
Cause I liked the view
When there was me and you
I can't believe that
I could be so blind
It's like you were floating
While I was falling
And I didn't mind
Cause I liked the view
Thought you felt it too
When there was me and you
文字输入组件的使用与介绍
++ 文字输入组件的使用与介绍
9-1:认识Swing的文字输入组件:
Swing与文字输入有关的组件分别是JTextField、JPasswordField、JTextArea、JEditorPane与JTextPane.JTextField与
JPasswordField为单行的文本编辑器;JTextArea为多行的文本编辑器;JEditorPane可显示多种文件格式;JTextPane可设置文件各种
样式。这些组件都继承了JTextComponent为类,它们之间的关系如下:
|--JTextField--JPasswordField
|
JTextComponent|
|--JTextArea
|
|--JEditorPane--JTextPane
JTextComponent提供了相当多实用的方法,可使处理输入组件更为方便,例如copy(),paste(),cut(),getText(),setText()等
相当直觉的方法:另外还有设置是否可编辑(setEditable()),setSelectionEnd(),setSelectionStart())、设置或取得光标位置
(getCaretPosition(),setCaretPosition())等等,这些相当常用的方法你都可以在JTextComponent类中找到.
Swing的文字输入组件均以Document来当作数据模式,当输入组件的内容有所改变时,均是更改此Document的内容。因此你可
以将同一个Document内容以不同的输入组件来显示,这就是MVC概念的一个基本应用。Document为一个interface,你可以实现此界
面或利用java提供的默认类来构造文字输入组件。
|---implements-->AbstractDocument---extends->PlainDocument
|
Document |
|
|--extends-->StyleDocument---implements--->DefaultStyleDocument---extends--->HTMLDocument
AbstractDocument----extends-->DefaultStyleDocument
PlainDocument是一个实体类,已经实现了AbstractDocument与Document中的所有抽象方法,你可以用此类直接构造出JTextField
、JPasswordField与JTextArea组件;相同的,你可以使用DefaultStyledDocument构造出JTextPane组件,这些关系我们均会在下面
各节中提到。下面我们开始介绍各种文字输入组件的使用:
9-2:使用JTextField组件:
JTextField继承JTextComponent类,因此它也可以使用JTextComponent抽象类里面许多好用的方法,如copy(),paste(),setText()
,isEditable()等等。我们可以在很多地方使用JTextField,JTextField是一个单行的输入组件,那么有没有多行的输入组件呢?有
的,就是JTextArea,我们将在后面介绍.
JTextField构造函数:
JTextField()
JTextField(Document doc,String text,int columns):使用指定的文件存储模式建立一个新的JTextField并设置其初始化字符串和
字段长度。
JTextField(int columns):建立一个新的JTextField并设置其初始字段长度。
JTextField(String text):建立一个新的JTextField并设置其初始字字符串。
JTextField(String text,int columns):建立一个新的JTextField并设置其初始字符串和字段长度.
9-2-1:构造一般的JTextField组件:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextField1{
public static void main(String args[]) {
JFrame f = new JFrame("JTextField1");
Container contentPane = f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
p1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST; //设定Layout的位置
gbc.insets = new Insets(2,2,2,2); //设定与边界的距离(上,左,下,右)
p1.setBorder(BorderFactory.createTitledBorder("您的基本数据"));
JLabel l1 = new JLabel("姓名:");
JLabel l2 = new JLabel("性别:");
JLabel l3 = new JLabel("身高:");
JLabel l4 = new JLabel("体重:");
JTextField t1 = new JTextField();
JTextField t2 = new JTextField(2);
JTextField t3 = new JTextField("175cm");
JTextField t4 = new JTextField("50kg太瘦了",10);
gbc.gridy=1;
gbc.gridx=0;
p1.add(l1,gbc);
gbc.gridx=1;
p1.add(t1,gbc);
gbc.gridy=2;
gbc.gridx=0;
p1.add(l2,gbc);
gbc.gridx=1;
p1.add(t2,gbc);
gbc.gridy=3;
gbc.gridx=0;
p1.add(l3,gbc);
gbc.gridx=1;
p1.add(t3,gbc);
gbc.gridy=4;
gbc.gridx=0;
p1.add(l4,gbc);
gbc.gridx=1;
p1.add(t4,gbc);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
9-2-2:利用Document构造JTextField:
Document是一个interface,主要的功能是定义一些方法,让我们在使用所有与Text相关的组件时,能够将输入文字的内容加以
结构化或规格化。将文字内容结构化又是什么呢?举例来说,就好像一本书的内容,它的结构一定会有各个大章,在各章中又会分
成许多小节,小节内会再有各个小重点等等,这样的树状组件结构就是结构化的一种。由于这个interface定义了10几个方法,但是
在这里我们所会用到的只有少数几个方法,为了不让大家混淆,因此我们先列出这个interface常被使用到的方法,有兴趣的可查阅
java api文件:
void addDocumentListener(DocumentListener listener):增加DocumentListener,使组件具有处理DocumentEvent功能。
void addUndoableEditListener(UndoableEditListener listener):增加UndoableEditListener,使组件具有处理UndoableEditEv
Ent功能,当文件中的内容被修改时自动记忆可以被复原的内容。
String getText(int offset,int length):取得document中的文字内容。
void insertString(int offset,String str,AttributeSet a):将字符串加入到Text组件的内容中。
void removeDocumentListener(DocumentListener listener):移除DocumentListener.
void removeUndoableEditListener(UndoableEditListener listener):移除UndoableEditListener,使复原功能失效。
还记得我们一开始在介绍JTextField时所提到的构造函数吗?其中有一个JTextField的构造函数是这样子的:
JTextField(Document doc,String text,int columns):使用指定的文件存储模式建立一个新的JTextField并设置其初始
化字符串和字段长度。
因此我们必须实作Document所有的方法,才能利用Document构造出JTextField,这样的做法有点麻烦,因为我们之前有提到Document
的方法有数十种,但是我们要用到的却只有其中几种,若是要将全部的方法实作那是相当费时的做法。大家还记行我们前几章介绍
JList时,利用继承AbstractListModel的抽象类来构造JList吗?由于抽象类已经了许多接口的方法,所以当我们继承这个抽象类后
便不需要实作这些方法。同样的java在这里也提供了一个AbstractDocument的抽象类来供我们使用。不过在这里我们并不是要使用
AbstractDocument,因为java在这部份已经提供了一个实体类:PlainDocument.这个实体类继承AbstractDocument,也就是具备了所
有AbstractDocument的方法,所以我们只要直接继承PlainDocument这个实体类就能利用Document来构造JTextField.这种概念跟
JList或是JTable的模式结构均是相同的。我们来看下面的范例:
JTextField3.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextField3{
public static void main(String args[]) {
JFrame f = new JFrame("JTextField3");
Container contentPane = f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
//p1.setLayout(new GridLayout(4,2));
p1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST; //设定Layout的位置
gbc.insets = new Insets(2,2,2,2); //设定与边界的距离(上,左,下,右)
p1.setBorder(BorderFactory.createTitledBorder("您的基本数据"));
JLabel l1 = new JLabel("姓名:");
JLabel l2 = new JLabel("性别:");
JLabel l3 = new JLabel("身高:");
JLabel l4 = new JLabel("体重:");
JTextField t1 = new JTextField(new JTextField3_FixedLengthDocument(10),"",10);
JTextField t2 = new JTextField(new JTextField3_FixedLengthDocument(1),"",2);
JTextField t3 = new JTextField(new JTextField3_FixedLengthDocument(5),"",5);
JTextField t4 = new JTextField(new JTextField3_FixedLengthDocument(5),"",5);
gbc.gridy=1;
gbc.gridx=0;
p1.add(l1,gbc);
gbc.gridx=1;
p1.add(t1,gbc);
gbc.gridy=2;
gbc.gridx=0;
p1.add(l2,gbc);
gbc.gridx=1;
p1.add(t2,gbc);
gbc.gridy=3;
gbc.gridx=0;
p1.add(l3,gbc);
gbc.gridx=1;
p1.add(t3,gbc);
gbc.gridy=4;
gbc.gridx=0;
p1.add(l4,gbc);
gbc.gridx=1;
p1.add(t4,gbc);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
JTextField3_FixedLengthDocument.java
import javax.swing.*;
import javax.swing.text.*;
import java.awt.Toolkit;
public class JTextField3_FixedLengthDocument extends PlainDocument{
private int maxLength;
public JTextField3_FixedLengthDocument(int maxLength){
this.maxLength = maxLength;
}
public void insertString(int offset,String str,AttributeSet att) throws BadLocationException
{
if ( getLength() + str.length() > maxLength ){
Toolkit.getDefaultToolkit().beep();
}else{
super.insertString(offset,str,att);
}
}
}
9-2-3:JTextField的事件处理:
在JTextField类中有addActionListener()方法,可以检测到用户是否在JTextField上按下Enter键,就如同前面所介绍JButton按
下按钮时所产生的事件(Event)一样,我们来看下面这个范例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextField4{
public static void main(String[] args){
JFrame f=new JFrame("JTextField4");
Container contentPane=f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1=new JPanel();
p1.setLayout(new GridLayout(2,2));
p1.setBorder(BorderFactory.createTitledBorder("JTextField事件处理范例"));
JLabel l1=new JLabel("输入");
JLabel l2=new JLabel("输入后,按下Enter==>");
final JLabel l3=new JLabel("");
final JTextField t1=new JTextField();
t1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
l3.setText(t1.getText());
}
});
p1.add(l1);
p1.add(t1);
p1.add(l2);
p1.add(l3);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
9-3:使用JPasswordField组件:
JPasswordField的类层次结构图:
java.lang.Object
--java.awt.Component
--javax.swing.JComponent
--javax.swing.text.JTextComponent
--javax.swing.JTextField
--javax.swing.JPasswordField
一般我们在网络中填写登录密码时,密码都会显示"*"号代表用户输入的字段,这样可避免用户输入的密码信息被旁人所偷窥。
而Swing中的JPasswordField就可以提供这样的功能。JPasswordField继承JTextField类,因此它也可以使用JTextField类里面许多
好用的方法,如addActionListener()、removeActionListener()、setHorizontalAlignment()等等。如同JTextField一样
JPasswordField也是一个单行的输入组件,不同的是JPasswordField多了屏蔽(Mask)的功能,也就是说在JPasswordField中的字符
都会以单一种的字符类型表现出来。
在使用JPasswordField之前,我们先看看它的构造函数:
JPasswordField()
JPasswordField(Document doc,String text,int columns):使用指定的文件存储模式建立一个新的JPasswordField并设置其初始化
字符串和字段长度。
JPasswordField(int columns):建立一个新的JPasswordField并设置其初始字段长度。
JPasswordField(String text):建立一个新的JPasswordField并设置其初始字字符串。
JPasswordField(String text,int columns):建立一个新的JPasswordField并设置其初始字符串和字段长度.
9-3-1:构造一般的JPasswordField组件:
JPasswordField的构造函数和JTextField的构造函数几乎一模本样,唯一不同的是在JPasswordField输入时字符会以屏蔽字符的
类型表示。我们来看下面这个范例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPasswordField1{
public static void main(String args[]) {
JFrame f = new JFrame("JPasswordField1");
Container contentPane = f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
//p1.setLayout(new GridLayout(4,2));
p1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST; //设定Layout的位置
gbc.insets = new Insets(2,2,2,2); //设定与边界的距离(上,左,下,右)
p1.setBorder(BorderFactory.createTitledBorder("您的基本数据"));
JLabel l1 = new JLabel("姓名:");
JLabel l2 = new JLabel("性别:");
JLabel l3 = new JLabel("身高:");
JLabel l4 = new JLabel("体重:");
JPasswordField t1 = new JPasswordField();
JPasswordField t2 = new JPasswordField(2);
JPasswordField t3 = new JPasswordField(" 175cm");
JPasswordField t4 = new JPasswordField(" 50kg太瘦了",10);
t1.setPreferredSize(t1.getPreferredSize());
gbc.gridy=1;
gbc.gridx=0;
p1.add(l1,gbc);
gbc.gridx=1;
p1.add(t1,gbc);
gbc.gridy=2;
gbc.gridx=0;
p1.add(l2,gbc);
gbc.gridx=1;
p1.add(t2,gbc);
gbc.gridy=3;
gbc.gridx=0;
p1.add(l3,gbc);
gbc.gridx=1;
p1.add(t3,gbc);
gbc.gridy=4;
gbc.gridx=0;
p1.add(l4,gbc);
gbc.gridx=1;
p1.add(t4,gbc);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
我们可以看到默认的字符串都以屏蔽字符"*"来表示,"*"字符是JPasswordField默认的屏蔽字符,我们可以利用JPasswordField
提供的setEchoChar()方法来改用其他字符来作为屏蔽字符。我们来看下面的范例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPasswordField2{
public static void main(String args[]) {
JFrame f = new JFrame("JPasswordField2");
Container contentPane = f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4,2));
p1.setBorder(BorderFactory.createTitledBorder("您的基本数据"));
JLabel l1 = new JLabel("姓名:");
JLabel l2 = new JLabel("性别:");
JLabel l3 = new JLabel("身高:");
JLabel l4 = new JLabel("体重:");
JPasswordField t1 = new JPasswordField(10);
JPasswordField t2 = new JPasswordField(2);
JPasswordField t3 = new JPasswordField(" 175cm");
JPasswordField t4 = new JPasswordField(" 50kg太瘦了",10);
t1.setEchoChar('#');
t2.setEchoChar('%');
t3.setEchoChar('&');
t4.setEchoChar('M');
p1.add(l1);
p1.add(t1);
p1.add(l2);
p1.add(t2);
p1.add(l3);
p1.add(t3);
p1.add(l4);
p1.add(t4);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
9-3-2:利用Document构造JPasswordField:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPasswordField3{
public static void main(String args[]) {
JFrame f = new JFrame("JPasswordField3");
Container contentPane = f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
//p1.setLayout(new GridLayout(4,2));
p1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST; //设定Layout的位置
gbc.insets = new Insets(2,2,2,2); //设定与边界的距离(上,左,下,右)
p1.setBorder(BorderFactory.createTitledBorder("您的基本数据"));
JLabel l1 = new JLabel("姓名:");
JLabel l2 = new JLabel("性别:");
JLabel l3 = new JLabel("身高:");
JLabel l4 = new JLabel("体重:");
JPasswordField t1 = new JPasswordField(new JPasswordField3_OnlyNumberDocument(10),"",10);
JPasswordField t2 = new JPasswordField(new JPasswordField3_OnlyNumberDocument(1),"",2);
JPasswordField t3 = new JPasswordField(new JPasswordField3_OnlyNumberDocument(5),"",5);
JPasswordField t4 = new JPasswordField(new JPasswordField3_OnlyNumberDocument(5),"",5);
gbc.gridy=1;
gbc.gridx=0;
p1.add(l1,gbc);
gbc.gridx=1;
p1.add(t1,gbc);
gbc.gridy=2;
gbc.gridx=0;
p1.add(l2,gbc);
gbc.gridx=1;
p1.add(t2,gbc);
gbc.gridy=3;
gbc.gridx=0;
p1.add(l3,gbc);
gbc.gridx=1;
p1.add(t3,gbc);
gbc.gridy=4;
gbc.gridx=0;
p1.add(l4,gbc);
gbc.gridx=1;
p1.add(t4,gbc);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
import javax.swing.*;
import javax.swing.text.*;
import java.awt.Toolkit;
public class JPasswordField3_OnlyNumberDocument extends PlainDocument{
private int maxLength;
int result;
public JPasswordField3_OnlyNumberDocument(int maxLength){
this.maxLength = maxLength;
}
public void insertString(int offset,String str,AttributeSet att) throws BadLocationException
{
for(int i=0;i<=9;i++){
result = Integer.toString(i).compareTo(str);
if (result == 0){ //是数字才处理
if ( getLength() + str.length() > maxLength ){
Toolkit.getDefaultToolkit().beep();
}else{
super.insertString(offset,str,att);
}
}
}
}
}
9-4:使用JTextArea组件:
JTextArea的类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JCompontent
--javax.swing.text.JTextComponent
--javax.swing.JTextArea
JTextArea继承JTextComponent为类,因此它也可以使用JTextComponent抽象类里面许多好用的方法,如compy(),paste(),
setText(),isEditable()等等。我们在前面有提到JTextArea是一个多行的输入组件,在这个组件中可以利用Enter来做换行的操作
。
在使用JTextArea之前,我们先看看JTextArea有哪些构造函数可以使用:
JTextArea的构造函数:
JTextArea():建立一个新的JTextArea.
JTextArea(Document doc):使用指定的文件存储模式建立一个新的JTextArea.
JTextArea(Document doc,String text,int row ,int columns):使用指定的文件存储模式建立一个新的JTextArea并设置其初始
字符串和列、字段长度。
JTextArea(int row,int columns):建立一个新的JTextArea并设置其初始列、字段长度。
JTextArea(String text):建立一个新的JTextArea并设置其初始字符串.
JTextArea(String text,int row,int columns):建立一个新的JTextArea并设置其初始字符串和列、字段长度。
9-4-1:构造JTextArea组件:
我们可以发现到JTextArea的构造函数和JTextField及JPasswordField的构造函数是相同雷同,而JTextArea多了一个字段的参数
值是因为JTextArea是二维的输入组件,在构造时不仅要设置字段长度也要设置行数。我们来看下面这个范例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextArea1{
public static void main(String[] args){
JFrame f=new JFrame("JTextArea1");
Container contentPane=f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1=new JPanel();
p1.setLayout(new GridBagLayout());
GridBagConstraints gbc=new GridBagConstraints();
gbc.anchor=GridBagConstraints.WEST;
gbc.insets=new Insets(2,2,2,2);
p1.setBorder(BorderFactory.createTitledBorder("构造一般的JTextArea"));
JLabel l1=new JLabel("一:");
JLabel l2=new JLabel("二:");
JLabel l3=new JLabel("三:");
JLabel l4=new JLabel("四:");
JTextArea t1=new JTextArea();
JTextArea t2=new JTextArea(2,8);
JTextArea t3=new JTextArea("JTextArea3");
JTextArea t4=new JTextArea("JTextArea4",5,10);
t1.setText("JTextArea1");//setText()方法会将原来的内容清除
t2.append("JTextArea2");//append()方法会将设置的字符串接在原来JTextArea内容文字之后.
t4.setLineWrap(true);//设置换行
gbc.gridy=1;
gbc.gridx=0;
p1.add(l1,gbc);
gbc.gridx=1;
p1.add(t1,gbc);
gbc.gridy=2;
gbc.gridx=0;
p1.add(l2,gbc);
gbc.gridx=1;
p1.add(t2,gbc);
gbc.gridy=3;
gbc.gridx=0;
p1.add(l3,gbc);
gbc.gridx=1;
p1.add(t3,gbc);
gbc.gridy=4;
gbc.gridx=0;
p1.add(l4,gbc);
gbc.gridx=1;
p1.add(t4,gbc);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
在JTextArea中我们可以使用setTabSize()方法设置[Tab]键的跳离距离,或是setFont()方法设置字体。当我们输入的文字超过
JTextArea的右边界及下边界时,会看不到接下来打的内容,那该怎么办呢?你可以使用JScrollPane使JTextArea具备滚动的能力,
或是搭配setLineWrap()方法就能让文字自动换行。JTextArea还提供一个setWrapStyleWord()方法,可以让换行的时候不会造成断
字的现象,这在Word或使用OutLook写信时都可以看到这个效果。例如我们在行尾中输入“自动换行”四个字,但此行最多只能在容
纳两个字,因此JTextArea会将此四个字均移到下一行,不会造成“自动”在上行,"换行"在下行的情形。这在处理英文输入上较为
重要,因为setWrapStyleWord()是利用空白当作是一个字输入的结果。我们来看下面的范例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextArea2{
public static void main(String[] args){
JFrame f=new JFrame("JTextArea2");
Container contentPane=f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1=new JPanel();
p1.setLayout(new GridLayout(1,1));
p1.setBorder(BorderFactory.createTitledBorder("构造TextArea-使用GridLayout,加ScrollBar"));
JTextArea t1=new JTextArea(5,25);
t1.setTabSize(10);
t1.setFont(new Font("标楷体",Font.BOLD,16));
t1.setLineWrap(true);//激活自动换行功能
t1.setWrapStyleWord(true);//激活断行不断字功能
p1.add(new JScrollPane(t1));//将JTextArea放入JScrollPane中,这样就能利用滚动的效果看到输入超过JTextArea高度的
//文字.
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
我们再举一个例子,使JTextArea具有copy、paste、cut的功能:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextArea3 implements ActionListener{
JTextArea textarea=null;
JButton b1,b2,b3;
public JTextArea3(){
JFrame f=new JFrame("JTextArea3");
Container contentPane=f.getContentPane();
contentPane.setLayout(new BorderLayout());
textarea=new JTextArea(10,15);
JScrollPane scrollPane=new JScrollPane(textarea);
JPanel panel=new JPanel();
panel.setLayout(new GridLayout(1,3));
b1=new JButton("Copy");
b1.addActionListener(this);
b2=new JButton("Paste");
b2.addActionListener(this);
b3=new JButton("Cut");
b3.addActionListener(this);
panel.add(b1);
panel.add(b2);
panel.add(b3);
contentPane.add(scrollPane,BorderLayout.CENTER);
contentPane.add(panel,BorderLayout.SOUTH);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String[] args){
new JTextArea3();
}
public void actionPerformed(ActionEvent e){
if (e.getSource()==b1){
textarea.copy();
}
if (e.getSource()==b2){
textarea.paste();
}
if (e.getSource()==b3){
textarea.cut();
}
}
}
9-4-2:JTextArea的事件处理:
由于JTextArea是一个二维的输入组件,因此[Enter]键在JTextArea中代表的意义只是单纯的换行字符而不再是一个事件驱动的
切入点。那么我们该 如何来处理JTextArea的事件呢?还记得我们在前面介绍过Listener的机制吗?相同的,我们一样需要使用
Listener的机制来处理发生在JTextArea中的事件,只是不再是以前提到的ActionListener了。在JTextArea中使用的Listener有两
种,一个是UndoableEditListener,另一个是DocumentListener.UndoableEditListener interface是负责纪录JTextArea中所有操作
发生的顺序并且可以运行还原上一步的功能。这个功能在目前的软件中应用相当广泛,如文书编辑软件Word中的复原功能、小画家
中的复原功能,相信大家都有使用过。DocumentListener interface则是纪录发生在JTextArea中所有的事件(如键入字符、删除
字符、剪下、贴上)并将所有的事件以树状的层次式结构组织起来;也就是说当JTextArea中的内容有任何变动时,会DocumentEvent
,此时必须使用DocumentListener接口中的方法来处理此事件。我们来看下面这个范例,使JTextArea具有复原的功能:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*由于会使用到复原和事件驱动功能,因此需要将javax.swing.undo和javax.swing.event两个package包含进来
*/
import javax.swing.undo.*;
import javax.swing.event.*;
/*JTextArea4类继承JFrame类并实作UndoableEditListener interface.实作UndoableEditListener interface就必须要编写其中的
*undoableEditHappened().
*/
public class JTextArea4 extends JFrame implements UndoableEditListener{
private UndoableEdit edit;
private JTextArea jta;
private JTextArea message;
private JMenuItem undoitem;
private JMenuItem redoitem;
public JTextArea4(){
super("JTextArea4");
jta = new JTextArea();
jta.getDocument().addUndoableEditListener(this);//将JTextArea加入UndoableEditListener.
message = new JTextArea();
message.setEditable(false);//利用setEditable()方法将另一个JTextArea设置为不可编辑.
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1,1));
p1.setBorder(BorderFactory.createTitledBorder("Edit Area"));
p1.add(new JScrollPane(jta));
//--begin:分别将两个JTextArea通过JPanel放到JFrame中。
JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(1,1));
p2.setBorder(BorderFactory.createTitledBorder("Message"));
p2.add(new JScrollPane(message));
getContentPane().setLayout(new GridLayout(2,1));
getContentPane().add(p1);
getContentPane().add(p2);
//--end
//建立目录菜单并放置到JFrame中.
JMenuBar bar = new JMenuBar();
JMenu theMenu = new JMenu("Edit");
undoitem = new JMenuItem("Undo");
redoitem = new JMenuItem("Redo");
theMenu.add(undoitem);
theMenu.add(redoitem);
bar.add(theMenu);
updateMenuItem();//构造目录菜单
setJMenuBar(bar);
setSize(300,300);
//采用inner class方式,分别构造菜单选项被点选后的运行操作。分别调用undo(),redo()方法来完成.
undoitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
edit.undo();
updateMenuItem();//运行undo功能
message.append("- Undo -\n");
}
});
redoitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
edit.redo();
updateMenuItem();//运行redo功能
message.append("- Redo -\n");
}
});
}//end of JTextArea4()
public void undoableEditHappened(UndoableEditEvent ev){
StringBuffer buf = new StringBuffer(200);
/*当用户在Text Area中有所操作时,就可以用getEdit()方法取得UndoableEdit对象,此对象纪录着刚刚用户的操作,因
*此可由些对象的undo()或redo()达到取消或复原的功能.
*/
edit = ev.getEdit();
buf.append("undoableEdit:");
buf.append(edit.getPresentationName());
buf.append("\n");
message.append(buf.toString());
updateMenuItem();
}//end of undoableEditHappened()
//判断是否此时是否可以运行undo或redo的功能,并且改变目录菜单的状态值.
public void updateMenuItem(){
if (edit != null){
undoitem.setEnabled(edit.canUndo());
redoitem.setEnabled(edit.canRedo());
undoitem.setText(edit.getUndoPresentationName());
redoitem.setText(edit.getRedoPresentationName());
}else{
undoitem.setEnabled(false);
redoitem.setEnabled(false);
undoitem.setText("Undo");
redoitem.setText("Redo");
}
}//end of updateMenu()
public static void main(String args[]) {
JFrame f = new JTextArea4();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.show();
}//end of main()
}//end of class JTextArea4
我们在前面提到Enter键在JTextArea中不再是事件驱动的切入点,因此我们要利用Listener的机制来控制JTextArea的事件驱动
。但是,我们要怎么样知道在JTextArea中的数据内容呢?这就要了解JTextArea的存储模式了,JTextArea把输入区内的每一行当成
一个独立的单无(Element),并依照Document内规划的树状结构来存储,也就是说在JTextArea的第一行属于Element 0、第二行属于
Element 1、第三行属于Element 2等等。不论我们在费心的去处理。接下来我们来看看,Element和DocumentListener interface的
用法。我们改写JTextArea4.java加入DocumentListener,将程序存储为JTextArea5.java.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.undo.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class JTextArea5 extends JFrame implements UndoableEditListener,DocumentListener{
private UndoableEdit edit;
private JTextArea jta;
private JTextArea message;
private JMenuItem undoitem;
private JMenuItem redoitem;
public JTextArea5(){
super("JTextArea");
jta=new JTextArea();
jta.getDocument().addUndoableEditListener(this);
jta.getDocument().addDocumentListener(this);
message = new JTextArea();
message.setEditable(false);
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1,1));
p1.setBorder(BorderFactory.createTitledBorder("Edit Area"));
p1.add(new JScrollPane(jta));
JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(1,1));
p2.setBorder(BorderFactory.createTitledBorder("Message"));
p2.add(new JScrollPane(message));
getContentPane().setLayout(new GridLayout(2,1));
getContentPane().add(p1);
getContentPane().add(p2);
JMenuBar bar = new JMenuBar();
JMenu theMenu = new JMenu("Edit");
undoitem = new JMenuItem("Undo");
redoitem = new JMenuItem("Redo");
theMenu.add(undoitem);
theMenu.add(redoitem);
bar.add(theMenu);
updateMenuItem();
setJMenuBar(bar);
setSize(300,300);
undoitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
edit.undo();
updateMenuItem();
message.append("- Undo -\n");
}
});
redoitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
edit.redo();
updateMenuItem();
message.append("- Redo -\n");
}
});
} //end of JTextArea5
public void undoableEditHappened(UndoableEditEvent ev){
StringBuffer buf = new StringBuffer(200);
edit = ev.getEdit();
buf.append("undoableEdit:");
buf.append(edit.getPresentationName());
buf.append("\n");
message.append(buf.toString());
updateMenuItem();
}//end of undoableEditHappened()
public void updateMenuItem(){
if (edit != null){
undoitem.setEnabled(edit.canUndo());
redoitem.setEnabled(edit.canRedo());
undoitem.setText(edit.getUndoPresentationName());
redoitem.setText(edit.getRedoPresentationName());
}else{
undoitem.setEnabled(false);
redoitem.setEnabled(false);
undoitem.setText("Undo");
redoitem.setText("Redo");
}
}//end of updateMenu()
public void showDE(DocumentEvent de){
StringBuffer debuf=new StringBuffer(100);
debuf.append(de.getType());
debuf.append("Offset:");
debuf.append(de.getOffset());
debuf.append("Length:");
debuf.append(de.getLength());
Element Eroot=jta.getDocument().getDefaultRootElement();
DocumentEvent.ElementChange Echange=de.getChange(Eroot);
if (Echange==null) {
debuf.append("(No Element Change)");
}else{
debuf.append("Element Change:index");
debuf.append("Echange.getIndex()");
}
debuf.append("\n");
message.append(debuf.toString());
}
public void changedUpdate(DocumentEvent de){
showDE(de);
}
public void insertUpdate(DocumentEvent de){
showDE(de);
}
public void removeUpdate(DocumentEvent de){
showDE(de);
}
public static void main(String[] args){
JFrame f=new JTextArea5() ;
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
f.show();
}
}
9-5:使用JEditorPane组件:
JEditorPane的类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.text.JTextComponent
--javax.swing.JEditorPane
JEditorPane继承JTextComponent类,因此它也可以使用JTextComponent抽象类里面的方法。JEditorPane的最主要功能在于展
现不同类型的文件格式内容。JEditorPane支持的文件类型有三种:第一种是纯文本类型,其类型的表示法为"text/plain",这种类型
的文件就是我们最常使用的txt文件,这类型的文件可以用记事本或WordPad等文书编辑软件来编辑。第二种是RTF类型,其表示法
为"text/rtf",这种类型的文件特色是能对文字内容做字体缩放、变形、上色等特殊效果。第三类是HTML类型,也就是我们在网络上
所浏览的网页类型,其表示法为"text/html",这类文件的特色相信大家都非常的清楚,除了在对字体效果的表现之外还具有在文件
内加入图片、超级链接等相关功能。但是JEditorPane并不是一个全功能的Web Browser,它仅能支持简单的HTML语法.JEditorPane支
持HTML类型的文件最主要的用途是用来制作在线辅助说明文件。
JEditorPane构造函数:
JEditorPane():建立一个新的JEditorPane.
JEditorPane(String url):以详细的URL字符串为基础来建立一个JEditorPane。
JEditorPane(String type,String text):建立一个被指定字符串text并指定初始化JEditorPane的类型。
JEditorPane(URL initialPage):以详细的URL字符串当作输入值来建立一个JEditorPane.
9-5-1:构造JEditorPane组件:
我们将一个HTML文件放在构造完成的JEditPane中:
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.awt.event.*;
public class JEditorPane1{
public static void main(String[] args){
JEditorPane editPane=null;
try{
File file=new File("docs/JEditorPane_1.html");
String str=file.getAbsolutePath();//取得文件位置的绝对路径
str="file:"+str;//将绝对路径合成一完整的输入字符串
/*利用setPage()方法将字符串中路径所指的文件加载JEditorPane.
*在setPage()方法中,输入的数据是String类型的字符串,其实这样的构造方式等同于利用JEditorPane的另一个构造函数
*JEditorPane(String str)来构造。因此如果我们将下面两行程序改写如下行:
* editPane=new JEditorPane(str);
*会得到相同的效果,所以我们就不再对此种构造方式再多加说明.
*/
editPane=new JEditorPane();//构造一个空的JEditorPane
editPane.setPage(str);
}catch(IOException ioe){
ioe.printStackTrace(System.err);
System.exit(0);
}
/*利用setEditable()方法将JEditorPane设为不可编辑.请注意,这行是相当重要的,若是我们将这个方法设为true,我们将会
*失去HTML文件本身的特性,如超级链接的功能等等。因此我们在使用下面JEditorPane2的例子时,一般都会将编辑的功能取
*消(设置false).目前这个超级链接功能并没有作用,这部份将在JEditorPane的事件处理中介绍.
*/
editPane.setEditable(false);
JFrame f=new JFrame("JEditorPane1");
f.setContentPane(new JScrollPane(editPane));
f.setSize(200,200);
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
我们在前面提到JEditorPane支持三种类型的文件格式,在上面的例子里我们并没有看到设置文件格式的步骤,那是因为在上面
的构造方法中系统会依照输入文件名称来自动判别文件类型。若是我们想要自己设置文件类型可利用setContentType()方法,或是
直接在JEditorPane构造函数中设置。如下面这个范例:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
public class JEditorPane2{
public static void main(String[] args){
String str=new String("This is a test.\nthis is Line2!\nThis is Line 3!");
JEditorPane editPane=new JEditorPane("text/plain",str);
editPane.setEditable(false);
JFrame f=new JFrame("JEditorPane2");
f.setContentPane(new JScrollPane(editPane));
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
以URL类当作JEditPane的参数来构造,但是要注意的地方是使用这种方式来构造里,计算机要连接上局域网络或网际网络不然
程序会找不到URL指定的位置而产生Exception使得程序无法动作.我们来看下面的范例吧!
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class JEditorPane3{
public static void main(String[] args){
JEditorPane editPane=null;
try{
URL address=new URL("http://www.sina.com.cn");
editPane=new JEditorPane(address);
}catch(MalformedURLException e){
System.out.println("Malformed URL:"+e);
}catch(IOException e){
System.out.println("IOException:"+e);
}
editPane.setEditable(false);
JFrame f=new JFrame("JEditorPane3");
f.setContentPane(new JScrollPane(editPane));
f.setSize(200,250);
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
9-5-2:JEditorPane的事件处理:
在JEditorPane文件中最常用到事件处理的部份就是HTML文件,那是因为HTML文件本身具有超级链接的功能来做文章链接的用途
。大家还记得我们这一节的第一个范例吗?我们不是加载了一份HTML文件到JEditorPane中吗?虽然画面上都有确实的将超级链接和
图片信息展现出来,可是你有没有发现当你想要点选超级链接的地方时却没有反应呢?那是因为我们并没有在JEditorPane中加入事
件处理机制的缘故。我们改写JEditorPane1.java加入事件处理机制,使JEditorPane具有正常的超链接功能。如下范例:
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.awt.event.*;
public class JEditorPane4{
public static void main(String[] args){
JEditorPane editPane = null;
try{
File thef = new File ("docs/JEditorPane_1.html");
String str = thef.getAbsolutePath();
str = "file:"+str;
editPane = new JEditorPane();
editPane.setPage(str);
}
catch(IOException ioe){
ioe.printStackTrace(System.err);
System.exit(0);
}
editPane.setEditable(false);
final JEditorPane thePane = editPane;
//采用inner class的方式编写触发超级链接事件时的对应操作类
editPane.addHyperlinkListener(new HyperlinkListener(){
public void hyperlinkUpdate(HyperlinkEvent hle){//覆写hyperlinkUpdate()方法,当超级链接事件触发时会进入这
//个区段运行.
try{
//判断是否为超级链接运行操作。若操作为真,则将新的HTML文件放到JEditorPane中,
//操作为(thePane.setPage(hle.getURL());)
if (hle.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
}
catch(IOException ioe){
ioe.printStackTrace(System.err);
}
}
});
JFrame f = new JFrame("JEditorPane4");
f.setContentPane(new JScrollPane(editPane));
f.setSize(200,250);
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}//end of main()
}//end of class JEditPane1
另外,若是我们是在纯文字模式(Plain Text)或RTF模式(RTF Text)下需要事件处理模式又该怎么办呢?你还记得我们在
JTextArea中是如何加入事件处理模式的吗?没错!在JEditorPane中也是相同的做法,也就是利用DocumentListener interface的
机制来处理,由于做法相当类似,因此我们就不在这里重复的说明.
9-6:使用JTextPane组件:
JTextPane的类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.text.JTextComponent
--javax.swing.JEditorPane
--javax.swing.JTextPane
我们在前面有介绍过JTextArea类,虽然JTextArea在某些功能上已经能够满足我们的需求,但是当我们想再加入更多的变化时
(如文字加入色彩、插入图片...)就会发现JTextArea类根本无法做到。要做到这些功能,我们必须使用JEditorPane的子类:
JTextpane。JTextPane提供了许多对文字的处理,如改变颜色、字体缩放、文字风格、加入图片等。我们先来看看JTextPane的构
造方法:
JTextPane构造函数:
JTextPane():建立一个新的JTextPane.
JTextPane(StyledDocument doc):以指定的文件模式建立一个新的JTextPane.
9-6-1:JTextPane的特性:
相信大家都有用过Word来写过报告或文章,那么你一定会知道我们在Word中可以对文章中的文字做很多的变化,这些变化都是
属于文字的“属性”变化。由于在JTextPane中产生的效果几乎都是由属性的变化而来,所以改变属性的类组件在JTextpane中是少
不了的。因此在介绍如何构造JTextPane之前,我们要先介绍两个在JTextPane中常用到属性类:
SimpleAttributeSet和StyleConstant.
属性的变化原本是利用AttributeSet interface来处理的,但是这个interface中包含了太多的方法,若是我们直接实作
AttributeSet interface那就需要实作此interface里所有的方法,这对编写程序来说并不是一个很理想的做法;而java另外提供了
SimpleAttributeSet类,实作了AttributeSet interface.因此,只要我们直接使用SimpleAttributeSet类就能具备AttributeSet
interface的所有功能,而不用一个个的编写AttributeSet中的方法。另外StyleConstant类则是提供AttributeSet类许多常用的属
性键值(Attribute Key)和方法来设置或取得JTextPane内容的状态。在StyleConstant类中包含了许多的常用的属性设置,包括本文
与边界空白区段设置、文字字体/大小/类型设置、背景颜色设置等。利用这两个类来辅助设计JTextPane便使JTextPane有更丰富
的内容变化。
JTextPane是专为文字和版面处理设计的组件。JTextPane对可输入区域内容的设计概念是一个类似Word的设计概念,也就是说在
JTextPane中的文字结构是有段落概念的。“段落”的概念就是以[Enter]键为每一段落的分界点,每按一次[Enter]键就增加一个段
落。记得我们在JTextArea中提过的Element存储模式吗?在JTextPane中也是采用相同的做法,但是差别在于规划存储的方式不同。
在JTextArea中并没有分段落,只是单纯的以[Enter]键当作存储成两个Element的分界。而在JTextPane则是以整个编辑区哉为根节
点,每个段落为枝节点 ,每个字符为叶节点来存储文件。也因为JTextPane是采用这样的方式来存储数据,因此在JTextPane中也可
以像Word文件一样将各个段落设置成不同的属性,如第一段为斜体字、字体大小为14号字、粗体字,第二段为斜体字、字体颜色为
蓝色、向左边界缩排2厘米等;另外,我们还可以设置JTextPane编辑区内输入的文字与各个边界间的距离。由这些功能看来,对于一
个TextComponent来说JTextPane是一个具有相当多实用功能的组件。
9-6-2:构造JTextPane组件:
在了解JTextPane的各项特性之后,我们现在马上来看JTextPane可以呈现什么样的效果,在下面这个例子中我们将对JTextPane
区域内的文字设置颜色、粗斜体、与底线等相关属性。
import javax.swing.*;
import javax.swing.text.*;
import java.awt.event.*;
import java.awt.*;
public class JTextPane1{
private JTextPane textPane;
public JTextPane1(){
textPane=new JTextPane();
textPane.setBackground(Color.black);
textPane.setEditable(false);
}
public void setYellow_Bold_20(String str){
SimpleAttributeSet attrset=new SimpleAttributeSet();
StyleConstants.setForeground(attrset,Color.yellow);
StyleConstants.setBold(attrset,true);
insert(str,attrset);
}
public void setBlue_Italic_Bold_22(String str){
SimpleAttributeSet attrset=new SimpleAttributeSet();
StyleConstants.setForeground(attrset,Color.blue);
StyleConstants.setItalic(attrset,true);
StyleConstants.setFontSize(attrset,24);
insert(str,attrset);
}
public void setRed_UnderLine_Italic_24(String str){
SimpleAttributeSet attrset=new SimpleAttributeSet();
StyleConstants.setForeground(attrset,Color.red);
StyleConstants.setUnderline(attrset,true);
StyleConstants.setItalic(attrset,true);
StyleConstants.setFontSize(attrset,24);
insert(str,attrset);
}
//这个方法最主要的用途是将字符串插入到JTextPane中。
public void insert(String str,AttributeSet attrset){
Document docs=textPane.getDocument();//利用getDocument()方法取得JTextPane的Document instance.0
str=str+"\n";
try{
docs.insertString(docs.getLength(),str,attrset);
}catch(BadLocationException ble){
System.out.println("BadLocationException:"+ble);
}
}
public Component getComponent(){
return textPane;
}
public static void main(String[] args){
JTextPane1 pane=new JTextPane1();
pane.setYellow_Bold_20("This is Line 1,yellow,Bold,Size 20");
pane.setBlue_Italic_Bold_22("This is Line 2,blue,Italic,Bold,Size 22");
pane.setRed_UnderLine_Italic_24("This is Line 3,red,UnderLine,Italic,Size 24");
JFrame f=new JFrame("JTextPane1");
f.getContentPane().add(pane.getComponent());
f.setSize(450,180);
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
若你想在JTextPane上置入图形或其他组件(如表格或按钮),你可以分别使用JTextPane所提供的insetIcon()与insertComponent()
方法来达到这个效果。
至于另外一种JTextPane的构造方式和JTextArea一样,差别在于JTextArea是采用Document interface而JTextPane是采用
9-1:认识Swing的文字输入组件:
Swing与文字输入有关的组件分别是JTextField、JPasswordField、JTextArea、JEditorPane与JTextPane.JTextField与
JPasswordField为单行的文本编辑器;JTextArea为多行的文本编辑器;JEditorPane可显示多种文件格式;JTextPane可设置文件各种
样式。这些组件都继承了JTextComponent为类,它们之间的关系如下:
|--JTextField--JPasswordField
|
JTextComponent|
|--JTextArea
|
|--JEditorPane--JTextPane
JTextComponent提供了相当多实用的方法,可使处理输入组件更为方便,例如copy(),paste(),cut(),getText(),setText()等
相当直觉的方法:另外还有设置是否可编辑(setEditable()),setSelectionEnd(),setSelectionStart())、设置或取得光标位置
(getCaretPosition(),setCaretPosition())等等,这些相当常用的方法你都可以在JTextComponent类中找到.
Swing的文字输入组件均以Document来当作数据模式,当输入组件的内容有所改变时,均是更改此Document的内容。因此你可
以将同一个Document内容以不同的输入组件来显示,这就是MVC概念的一个基本应用。Document为一个interface,你可以实现此界
面或利用java提供的默认类来构造文字输入组件。
|---implements-->AbstractDocument---extends->PlainDocument
|
Document |
|
|--extends-->StyleDocument---implements--->DefaultStyleDocument---extends--->HTMLDocument
AbstractDocument----extends-->DefaultStyleDocument
PlainDocument是一个实体类,已经实现了AbstractDocument与Document中的所有抽象方法,你可以用此类直接构造出JTextField
、JPasswordField与JTextArea组件;相同的,你可以使用DefaultStyledDocument构造出JTextPane组件,这些关系我们均会在下面
各节中提到。下面我们开始介绍各种文字输入组件的使用:
9-2:使用JTextField组件:
JTextField继承JTextComponent类,因此它也可以使用JTextComponent抽象类里面许多好用的方法,如copy(),paste(),setText()
,isEditable()等等。我们可以在很多地方使用JTextField,JTextField是一个单行的输入组件,那么有没有多行的输入组件呢?有
的,就是JTextArea,我们将在后面介绍.
JTextField构造函数:
JTextField()
JTextField(Document doc,String text,int columns):使用指定的文件存储模式建立一个新的JTextField并设置其初始化字符串和
字段长度。
JTextField(int columns):建立一个新的JTextField并设置其初始字段长度。
JTextField(String text):建立一个新的JTextField并设置其初始字字符串。
JTextField(String text,int columns):建立一个新的JTextField并设置其初始字符串和字段长度.
9-2-1:构造一般的JTextField组件:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextField1{
public static void main(String args[]) {
JFrame f = new JFrame("JTextField1");
Container contentPane = f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
p1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST; //设定Layout的位置
gbc.insets = new Insets(2,2,2,2); //设定与边界的距离(上,左,下,右)
p1.setBorder(BorderFactory.createTitledBorder("您的基本数据"));
JLabel l1 = new JLabel("姓名:");
JLabel l2 = new JLabel("性别:");
JLabel l3 = new JLabel("身高:");
JLabel l4 = new JLabel("体重:");
JTextField t1 = new JTextField();
JTextField t2 = new JTextField(2);
JTextField t3 = new JTextField("175cm");
JTextField t4 = new JTextField("50kg太瘦了",10);
gbc.gridy=1;
gbc.gridx=0;
p1.add(l1,gbc);
gbc.gridx=1;
p1.add(t1,gbc);
gbc.gridy=2;
gbc.gridx=0;
p1.add(l2,gbc);
gbc.gridx=1;
p1.add(t2,gbc);
gbc.gridy=3;
gbc.gridx=0;
p1.add(l3,gbc);
gbc.gridx=1;
p1.add(t3,gbc);
gbc.gridy=4;
gbc.gridx=0;
p1.add(l4,gbc);
gbc.gridx=1;
p1.add(t4,gbc);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
9-2-2:利用Document构造JTextField:
Document是一个interface,主要的功能是定义一些方法,让我们在使用所有与Text相关的组件时,能够将输入文字的内容加以
结构化或规格化。将文字内容结构化又是什么呢?举例来说,就好像一本书的内容,它的结构一定会有各个大章,在各章中又会分
成许多小节,小节内会再有各个小重点等等,这样的树状组件结构就是结构化的一种。由于这个interface定义了10几个方法,但是
在这里我们所会用到的只有少数几个方法,为了不让大家混淆,因此我们先列出这个interface常被使用到的方法,有兴趣的可查阅
java api文件:
void addDocumentListener(DocumentListener listener):增加DocumentListener,使组件具有处理DocumentEvent功能。
void addUndoableEditListener(UndoableEditListener listener):增加UndoableEditListener,使组件具有处理UndoableEditEv
Ent功能,当文件中的内容被修改时自动记忆可以被复原的内容。
String getText(int offset,int length):取得document中的文字内容。
void insertString(int offset,String str,AttributeSet a):将字符串加入到Text组件的内容中。
void removeDocumentListener(DocumentListener listener):移除DocumentListener.
void removeUndoableEditListener(UndoableEditListener listener):移除UndoableEditListener,使复原功能失效。
还记得我们一开始在介绍JTextField时所提到的构造函数吗?其中有一个JTextField的构造函数是这样子的:
JTextField(Document doc,String text,int columns):使用指定的文件存储模式建立一个新的JTextField并设置其初始
化字符串和字段长度。
因此我们必须实作Document所有的方法,才能利用Document构造出JTextField,这样的做法有点麻烦,因为我们之前有提到Document
的方法有数十种,但是我们要用到的却只有其中几种,若是要将全部的方法实作那是相当费时的做法。大家还记行我们前几章介绍
JList时,利用继承AbstractListModel的抽象类来构造JList吗?由于抽象类已经了许多接口的方法,所以当我们继承这个抽象类后
便不需要实作这些方法。同样的java在这里也提供了一个AbstractDocument的抽象类来供我们使用。不过在这里我们并不是要使用
AbstractDocument,因为java在这部份已经提供了一个实体类:PlainDocument.这个实体类继承AbstractDocument,也就是具备了所
有AbstractDocument的方法,所以我们只要直接继承PlainDocument这个实体类就能利用Document来构造JTextField.这种概念跟
JList或是JTable的模式结构均是相同的。我们来看下面的范例:
JTextField3.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextField3{
public static void main(String args[]) {
JFrame f = new JFrame("JTextField3");
Container contentPane = f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
//p1.setLayout(new GridLayout(4,2));
p1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST; //设定Layout的位置
gbc.insets = new Insets(2,2,2,2); //设定与边界的距离(上,左,下,右)
p1.setBorder(BorderFactory.createTitledBorder("您的基本数据"));
JLabel l1 = new JLabel("姓名:");
JLabel l2 = new JLabel("性别:");
JLabel l3 = new JLabel("身高:");
JLabel l4 = new JLabel("体重:");
JTextField t1 = new JTextField(new JTextField3_FixedLengthDocument(10),"",10);
JTextField t2 = new JTextField(new JTextField3_FixedLengthDocument(1),"",2);
JTextField t3 = new JTextField(new JTextField3_FixedLengthDocument(5),"",5);
JTextField t4 = new JTextField(new JTextField3_FixedLengthDocument(5),"",5);
gbc.gridy=1;
gbc.gridx=0;
p1.add(l1,gbc);
gbc.gridx=1;
p1.add(t1,gbc);
gbc.gridy=2;
gbc.gridx=0;
p1.add(l2,gbc);
gbc.gridx=1;
p1.add(t2,gbc);
gbc.gridy=3;
gbc.gridx=0;
p1.add(l3,gbc);
gbc.gridx=1;
p1.add(t3,gbc);
gbc.gridy=4;
gbc.gridx=0;
p1.add(l4,gbc);
gbc.gridx=1;
p1.add(t4,gbc);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
JTextField3_FixedLengthDocument.java
import javax.swing.*;
import javax.swing.text.*;
import java.awt.Toolkit;
public class JTextField3_FixedLengthDocument extends PlainDocument{
private int maxLength;
public JTextField3_FixedLengthDocument(int maxLength){
this.maxLength = maxLength;
}
public void insertString(int offset,String str,AttributeSet att) throws BadLocationException
{
if ( getLength() + str.length() > maxLength ){
Toolkit.getDefaultToolkit().beep();
}else{
super.insertString(offset,str,att);
}
}
}
9-2-3:JTextField的事件处理:
在JTextField类中有addActionListener()方法,可以检测到用户是否在JTextField上按下Enter键,就如同前面所介绍JButton按
下按钮时所产生的事件(Event)一样,我们来看下面这个范例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextField4{
public static void main(String[] args){
JFrame f=new JFrame("JTextField4");
Container contentPane=f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1=new JPanel();
p1.setLayout(new GridLayout(2,2));
p1.setBorder(BorderFactory.createTitledBorder("JTextField事件处理范例"));
JLabel l1=new JLabel("输入");
JLabel l2=new JLabel("输入后,按下Enter==>");
final JLabel l3=new JLabel("");
final JTextField t1=new JTextField();
t1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
l3.setText(t1.getText());
}
});
p1.add(l1);
p1.add(t1);
p1.add(l2);
p1.add(l3);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
9-3:使用JPasswordField组件:
JPasswordField的类层次结构图:
java.lang.Object
--java.awt.Component
--javax.swing.JComponent
--javax.swing.text.JTextComponent
--javax.swing.JTextField
--javax.swing.JPasswordField
一般我们在网络中填写登录密码时,密码都会显示"*"号代表用户输入的字段,这样可避免用户输入的密码信息被旁人所偷窥。
而Swing中的JPasswordField就可以提供这样的功能。JPasswordField继承JTextField类,因此它也可以使用JTextField类里面许多
好用的方法,如addActionListener()、removeActionListener()、setHorizontalAlignment()等等。如同JTextField一样
JPasswordField也是一个单行的输入组件,不同的是JPasswordField多了屏蔽(Mask)的功能,也就是说在JPasswordField中的字符
都会以单一种的字符类型表现出来。
在使用JPasswordField之前,我们先看看它的构造函数:
JPasswordField()
JPasswordField(Document doc,String text,int columns):使用指定的文件存储模式建立一个新的JPasswordField并设置其初始化
字符串和字段长度。
JPasswordField(int columns):建立一个新的JPasswordField并设置其初始字段长度。
JPasswordField(String text):建立一个新的JPasswordField并设置其初始字字符串。
JPasswordField(String text,int columns):建立一个新的JPasswordField并设置其初始字符串和字段长度.
9-3-1:构造一般的JPasswordField组件:
JPasswordField的构造函数和JTextField的构造函数几乎一模本样,唯一不同的是在JPasswordField输入时字符会以屏蔽字符的
类型表示。我们来看下面这个范例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPasswordField1{
public static void main(String args[]) {
JFrame f = new JFrame("JPasswordField1");
Container contentPane = f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
//p1.setLayout(new GridLayout(4,2));
p1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST; //设定Layout的位置
gbc.insets = new Insets(2,2,2,2); //设定与边界的距离(上,左,下,右)
p1.setBorder(BorderFactory.createTitledBorder("您的基本数据"));
JLabel l1 = new JLabel("姓名:");
JLabel l2 = new JLabel("性别:");
JLabel l3 = new JLabel("身高:");
JLabel l4 = new JLabel("体重:");
JPasswordField t1 = new JPasswordField();
JPasswordField t2 = new JPasswordField(2);
JPasswordField t3 = new JPasswordField(" 175cm");
JPasswordField t4 = new JPasswordField(" 50kg太瘦了",10);
t1.setPreferredSize(t1.getPreferredSize());
gbc.gridy=1;
gbc.gridx=0;
p1.add(l1,gbc);
gbc.gridx=1;
p1.add(t1,gbc);
gbc.gridy=2;
gbc.gridx=0;
p1.add(l2,gbc);
gbc.gridx=1;
p1.add(t2,gbc);
gbc.gridy=3;
gbc.gridx=0;
p1.add(l3,gbc);
gbc.gridx=1;
p1.add(t3,gbc);
gbc.gridy=4;
gbc.gridx=0;
p1.add(l4,gbc);
gbc.gridx=1;
p1.add(t4,gbc);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
我们可以看到默认的字符串都以屏蔽字符"*"来表示,"*"字符是JPasswordField默认的屏蔽字符,我们可以利用JPasswordField
提供的setEchoChar()方法来改用其他字符来作为屏蔽字符。我们来看下面的范例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPasswordField2{
public static void main(String args[]) {
JFrame f = new JFrame("JPasswordField2");
Container contentPane = f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4,2));
p1.setBorder(BorderFactory.createTitledBorder("您的基本数据"));
JLabel l1 = new JLabel("姓名:");
JLabel l2 = new JLabel("性别:");
JLabel l3 = new JLabel("身高:");
JLabel l4 = new JLabel("体重:");
JPasswordField t1 = new JPasswordField(10);
JPasswordField t2 = new JPasswordField(2);
JPasswordField t3 = new JPasswordField(" 175cm");
JPasswordField t4 = new JPasswordField(" 50kg太瘦了",10);
t1.setEchoChar('#');
t2.setEchoChar('%');
t3.setEchoChar('&');
t4.setEchoChar('M');
p1.add(l1);
p1.add(t1);
p1.add(l2);
p1.add(t2);
p1.add(l3);
p1.add(t3);
p1.add(l4);
p1.add(t4);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
9-3-2:利用Document构造JPasswordField:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPasswordField3{
public static void main(String args[]) {
JFrame f = new JFrame("JPasswordField3");
Container contentPane = f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
//p1.setLayout(new GridLayout(4,2));
p1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST; //设定Layout的位置
gbc.insets = new Insets(2,2,2,2); //设定与边界的距离(上,左,下,右)
p1.setBorder(BorderFactory.createTitledBorder("您的基本数据"));
JLabel l1 = new JLabel("姓名:");
JLabel l2 = new JLabel("性别:");
JLabel l3 = new JLabel("身高:");
JLabel l4 = new JLabel("体重:");
JPasswordField t1 = new JPasswordField(new JPasswordField3_OnlyNumberDocument(10),"",10);
JPasswordField t2 = new JPasswordField(new JPasswordField3_OnlyNumberDocument(1),"",2);
JPasswordField t3 = new JPasswordField(new JPasswordField3_OnlyNumberDocument(5),"",5);
JPasswordField t4 = new JPasswordField(new JPasswordField3_OnlyNumberDocument(5),"",5);
gbc.gridy=1;
gbc.gridx=0;
p1.add(l1,gbc);
gbc.gridx=1;
p1.add(t1,gbc);
gbc.gridy=2;
gbc.gridx=0;
p1.add(l2,gbc);
gbc.gridx=1;
p1.add(t2,gbc);
gbc.gridy=3;
gbc.gridx=0;
p1.add(l3,gbc);
gbc.gridx=1;
p1.add(t3,gbc);
gbc.gridy=4;
gbc.gridx=0;
p1.add(l4,gbc);
gbc.gridx=1;
p1.add(t4,gbc);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
import javax.swing.*;
import javax.swing.text.*;
import java.awt.Toolkit;
public class JPasswordField3_OnlyNumberDocument extends PlainDocument{
private int maxLength;
int result;
public JPasswordField3_OnlyNumberDocument(int maxLength){
this.maxLength = maxLength;
}
public void insertString(int offset,String str,AttributeSet att) throws BadLocationException
{
for(int i=0;i<=9;i++){
result = Integer.toString(i).compareTo(str);
if (result == 0){ //是数字才处理
if ( getLength() + str.length() > maxLength ){
Toolkit.getDefaultToolkit().beep();
}else{
super.insertString(offset,str,att);
}
}
}
}
}
9-4:使用JTextArea组件:
JTextArea的类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JCompontent
--javax.swing.text.JTextComponent
--javax.swing.JTextArea
JTextArea继承JTextComponent为类,因此它也可以使用JTextComponent抽象类里面许多好用的方法,如compy(),paste(),
setText(),isEditable()等等。我们在前面有提到JTextArea是一个多行的输入组件,在这个组件中可以利用Enter来做换行的操作
。
在使用JTextArea之前,我们先看看JTextArea有哪些构造函数可以使用:
JTextArea的构造函数:
JTextArea():建立一个新的JTextArea.
JTextArea(Document doc):使用指定的文件存储模式建立一个新的JTextArea.
JTextArea(Document doc,String text,int row ,int columns):使用指定的文件存储模式建立一个新的JTextArea并设置其初始
字符串和列、字段长度。
JTextArea(int row,int columns):建立一个新的JTextArea并设置其初始列、字段长度。
JTextArea(String text):建立一个新的JTextArea并设置其初始字符串.
JTextArea(String text,int row,int columns):建立一个新的JTextArea并设置其初始字符串和列、字段长度。
9-4-1:构造JTextArea组件:
我们可以发现到JTextArea的构造函数和JTextField及JPasswordField的构造函数是相同雷同,而JTextArea多了一个字段的参数
值是因为JTextArea是二维的输入组件,在构造时不仅要设置字段长度也要设置行数。我们来看下面这个范例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextArea1{
public static void main(String[] args){
JFrame f=new JFrame("JTextArea1");
Container contentPane=f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1=new JPanel();
p1.setLayout(new GridBagLayout());
GridBagConstraints gbc=new GridBagConstraints();
gbc.anchor=GridBagConstraints.WEST;
gbc.insets=new Insets(2,2,2,2);
p1.setBorder(BorderFactory.createTitledBorder("构造一般的JTextArea"));
JLabel l1=new JLabel("一:");
JLabel l2=new JLabel("二:");
JLabel l3=new JLabel("三:");
JLabel l4=new JLabel("四:");
JTextArea t1=new JTextArea();
JTextArea t2=new JTextArea(2,8);
JTextArea t3=new JTextArea("JTextArea3");
JTextArea t4=new JTextArea("JTextArea4",5,10);
t1.setText("JTextArea1");//setText()方法会将原来的内容清除
t2.append("JTextArea2");//append()方法会将设置的字符串接在原来JTextArea内容文字之后.
t4.setLineWrap(true);//设置换行
gbc.gridy=1;
gbc.gridx=0;
p1.add(l1,gbc);
gbc.gridx=1;
p1.add(t1,gbc);
gbc.gridy=2;
gbc.gridx=0;
p1.add(l2,gbc);
gbc.gridx=1;
p1.add(t2,gbc);
gbc.gridy=3;
gbc.gridx=0;
p1.add(l3,gbc);
gbc.gridx=1;
p1.add(t3,gbc);
gbc.gridy=4;
gbc.gridx=0;
p1.add(l4,gbc);
gbc.gridx=1;
p1.add(t4,gbc);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
在JTextArea中我们可以使用setTabSize()方法设置[Tab]键的跳离距离,或是setFont()方法设置字体。当我们输入的文字超过
JTextArea的右边界及下边界时,会看不到接下来打的内容,那该怎么办呢?你可以使用JScrollPane使JTextArea具备滚动的能力,
或是搭配setLineWrap()方法就能让文字自动换行。JTextArea还提供一个setWrapStyleWord()方法,可以让换行的时候不会造成断
字的现象,这在Word或使用OutLook写信时都可以看到这个效果。例如我们在行尾中输入“自动换行”四个字,但此行最多只能在容
纳两个字,因此JTextArea会将此四个字均移到下一行,不会造成“自动”在上行,"换行"在下行的情形。这在处理英文输入上较为
重要,因为setWrapStyleWord()是利用空白当作是一个字输入的结果。我们来看下面的范例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextArea2{
public static void main(String[] args){
JFrame f=new JFrame("JTextArea2");
Container contentPane=f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1=new JPanel();
p1.setLayout(new GridLayout(1,1));
p1.setBorder(BorderFactory.createTitledBorder("构造TextArea-使用GridLayout,加ScrollBar"));
JTextArea t1=new JTextArea(5,25);
t1.setTabSize(10);
t1.setFont(new Font("标楷体",Font.BOLD,16));
t1.setLineWrap(true);//激活自动换行功能
t1.setWrapStyleWord(true);//激活断行不断字功能
p1.add(new JScrollPane(t1));//将JTextArea放入JScrollPane中,这样就能利用滚动的效果看到输入超过JTextArea高度的
//文字.
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
我们再举一个例子,使JTextArea具有copy、paste、cut的功能:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextArea3 implements ActionListener{
JTextArea textarea=null;
JButton b1,b2,b3;
public JTextArea3(){
JFrame f=new JFrame("JTextArea3");
Container contentPane=f.getContentPane();
contentPane.setLayout(new BorderLayout());
textarea=new JTextArea(10,15);
JScrollPane scrollPane=new JScrollPane(textarea);
JPanel panel=new JPanel();
panel.setLayout(new GridLayout(1,3));
b1=new JButton("Copy");
b1.addActionListener(this);
b2=new JButton("Paste");
b2.addActionListener(this);
b3=new JButton("Cut");
b3.addActionListener(this);
panel.add(b1);
panel.add(b2);
panel.add(b3);
contentPane.add(scrollPane,BorderLayout.CENTER);
contentPane.add(panel,BorderLayout.SOUTH);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String[] args){
new JTextArea3();
}
public void actionPerformed(ActionEvent e){
if (e.getSource()==b1){
textarea.copy();
}
if (e.getSource()==b2){
textarea.paste();
}
if (e.getSource()==b3){
textarea.cut();
}
}
}
9-4-2:JTextArea的事件处理:
由于JTextArea是一个二维的输入组件,因此[Enter]键在JTextArea中代表的意义只是单纯的换行字符而不再是一个事件驱动的
切入点。那么我们该 如何来处理JTextArea的事件呢?还记得我们在前面介绍过Listener的机制吗?相同的,我们一样需要使用
Listener的机制来处理发生在JTextArea中的事件,只是不再是以前提到的ActionListener了。在JTextArea中使用的Listener有两
种,一个是UndoableEditListener,另一个是DocumentListener.UndoableEditListener interface是负责纪录JTextArea中所有操作
发生的顺序并且可以运行还原上一步的功能。这个功能在目前的软件中应用相当广泛,如文书编辑软件Word中的复原功能、小画家
中的复原功能,相信大家都有使用过。DocumentListener interface则是纪录发生在JTextArea中所有的事件(如键入字符、删除
字符、剪下、贴上)并将所有的事件以树状的层次式结构组织起来;也就是说当JTextArea中的内容有任何变动时,会DocumentEvent
,此时必须使用DocumentListener接口中的方法来处理此事件。我们来看下面这个范例,使JTextArea具有复原的功能:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*由于会使用到复原和事件驱动功能,因此需要将javax.swing.undo和javax.swing.event两个package包含进来
*/
import javax.swing.undo.*;
import javax.swing.event.*;
/*JTextArea4类继承JFrame类并实作UndoableEditListener interface.实作UndoableEditListener interface就必须要编写其中的
*undoableEditHappened().
*/
public class JTextArea4 extends JFrame implements UndoableEditListener{
private UndoableEdit edit;
private JTextArea jta;
private JTextArea message;
private JMenuItem undoitem;
private JMenuItem redoitem;
public JTextArea4(){
super("JTextArea4");
jta = new JTextArea();
jta.getDocument().addUndoableEditListener(this);//将JTextArea加入UndoableEditListener.
message = new JTextArea();
message.setEditable(false);//利用setEditable()方法将另一个JTextArea设置为不可编辑.
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1,1));
p1.setBorder(BorderFactory.createTitledBorder("Edit Area"));
p1.add(new JScrollPane(jta));
//--begin:分别将两个JTextArea通过JPanel放到JFrame中。
JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(1,1));
p2.setBorder(BorderFactory.createTitledBorder("Message"));
p2.add(new JScrollPane(message));
getContentPane().setLayout(new GridLayout(2,1));
getContentPane().add(p1);
getContentPane().add(p2);
//--end
//建立目录菜单并放置到JFrame中.
JMenuBar bar = new JMenuBar();
JMenu theMenu = new JMenu("Edit");
undoitem = new JMenuItem("Undo");
redoitem = new JMenuItem("Redo");
theMenu.add(undoitem);
theMenu.add(redoitem);
bar.add(theMenu);
updateMenuItem();//构造目录菜单
setJMenuBar(bar);
setSize(300,300);
//采用inner class方式,分别构造菜单选项被点选后的运行操作。分别调用undo(),redo()方法来完成.
undoitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
edit.undo();
updateMenuItem();//运行undo功能
message.append("- Undo -\n");
}
});
redoitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
edit.redo();
updateMenuItem();//运行redo功能
message.append("- Redo -\n");
}
});
}//end of JTextArea4()
public void undoableEditHappened(UndoableEditEvent ev){
StringBuffer buf = new StringBuffer(200);
/*当用户在Text Area中有所操作时,就可以用getEdit()方法取得UndoableEdit对象,此对象纪录着刚刚用户的操作,因
*此可由些对象的undo()或redo()达到取消或复原的功能.
*/
edit = ev.getEdit();
buf.append("undoableEdit:");
buf.append(edit.getPresentationName());
buf.append("\n");
message.append(buf.toString());
updateMenuItem();
}//end of undoableEditHappened()
//判断是否此时是否可以运行undo或redo的功能,并且改变目录菜单的状态值.
public void updateMenuItem(){
if (edit != null){
undoitem.setEnabled(edit.canUndo());
redoitem.setEnabled(edit.canRedo());
undoitem.setText(edit.getUndoPresentationName());
redoitem.setText(edit.getRedoPresentationName());
}else{
undoitem.setEnabled(false);
redoitem.setEnabled(false);
undoitem.setText("Undo");
redoitem.setText("Redo");
}
}//end of updateMenu()
public static void main(String args[]) {
JFrame f = new JTextArea4();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.show();
}//end of main()
}//end of class JTextArea4
我们在前面提到Enter键在JTextArea中不再是事件驱动的切入点,因此我们要利用Listener的机制来控制JTextArea的事件驱动
。但是,我们要怎么样知道在JTextArea中的数据内容呢?这就要了解JTextArea的存储模式了,JTextArea把输入区内的每一行当成
一个独立的单无(Element),并依照Document内规划的树状结构来存储,也就是说在JTextArea的第一行属于Element 0、第二行属于
Element 1、第三行属于Element 2等等。不论我们在费心的去处理。接下来我们来看看,Element和DocumentListener interface的
用法。我们改写JTextArea4.java加入DocumentListener,将程序存储为JTextArea5.java.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.undo.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class JTextArea5 extends JFrame implements UndoableEditListener,DocumentListener{
private UndoableEdit edit;
private JTextArea jta;
private JTextArea message;
private JMenuItem undoitem;
private JMenuItem redoitem;
public JTextArea5(){
super("JTextArea");
jta=new JTextArea();
jta.getDocument().addUndoableEditListener(this);
jta.getDocument().addDocumentListener(this);
message = new JTextArea();
message.setEditable(false);
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1,1));
p1.setBorder(BorderFactory.createTitledBorder("Edit Area"));
p1.add(new JScrollPane(jta));
JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(1,1));
p2.setBorder(BorderFactory.createTitledBorder("Message"));
p2.add(new JScrollPane(message));
getContentPane().setLayout(new GridLayout(2,1));
getContentPane().add(p1);
getContentPane().add(p2);
JMenuBar bar = new JMenuBar();
JMenu theMenu = new JMenu("Edit");
undoitem = new JMenuItem("Undo");
redoitem = new JMenuItem("Redo");
theMenu.add(undoitem);
theMenu.add(redoitem);
bar.add(theMenu);
updateMenuItem();
setJMenuBar(bar);
setSize(300,300);
undoitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
edit.undo();
updateMenuItem();
message.append("- Undo -\n");
}
});
redoitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
edit.redo();
updateMenuItem();
message.append("- Redo -\n");
}
});
} //end of JTextArea5
public void undoableEditHappened(UndoableEditEvent ev){
StringBuffer buf = new StringBuffer(200);
edit = ev.getEdit();
buf.append("undoableEdit:");
buf.append(edit.getPresentationName());
buf.append("\n");
message.append(buf.toString());
updateMenuItem();
}//end of undoableEditHappened()
public void updateMenuItem(){
if (edit != null){
undoitem.setEnabled(edit.canUndo());
redoitem.setEnabled(edit.canRedo());
undoitem.setText(edit.getUndoPresentationName());
redoitem.setText(edit.getRedoPresentationName());
}else{
undoitem.setEnabled(false);
redoitem.setEnabled(false);
undoitem.setText("Undo");
redoitem.setText("Redo");
}
}//end of updateMenu()
public void showDE(DocumentEvent de){
StringBuffer debuf=new StringBuffer(100);
debuf.append(de.getType());
debuf.append("Offset:");
debuf.append(de.getOffset());
debuf.append("Length:");
debuf.append(de.getLength());
Element Eroot=jta.getDocument().getDefaultRootElement();
DocumentEvent.ElementChange Echange=de.getChange(Eroot);
if (Echange==null) {
debuf.append("(No Element Change)");
}else{
debuf.append("Element Change:index");
debuf.append("Echange.getIndex()");
}
debuf.append("\n");
message.append(debuf.toString());
}
public void changedUpdate(DocumentEvent de){
showDE(de);
}
public void insertUpdate(DocumentEvent de){
showDE(de);
}
public void removeUpdate(DocumentEvent de){
showDE(de);
}
public static void main(String[] args){
JFrame f=new JTextArea5() ;
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
f.show();
}
}
9-5:使用JEditorPane组件:
JEditorPane的类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.text.JTextComponent
--javax.swing.JEditorPane
JEditorPane继承JTextComponent类,因此它也可以使用JTextComponent抽象类里面的方法。JEditorPane的最主要功能在于展
现不同类型的文件格式内容。JEditorPane支持的文件类型有三种:第一种是纯文本类型,其类型的表示法为"text/plain",这种类型
的文件就是我们最常使用的txt文件,这类型的文件可以用记事本或WordPad等文书编辑软件来编辑。第二种是RTF类型,其表示法
为"text/rtf",这种类型的文件特色是能对文字内容做字体缩放、变形、上色等特殊效果。第三类是HTML类型,也就是我们在网络上
所浏览的网页类型,其表示法为"text/html",这类文件的特色相信大家都非常的清楚,除了在对字体效果的表现之外还具有在文件
内加入图片、超级链接等相关功能。但是JEditorPane并不是一个全功能的Web Browser,它仅能支持简单的HTML语法.JEditorPane支
持HTML类型的文件最主要的用途是用来制作在线辅助说明文件。
JEditorPane构造函数:
JEditorPane():建立一个新的JEditorPane.
JEditorPane(String url):以详细的URL字符串为基础来建立一个JEditorPane。
JEditorPane(String type,String text):建立一个被指定字符串text并指定初始化JEditorPane的类型。
JEditorPane(URL initialPage):以详细的URL字符串当作输入值来建立一个JEditorPane.
9-5-1:构造JEditorPane组件:
我们将一个HTML文件放在构造完成的JEditPane中:
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.awt.event.*;
public class JEditorPane1{
public static void main(String[] args){
JEditorPane editPane=null;
try{
File file=new File("docs/JEditorPane_1.html");
String str=file.getAbsolutePath();//取得文件位置的绝对路径
str="file:"+str;//将绝对路径合成一完整的输入字符串
/*利用setPage()方法将字符串中路径所指的文件加载JEditorPane.
*在setPage()方法中,输入的数据是String类型的字符串,其实这样的构造方式等同于利用JEditorPane的另一个构造函数
*JEditorPane(String str)来构造。因此如果我们将下面两行程序改写如下行:
* editPane=new JEditorPane(str);
*会得到相同的效果,所以我们就不再对此种构造方式再多加说明.
*/
editPane=new JEditorPane();//构造一个空的JEditorPane
editPane.setPage(str);
}catch(IOException ioe){
ioe.printStackTrace(System.err);
System.exit(0);
}
/*利用setEditable()方法将JEditorPane设为不可编辑.请注意,这行是相当重要的,若是我们将这个方法设为true,我们将会
*失去HTML文件本身的特性,如超级链接的功能等等。因此我们在使用下面JEditorPane2的例子时,一般都会将编辑的功能取
*消(设置false).目前这个超级链接功能并没有作用,这部份将在JEditorPane的事件处理中介绍.
*/
editPane.setEditable(false);
JFrame f=new JFrame("JEditorPane1");
f.setContentPane(new JScrollPane(editPane));
f.setSize(200,200);
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
我们在前面提到JEditorPane支持三种类型的文件格式,在上面的例子里我们并没有看到设置文件格式的步骤,那是因为在上面
的构造方法中系统会依照输入文件名称来自动判别文件类型。若是我们想要自己设置文件类型可利用setContentType()方法,或是
直接在JEditorPane构造函数中设置。如下面这个范例:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
public class JEditorPane2{
public static void main(String[] args){
String str=new String("This is a test.\nthis is Line2!\nThis is Line 3!");
JEditorPane editPane=new JEditorPane("text/plain",str);
editPane.setEditable(false);
JFrame f=new JFrame("JEditorPane2");
f.setContentPane(new JScrollPane(editPane));
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
以URL类当作JEditPane的参数来构造,但是要注意的地方是使用这种方式来构造里,计算机要连接上局域网络或网际网络不然
程序会找不到URL指定的位置而产生Exception使得程序无法动作.我们来看下面的范例吧!
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class JEditorPane3{
public static void main(String[] args){
JEditorPane editPane=null;
try{
URL address=new URL("http://www.sina.com.cn");
editPane=new JEditorPane(address);
}catch(MalformedURLException e){
System.out.println("Malformed URL:"+e);
}catch(IOException e){
System.out.println("IOException:"+e);
}
editPane.setEditable(false);
JFrame f=new JFrame("JEditorPane3");
f.setContentPane(new JScrollPane(editPane));
f.setSize(200,250);
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
9-5-2:JEditorPane的事件处理:
在JEditorPane文件中最常用到事件处理的部份就是HTML文件,那是因为HTML文件本身具有超级链接的功能来做文章链接的用途
。大家还记得我们这一节的第一个范例吗?我们不是加载了一份HTML文件到JEditorPane中吗?虽然画面上都有确实的将超级链接和
图片信息展现出来,可是你有没有发现当你想要点选超级链接的地方时却没有反应呢?那是因为我们并没有在JEditorPane中加入事
件处理机制的缘故。我们改写JEditorPane1.java加入事件处理机制,使JEditorPane具有正常的超链接功能。如下范例:
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.awt.event.*;
public class JEditorPane4{
public static void main(String[] args){
JEditorPane editPane = null;
try{
File thef = new File ("docs/JEditorPane_1.html");
String str = thef.getAbsolutePath();
str = "file:"+str;
editPane = new JEditorPane();
editPane.setPage(str);
}
catch(IOException ioe){
ioe.printStackTrace(System.err);
System.exit(0);
}
editPane.setEditable(false);
final JEditorPane thePane = editPane;
//采用inner class的方式编写触发超级链接事件时的对应操作类
editPane.addHyperlinkListener(new HyperlinkListener(){
public void hyperlinkUpdate(HyperlinkEvent hle){//覆写hyperlinkUpdate()方法,当超级链接事件触发时会进入这
//个区段运行.
try{
//判断是否为超级链接运行操作。若操作为真,则将新的HTML文件放到JEditorPane中,
//操作为(thePane.setPage(hle.getURL());)
if (hle.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
}
catch(IOException ioe){
ioe.printStackTrace(System.err);
}
}
});
JFrame f = new JFrame("JEditorPane4");
f.setContentPane(new JScrollPane(editPane));
f.setSize(200,250);
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}//end of main()
}//end of class JEditPane1
另外,若是我们是在纯文字模式(Plain Text)或RTF模式(RTF Text)下需要事件处理模式又该怎么办呢?你还记得我们在
JTextArea中是如何加入事件处理模式的吗?没错!在JEditorPane中也是相同的做法,也就是利用DocumentListener interface的
机制来处理,由于做法相当类似,因此我们就不在这里重复的说明.
9-6:使用JTextPane组件:
JTextPane的类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.text.JTextComponent
--javax.swing.JEditorPane
--javax.swing.JTextPane
我们在前面有介绍过JTextArea类,虽然JTextArea在某些功能上已经能够满足我们的需求,但是当我们想再加入更多的变化时
(如文字加入色彩、插入图片...)就会发现JTextArea类根本无法做到。要做到这些功能,我们必须使用JEditorPane的子类:
JTextpane。JTextPane提供了许多对文字的处理,如改变颜色、字体缩放、文字风格、加入图片等。我们先来看看JTextPane的构
造方法:
JTextPane构造函数:
JTextPane():建立一个新的JTextPane.
JTextPane(StyledDocument doc):以指定的文件模式建立一个新的JTextPane.
9-6-1:JTextPane的特性:
相信大家都有用过Word来写过报告或文章,那么你一定会知道我们在Word中可以对文章中的文字做很多的变化,这些变化都是
属于文字的“属性”变化。由于在JTextPane中产生的效果几乎都是由属性的变化而来,所以改变属性的类组件在JTextpane中是少
不了的。因此在介绍如何构造JTextPane之前,我们要先介绍两个在JTextPane中常用到属性类:
SimpleAttributeSet和StyleConstant.
属性的变化原本是利用AttributeSet interface来处理的,但是这个interface中包含了太多的方法,若是我们直接实作
AttributeSet interface那就需要实作此interface里所有的方法,这对编写程序来说并不是一个很理想的做法;而java另外提供了
SimpleAttributeSet类,实作了AttributeSet interface.因此,只要我们直接使用SimpleAttributeSet类就能具备AttributeSet
interface的所有功能,而不用一个个的编写AttributeSet中的方法。另外StyleConstant类则是提供AttributeSet类许多常用的属
性键值(Attribute Key)和方法来设置或取得JTextPane内容的状态。在StyleConstant类中包含了许多的常用的属性设置,包括本文
与边界空白区段设置、文字字体/大小/类型设置、背景颜色设置等。利用这两个类来辅助设计JTextPane便使JTextPane有更丰富
的内容变化。
JTextPane是专为文字和版面处理设计的组件。JTextPane对可输入区域内容的设计概念是一个类似Word的设计概念,也就是说在
JTextPane中的文字结构是有段落概念的。“段落”的概念就是以[Enter]键为每一段落的分界点,每按一次[Enter]键就增加一个段
落。记得我们在JTextArea中提过的Element存储模式吗?在JTextPane中也是采用相同的做法,但是差别在于规划存储的方式不同。
在JTextArea中并没有分段落,只是单纯的以[Enter]键当作存储成两个Element的分界。而在JTextPane则是以整个编辑区哉为根节
点,每个段落为枝节点 ,每个字符为叶节点来存储文件。也因为JTextPane是采用这样的方式来存储数据,因此在JTextPane中也可
以像Word文件一样将各个段落设置成不同的属性,如第一段为斜体字、字体大小为14号字、粗体字,第二段为斜体字、字体颜色为
蓝色、向左边界缩排2厘米等;另外,我们还可以设置JTextPane编辑区内输入的文字与各个边界间的距离。由这些功能看来,对于一
个TextComponent来说JTextPane是一个具有相当多实用功能的组件。
9-6-2:构造JTextPane组件:
在了解JTextPane的各项特性之后,我们现在马上来看JTextPane可以呈现什么样的效果,在下面这个例子中我们将对JTextPane
区域内的文字设置颜色、粗斜体、与底线等相关属性。
import javax.swing.*;
import javax.swing.text.*;
import java.awt.event.*;
import java.awt.*;
public class JTextPane1{
private JTextPane textPane;
public JTextPane1(){
textPane=new JTextPane();
textPane.setBackground(Color.black);
textPane.setEditable(false);
}
public void setYellow_Bold_20(String str){
SimpleAttributeSet attrset=new SimpleAttributeSet();
StyleConstants.setForeground(attrset,Color.yellow);
StyleConstants.setBold(attrset,true);
insert(str,attrset);
}
public void setBlue_Italic_Bold_22(String str){
SimpleAttributeSet attrset=new SimpleAttributeSet();
StyleConstants.setForeground(attrset,Color.blue);
StyleConstants.setItalic(attrset,true);
StyleConstants.setFontSize(attrset,24);
insert(str,attrset);
}
public void setRed_UnderLine_Italic_24(String str){
SimpleAttributeSet attrset=new SimpleAttributeSet();
StyleConstants.setForeground(attrset,Color.red);
StyleConstants.setUnderline(attrset,true);
StyleConstants.setItalic(attrset,true);
StyleConstants.setFontSize(attrset,24);
insert(str,attrset);
}
//这个方法最主要的用途是将字符串插入到JTextPane中。
public void insert(String str,AttributeSet attrset){
Document docs=textPane.getDocument();//利用getDocument()方法取得JTextPane的Document instance.0
str=str+"\n";
try{
docs.insertString(docs.getLength(),str,attrset);
}catch(BadLocationException ble){
System.out.println("BadLocationException:"+ble);
}
}
public Component getComponent(){
return textPane;
}
public static void main(String[] args){
JTextPane1 pane=new JTextPane1();
pane.setYellow_Bold_20("This is Line 1,yellow,Bold,Size 20");
pane.setBlue_Italic_Bold_22("This is Line 2,blue,Italic,Bold,Size 22");
pane.setRed_UnderLine_Italic_24("This is Line 3,red,UnderLine,Italic,Size 24");
JFrame f=new JFrame("JTextPane1");
f.getContentPane().add(pane.getComponent());
f.setSize(450,180);
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
若你想在JTextPane上置入图形或其他组件(如表格或按钮),你可以分别使用JTextPane所提供的insetIcon()与insertComponent()
方法来达到这个效果。
至于另外一种JTextPane的构造方式和JTextArea一样,差别在于JTextArea是采用Document interface而JTextPane是采用
Saturday, 5 May 2007
Saturday, 28 April 2007
may_pre
于谦情报:
网线,10米至20米
电饭锅,全自动
西装, 体恤
文具
味精
无线网卡
大箱子
CD, 耳机
药,花露水
雨伞
有中国特色的小礼物
NOTTINGHAM有泡面卖,有一个PAND SHOP.经常去CHECK学校邮箱,多留意学校上课网,根据前几年的试卷来推测本年的考试题,多做笔记.
尽量和外国人住在一起
出去以前去于谦那里拿PAY AS YOU GO SIM CARD
问清各个学科所占比例,各个学年所占比例.
有空去爱丁堡和伦敦走走
银行卡的办理需要1个月左,很多东西需要根据银行卡
http://blog.sina.com.cn/u/4cacf58b010009ip
一、随身行李(6公斤,手提电脑除外)
基本随身物品:
护照
Offer
体检证明 : 《国际旅行健康证明书》和《国际预防接种证书》
机票 ( 请提前一个月预定 )
护照 / 签证 /Offer 的复印件,要和原件分开放。
护照大小的免冠照片 ( 带 20 张以上 2 寸,到了英国用的地方很多 ) 。
现金,随身携带 100 英镑或多少不等的现金以备急需。 ( 如果可能带 10 镑左右的硬币,在机场打电话用, Heathrow 机场的电话很多只能打出不能打进的。 )
紧急联络电话,包括学校、系、导师的电话等。还有家庭亲戚同学朋友联系方式,电子版本.
你在英国的机场入境时,入境官员和卫生官员会要求你出示以上文件,因此应将其放在随身携带的手提包中,以方便取出。除此之外,还需要填写入境登记卡,此卡由乘务员在飞机快着陆时发放。
其他随身物品:(飞机上的同胞应该不少,有什么需要帮助的尽管提出。)
如有晕车晕机历史的,携带晕机药。
雨伞 ( 或者雨衣,放在托运行李中即可,但是要放在比较好拿出来的地方 ) 。
电子词典 ( 因人而异 ) 。
笔和记事本,到达英国入境时要用。
地图 ( 可在机场的 Information Centre 拿一份 ) 。
现金:相当于 5000 美金的英镑,大概 2800 英镑。
其他日用品:洗面液,面巾纸,女孩子的各类化妆品, CD 、 MP3 、小说等等。
二、托运行李 ( 30 公斤 , 长宽高之和不超过 158 公分的行李箱)
不要忘记清楚标识你的行李 , 把你的姓名和在英联系方式写在标签上。
1 、 衣 :内衣,袜子
春秋:防雨夹克,薄毛衣,长袖衫, 牛仔裤 ,绒衣,( 英国穿毛衣的机会多)
夏:体恤衫(长袖,短袖),短裤,脱鞋,凉鞋.
冬:厚毛衣, 羽绒服,夹克,皮衣, 薄毛裤,羽绒背心,围巾,手套 ,帽子等
正装:西服,衬衫(长,短),领带, 唐装(英国穿正装的机会不多)
2 、 鞋 : 运动鞋 ,皮鞋,拖鞋
3 、 食 :花椒,大料,木筷(勺),水果刀,电饭煲,热得快,牙签,茶叶,菜刀,
4 、 药 :感冒类药(39冲剂), 花露水, 皮眼平,黄莲上清丸,螺旋霉素,胃药,皮炎平,云南白药,清凉油,风油精,晕车药,止疼片,跌打损伤药,退烧药等。(但千万不要带中草药)
5 、 住 :牙膏,牙刷,洗头水(小袋),指甲刀,耳勺,剪刀, 指甲刀,透明胶,床单,被罩 , 枕套 , 毛巾 , 浴巾 , 睡衣 , 刮胡刀 , 眼镜 , 手电 , 梳子 , 小镜子 , 蚊香 , 卫生球 , 干燥剂 ,
6 、 眼镜: 近视眼镜(除现戴的再备一副);隐形眼镜(两副);护理液(两瓶)太阳镜;眼药水;
7 、 其他 : 电池 ( 最好是充电电池,英国电池很贵 ) 和充电器。小电器,如 MD 、 Discman 、 Walkman 、电动剃须刀(最好可直接充电的)、闹钟等。相机(较多胶卷或数码相机)。
书籍一类要有选择的带,毕竟占重量也占空间,词典一类的工具书和必要的专业书籍即可,如果非要带很多的话最好单独办理邮寄,或者海运也好。
移动硬盘,刻录光盘。 (一般是无人过问的)
礼品。礼品无需很贵重,诸如茶叶、中国邮票就可以了。 CD 可以拿一些中国传统乐器的 ( 包装好一点 , 送老外很好的礼品 ) 。最后还可以带两条烟过来。
可选项:(适合长期居住,纨绔一族的)
DVD Player( 全区解码 ) 、电火锅、豆浆机、麻酱或火锅调料等。有线电话。
小结:大多数的东西是可以在这边买的到的。只是价钱有的差别大一些,有的小一些。目前为止发现买不到的只有韭菜花。
注意:机场现在对行李超重检查的很严格的,不要存在侥幸心理,打无准备之仗。
三、体检信息
" 体检时间:您可以在签证前或签证后体检(体检通常需要三到五个工作日出结果,请注意体检当天应空腹,带上本人身份证,外地学生也可在北京体检)。
" 体检地点:请您到居住地所在地的检验检疫局体检(使馆无体检表),或者到北京出入境检验检疫局保健中心体检,办理《国际旅行健康证明书》和《国际预防接种证书》。
北京出入境检验检验局保健中心:授权发放健康卡(也叫黄皮本)的机构。
位于和平里北街 20 号,和平里医院旁边。在灯市口车站乘坐 104 快车,蒋宅口下车即是。电话: 64274240—8 。每天上午体检。
收费: 400 元左右 RMB
" 体检的作用:方便出境抽查。这是入境的最后一关。如被抽查到,出示健康卡,即可通过;如没有健康卡,将被要求做临时体检。(在英国居留 6 个月以上,应有健康卡)
http://blog.sina.com.cn/u/4cacf58b010009in
图书馆:藏藏书100多万册,5000余种期刊;图书馆年资料经费支出为平均每位全日制学生40英镑。
计算机资源:设有学术计算机服务网,所有学生宿舍均可接通。
旅行:夜间无偿提供学生去图书馆和吧的小型公共汽车,校园有车直通车站、机场和码头。还有自行车租赁
http://blog.sina.com.cn/zliybwc#feeds_FEEDS_1286403467
服饰
外套:至少要有一件到两件带帽子, 防水性好的, 可以当雨衣用. 冬天的英国雨水充足, 而且说不定什么时候就下雨, 这样的衣服会非常实用!
毛衣: 一到两件; 英国冬天的感觉与大陆不同; 由于房间里暖气的充足, 在户外活动时间的短暂, 决定了毛衣不象国内般流行. 就是在最冷的冬天, 很多人都是外头一件厚实的外套,里面一件薄的毛衣. 如果有条件最好带羊绒制品, 薄而御寒.
毛裤秋裤: 基本不用; 但如果实在怕冷可以带一条来, 但你会瞬间发现是多么的无用.
外裤: 一般长裤即可, 但最好有一条很厚实的, 在最冷的时候穿.
袜子: 厚实保暖类.
手套: 厚的手套在英国非常必需.
围巾: 最好两条,因为到了十二月到二月期间, 围巾几乎要天天带, 多一条没坏处.
帽子: 绝对需要; 要棉的那种, 把耳朵都遮上, 尤其如果你要骑车, 没有帽子会冷得你头疼.
内衣
春夏服饰(之所以把春天和夏天列在一起是考虑到英国的最热都不过20度, 在国内看来都算是三到五月的春天.):
外衣: 薄风衣; 在微寒的春天早晨还是需要的; 同样需要带帽子和防水的.
各种男式或女式衬衫/ T恤; 长袖也要考虑, 毕竟英国十几度的白天是很普遍的.
帽子: 夏天太阳也会很大, 带个运动帽可以保护你的脸不晒黑, 而且尽显青春风采!
袜子: 薄一些的运动袜
鞋: 运动鞋一双, 拖鞋一双; 皮鞋一双(鞋油);
运动服: 喜欢运动的朋友可以带一到两套;
洗涤用品
我个人不主张在本身重量就不富裕的行囊中携带太多的洗涤用品. 因为这种东西很占份量,而且消耗很快, 不可能一次就带够一年用的, 最终还是得在英国本地买. 在英国最便宜的洗衣粉1.215KG才70多P, 合人民币8元多. 而TESCO values包装的六块装肥皂也不超过1镑. 而其他洗碗什么的洗涤剂就更没必要大老远从中国运来了, 大多数学生宿舍公用厨房都应该配备有.
个人卫生用品( 记住上面的原则, 够刚到的几天的即可):
牙杯
牙刷
小管装牙膏(大管比较重)//防上火, 中华中草药
香皂
香皂盒
洗发水
洗面奶
毛巾(多备几条, 英国毛巾较贵)
厨房用品
刀具: 一把锋利的水果刀; 喜欢自己剁东西的朋友可以考虑带把菜刀.
杯子: 一般的喝水杯
筷子; 最好带两到三双; 根据本人经验, 很多中国朋友吃饭都需要客人自带碗筷, 可见主人准备不充足.哈哈!
勺子
叉子
塑料饭盒; 非常实用, 一可以替代碗碟, 二可以装便当带到学校或工作地方, 尤其是那些不包餐的PART TIME工作.
圆底锅: 炒菜很需要
炒菜勺
碗(塑料, 适合微波炉用, 而且重量轻.)
盘子(塑料, 适合微波炉用, 而且重量轻.)
床上用品
床单;两套, 可以换洗.
枕套;
背罩.
其他
面霜
橡皮筋
针线盒; 此物英国昂贵, 最好自备.
电子塑料闹钟
指甲剪
小镜子
梳子
雨伞
CD(多张)(带你最爱的歌,以缓解乡愁)
太阳镜
眼镜盒
插头转换头
相机
收音机
衣架//自己做, 但需要夹子
软盘(可以把重要的学习资料或各种数据储存在里面, 非常有用! 尤其对那些没有自带电脑的朋友)
学习用品
书包(双肩背或挎包都可以, 但后者在英国比较流行.)
文具盒或笔袋
笔(若签字笔,圆珠笔、铅笔、铅芯, 如需要钢笔则要考虑灌墨问题.)
橡皮
刀片
直尺
电子字典,如快译通或文曲星(听很多网友都推荐文曲星PC505型号,物美价廉)
录音笔/录音机; 如果你怕听课有困难, 可以带一支录音笔.
磁带
充电器/充电电池(5号和7号)
计算器
涂改液
笔记本
讲义夹
钉书器
打孔机; 在纸张上打小圆孔, 方便存放在文件夹
胶水
透明胶
牛津或郎文双解英汉字典
汉英字典
注意: 如果是学ENGINEERING, ARCHITECTURE或ART的学生, 则另外需要带一些学习用品, 包括圆规, 特殊尺笔或颜料等, 来之前最好查询清楚. 因为这样的用品在英国会很昂贵!
药物
·体温表·橡皮膏 ·医用棉花 ·医用剪刀·医用镊子·医用纱布注意:以上物件务必使用医用类型,以保证卫生。药品:尤其注意的是: 感冒退烧药品需要多带, 由于英国感冒症状非常常见,且容易传染.抗过敏及消炎药品也需常备.分类药名作用退烧类药物阿思匹林
呼吸系统常用药物康泰克用于感冒
速效伤风胶囊清热解毒、用于感冒发热
消化系统常用药物胃复安止吐、消除胃涨
胃舒平抗酸、保护溃疡面,用于胃溃疡、胃酸过多、胃痛等
999胃泰
止痛药芬必得
万应止痛膏
解热止痛片
牙痛一粒丸治牙痛
抗过敏息斯敏
扑尔敏过敏性疾病、伤风流涕、药物过敏等
外用药创可贴止血、消炎、护创
紫药水杀菌,用于皮肤、粘膜感染及溃疡
皮康霜
皮炎平用于皮肤瘙痒
云南白药用于跌打损伤
驱风油
四环素软膏抗菌排脓,用于痤疮、皮炎、冻疮、烫伤、烧伤
诺氟沙星滴眼液多种病原菌引起的外眼部感染,如角膜炎、结膜炎等
盐酸环丙沙星滴眼液用于眼睛疾病
正红花油烫伤、蚊虫叮咬
达克宁霜用于治疗脚气等
消炎、消火牛黄解毒片
西瓜霜润喉片清音利咽、消肿止痛
最后需要注意的是: 任何衣物都要保证不缩水; 因为这里的衣服基本都是烘干, 不是自然晾晒干
护照(签证)(均要复制两份,一份随身,一份留家中)
入学通知(均要复制两份,一份随身,一份留家中)
机票钱(包括零钱)
体检证明(包括接种证明、小药箱)
其他文件(如成绩单、学位证书、推荐信,均要复制两份,一份随身,一份留家中)
护照照片 (最好使用白色背景)
接机人姓名、电话
在英亲戚朋友通信录
紧急联络电话
我国驻当地大使馆、商务办事处电话。
前两天生活用品(换洗内衣裤一套、药品、纸笔、眼镜、牙刷牙膏、毛巾、手纸)
网线,10米至20米
电饭锅,全自动
西装, 体恤
文具
味精
无线网卡
大箱子
CD, 耳机
药,花露水
雨伞
有中国特色的小礼物
NOTTINGHAM有泡面卖,有一个PAND SHOP.经常去CHECK学校邮箱,多留意学校上课网,根据前几年的试卷来推测本年的考试题,多做笔记.
尽量和外国人住在一起
出去以前去于谦那里拿PAY AS YOU GO SIM CARD
问清各个学科所占比例,各个学年所占比例.
有空去爱丁堡和伦敦走走
银行卡的办理需要1个月左,很多东西需要根据银行卡
http://blog.sina.com.cn/u/4cacf58b010009ip
一、随身行李(6公斤,手提电脑除外)
基本随身物品:
护照
Offer
体检证明 : 《国际旅行健康证明书》和《国际预防接种证书》
机票 ( 请提前一个月预定 )
护照 / 签证 /Offer 的复印件,要和原件分开放。
护照大小的免冠照片 ( 带 20 张以上 2 寸,到了英国用的地方很多 ) 。
现金,随身携带 100 英镑或多少不等的现金以备急需。 ( 如果可能带 10 镑左右的硬币,在机场打电话用, Heathrow 机场的电话很多只能打出不能打进的。 )
紧急联络电话,包括学校、系、导师的电话等。还有家庭亲戚同学朋友联系方式,电子版本.
你在英国的机场入境时,入境官员和卫生官员会要求你出示以上文件,因此应将其放在随身携带的手提包中,以方便取出。除此之外,还需要填写入境登记卡,此卡由乘务员在飞机快着陆时发放。
其他随身物品:(飞机上的同胞应该不少,有什么需要帮助的尽管提出。)
如有晕车晕机历史的,携带晕机药。
雨伞 ( 或者雨衣,放在托运行李中即可,但是要放在比较好拿出来的地方 ) 。
电子词典 ( 因人而异 ) 。
笔和记事本,到达英国入境时要用。
地图 ( 可在机场的 Information Centre 拿一份 ) 。
现金:相当于 5000 美金的英镑,大概 2800 英镑。
其他日用品:洗面液,面巾纸,女孩子的各类化妆品, CD 、 MP3 、小说等等。
二、托运行李 ( 30 公斤 , 长宽高之和不超过 158 公分的行李箱)
不要忘记清楚标识你的行李 , 把你的姓名和在英联系方式写在标签上。
1 、 衣 :内衣,袜子
春秋:防雨夹克,薄毛衣,长袖衫, 牛仔裤 ,绒衣,( 英国穿毛衣的机会多)
夏:体恤衫(长袖,短袖),短裤,脱鞋,凉鞋.
冬:厚毛衣, 羽绒服,夹克,皮衣, 薄毛裤,羽绒背心,围巾,手套 ,帽子等
正装:西服,衬衫(长,短),领带, 唐装(英国穿正装的机会不多)
2 、 鞋 : 运动鞋 ,皮鞋,拖鞋
3 、 食 :花椒,大料,木筷(勺),水果刀,电饭煲,热得快,牙签,茶叶,菜刀,
4 、 药 :感冒类药(39冲剂), 花露水, 皮眼平,黄莲上清丸,螺旋霉素,胃药,皮炎平,云南白药,清凉油,风油精,晕车药,止疼片,跌打损伤药,退烧药等。(但千万不要带中草药)
5 、 住 :牙膏,牙刷,洗头水(小袋),指甲刀,耳勺,剪刀, 指甲刀,透明胶,床单,被罩 , 枕套 , 毛巾 , 浴巾 , 睡衣 , 刮胡刀 , 眼镜 , 手电 , 梳子 , 小镜子 , 蚊香 , 卫生球 , 干燥剂 ,
6 、 眼镜: 近视眼镜(除现戴的再备一副);隐形眼镜(两副);护理液(两瓶)太阳镜;眼药水;
7 、 其他 : 电池 ( 最好是充电电池,英国电池很贵 ) 和充电器。小电器,如 MD 、 Discman 、 Walkman 、电动剃须刀(最好可直接充电的)、闹钟等。相机(较多胶卷或数码相机)。
书籍一类要有选择的带,毕竟占重量也占空间,词典一类的工具书和必要的专业书籍即可,如果非要带很多的话最好单独办理邮寄,或者海运也好。
移动硬盘,刻录光盘。 (一般是无人过问的)
礼品。礼品无需很贵重,诸如茶叶、中国邮票就可以了。 CD 可以拿一些中国传统乐器的 ( 包装好一点 , 送老外很好的礼品 ) 。最后还可以带两条烟过来。
可选项:(适合长期居住,纨绔一族的)
DVD Player( 全区解码 ) 、电火锅、豆浆机、麻酱或火锅调料等。有线电话。
小结:大多数的东西是可以在这边买的到的。只是价钱有的差别大一些,有的小一些。目前为止发现买不到的只有韭菜花。
注意:机场现在对行李超重检查的很严格的,不要存在侥幸心理,打无准备之仗。
三、体检信息
" 体检时间:您可以在签证前或签证后体检(体检通常需要三到五个工作日出结果,请注意体检当天应空腹,带上本人身份证,外地学生也可在北京体检)。
" 体检地点:请您到居住地所在地的检验检疫局体检(使馆无体检表),或者到北京出入境检验检疫局保健中心体检,办理《国际旅行健康证明书》和《国际预防接种证书》。
北京出入境检验检验局保健中心:授权发放健康卡(也叫黄皮本)的机构。
位于和平里北街 20 号,和平里医院旁边。在灯市口车站乘坐 104 快车,蒋宅口下车即是。电话: 64274240—8 。每天上午体检。
收费: 400 元左右 RMB
" 体检的作用:方便出境抽查。这是入境的最后一关。如被抽查到,出示健康卡,即可通过;如没有健康卡,将被要求做临时体检。(在英国居留 6 个月以上,应有健康卡)
http://blog.sina.com.cn/u/4cacf58b010009in
图书馆:藏藏书100多万册,5000余种期刊;图书馆年资料经费支出为平均每位全日制学生40英镑。
计算机资源:设有学术计算机服务网,所有学生宿舍均可接通。
旅行:夜间无偿提供学生去图书馆和吧的小型公共汽车,校园有车直通车站、机场和码头。还有自行车租赁
http://blog.sina.com.cn/zliybwc#feeds_FEEDS_1286403467
服饰
外套:至少要有一件到两件带帽子, 防水性好的, 可以当雨衣用. 冬天的英国雨水充足, 而且说不定什么时候就下雨, 这样的衣服会非常实用!
毛衣: 一到两件; 英国冬天的感觉与大陆不同; 由于房间里暖气的充足, 在户外活动时间的短暂, 决定了毛衣不象国内般流行. 就是在最冷的冬天, 很多人都是外头一件厚实的外套,里面一件薄的毛衣. 如果有条件最好带羊绒制品, 薄而御寒.
毛裤秋裤: 基本不用; 但如果实在怕冷可以带一条来, 但你会瞬间发现是多么的无用.
外裤: 一般长裤即可, 但最好有一条很厚实的, 在最冷的时候穿.
袜子: 厚实保暖类.
手套: 厚的手套在英国非常必需.
围巾: 最好两条,因为到了十二月到二月期间, 围巾几乎要天天带, 多一条没坏处.
帽子: 绝对需要; 要棉的那种, 把耳朵都遮上, 尤其如果你要骑车, 没有帽子会冷得你头疼.
内衣
春夏服饰(之所以把春天和夏天列在一起是考虑到英国的最热都不过20度, 在国内看来都算是三到五月的春天.):
外衣: 薄风衣; 在微寒的春天早晨还是需要的; 同样需要带帽子和防水的.
各种男式或女式衬衫/ T恤; 长袖也要考虑, 毕竟英国十几度的白天是很普遍的.
帽子: 夏天太阳也会很大, 带个运动帽可以保护你的脸不晒黑, 而且尽显青春风采!
袜子: 薄一些的运动袜
鞋: 运动鞋一双, 拖鞋一双; 皮鞋一双(鞋油);
运动服: 喜欢运动的朋友可以带一到两套;
洗涤用品
我个人不主张在本身重量就不富裕的行囊中携带太多的洗涤用品. 因为这种东西很占份量,而且消耗很快, 不可能一次就带够一年用的, 最终还是得在英国本地买. 在英国最便宜的洗衣粉1.215KG才70多P, 合人民币8元多. 而TESCO values包装的六块装肥皂也不超过1镑. 而其他洗碗什么的洗涤剂就更没必要大老远从中国运来了, 大多数学生宿舍公用厨房都应该配备有.
个人卫生用品( 记住上面的原则, 够刚到的几天的即可):
牙杯
牙刷
小管装牙膏(大管比较重)//防上火, 中华中草药
香皂
香皂盒
洗发水
洗面奶
毛巾(多备几条, 英国毛巾较贵)
厨房用品
刀具: 一把锋利的水果刀; 喜欢自己剁东西的朋友可以考虑带把菜刀.
杯子: 一般的喝水杯
筷子; 最好带两到三双; 根据本人经验, 很多中国朋友吃饭都需要客人自带碗筷, 可见主人准备不充足.哈哈!
勺子
叉子
塑料饭盒; 非常实用, 一可以替代碗碟, 二可以装便当带到学校或工作地方, 尤其是那些不包餐的PART TIME工作.
圆底锅: 炒菜很需要
炒菜勺
碗(塑料, 适合微波炉用, 而且重量轻.)
盘子(塑料, 适合微波炉用, 而且重量轻.)
床上用品
床单;两套, 可以换洗.
枕套;
背罩.
其他
面霜
橡皮筋
针线盒; 此物英国昂贵, 最好自备.
电子塑料闹钟
指甲剪
小镜子
梳子
雨伞
CD(多张)(带你最爱的歌,以缓解乡愁)
太阳镜
眼镜盒
插头转换头
相机
收音机
衣架//自己做, 但需要夹子
软盘(可以把重要的学习资料或各种数据储存在里面, 非常有用! 尤其对那些没有自带电脑的朋友)
学习用品
书包(双肩背或挎包都可以, 但后者在英国比较流行.)
文具盒或笔袋
笔(若签字笔,圆珠笔、铅笔、铅芯, 如需要钢笔则要考虑灌墨问题.)
橡皮
刀片
直尺
电子字典,如快译通或文曲星(听很多网友都推荐文曲星PC505型号,物美价廉)
录音笔/录音机; 如果你怕听课有困难, 可以带一支录音笔.
磁带
充电器/充电电池(5号和7号)
计算器
涂改液
笔记本
讲义夹
钉书器
打孔机; 在纸张上打小圆孔, 方便存放在文件夹
胶水
透明胶
牛津或郎文双解英汉字典
汉英字典
注意: 如果是学ENGINEERING, ARCHITECTURE或ART的学生, 则另外需要带一些学习用品, 包括圆规, 特殊尺笔或颜料等, 来之前最好查询清楚. 因为这样的用品在英国会很昂贵!
药物
·体温表·橡皮膏 ·医用棉花 ·医用剪刀·医用镊子·医用纱布注意:以上物件务必使用医用类型,以保证卫生。药品:尤其注意的是: 感冒退烧药品需要多带, 由于英国感冒症状非常常见,且容易传染.抗过敏及消炎药品也需常备.分类药名作用退烧类药物阿思匹林
呼吸系统常用药物康泰克用于感冒
速效伤风胶囊清热解毒、用于感冒发热
消化系统常用药物胃复安止吐、消除胃涨
胃舒平抗酸、保护溃疡面,用于胃溃疡、胃酸过多、胃痛等
999胃泰
止痛药芬必得
万应止痛膏
解热止痛片
牙痛一粒丸治牙痛
抗过敏息斯敏
扑尔敏过敏性疾病、伤风流涕、药物过敏等
外用药创可贴止血、消炎、护创
紫药水杀菌,用于皮肤、粘膜感染及溃疡
皮康霜
皮炎平用于皮肤瘙痒
云南白药用于跌打损伤
驱风油
四环素软膏抗菌排脓,用于痤疮、皮炎、冻疮、烫伤、烧伤
诺氟沙星滴眼液多种病原菌引起的外眼部感染,如角膜炎、结膜炎等
盐酸环丙沙星滴眼液用于眼睛疾病
正红花油烫伤、蚊虫叮咬
达克宁霜用于治疗脚气等
消炎、消火牛黄解毒片
西瓜霜润喉片清音利咽、消肿止痛
最后需要注意的是: 任何衣物都要保证不缩水; 因为这里的衣服基本都是烘干, 不是自然晾晒干
护照(签证)(均要复制两份,一份随身,一份留家中)
入学通知(均要复制两份,一份随身,一份留家中)
机票钱(包括零钱)
体检证明(包括接种证明、小药箱)
其他文件(如成绩单、学位证书、推荐信,均要复制两份,一份随身,一份留家中)
护照照片 (最好使用白色背景)
接机人姓名、电话
在英亲戚朋友通信录
紧急联络电话
我国驻当地大使馆、商务办事处电话。
前两天生活用品(换洗内衣裤一套、药品、纸笔、眼镜、牙刷牙膏、毛巾、手纸)
Friday, 27 April 2007
hashtable
Hashtables提供了一个很有用的方法可以使应用程序的性能达到最佳。
Hashtables(哈希表)在计算机领域中已不是一个新概念了。它们是用来加快计算机的处理速度的,用当今的标准来处理,速度非常慢,而它们可以让你在查询许多数据条目时,很快地找到一个特殊的条目。尽管现代的机器速度已快了几千倍,但是为了得到应用程序的最佳性能,hashtables仍然是个很有用的方法。
设想一下,你有一个包含约一千条记录的数据文件,比如一个小企业的客户记录,还有一个程序,它把记录读到内存中进行处理。每个记录包含一个唯一的五位数的客户ID号、客户名字、地址、帐户结余等等。假设记录不是按客户ID号顺序分类的,所以,如果程序要将客户ID号作为“key” 来查找一个特殊的客户记录,唯一的查找方法就是连续地搜索每个记录。有时侯,它会很快找到你需要的记录;但有时侯,在程序找到你需要的记录前,它几乎已搜索到了最后一条记录。如果要在1,000条记录中搜索,那么查找任何一条记录都需要程序平均查核500.5 ((1000 + 1 )/2)条记录。如果你常需要查找数据,你应该需要一个更快的方法来找到一条记录。
一种加快搜索的方法就是把记录分成几段,这样,你就不用搜索一个很大的列表了,而是搜索几个短的列表。对于我们数字式的客户ID号,你可以建10个列表,以0开头的ID号组成一个列表,以1开头的ID号组成一个列表,依此类推。那么要查找客户ID号38016,你只需要搜索以3开头的列表就行了。如果有1,000条记录,每个列表的平均长度为100(1,000条记录被分成10个列表),那么搜索一条记录的平均比较次数就降到了约50(见图1)。
当然,如果约十分之一的客户号是以0开头的,另外十分之一是以1开头的,等等,那么这种方法会很适合。如果90%的客户号以0开头,那么那个列表就会有900条记录,每次查找平均需要进行450次比较。另外,程序需要执行的搜索有90%都是针对以0开头的号码的。因此,平均比较数就大大超过简单数学运算的范围了。
如果我们可以按这样一种方式在我们的列表中分配记录,情况就会好一些,即每个列表约有相同条目的记录,而不管键值中数字的分布。我们需要一种方法能够把客户号码混合到一起并更好地分布结果。例如,我们可以取号码中的每位数,乘以某个大的数(随着数字位置的不同而不同), 然后将结果相加产生一个总数,把这个数除以10,并将余数作为索引值(index)(除数相同的分到一组)。当读入记录时,程序在客户号码上运行这个哈希(hash) 函数来确定记录属于哪个列表。当用户需要查询时,将同一个哈希函数作为一个“key”用于客户号码,这样就可以搜索正确的列表了。 像这样的一个数据结构就称为一个哈希表(hashtable)。
Java中的Hashtables
Java包含两个类,java.util.Hashtable 和java.util.HashMap,它们提供了一个多种用途的hashtable机制。这两个类很相似,通常提供相同的公有接口。但它们的确有一些重要的不同点,我在后面会讲到。
Hashtable和HashMap对象可以让你把一个key和一个value结合起来,并用put() 方法把这对key/value输入到表中。然后你可以通过调用get()方法,把key作为参数来得到这个value(值)。只要满足两个基本的要求,key和value可以是任何对象。注意,因为key和value必须是对象,所以原始类型(primitive types)必须通过运用诸如Integer(int)的方法转换成对象。
为了将一个特定类的对象用做一个key,这个类必须提供两个方法,equals() 和 hashCode()。这两个方法在java.lang.Object中,所以所有的类都可以继承这两个方法;但是,这两个方法在Object类中的实现一般没什么用,所以你通常需要自己重载这两个方法。Equals()方法把它的对象同另一个对象进行比较,如果这两个对象代表相同的信息,则返回true。该方法也查看并确保这两个对象属于相同的类。如果两个参照对象是完全一样的对象,Object.equals()返回true,这就说明了为什么这个方法通常不是很适合的原因。在大多数情况下,你需要一个方法来一个字段一个字段地进行比较,所以我们认为代表相同数据的不同对象是相等的。
HashCode()方法通过运用对象的内容执行一个哈希函数来生成一个int值。Hashtable和HashMap用这个值来算出一对key/value位于哪个bucket(哈希元)(或列表)中。作为例子,我们可以查看一下String 类,因为它有自己的方法来实现这两个方法。String.equals()对两个String对象一个字符一个字符地进行比较,如果字符串是相同的,则返回true:
String myName = "Einstein";
// The following test is
// always true
if ( myName.equals("Einstein") )
{ ...
String.hashCode()在一个字符串上运行哈希函数。字符串中每个字符的数字代码都乘以31,结果取决于字符串中字符的位置。然后将这些计算的结果相加,得到一个总数。这个过程似乎很复杂,但是它确保能够更好地分布值。它也证明了你在开发你自己的hashCode()方法时,能够走多远,确信结果是唯一的。
例如,假设我要用一个hashtable来实现一个书的目录,把书的ISBN号码作为搜索键来进行搜索。我可以用String类来承载细节,并准备好了equals()和hashCode()方法。我们可以用put()方法添加成对的key/value到hashtable中。
Put()方法接受两个参数,它们都属于Object类型。第一个参数是key;第二个参数是value。Put()方法调用key的hashCode()方法,用表中的列表数来除这个结果。把余数作为索引值来确定该条记录添加到哪个列表中。注意,key在表中是唯一的;如果你用一个已经存在的key来调用put(),匹配的条目就被修改了,因此它参照的是一个新的值,而旧的值被返回了(当key在表中不存在时,put()返回空值)。要读取表中的一个值,我们把搜索键用于get()方法。它返回一个转换到正确类型的Object参照:
BookRecord br =(BookRecord)isbnTable.get("0-345-40946-9");
System.out.println("Author: " + br.author+ " Title: " + br.title);
另一个有用的方法是remove(),其用法同get()几乎一样,它把条目从表中删除,并返回给调用程序。
你自己的类
如果你想把一个原始类型用做一个key,你必须创建一个同等类型的对象。例如,如果你想用一个整数key,你应该用构造器Integer(int)从整数中生成一个对象。所有的封装类如Integer、Float和Boolean都把原始值看做是对象,它们重载了equals()和hashCode()方法,因此,它们可以被用做key。JDK中提供的许多其它的类也是这样的(甚至Hashtable和HashMap类都实现它们自己的equals()和hashCode()方法),但你把任何类的对象用做hashtable keys前,应该查看文件。查看类的来源,看看equals()和hashCode()是如何实现的,也很有必要。例如,Byte、Character、Short和Integer都返回所代表的整数值作为哈希码。这可能适合,也可能不适合你的需求。
如果你想创建一个hashtable,这个hashtable运用你自己定义的一个类的对象作为key,那么你应该确信这个类的equals()和hashCode()方法提供有用的值。首先查看你扩展的类,确定它的实现是否满足你的需求。如果没有,你应该重载方法。
任何equals()方法的基本设计约束是,如果传递给它的对象属于同一个类,而且它的数据字段设定为表示同样数据的值,那么它就应该返回true。你也应该确信,如果传递一个空的参数给该方法,那么你的代码返回false:
public boolean equals(Object o){
if ( (o == null)|| !(o instanceof myClass)){
return false;
}
// Now compare data fields...
另外,在设计一个hashCode()方法时,应该记住一些规则。首先,该方法必须为一个特定的对象返回相同的值,而不管这个方法被调用了多少次(当然,只要对象的内容在调用之间没有改变,在将一个对象用做一个hashtable的key时,应该避免这一点)。第二,如果由你的equals()方法定义的两个对象是相等的,那么它们也必须生成相同的哈希码。第三,这更像是一个方针,而不是一个原则,你应该设法设计方法,使它为不同的对象内容生成不同的结果。如果偶尔不同的对象正好生成了相同的哈希码,这也不要紧。但是,如果该方法只能返回范围在1到10的值,那么只能用10个列表,而不管在hashtable中有多少个列表。
在设计equals()和hashCode()时,另一个要记住的因素是性能问题。每次调用put()或get(),都包括调用hashCode()来查找正确的列表,当get()扫描列表来查找key时,它为列表中的每个元素调用equals()。实现这些方法使它们尽可能快而有效地运行,尤其当你打算使你的类公开可用时,因为其它的用户可能想在执行速度很重要的情况下,在高性能的应用程序中运用你的类。
Hashtable性能
影响hashtable功效的主要因素就是表中列表的平均长度,因为平均搜索时间与这个平均长度直接相关。很显然,要减小平均长度,你必须增加hashtable中列表的数量;如果列表数量非常大,以至于大多数列表或所有列表只包含一条记录,你就会获得最佳的搜索效率。然而,这样做可能太过分了。如果你的hashtable的列表数远远多于数据条目,那你就没有必要做这样的内存花费了,而在一些情况下,人们也不可能接受这样的做法。
在我们前面的例子中,我们预先知道我们有多少条记录1,000。知道这点后,我们就可以决定我们的hashtable应该包含多少个列表,以便达成搜索速度和内存使用效率之间最好的折衷方式。然而,在许多情况下,你预先不知道你要处理多少条记录;数据被读取的文件可能会不断扩大,或者记录的数量可能一天一天地发生很大的变化。
随着条目的增加,Hashtable和HashMap类通过动态地扩展表来处理这个问题。这两个类都有接受表中列表最初数量的构造器,和一个作为参数的负载系数(load factor):
public Hashtable(int initialCapacity,float loadFactor)
public HashMap(int initialCapacity,float loadFactor)
将这两个数相乘计算出一个临界值。每次给哈希表添加一个新的条目时,计数就被更新,当计数超过临界值时,表被重新设置(rehash)。(列表数量增加到以前数量的两倍加1,所有的条目转移到正确的列表中。)缺省的构造器设定最初的容量为11,负载系数是0.75,所以临界值是8。当第九条记录被添加到表中时,就重新调整哈希表,使其有23个列表,新的临界值将是17(23*0.75的整数部分)。你可以看到,负载系数是哈希表中平均列表数量的上限,这就意味着,在缺省情况下,哈希表很少会有许多包含不只一条记录的列表。比较我们最初的例子,在那个例子中,我们有1,000条记录,分布在10个列表中。如果我们用缺省值,这个表将会扩展到含有1,500多个列表。但你可以控制这点。如果用负载系数相乘的列表数量大于你处理的条目数,那么表永远不会重制,所以我们可以仿效下面的例子:// Table will not rehash until it
// has 1,100 entries (10*110):
Hashtable myHashTable = new Hashtable(10, 110.0F);
你可能不想这么做,除非你没有为空的列表节省内存,而且不介意额外的搜索时间,这可能在嵌入系统中会出现这种情况。然而,这种方法可能很有用,因为重新设置很占用计算时间,而这种方法可以保证永远不会发生重新设置这种情况。注意,虽然调用put()可以使表增大(列表数量增加),调用remove()不会有相反的结果。所以,如果你有一个大的表,而且从中删除了大部分条目,结果你会有一个大的但是大部分是空的表。
Hashtable和HashMap
Hashtable和HashMap类有三个重要的不同之处。第一个不同主要是历史原因。Hashtable是基于陈旧的Dictionary类的,HashMap是Java 1.2引进的Map接口的一个实现。
也许最重要的不同是Hashtable的方法是同步的,而HashMapu方法不是。这就意味着,虽然你可以不用采取任何特殊的行为就可以在一个多线程的应用程序中用一个Hashtable,但你必须同样地为一个HashMap提供外同步。一个方便的方法就是利用Collections类的静态的synchronizedMap()方法,它创建一个线程安全的Map对象,并把它作为一个封装的对象来返回。这个对象的方法可以让你同步访问潜在的HashMap。这么做的结果就是当你不需要同步时,你不能切断Hashtable中的同步(比如在一个单线程的应用程序中),而且同步增加了很多处理费用。第三点不同是,只有HashMap可以让你将空值作为一个表的条目的key或value。HashMap中只有一条记录可以是一个空的key,但任意数量的条目可以是空的value。这就是说,如果在表中没有发现搜索键,或者如果发现了搜索键,但它是一个空的值,那么get()将返回null。如果有必要,用containKey()方法来区别这两种情况。
一些资料建议,当需要同步时,用Hashtable,反之用HashMap。但是,因为在需要时,HashMap可以被同步,HashMap的功能比Hashtable的功能更多,而且它不是基于一个陈旧的类的,所以有人认为,在各种情况下,HashMap都优先于Hashtable。
关于Properties
有时侯,你可能想用一个hashtable来映射key的字符串到value的字符串。DOS、Windows和Unix中的环境字符串就有一些例子,如key的字符串PATH被映射到value的字符串C:\WINDOWS;C:\WINDOWS\SYSTEM。Hashtables是表示这些的一个简单的方法,但Java提供了另外一种方法。
Java.util.Properties类是Hashtable的一个子类,设计用于String keys和values。Properties对象的用法同Hashtable的用法相象,但是类增加了两个节省时间的方法,你应该知道。Store()方法把一个Properties对象的内容以一种可读的形式保存到一个文件中。Load()方法正好相反,用来读取文件,并设定Properties对象来包含keys和values。注意,因为Properties扩展了Hashtable,你可以用超类的put()方法来添加不是String对象的keys和values。这是不可取的。另外,如果你将store()用于一个不包含String对象的Properties对象,store()将失败。作为put()和get()的替代,你应该用setProperty()和getProperty(),它们用String参数。好了,我希望你现在可以知道如何用hashtables来加速你的处理了。
关于作者:
Pete Ford已经做了20多年的软件开发工作了,他主要在嵌入系统和turnkey system方面进行研究。他生活并工作于德克萨斯州的达拉斯。你可以通过p_ford@mindspring.com联系他
哈希表是一种重要的存储方式,也是一种常见的检索方法。其基本思想是将关系码的值作为自变量,通过一定的函数关系计算出对应的函数值,把这个数值解释为结点的存储地址,将结点存入计算得到存储地址所对应的存储单元。检索时采用检索关键码的方法。现在哈希表有一套完整的算法来进行插入、删除和解决冲突。在Java中哈希表用于存储对象,实现快速检索。
Java.util.Hashtable提供了种方法让用户使用哈希表,而不需要考虑其哈希表真正如何工作。
哈希表类中提供了三种构造方法,分别是:
public Hashtable()
public Hashtable(int initialcapacity)
public Hashtable(int initialCapacity,float loadFactor)
参数initialCapacity是Hashtable的初始容量,它的值应大于0。loadFactor又称装载因子,是一个0.0到0.1之间的float型的浮点数。它是一个百分比,表明了哈希表何时需要扩充,例如,有一哈希表,容量为100,而装载因子为0.9,那么当哈希表90%的容量已被使用时,此哈希表会自动扩充成一个更大的哈希表。如果用户不赋这些参数,系统会自动进行处理,而不需要用户操心。
Hashtable提供了基本的插入、检索等方法。
■插入
public synchronized void put(Object key,Object value)
给对象value设定一关键字key,并将其加到Hashtable中。若此关键字已经存在,则将此关键字对应的旧对象更新为新的对象Value。这表明在哈希表中相同的关键字不可能对应不同的对象(从哈希表的基本思想来看,这也是显而易见的)。
■检索
public synchronized Object get(Object key)
根据给定关键字key获取相对应的对象。
public synchronized boolean containsKey(Object key)
判断哈希表中是否包含关键字key。
public synchronized boolean contains(Object value)
判断value是否是哈希表中的一个元素。
■删除
public synchronized object remove(object key)
从哈希表中删除关键字key所对应的对象。
public synchronized void clear()
清除哈希表
另外,Hashtalbe还提供方法获取相对应的枚举集合:
public synchronized Enumeration keys()
返回关键字对应的枚举对象。
public synchronized Enumeration elements()
返回元素对应的枚举对象。
例8.5 Hashtable.java给出了使用Hashtable的例子。
例8.5 Hashtalbe.java。
//import java.lang.*;
import java.util.Hashtable;
import java.util.Enumeration;
public class HashApp{
public static void main(String args[]){
Hashtable hash=new Hashtable(2,(float)0.8);
//创建了一个哈希表的对象hash,初始容量为2,装载因子为0.8
hash.put("Jiangsu","Nanjing");
//将字符串对象“Jiangsu”给定一关键字“Nanjing”,并将它加入hash
hash.put("Beijing","Beijing");
hash.put("Zhejiang","Hangzhou");
System.out.println("The hashtable hash1 is: "+hash);
System.out.println("The size of this hash table is "+hash.size());
//打印hash的内容和大小
Enumeration enum1=hash.elements();
System.out.print("The element of hash is: ");
while(enum1.hasMoreElements())
System.out.print(enum1.nextElement()+" ");
System.out.println();
//依次打印hash中的内容
if(hash.containsKey("Jiangsu"))
System.out.println("The capatial of Jiangsu is "+hash.get("Jiangsu"));
hash.remove("Beijing");
//删除关键字Beijing对应对象
System.out.println("The hashtable hash2 is: "+hash);
System.out.println("The size of this hash table is "+hash.size());
}
}
运行结果:
The hashtable hash1 is: {Beijing=Beijing, Zhejiang=Hangzhou, Jiangsu=Nanjing}
The size of this hash table is 3
The element of hash is: Beijing Hangzhou Nanjing
The capatial of Jiangsu is Nanjing
The hashtable hash2 is: {Zhejiang=Hangzhou, Jiangsu=Nanjing}
The size of this hash table is 2
Hashtable是Dictionary(字典)类的子类。在字典类中就把关键字对应到数据值。字典类是一个抽象类。在java.util中还有一个类Properties,它是Hashtable的子类。用它可以进行与对象属性相关的操作
http://www.skyabove.cn/article.asp?id=32
Hashtables(哈希表)在计算机领域中已不是一个新概念了。它们是用来加快计算机的处理速度的,用当今的标准来处理,速度非常慢,而它们可以让你在查询许多数据条目时,很快地找到一个特殊的条目。尽管现代的机器速度已快了几千倍,但是为了得到应用程序的最佳性能,hashtables仍然是个很有用的方法。
设想一下,你有一个包含约一千条记录的数据文件,比如一个小企业的客户记录,还有一个程序,它把记录读到内存中进行处理。每个记录包含一个唯一的五位数的客户ID号、客户名字、地址、帐户结余等等。假设记录不是按客户ID号顺序分类的,所以,如果程序要将客户ID号作为“key” 来查找一个特殊的客户记录,唯一的查找方法就是连续地搜索每个记录。有时侯,它会很快找到你需要的记录;但有时侯,在程序找到你需要的记录前,它几乎已搜索到了最后一条记录。如果要在1,000条记录中搜索,那么查找任何一条记录都需要程序平均查核500.5 ((1000 + 1 )/2)条记录。如果你常需要查找数据,你应该需要一个更快的方法来找到一条记录。
一种加快搜索的方法就是把记录分成几段,这样,你就不用搜索一个很大的列表了,而是搜索几个短的列表。对于我们数字式的客户ID号,你可以建10个列表,以0开头的ID号组成一个列表,以1开头的ID号组成一个列表,依此类推。那么要查找客户ID号38016,你只需要搜索以3开头的列表就行了。如果有1,000条记录,每个列表的平均长度为100(1,000条记录被分成10个列表),那么搜索一条记录的平均比较次数就降到了约50(见图1)。
当然,如果约十分之一的客户号是以0开头的,另外十分之一是以1开头的,等等,那么这种方法会很适合。如果90%的客户号以0开头,那么那个列表就会有900条记录,每次查找平均需要进行450次比较。另外,程序需要执行的搜索有90%都是针对以0开头的号码的。因此,平均比较数就大大超过简单数学运算的范围了。
如果我们可以按这样一种方式在我们的列表中分配记录,情况就会好一些,即每个列表约有相同条目的记录,而不管键值中数字的分布。我们需要一种方法能够把客户号码混合到一起并更好地分布结果。例如,我们可以取号码中的每位数,乘以某个大的数(随着数字位置的不同而不同), 然后将结果相加产生一个总数,把这个数除以10,并将余数作为索引值(index)(除数相同的分到一组)。当读入记录时,程序在客户号码上运行这个哈希(hash) 函数来确定记录属于哪个列表。当用户需要查询时,将同一个哈希函数作为一个“key”用于客户号码,这样就可以搜索正确的列表了。 像这样的一个数据结构就称为一个哈希表(hashtable)。
Java中的Hashtables
Java包含两个类,java.util.Hashtable 和java.util.HashMap,它们提供了一个多种用途的hashtable机制。这两个类很相似,通常提供相同的公有接口。但它们的确有一些重要的不同点,我在后面会讲到。
Hashtable和HashMap对象可以让你把一个key和一个value结合起来,并用put() 方法把这对key/value输入到表中。然后你可以通过调用get()方法,把key作为参数来得到这个value(值)。只要满足两个基本的要求,key和value可以是任何对象。注意,因为key和value必须是对象,所以原始类型(primitive types)必须通过运用诸如Integer(int)的方法转换成对象。
为了将一个特定类的对象用做一个key,这个类必须提供两个方法,equals() 和 hashCode()。这两个方法在java.lang.Object中,所以所有的类都可以继承这两个方法;但是,这两个方法在Object类中的实现一般没什么用,所以你通常需要自己重载这两个方法。Equals()方法把它的对象同另一个对象进行比较,如果这两个对象代表相同的信息,则返回true。该方法也查看并确保这两个对象属于相同的类。如果两个参照对象是完全一样的对象,Object.equals()返回true,这就说明了为什么这个方法通常不是很适合的原因。在大多数情况下,你需要一个方法来一个字段一个字段地进行比较,所以我们认为代表相同数据的不同对象是相等的。
HashCode()方法通过运用对象的内容执行一个哈希函数来生成一个int值。Hashtable和HashMap用这个值来算出一对key/value位于哪个bucket(哈希元)(或列表)中。作为例子,我们可以查看一下String 类,因为它有自己的方法来实现这两个方法。String.equals()对两个String对象一个字符一个字符地进行比较,如果字符串是相同的,则返回true:
String myName = "Einstein";
// The following test is
// always true
if ( myName.equals("Einstein") )
{ ...
String.hashCode()在一个字符串上运行哈希函数。字符串中每个字符的数字代码都乘以31,结果取决于字符串中字符的位置。然后将这些计算的结果相加,得到一个总数。这个过程似乎很复杂,但是它确保能够更好地分布值。它也证明了你在开发你自己的hashCode()方法时,能够走多远,确信结果是唯一的。
例如,假设我要用一个hashtable来实现一个书的目录,把书的ISBN号码作为搜索键来进行搜索。我可以用String类来承载细节,并准备好了equals()和hashCode()方法。我们可以用put()方法添加成对的key/value到hashtable中。
Put()方法接受两个参数,它们都属于Object类型。第一个参数是key;第二个参数是value。Put()方法调用key的hashCode()方法,用表中的列表数来除这个结果。把余数作为索引值来确定该条记录添加到哪个列表中。注意,key在表中是唯一的;如果你用一个已经存在的key来调用put(),匹配的条目就被修改了,因此它参照的是一个新的值,而旧的值被返回了(当key在表中不存在时,put()返回空值)。要读取表中的一个值,我们把搜索键用于get()方法。它返回一个转换到正确类型的Object参照:
BookRecord br =(BookRecord)isbnTable.get("0-345-40946-9");
System.out.println("Author: " + br.author+ " Title: " + br.title);
另一个有用的方法是remove(),其用法同get()几乎一样,它把条目从表中删除,并返回给调用程序。
你自己的类
如果你想把一个原始类型用做一个key,你必须创建一个同等类型的对象。例如,如果你想用一个整数key,你应该用构造器Integer(int)从整数中生成一个对象。所有的封装类如Integer、Float和Boolean都把原始值看做是对象,它们重载了equals()和hashCode()方法,因此,它们可以被用做key。JDK中提供的许多其它的类也是这样的(甚至Hashtable和HashMap类都实现它们自己的equals()和hashCode()方法),但你把任何类的对象用做hashtable keys前,应该查看文件。查看类的来源,看看equals()和hashCode()是如何实现的,也很有必要。例如,Byte、Character、Short和Integer都返回所代表的整数值作为哈希码。这可能适合,也可能不适合你的需求。
如果你想创建一个hashtable,这个hashtable运用你自己定义的一个类的对象作为key,那么你应该确信这个类的equals()和hashCode()方法提供有用的值。首先查看你扩展的类,确定它的实现是否满足你的需求。如果没有,你应该重载方法。
任何equals()方法的基本设计约束是,如果传递给它的对象属于同一个类,而且它的数据字段设定为表示同样数据的值,那么它就应该返回true。你也应该确信,如果传递一个空的参数给该方法,那么你的代码返回false:
public boolean equals(Object o){
if ( (o == null)|| !(o instanceof myClass)){
return false;
}
// Now compare data fields...
另外,在设计一个hashCode()方法时,应该记住一些规则。首先,该方法必须为一个特定的对象返回相同的值,而不管这个方法被调用了多少次(当然,只要对象的内容在调用之间没有改变,在将一个对象用做一个hashtable的key时,应该避免这一点)。第二,如果由你的equals()方法定义的两个对象是相等的,那么它们也必须生成相同的哈希码。第三,这更像是一个方针,而不是一个原则,你应该设法设计方法,使它为不同的对象内容生成不同的结果。如果偶尔不同的对象正好生成了相同的哈希码,这也不要紧。但是,如果该方法只能返回范围在1到10的值,那么只能用10个列表,而不管在hashtable中有多少个列表。
在设计equals()和hashCode()时,另一个要记住的因素是性能问题。每次调用put()或get(),都包括调用hashCode()来查找正确的列表,当get()扫描列表来查找key时,它为列表中的每个元素调用equals()。实现这些方法使它们尽可能快而有效地运行,尤其当你打算使你的类公开可用时,因为其它的用户可能想在执行速度很重要的情况下,在高性能的应用程序中运用你的类。
Hashtable性能
影响hashtable功效的主要因素就是表中列表的平均长度,因为平均搜索时间与这个平均长度直接相关。很显然,要减小平均长度,你必须增加hashtable中列表的数量;如果列表数量非常大,以至于大多数列表或所有列表只包含一条记录,你就会获得最佳的搜索效率。然而,这样做可能太过分了。如果你的hashtable的列表数远远多于数据条目,那你就没有必要做这样的内存花费了,而在一些情况下,人们也不可能接受这样的做法。
在我们前面的例子中,我们预先知道我们有多少条记录1,000。知道这点后,我们就可以决定我们的hashtable应该包含多少个列表,以便达成搜索速度和内存使用效率之间最好的折衷方式。然而,在许多情况下,你预先不知道你要处理多少条记录;数据被读取的文件可能会不断扩大,或者记录的数量可能一天一天地发生很大的变化。
随着条目的增加,Hashtable和HashMap类通过动态地扩展表来处理这个问题。这两个类都有接受表中列表最初数量的构造器,和一个作为参数的负载系数(load factor):
public Hashtable(int initialCapacity,float loadFactor)
public HashMap(int initialCapacity,float loadFactor)
将这两个数相乘计算出一个临界值。每次给哈希表添加一个新的条目时,计数就被更新,当计数超过临界值时,表被重新设置(rehash)。(列表数量增加到以前数量的两倍加1,所有的条目转移到正确的列表中。)缺省的构造器设定最初的容量为11,负载系数是0.75,所以临界值是8。当第九条记录被添加到表中时,就重新调整哈希表,使其有23个列表,新的临界值将是17(23*0.75的整数部分)。你可以看到,负载系数是哈希表中平均列表数量的上限,这就意味着,在缺省情况下,哈希表很少会有许多包含不只一条记录的列表。比较我们最初的例子,在那个例子中,我们有1,000条记录,分布在10个列表中。如果我们用缺省值,这个表将会扩展到含有1,500多个列表。但你可以控制这点。如果用负载系数相乘的列表数量大于你处理的条目数,那么表永远不会重制,所以我们可以仿效下面的例子:// Table will not rehash until it
// has 1,100 entries (10*110):
Hashtable myHashTable = new Hashtable(10, 110.0F);
你可能不想这么做,除非你没有为空的列表节省内存,而且不介意额外的搜索时间,这可能在嵌入系统中会出现这种情况。然而,这种方法可能很有用,因为重新设置很占用计算时间,而这种方法可以保证永远不会发生重新设置这种情况。注意,虽然调用put()可以使表增大(列表数量增加),调用remove()不会有相反的结果。所以,如果你有一个大的表,而且从中删除了大部分条目,结果你会有一个大的但是大部分是空的表。
Hashtable和HashMap
Hashtable和HashMap类有三个重要的不同之处。第一个不同主要是历史原因。Hashtable是基于陈旧的Dictionary类的,HashMap是Java 1.2引进的Map接口的一个实现。
也许最重要的不同是Hashtable的方法是同步的,而HashMapu方法不是。这就意味着,虽然你可以不用采取任何特殊的行为就可以在一个多线程的应用程序中用一个Hashtable,但你必须同样地为一个HashMap提供外同步。一个方便的方法就是利用Collections类的静态的synchronizedMap()方法,它创建一个线程安全的Map对象,并把它作为一个封装的对象来返回。这个对象的方法可以让你同步访问潜在的HashMap。这么做的结果就是当你不需要同步时,你不能切断Hashtable中的同步(比如在一个单线程的应用程序中),而且同步增加了很多处理费用。第三点不同是,只有HashMap可以让你将空值作为一个表的条目的key或value。HashMap中只有一条记录可以是一个空的key,但任意数量的条目可以是空的value。这就是说,如果在表中没有发现搜索键,或者如果发现了搜索键,但它是一个空的值,那么get()将返回null。如果有必要,用containKey()方法来区别这两种情况。
一些资料建议,当需要同步时,用Hashtable,反之用HashMap。但是,因为在需要时,HashMap可以被同步,HashMap的功能比Hashtable的功能更多,而且它不是基于一个陈旧的类的,所以有人认为,在各种情况下,HashMap都优先于Hashtable。
关于Properties
有时侯,你可能想用一个hashtable来映射key的字符串到value的字符串。DOS、Windows和Unix中的环境字符串就有一些例子,如key的字符串PATH被映射到value的字符串C:\WINDOWS;C:\WINDOWS\SYSTEM。Hashtables是表示这些的一个简单的方法,但Java提供了另外一种方法。
Java.util.Properties类是Hashtable的一个子类,设计用于String keys和values。Properties对象的用法同Hashtable的用法相象,但是类增加了两个节省时间的方法,你应该知道。Store()方法把一个Properties对象的内容以一种可读的形式保存到一个文件中。Load()方法正好相反,用来读取文件,并设定Properties对象来包含keys和values。注意,因为Properties扩展了Hashtable,你可以用超类的put()方法来添加不是String对象的keys和values。这是不可取的。另外,如果你将store()用于一个不包含String对象的Properties对象,store()将失败。作为put()和get()的替代,你应该用setProperty()和getProperty(),它们用String参数。好了,我希望你现在可以知道如何用hashtables来加速你的处理了。
关于作者:
Pete Ford已经做了20多年的软件开发工作了,他主要在嵌入系统和turnkey system方面进行研究。他生活并工作于德克萨斯州的达拉斯。你可以通过p_ford@mindspring.com联系他
哈希表是一种重要的存储方式,也是一种常见的检索方法。其基本思想是将关系码的值作为自变量,通过一定的函数关系计算出对应的函数值,把这个数值解释为结点的存储地址,将结点存入计算得到存储地址所对应的存储单元。检索时采用检索关键码的方法。现在哈希表有一套完整的算法来进行插入、删除和解决冲突。在Java中哈希表用于存储对象,实现快速检索。
Java.util.Hashtable提供了种方法让用户使用哈希表,而不需要考虑其哈希表真正如何工作。
哈希表类中提供了三种构造方法,分别是:
public Hashtable()
public Hashtable(int initialcapacity)
public Hashtable(int initialCapacity,float loadFactor)
参数initialCapacity是Hashtable的初始容量,它的值应大于0。loadFactor又称装载因子,是一个0.0到0.1之间的float型的浮点数。它是一个百分比,表明了哈希表何时需要扩充,例如,有一哈希表,容量为100,而装载因子为0.9,那么当哈希表90%的容量已被使用时,此哈希表会自动扩充成一个更大的哈希表。如果用户不赋这些参数,系统会自动进行处理,而不需要用户操心。
Hashtable提供了基本的插入、检索等方法。
■插入
public synchronized void put(Object key,Object value)
给对象value设定一关键字key,并将其加到Hashtable中。若此关键字已经存在,则将此关键字对应的旧对象更新为新的对象Value。这表明在哈希表中相同的关键字不可能对应不同的对象(从哈希表的基本思想来看,这也是显而易见的)。
■检索
public synchronized Object get(Object key)
根据给定关键字key获取相对应的对象。
public synchronized boolean containsKey(Object key)
判断哈希表中是否包含关键字key。
public synchronized boolean contains(Object value)
判断value是否是哈希表中的一个元素。
■删除
public synchronized object remove(object key)
从哈希表中删除关键字key所对应的对象。
public synchronized void clear()
清除哈希表
另外,Hashtalbe还提供方法获取相对应的枚举集合:
public synchronized Enumeration keys()
返回关键字对应的枚举对象。
public synchronized Enumeration elements()
返回元素对应的枚举对象。
例8.5 Hashtable.java给出了使用Hashtable的例子。
例8.5 Hashtalbe.java。
//import java.lang.*;
import java.util.Hashtable;
import java.util.Enumeration;
public class HashApp{
public static void main(String args[]){
Hashtable hash=new Hashtable(2,(float)0.8);
//创建了一个哈希表的对象hash,初始容量为2,装载因子为0.8
hash.put("Jiangsu","Nanjing");
//将字符串对象“Jiangsu”给定一关键字“Nanjing”,并将它加入hash
hash.put("Beijing","Beijing");
hash.put("Zhejiang","Hangzhou");
System.out.println("The hashtable hash1 is: "+hash);
System.out.println("The size of this hash table is "+hash.size());
//打印hash的内容和大小
Enumeration enum1=hash.elements();
System.out.print("The element of hash is: ");
while(enum1.hasMoreElements())
System.out.print(enum1.nextElement()+" ");
System.out.println();
//依次打印hash中的内容
if(hash.containsKey("Jiangsu"))
System.out.println("The capatial of Jiangsu is "+hash.get("Jiangsu"));
hash.remove("Beijing");
//删除关键字Beijing对应对象
System.out.println("The hashtable hash2 is: "+hash);
System.out.println("The size of this hash table is "+hash.size());
}
}
运行结果:
The hashtable hash1 is: {Beijing=Beijing, Zhejiang=Hangzhou, Jiangsu=Nanjing}
The size of this hash table is 3
The element of hash is: Beijing Hangzhou Nanjing
The capatial of Jiangsu is Nanjing
The hashtable hash2 is: {Zhejiang=Hangzhou, Jiangsu=Nanjing}
The size of this hash table is 2
Hashtable是Dictionary(字典)类的子类。在字典类中就把关键字对应到数据值。字典类是一个抽象类。在java.util中还有一个类Properties,它是Hashtable的子类。用它可以进行与对象属性相关的操作
http://www.skyabove.cn/article.asp?id=32
enum
An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
In the Java programming language, you define an enum type by using the enum keyword. For example, you would specify a days-of-the-week enum type as:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.
for (Planet p : Planet.values()) {
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}
Note: All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.
Each enum constant is declared with values for the mass and radius parameters. These values are passed to the constructor when the constant is created. Java requires that the constants be defined first, prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must end with a semicolon.
Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.
ref:
Enum Types
掌握JDK1.5枚举类型
体验JAVA 5的新增语言特性
In the Java programming language, you define an enum type by using the enum keyword. For example, you would specify a days-of-the-week enum type as:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.
for (Planet p : Planet.values()) {
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}
Note: All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.
Each enum constant is declared with values for the mass and radius parameters. These values are passed to the constructor when the constant is created. Java requires that the constants be defined first, prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must end with a semicolon.
Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.
ref:
Enum Types
掌握JDK1.5枚举类型
体验JAVA 5的新增语言特性
enum
An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
In the Java programming language, you define an enum type by using the enum keyword. For example, you would specify a days-of-the-week enum type as:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.
for (Planet p : Planet.values()) {
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}
Note: All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.
Each enum constant is declared with values for the mass and radius parameters. These values are passed to the constructor when the constant is created. Java requires that the constants be defined first, prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must end with a semicolon.
Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.
ref:
Enum Types
掌握JDK1.5枚举类型
In the Java programming language, you define an enum type by using the enum keyword. For example, you would specify a days-of-the-week enum type as:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.
for (Planet p : Planet.values()) {
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}
Note: All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.
Each enum constant is declared with values for the mass and radius parameters. These values are passed to the constructor when the constant is created. Java requires that the constants be defined first, prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must end with a semicolon.
Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.
ref:
Enum Types
掌握JDK1.5枚举类型
Wednesday, 25 April 2007
Subscribe to:
Posts (Atom)