Swing
Wie kann ich ein Textfeld erstellen, indem nur Zahlen eingegeben werden können?
package de.bastie.howto.swing.text;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import javax.swing.text.AttributeSet;
import java.math.BigDecimal;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NumberDocument extends PlainDocument{
private BigDecimal testInstance;
public void insertString (final int offset,
final String text,
final AttributeSet attributeSet)
throws BadLocationException {
if (this.isNumber(text)){
super.insertString (offset, text, attributeSet);
}
}
protected boolean isNumber (final String toTest) {
try {
if (toTest.length() > 0)
this.testInstance = new BigDecimal (toTest);
return true;
}
catch (final NumberFormatException ignored){
}
return false;
}
public static void main (final String [] ignored){
JFrame jFrameTest = new JFrame ("Test");
jFrameTest.addWindowListener (new WindowAdapter (){
public void windowClosing (final WindowEvent exitApplication){
System.exit (0);
}
});
jFrameTest.getContentPane().setLayout (new BorderLayout (0,0));
jFrameTest.getContentPane().add (
new JTextField (new NumberDocument (), "", 0), BorderLayout.NORTH);
jFrameTest.pack ();
jFrameTest.setVisible (true);
}
}
all rights reserved © Bastie - Sebastian Ritter @:
w³: http://www.Bastie.de
Diese Seite ist Bestandteil der
Internetpräsenz unter http://www.Bastie.de
Java
Cobol
Software
Resourcen
Service
Links
Über mich
Zum Gästebuch
Forum