Validação de Campos

2 respostas
G

Pessoal,

Gostaria de saber como faço para validar a edição em um campo, por exemplo, tenho um campo que deve receber apenas caracteres numéricos, então gostaria de amarrá-lo para que o mesmo não aceite qualquer outro caractere.
Obrigado!

2 Respostas

B

de uma olhada nesse codigo, quando for acrescentar o JTexlField a sua tela use
private IntegerTextField jtf;
jtf = new IntegerTextField();

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import java.text.*;
 
public class IntegerJTextField extends JTextField
{
 
    private long maxValue = Long.MAX_VALUE;
    private long minValue = 0;
    private int maxLength = String.valueOf(maxValue).length();
    private boolean isIPField = false;
 
    /**
    * Default constructor for IntegerJTextField.
    */
    public IntegerJTextField()
    {
	super();
    }
 
    protected Document createDefaultModel()
    {
	return new IntegerDocument();
    }
 
    public void setMinValue(long value)
    {
	minValue = value;
    }
 
    public long getMinValue()
    {
	return minValue;
    }
 
 
    public void setIPField(boolean value)
    {
	isIPField = value;
    }
 
    public boolean getIPField()
    {
	return isIPField;
    }
 
    public void setMaxValue(long value)
    {
	maxValue = value;
    }
 
    public long getMaxValue()
    {
	return maxValue;
    }
 
    public void setMaxLength(int value)
    {
	maxLength = value;
    }
 
    public int getMaxLength()
    {
	return maxLength;
    }
 
 
    private class IntegerDocument extends PlainDocument
    {
	public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
	{
	    long typedValue = -1;
 
  	    StringBuffer textBuffer = new StringBuffer(IntegerJTextField.this.getText().trim());
  	    //The offset argument must be greater than or equal to 0, and less than or equal to the length of this string buffer
  	    if((offs >= 0) && (offs <= textBuffer.length()))
  	    {
  	    	    textBuffer.insert(offs,str);
	    		String textValue = textBuffer.toString();
	    		if(textBuffer.length() > maxLength)
	    		{
					JOptionPane.showMessageDialog(IntegerJTextField.this, "The number of characters 	must be less than or equal to " + getMaxLength(), "Error Message",JOptionPane.ERROR_MESSAGE);
					return;
	    		}
 
				if((textValue == null) || (textValue.equals("")))
				{
					remove(0,getLength());
					super.insertString(0, "", null);
					return;
				}
 
				if(textValue.equals("-") && minValue < 0)
				{
					super.insertString(offs,new String(str), a);
					return;
				}
 
		// 	    if(maxLength == 3 && str.equals(".") && isIPField)
				if(str.equals(".") && isIPField)
				{
					super.insertString(offs,new String(str),a);
					return;
				}
				else
				{
					try
					{
						typedValue = Long.parseLong(textValue);
						if((typedValue > maxValue) || (typedValue < minValue))
						{
							JOptionPane.showMessageDialog(IntegerJTextField.this, "The value can only be from "+getMinValue()+" to " + getMaxValue(), "Error Message", JOptionPane.ERROR_MESSAGE);
						}
						else
						{
							super.insertString(offs,new String(str),a);
						}
					}
					catch(NumberFormatException ex)
					{
						Toolkit.getDefaultToolkit().beep();
						JOptionPane.showMessageDialog(IntegerJTextField.this, "Only numeric values allowed.", "Error Message", JOptionPane.ERROR_MESSAGE);
					}
				}
		}
    }
}
}
D

uma sugestão mais prática é jogar o valor do campo para uma variavel do tipo Integer, se caso você escrever no campo uma letra ao passar isso para variavel vai estourar uma exceção, ai é só tratar a exceção e correr pro abraço.

Criado 22 de setembro de 2007
Ultima resposta 2 de out. de 2007
Respostas 2
Participantes 3