2012-10-12 240 views
5

Tengo un código aquí que obtuve del weblog de MDP. el filtro de tamaño y el filtro numérico. cómo hago que un campo de texto establezca su filtro para dos filtros de documentos.Cómo hacer que el campo de texto tenga 2 filtros de documento

Aquí isthe numberfilter

import javax.swing.text.BadLocationException; 
import javax.swing.text.AttributeSet; 
import javax.swing.text.DocumentFilter; 

public class IntFilter extends DocumentFilter { 

public void insertString(DocumentFilter.FilterBypass fb, int offset, 
         String string, AttributeSet attr) 
     throws BadLocationException { 

    StringBuffer buffer = new StringBuffer(string); 
    for (int i = buffer.length() - 1; i >= 0; i--) { 
     char ch = buffer.charAt(i); 
     if (!Character.isDigit(ch)) { 
      buffer.deleteCharAt(i); 
     } 
    } 
    super.insertString(fb, offset, buffer.toString(), attr); 
} 

public void replace(DocumentFilter.FilterBypass fb, 
        int offset, int length, String string, AttributeSet attr) throws BadLocationException { 
    if (length > 0) fb.remove(offset, length); 
    insertString(fb, offset, string, attr); 
} 
} 

este código es para el sizefilter

import java.awt.*; 
import javax.swing.text.AttributeSet; 
import javax.swing.text.BadLocationException; 
import javax.swing.text.DocumentFilter; 

public class SizeFilter extends DocumentFilter { 

private int maxCharacters;  

public SizeFilter(int maxChars) { 
    maxCharacters = maxChars; 
} 

public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) 
     throws BadLocationException { 

    if ((fb.getDocument().getLength() + str.length()) <= maxCharacters) 
     super.insertString(fb, offs, str, a); 
    else 
     Toolkit.getDefaultToolkit().beep(); 
} 

public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) 
     throws BadLocationException { 

    if ((fb.getDocument().getLength() + str.length() 
      - length) <= maxCharacters) 
     super.replace(fb, offs, length, str, a); 
    else 
     Toolkit.getDefaultToolkit().beep(); 
} 
} 

Respuesta

3

Tienes dos opciones en lo que puedo ver. O bien crear un filtro compuesto que itera sobre cada filtro:

public class CompositeFilter extends DocumentFilter { 
    private final DocumentFilter[] filters; 

    public CompositeFilter(DocumentFilter... filters) { 
     this.filters = filters; 
    } 

    public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) 
     throws BadLocationException { 
     for (DocumentFilter filter : filters) { 
      filter.insertString(fb, offs, str, a); 
     } 
    } 

    public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) 
     throws BadLocationException { 
     for (DocumentFilter filter : filters) { 
      filter.replace(fb, offs, length, a); 
     } 
    } 
} 

Probablemente usted desea crear una instancia del compuesto con el filtro más restrictivo en primer lugar, por lo que tendría que construir de este modo:

new CompositeFilter(new SizeFilter(10), new IntFilter()); 

Si el orden es críticamente importante, puede considerar reescribir sus filtros como decoradores, por ejemplo pasa el segundo filtro al primero y luego llámalo.

public class SizeFilter extends DocumentFilter { 
    private int maxCharacters;  
    private final DocumentFilter delegate; 

    public SizeFilter(int maxChars, DocumentFilter delegate) { 
     maxCharacters = maxChars; 
     this.delegate = delegate; 
    } 

    public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) 
     throws BadLocationException { 

     if ((fb.getDocument().getLength() + str.length()) <= maxCharacters) 
      delegate.insertString(fb, offs, str, a); 
     else 
      Toolkit.getDefaultToolkit().beep(); 
    } 

    public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) 
     throws BadLocationException { 

     if ((fb.getDocument().getLength() + str.length() - length) <= maxCharacters) 
      delegate.replace(fb, offs, length, str, a); 
     else 
      Toolkit.getDefaultToolkit().beep(); 
     } 
    } 
} 
+2

probé el primer código y solucioné algunos errores de importación. y theres éste error en esta parte: 'filter.replace (FB, offs, longitud, a);' Este es el error: ** método de sustituir en javax.swing.text.DocumentFilter clase no puede aplicarse a tipos determinados requerido: javax.swing.text.DocumentFilter.FilterBypass, int, int, java.lang.String, javax.swing.text.AttributeSet encontrado: javax.swing.text.DocumentFilter.FilterBypass, int, int, javax.print.attribute.AttributeSet ** –

+1

Has importado el AttributeSet incorrecto. –

+1

ahora que he combinado los dos filtros, simplemente no funciona, no sé por qué. pero de alguna manera limita el campo de texto solo a caracteres y más allá del límite solo puedo escribir números –

Cuestiones relacionadas