In the code below, the insertString and replace methods are redefined. For the new IntFilter filter, which analyzes the string and inserts only numbers and the symbol -:

JFormattedTextField intField3 = new JFormattedTextField( new InternationalFormatter( NumberFormat.getIntegerInstance()) { protected DocumentFilter getDocumentFilter() { return filter; } private DocumentFilter filter = new IntFilter(); } ); intField3.setValue( new Integer(100) ); 

The compiler swears at

 super.insertString(fb, offset, builder.toString(), attr); 

and

 super.replace(fb, offset, length, string, attr); 

Writes what: cannot be applied to given types

Here is the IntFilter class code

 package swingformattest; import java.lang.reflect.Array; import javax.print.attribute.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DocumentFilter; /** * Фильтр ограничивающий ввод цифрами и знаком минус * @author Igor */ public class IntFilter extends DocumentFilter { public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { StringBuilder builder = new StringBuilder( string ); for ( int i = builder.length(); i >= 0; i-- ) { int cp = builder.codePointAt( i ); if ( !Character.isDigit(cp) && cp != '-' ) { builder.deleteCharAt( i ); if ( Character.isSupplementaryCodePoint( cp ) ) { i--; builder.deleteCharAt( i ); } } } super.insertString(fb, offset, builder.toString(), attr); } public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attrs) throws BadLocationException { if ( string != null ) { StringBuilder builder = new StringBuilder( string ); for ( int i = builder.length(); i >= 0; i-- ) { int cp = builder.codePointAt( i ); if ( !Character.isDigit(cp) && cp != '-' ) { builder.deleteCharAt( i ); if ( Character.isSupplementaryCodePoint( cp ) ) { i--; builder.deleteCharAt( i ); } } } } super.replace(fb, offset, length, string, attr); } } 

This example is taken from the book of Horstman Java 2 Volume 1.

    1 answer 1

    You imported the wrong AttributeSet :). You need

     import javax.swing.text.AttributeSet; 

    The negative side of auto import IDE.