Impedir a entrada de alguns caracteres num TextField

10 respostas
M

Quero restringir a entrada de 3 caracteres num TextField.
Virgula, aspas e paretese. Alguem sabe como fazer isso?

10 Respostas

Vinny

vc pode usar o método charAt() da clase String, como por exemplo:

String s = "Conteudo"; boolean temCaracteres = false; for (int i = 0; i < s.length(); i++){ if (s.charAt(i) == ','){ temCaracteres = true; break; } }

mostrei um exemplo so com a virgula ai depois vc faz os outros tratamentos.

A

Duas alternativas: método contains() ou indexOf() da classe String.

mauricioadl

Uma forma bastante elegante seria voce reescrever o metodo insert e passar um ER nele antes de inserir, algo assim:

private class Doc extends PlainDocument {
		@Override
		public void insertString(int offs, String str, AttributeSet a)
				throws BadLocationException {
			if(Pattern.matches("[a-z]", str)){
				super.insertString(offs, str, a);
			}
		}
	}

E no seu JTextField voce faz assim:

JTextField j = new JTextField(); j.setDocument(new Doc());

Nesse exemplo permite que somente aceita caracteres de a-z minusculos.

[]'s

M

.

Vinny
Mata Hary:
Primeiro quero agradecer pela ajuda.

Não funcionou. Continua aceitando a virgula

O código é este:

import javax.microedition.midlet.*; 
import javax.microedition.lcdui.*; 
import java.io.*; 
import javax.microedition.io.*; 

public class GravaTxt extends MIDlet implements CommandListener, Runnable { 
private Command exit, start; 
private Display display; 
private Form form;
public TextField tf_nome;
public TextField tf_email;
public GravaTxt ()  
{ 
display = Display.getDisplay(this); 
exit = new Command("Sair", Command.EXIT, 1); 
start = new Command("Gravar", Command.EXIT, 1); 
form = new Form("Gravar no arquivo"); 
form.addCommand(exit); 
form.addCommand(start); 
form.setCommandListener(this); 
} 
public void startApp() throws MIDletStateChangeException  
{ 
display.setCurrent(form);
tf_nome = new TextField("Nome: ", "", 50, TextField.ANY);
tf_email = new TextField("Email: ", "", 50, TextField.EMAILADDR);
form.append(tf_nome);
form.append(tf_email);

} 
public void run(){ 
try{ 
javax.microedition.io.file.FileConnection filecon = 
(javax.microedition.io.file.FileConnection) 
Connector.open("file:///root1/cadastro.txt", Connector.READ_WRITE); 
OutputStream out = filecon.openOutputStream(filecon.fileSize()); 
PrintStream output = new PrintStream(out);
//método charAt()
String s = ((TextField)tf_nome).getString();   
boolean temCaracteres = false;   
for (int i = 0; i < s.length(); i++){   
  if (s.charAt(i) == ','){   
     temCaracteres = true;   
     break;   
  }   
}  
//fim método charAt()
output.println("('" + ((TextField)tf_nome).getString() + "'," + "'" + ((TextField)tf_email).getString() + "')");
out.close(); 
filecon.close(); 
Alert alert = new Alert("Concluído", "Gravado com sucesso!", null, null); 
alert.setTimeout(Alert.FOREVER); 
alert.setType(AlertType.ERROR); 
display.setCurrent(alert); 
}

catch( ConnectionNotFoundException error ) 
{ 
Alert alert = new Alert( 
"Erro", "Arquivo não encontrado..", null, null); 
alert.setTimeout(Alert.FOREVER); 
alert.setType(AlertType.ERROR); 
display.setCurrent(alert);       
} 
catch( IOException error ) 
{ 
Alert alert = new Alert("Erro", error.toString(), null, null); 
alert.setTimeout(Alert.FOREVER); 
alert.setType(AlertType.ERROR); 
display.setCurrent(alert);       
} 
} 

public void pauseApp()  
{ 
} 
public void destroyApp(boolean unconditional)  
{ 
} 
public void commandAction(Command command, Displayable displayable)  
{ 
if (command == exit)  
{ 
destroyApp(false); 
notifyDestroyed(); 
} 
else if (command == start)  
{ 
new Thread(this).start(); 

} 
} 
}

Quando for postar código utiliza a Tag code fica mais legivel.

Bom mas então o metodo charAt() que eu te mostrei o exemplo ele apenas identifica se tem virgula ou não.

Mas agora se vc quer identificar se tem os caracteres não permitido e retirá-los da string vc usa o método "replace"

String s = "Minha string de teste, ponto."

s = s.replace(",","");

Dessa forma todas as Virgulas encontradas na String serão substituídas por nada, ou melhor dizendo removidas.

guilherme.dio

Porque você não utiliza o evento caretUpdate(), sendo asism vc pode criar um array como valores que vc não deseja, e ao dar update no textfield, s eo valor inserido for encontrado no array, vc simplesmente não o mostra no textfield.

M

Mata Hary:
Quero restringir a entrada de 3 caracteres num TextField.
Virgula, aspas e paretese. Alguem sabe como fazer isso?

M

mauricioadl:
Uma forma bastante elegante seria voce reescrever o metodo insert e passar um ER nele antes de inserir, algo assim:

