JFormattedTextField

1 resposta
Hempx

Tenho campos que apenas podem aceitar numeros ou o ".";

Tentei usar um JFormattedTextField para restringir isso...

MaskFormatter formato = null;

		try {
			
			formato = new MaskFormatter( "*****" );
			formato.setValidCharacters( "[telefone removido]." );
		}
		catch( ParseException pex ) {
			pex.printStackTrace();
		}
		
		JFormattedTextField field = new JFormattedTextField( formato );

Só que meu problema é o seguinte... nem sempre necessariamente a pessoa digitara todos os numeros... Ex:
ela pode digitar "234" ou "8794.6" ... so que quando uso uma mascara parece que necessariamente eu sempre tenho que preencher totalmente ela... tem algum metado que especifica que a mascara pode ser totalmente completa ou apenas parcialmente??
vlws...

1 Resposta

Hempx

Como ninguem me respondeu eu fiz uma adaptação do exemplo do tutorial aqui do guj msm ( [url]http://www.guj.com.br/servlet/guj?PARSE=true&MAMUTE_ACTION=br.com.guj.action.ListTutorial&MAMUTE_TEMPLATE=ShowTutorial&LIST_TUTORIAL=single&TutorialId=29&PAGE=1[/url]

:arrow: Meu objetivo é garantir que sempre o que a pessoal escreveu no JTextField possa ser mandado para um valor Double sem gerar nenhuma Exception

Não testei 100% ... Se alguem tiver com o msm problema e possa melhorar o codigo ou tem uma solução melhor post aqui nesse tópico.

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

/*
 * Created on 12/12/2003
 *
 *  PlainDocument que aceita apenas valores numericos
 * e usa o '.' como separador decimal
 */

/**
 * @author hempx
 */
public class DocumentNumber extends PlainDocument{
	private int maxLength;
	private int ponto; // posição do separador decimal, -1 quando ele não foi inserido ainda.
	
	public DocumentNumber( int maxLength ) {
		super();
		this.maxLength = maxLength;
		this.ponto = -1;
	}
	
	public void insertString( int offset, String str, AttributeSet attr )
		throws BadLocationException
	{
		if( str == null )
		   return;
		
		if( maxLength <= 0 ) {
			super.insertString( offset, str, attr );
		}
			
		int ilen = getLength() + str.length();
		
		if( ilen <= maxLength ){
			if( verificaInput( str, offset ) )		
		       super.insertString( offset, str, attr );
		    else
		       return;
		}
		else {
			if( getLength() == maxLength )
			   return;
			String newStr = str.substring( 0, ( maxLength - getLength() ) );
			if( verificaInput( newStr, offset ) )
			   super.insertString( offset, newStr, attr );
			else
			   return;
			
		}
		
	}
	
	public void remove( int offs, int len ) throws BadLocationException {

		if( ponto >= offs && ponto < ( offs + len ) )
		   ponto = -1;
		else if( ponto != -1 && ( offs + len  ) <= ponto )
		   ponto = ponto - len;
		super.remove( offs, len );
			

	}

	private boolean verificaInput( String str, int offset ){
		char[] tmp = str.toCharArray();
		

		for( int i = 0; i < tmp.length; i++ ) {
			if( tmp[i] == '.' && ponto != -1  )
			   return false;
			   
			switch( tmp[i] ){
				case '1' :
			   		break;
				case '2' :
					break;
				case '3' :
					break;
				case '4' :
					break;
				case '5' :
					break;
				case '6' :
					break;
				case '7' :
					break;
				case '8' :
					break;
				case '9' :
					break;
				case '0' :
					break;
				case '.' :
					ponto = offset + i;
					break;
				default:
					return false;
				
			}
		}
		
		return true;
		
	}
}
Exemplo de como usar:
JTextField txtField = new JTextField( 10 );
txtField.setDocument( new DocumentNumber( 10 ) );
Criado 3 de dezembro de 2003
Ultima resposta 12 de dez. de 2003
Respostas 1
Participantes 1