package de.tutorials;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class TextFeldDemo extends JFrame{
public TextFeldDemo() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
JTextField demo = new JTextField(30);
demo.setDocument(new IntegerDocument());
getContentPane().add(demo);
pack();
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new TextFeldDemo().setVisible(true);
}
class IntegerDocument extends PlainDocument {
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
try {
Integer.parseInt(str);
super.insertString(offs, str, a);
} catch (NumberFormatException e) {
Toolkit.getDefaultToolkit().beep();
}
}
}
}