Erro ao limpar JTextField

4 respostas
Alix

Olá povo. ^-^

Bom.. eu fiz uma restrição nos meus campo, uns que aceitam apenas números e outro que aceita apenas string. Ele está funcionando direitinho, porem na hora de limpar o campo ao terminar de salvar, alterar ou mesmo no botão limpar. Ele acusa um erro por causa dessa restrição.

BOTÃO LIMPAR

private void BT_LimparMouseClicked(java.awt.event.MouseEvent evt) {
        TF_Pesquisa.setText(null);
        TF_Nome.setText(null);
        TF_Idade.setText(null);
        TF_CPF.setText(null);
        TF_Cod.setText(null);
        TF_Res.setText(null);
        TF_Cel.setText(null);
        LB_Foto.setIcon(null);
        chk_Presenca.enable(false);
    }

Já tentei usar também

private void BT_LimparMouseClicked(java.awt.event.MouseEvent evt) {
        TF_Pesquisa.setText("");
        TF_Nome.setText("");
        TF_Idade.setText("");
        TF_CPF.setText("");
        TF_Cod.setText("");
        TF_Res.setText("");
        TF_Cel.setText("");
        LB_Foto.setIcon(null);
        chk_Presenca.enable(false);
    }

Mas ae ele limpa apenas a foto, e os outros campos ficam lá. @-@

CLASSE QUE VERIFICA OS CAMPOS

package a;
import javax.swing.text.AttributeSet;  
import javax.swing.text.BadLocationException;  
/* 
* Esta classe permite que apenas números sejam inseridos em um JTextField 
* Para usar este Document: ((AbstractDocuement) jTextField.getDocument()).setDocumentFilter(new IntegerDocument()); 
*/  

public class ValidarNum extends TamanhoNum {  
      
    public ValidarNum(int maxLenght) {  
        super(maxLenght);  
    }  
      
    @Override  
    public void insertString(FilterBypass fb, int offset, String str, AttributeSet attr) throws BadLocationException {  
        char c;  
        byte n = 1;  
          
        // percorre a string  
        for (byte i=0;i<str.length();i++){  
              
            // armazena o caracter  
            c = str.charAt(i);  
              
            // se não for número ou ponto  
            if(!Character.isDigit(c) & c != ' ')  
                    n = 0;  
        }  
          
        // se n não for igual a zero, todos os caracteres são numéricos  
        if(n != 0)  
            super.insertString(fb, offset, str, attr);  
    }
        @Override  
    public void replace(FilterBypass fb, int offset, int length, String str, AttributeSet attr) throws BadLocationException {  
        char c;  
        byte n = 1;  
          
        // percorre a string  
        for (byte i=0;i<str.length();i++){  
              
            // armazena o caracter  
            c = str.charAt(i);  
              
            // se não for número ou ponto  
            if(!Character.isDigit(c) & c != ' ')  
                    n = 0;  
        }  
          
        // se n não for igual a zero, todos os caracteres são numéricos  
        if(n != 0)  
            super.insertString(fb, offset, str, attr);  
    }  
}

Erro que aparece ao clicar no botão limpar..

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at a.ValidarNum.replace(ValidarNum.java:41)
at javax.swing.text.AbstractDocument.replace(AbstractDocument.java:662)
at javax.swing.text.JTextComponent.setText(JTextComponent.java:1718)
at Caixa.Cadastro.BT_LimparMouseClicked(Cadastro.java:560)
at Caixa.Cadastro.access$200(Cadastro.java:31)
at Caixa.Cadastro$3.mouseClicked(Cadastro.java:182)
at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270)
at java.awt.Component.processMouseEvent(Component.java:6508)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4501)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2713)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:680)
at java.awt.EventQueue$4.run(EventQueue.java:678)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
-------------------------------------------------------------------------------------------------------------------

Alguém sabe como mudar isso? >#<
Flws =P

4 Respostas

romarcio

Coloca um if (str != null) para testar se a variavel str está nula ou não antes de realizar o for da linha 41.

Alix

Humm… dessa vez ele não apresentou mais o erro, porem ele limpa apenas o campo JLabel e os outros continuam.

romarcio

O problema então é que seu str está chegando nulo no for. Descubra porque isso está acontecendo.

Alix

Bom... eu tenho uma classe também que conta o tamanho
Mas como no erro... não apontou ela, achei que não tinha nada. '-'

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

/* 
* Esta classe limita o número de caracteres inseridos em um JTextField 
* Para usar este Document: ((AbstractDocument)jTextField.getDocuement()).setDocumentFilter(new FixedLengthDocument(5)); 
*/  

public class TamanhoNum extends DocumentFilter {  
    private int iMaxLength;    
     
    public TamanhoNum(int maxlen) {    
        super();    
        iMaxLength = maxlen;    
    }  
      
    @Override  
    public void insertString(FilterBypass fb, int offset, String str, AttributeSet attr) throws BadLocationException {  
        if (str == null) return;    
  
        // aceitara qualquer número de caracteres  
        if (iMaxLength <= 0) {                     
            fb.insertString(offset, str, attr);    
            return;    
        }  
          
        int ilen = (fb.getDocument().getLength() + str.length());  
          
        // se o comprimento final for menor, aceita str  
        if (ilen <= iMaxLength) {  
            fb.insertString(offset, str, attr);   
        } else {  
            // se o comprimento for igual ao máximo, não faz nada  
            if (fb.getDocument().getLength() == iMaxLength) return;  
              
            // se ainda resta espaço na String, pega os caracteres aceitos  
            String newStr = str.substring(0, (iMaxLength - fb.getDocument().getLength()));    
  
            fb.insertString(offset, newStr, attr);    
        }  
    }  
  
    @Override  
    public void replace(FilterBypass fb, int offset, int length, String str, AttributeSet attr) throws BadLocationException {  
        if (str == null) return;    
  
        // aceitara qualquer número de caracteres  
        if (iMaxLength <= 0) {                     
            fb.insertString(offset, str, attr);    
            return;    
        }  
          
        int ilen = (fb.getDocument().getLength() + str.length());  
          
        // se o comprimento final for menor, aceita str  
        if (ilen <= iMaxLength) {  
            fb.insertString(offset, str, attr);   
        } else {  
            // se o comprimento for igual ao máximo, não faz nada  
            if (fb.getDocument().getLength() == iMaxLength) return;  
              
            // se ainda resta espaço na String, pega os caracteres aceitos  
            String newStr = str.substring(0, (iMaxLength - fb.getDocument().getLength()));    
  
            fb.insertString(offset, newStr, attr);    
        }  
    }  
}
Criado 5 de maio de 2012
Ultima resposta 5 de mai. de 2012
Respostas 4
Participantes 2