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.

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.

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.

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


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


计世网论坛

计世网论坛,里面的文章还是不错的
http://www3.ccw.com.cn/forumdisplay.php?fid=9&page=1

文字输入组件的使用与介绍

++ 文字输入组件的使用与介绍

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胃泰

止痛药芬必得
万应止痛膏
解热止痛片
牙痛一粒丸治牙痛
抗过敏息斯敏
扑尔敏过敏性疾病、伤风流涕、药物过敏等
外用药创可贴止血、消炎、护创
紫药水杀菌,用于皮肤、粘膜感染及溃疡
皮康霜
皮炎平用于皮肤瘙痒
云南白药用于跌打损伤
驱风油
四环素软膏抗菌排脓,用于痤疮、皮炎、冻疮、烫伤、烧伤
诺氟沙星滴眼液多种病原菌引起的外眼部感染,如角膜炎、结膜炎等
盐酸环丙沙星滴眼液用于眼睛疾病
正红花油烫伤、蚊虫叮咬
达克宁霜用于治疗脚气等
消炎、消火牛黄解毒片
西瓜霜润喉片清音利咽、消肿止痛

最后需要注意的是: 任何衣物都要保证不缩水; 因为这里的衣服基本都是烘干, 不是自然晾晒干
护照(签证)(均要复制两份,一份随身,一份留家中)
入学通知(均要复制两份,一份随身,一份留家中)
机票钱(包括零钱)
体检证明(包括接种证明、小药箱)
其他文件(如成绩单、学位证书、推荐信,均要复制两份,一份随身,一份留家中)
护照照片 (最好使用白色背景)
接机人姓名、电话
在英亲戚朋友通信录
紧急联络电话
我国驻当地大使馆、商务办事处电话。
前两天生活用品(换洗内衣裤一套、药品、纸笔、眼镜、牙刷牙膏、毛巾、手纸)

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

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的新增语言特性

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枚举类型

Wednesday, 25 April 2007

linux_beryl

http://www.youtube.com/watch?v=xC5uEe5OzNQ&mode=related&search=

lecture 7;8;9

lecture 6

Memory-Mapped Input and Output

Within SPIM: console and keyboard are using by CPU to communicate with external devices.

Some MIPS addresses are actually device registers

  • Console I/O in SPIM
  • SPIM emulates MMIO
  • Must select ‘Mapped I/O’ in PCSpim settings
  • Receiver – keyboard
  • Transmitter – display
  • Can still use syscalls

Keyboard Input

  1. Receiver control (at FFFF000016) consists of 2 bits
  2. Bit 0 is the ‘ready’ bit – unread input from keyboard
  3. Receiver data (at FFFF000416) contains last pressed key
  4. Reading data register resets ‘ready’ bit
  5. Read from control register
  6. AND off the ‘ready’ bit
  7. If zero, no keypress
  8. Keep waiting
  9. Else read data register
  • li $t0, 0xffff0000
  • rd poll:
  • lw $v0, 0($t0)
  • andi $v0, $v0, 0x01
  • beq $v0, $zero, rd poll
  • lw $v0, 4($t0)
  • # last key code in $v0

Character Display

  1. Transmitter control (at FFFF000816) consists of 2 bits
  2. Bit 0 is the ‘ready’ bit – display accepting new character
  3. Transmitter data (at FFFF000C16) takes ASCII character
  4. Writing data register resets ‘ready’ bit
  5. Read from control register
  6. AND off the ‘ready’ bit
  7. If zero, not ready
  8. Keep waiting
  9. Else send to data register
  • # character in $a0
  • li $t0, 0xffff0008
  • wr poll:
  • lw $v0, 0($t0)
  • andi $v0, $v0, 0x01
  • beq $v0, $zero, wr poll
  • sw $a0, 4($t0)

half-adder

  • S = A &B
  • C = A ^ B

Full-Adder

  • S = A &amp;amp;amp;amp;B& Cin
  • Cout = (A^B)&(B^Cin)&(A^Cin)


Ripple Carry Adder

  • A chain of full-adders can sum as many bits as needed
  • The Cout of each adder is wired to the Cin of the next
  • Present the nth bit of inputs A and B to the nth adder
  • Set C0 to 0; carry out C4 indicates overflow
  • Calculates S = A + B, where Sn is the nth bit of S. . .
  • The carry bits ripples across the full adders
  • Simplest, but not the fastest (c.f. carry look-ahead)

Representing Negative Numbers

  • Sign and Magnitude :What we use in decimal notation: +/− and 0, 1, 2, · · ·, becide the sign bit, other bits are same for a pair of positive and negative number.
  • Ones’ Complement : Represent −x by its bitwise inverse (NOT). the bits are revise between positve and negative number, +0 and -0 are special.
  • Excess-n :Zero represented by binary n: 02 is thus −n
  • Two’s Complement :For an n-bit number, represent −x by 2n − x

Method of Complements :Subtract each digit of x from b − 1, then add 1 to result

Two’s Complements :In base 2 with n bits, represent −x using 2n − x

But there’s a quicker way to calculate 2n − x:

  1. Take the bitwise inverse (NOT) of x, then add 1 to result
  2. Addition as for unsigned numbers; just ignore carry bit
  3. Conventionally we take the MSB to represent the sign 0 for positive, 1 for negative