private class Doc extends PlainDocument {
		@Override
		public void insertString(int offs, String str, AttributeSet a)
				throws BadLocationException {
			if(Pattern.matches("[a-z]", str)){
				super.insertString(offs, str, a);
			}
		}
	}

E no seu JTextField voce faz assim:

JTextField j = new JTextField(); j.setDocument(new Doc());

Nesse exemplo permite que somente aceita caracteres de a-z minusculos.

[]'s

Eu ja tentei JTextField, mas o J2ME não aceita.

M

E não posso usar replace. Eu quero impedir o usuario de digitar.
O texto será salvo assim:

('nome da pessoa','email da pessoa')

Por isso nao quero que a pessoa digite virgula, aspas e parenteses, para não confundir a leitura dos dados, mas se eu usar replace vai tirar as virgula, parenteses e aspas que eu coloquei e vou precisar deles porque servem para separar os campos e cadastros.

O código é este:

import javax.microedition.midlet.*; 
import javax.microedition.lcdui.*; 
import java.io.*; 
import javax.microedition.io.*; 

public class GravaTxt extends MIDlet implements CommandListener, Runnable { 
private Command exit, start; 
private Display display; 
private Form form;
public TextField tf_nome;
public TextField tf_email;
public GravaTxt ()  
{ 
display = Display.getDisplay(this); 
exit = new Command("Sair", Command.EXIT, 1); 
start = new Command("Gravar", Command.EXIT, 1); 
form = new Form("Gravar no arquivo"); 
form.addCommand(exit); 
form.addCommand(start); 
form.setCommandListener(this); 
} 
public void startApp() throws MIDletStateChangeException  
{ 
display.setCurrent(form);
tf_nome = new TextField("Nome: ", "", 50, TextField.ANY);
tf_email = new TextField("Email: ", "", 50, TextField.EMAILADDR);
form.append(tf_nome);
form.append(tf_email);

} 
public void run(){ 
try{ 
javax.microedition.io.file.FileConnection filecon = 
(javax.microedition.io.file.FileConnection) 
Connector.open("file:///root1/cadastro.txt", Connector.READ_WRITE); 
OutputStream out = filecon.openOutputStream(filecon.fileSize()); 
PrintStream output = new PrintStream(out);
//método charAt()
String s = ((TextField)tf_nome).getString();   
boolean temCaracteres = false;   
for (int i = 0; i < s.length(); i++){   
  if (s.charAt(i) == ','){   
     temCaracteres = true;   
     break;   
  }   
}  
//fim método charAt()
output.println("('" + ((TextField)tf_nome).getString() + "'," + "'" + ((TextField)tf_email).getString() + "')");
out.close(); 
filecon.close(); 
Alert alert = new Alert("Concluído", "Gravado com sucesso!", null, null); 
alert.setTimeout(Alert.FOREVER); 
alert.setType(AlertType.ERROR); 
display.setCurrent(alert); 
}

catch( ConnectionNotFoundException error ) 
{ 
Alert alert = new Alert( 
"Erro", "Arquivo não encontrado..", null, null); 
alert.setTimeout(Alert.FOREVER); 
alert.setType(AlertType.ERROR); 
display.setCurrent(alert);       
} 
catch( IOException error ) 
{ 
Alert alert = new Alert("Erro", error.toString(), null, null); 
alert.setTimeout(Alert.FOREVER); 
alert.setType(AlertType.ERROR); 
display.setCurrent(alert);       
} 
} 

public void pauseApp()  
{ 
} 
public void destroyApp(boolean unconditional)  
{ 
} 
public void commandAction(Command command, Displayable displayable)  
{ 
if (command == exit)  
{ 
destroyApp(false); 
notifyDestroyed(); 
} 
else if (command == start)  
{ 
new Thread(this).start(); 

} 
} 
}
[/quote]

Quando for postar código utiliza a Tag code fica mais legivel.

Bom mas então o metodo charAt() que eu te mostrei o exemplo ele apenas identifica se tem virgula ou não.

Mas agora se vc quer identificar se tem os caracteres não permitido e retirá-los da string vc usa o método "replace"

String s = "Minha string de teste, ponto."

s = s.replace(",","");

Dessa forma todas as Virgulas encontradas na String serão substituídas por nada, ou melhor dizendo removidas.

mauricioadl

Mata Hary:
mauricioadl:
Uma forma bastante elegante seria voce reescrever o metodo insert e passar um ER nele antes de inserir, algo assim:

private class Doc extends PlainDocument {
		@Override
		public void insertString(int offs, String str, AttributeSet a)
				throws BadLocationException {
			if(Pattern.matches("[a-z]", str)){
				super.insertString(offs, str, a);
			}
		}
	}

E no seu JTextField voce faz assim:

JTextField j = new JTextField(); j.setDocument(new Doc());

Nesse exemplo permite que somente aceita caracteres de a-z minusculos.

[]'s

Eu ja tentei JTextField, mas o J2ME não aceita.

Foi malz, nao percebi q era ME.

Criado 19 de dezembro de 2011
Ultima resposta 19 de dez. de 2011
Respostas 10
Participantes 5