E' già stato trattato come argomento... io mi sono creato una classe a parte che estende JTextField e ci appiccico un Document adhoc.
codice:
import javax.swing.*;
import java.util.regex.*;
import javax.swing.text.*;
/**
*
* @author Andrea
*/
public class JNumberTextField extends JTextField {
private class NumbersOnly extends PlainDocument {
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
Pattern p = Pattern.compile("\\D*");
Matcher m = p.matcher(str);
if (str == null || m.matches()) {
return;
}
super.insertString(offs, str, a);
}
}
/** Creates a new instance of JNumberTextField */
public JNumberTextField() {
super();
this.setDocument(new NumbersOnly());
}
}