Thus n bits can represent from −2n−1 up to 2n−1 − 1

All modern processors primarily use two’s complement


lecture 7

Sign Extension :For a signed byte, copy the MSB (bit 7) 24 times:

lb and lh performs sign extension;

However, add and addi also check for overflow

Overflow when result exceeds −231 _ x <>On overflow, trigger an error exception Try

  • li $t0, 0x7fffffff
  • addi $t0, $t0, 1
  • Checking for Overflow
  • addu $s0, $s1, $s2
  • xor $t0, $s1, $s2
  • blt $t0, $zero, no overflow
  • xor $t0, $s0, $s1
  • bge $t0, $zero, no overflow
  • # we have overflow!
  • no overflow: # rest of program

Multiplication Product of m- and n-digit numbers requires m + n digits

n-Bit Binary Multiplication

Muln produces a 64-bit word; divn two 32-bit results

Slow compared to e.g. addition; takes many cycles Would stall the next instructions in the pipeline Independent unit (from main ALU) for muln and divn Source operands come from the usual register file Results written to two special registers HI and LO


lecture 8

Shifting the Point What is 0.110 in binary? 0.110 = 0.0001001001 . . .2 Digits repeat forever – no exact finite representation!

Use binary scaling: e.g.

  • let one increment represent 1/16th Hence,
  • 0000.00012 = 1 _= 1/16 = 0.0625
  • 0001.10002 = 24 _= 24/16 = 1.5 Fixed Point Arithmetic

Fixed position for binary point Addition same as integers: a/c + b/c = (a + b)/c
Multiplication mostly unchanged, but must scale after
a b
- * - =
(a × b)/c
c c
e.g. 1.5 × 2.5 = 3.75
0001.10002 × 0010.10002 = 0011.1100 00002

Scientific Notation

  • General form ±m × be where
  • The mantissa contains a decimal point
  • The exponent is an integer e 2 Z
  • The base can be any positive integer b 2 N_
  • A number is normalised when 1 _ m < 0016 =" 0" 6=" 0" ff16 =" 0" 6=" 0"> largest representable number
Why do we want infinities and NaN?
  • Alternative is to give a wrong value, or raise an exception
  • Overflow gives ±1 (underflow gives denormalised)
  • In long computations, only a few results may be wrong
  • Raising exceptions would abort entire process
  • Giving a misleading result is just plain dangerous
  • Infinities and NaN propagate through calculations, e.g. 1 + (1 ÷ 0) = 1 +1 = 1 ; (0 ÷ 0) + 1 = NaN + 1 = NaN


lecture 9

Floating Point Addition

  1. Suppose f0 = m0 × 2e0 and f1 = m1 × 2e1
  2. Then f0 × f1 = m0 × m1 × 2e0+e1
  3. Shift the smaller number right until exponents match
  4. Add/subtract the mantissas, depending on sign
  5. Normalise the sum by adjusting exponent
  6. Check for overflow
  7. Round to available bits
  8. Result may need further normalisation; if so, goto step 3
Floating Point Multiplication: Suppose f0 = m0 × 2e0 and f1 = m1 × 2e1 ; Then f0 × f1 = m0 × m1 × 2e0+e1
  • 1 Add the exponents (be careful, excess-n encoding!)
  • 2 Multiply the mantissas, setting the sign of the product
  • 3 Normalise the product by adjusting exponent
  • 4 Check for overflow
  • 5 Round to available bits
  • 6 Result may need further normalisation; if so, goto step 3

IEEE 754 Rounding
Hardware needs two extra bits (round, guard) for rounding
IEEE 754 defines four rounding modes

  • Round Up Always toward +1 Round Down Always toward −1 Towards Zero Round
  • down if positive, up if negative
  • Round to Even Rounds to nearest even value: in a tie, pick the closest ‘even’ number: e.g. 1.5 rounds to 2.0, but 4.5 rounds to 4.0
MIPS and Java uses round to even by default; If the closest’s bit is 1, then add 1. or stay the same.

Here be Dragons
Cannot rely on e.g. (a + b) + c = a + (b + c)
e.g. calculate 1 + 1020 − 1020 on a computer

Absolute and Relative Error

  • We wish to represent some given some number m
  • Its IEEE 754 representation is n – an approximation
  • The absolute error is defined to be
  • a = |m − n|
  • The relative error is defined as
  • r = |m − n|/n
  • m The true value of n lies within the ranges
  • n ± a = [n − a, n + a], or
  • n(1 ± r ) = [n(1 − r ), n(1 + r )]

Error Propagation

  • Addition or subtraction sums absolute error of operands (x ± ax ) + (y ± ay ) = (x + y) ± (ax + ay )
  • When x _ −y, the error can be as large as the result
  • Multiplication or division sums relative error of operands : x(1 ± rx ) × y(1 ± ry ) = (x × y)(1 ± (rx + ry ) ± rx*ry ) We can ignore the much smaller rx*ry term

Example: given the relative error of x, y and z,

  • what is the absolute error in the expression y2 − 4xz?
  • y2(1 ± 2ry ) − 4xz(1 ± (rx + rz )) = (y2 − 4xz) ± (2y2ry + 4xz(rx + rz ))