《Java2图形设计卷II:Swing》配套光盘源码
源代码在线查看: test.java
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JApplet {
JTextField tf = new JTextField(3);
public Test() {
Container contentPane = getContentPane();
JLabel label = new JLabel("Enter an Integer:");
tf.setDocument(new IntegerDocument());
contentPane.setLayout(new FlowLayout());
contentPane.add(label);
contentPane.add(tf);
}
}
class IntegerDocument extends PlainDocument {
public void insertString(int offset, String s,
AttributeSet attributeSet)
throws BadLocationException {
try {
Integer.parseInt(s);
}
catch(Exception ex) { // only allow integer values
Toolkit.getDefaultToolkit().beep();
return;
}
super.insertString(offset, s, attributeSet);
}
}