Restringir Texto no JTextField
 09 Novembro 2017
 Java | Swing
 Rodrigo Costa Corrêa

Muitas vezes precisamos limitar o texto que o usuário digita em algum campos do formulário. No campo de e-mail, por exemplo, o usuário não pode digitar acentos ou caracteres especiais. Uma forma de resolver isso é após o envio do formulário, onde o texto é validado e uma mensagem de erro é enviada para o usuário. Isso irrita muito o usuário, pois as vezes ele preenche um formulário imenso e no fim recebe a mensaem de erro.

Criei essas funções para poder restringir o texto digitado em JTextField. Com isso, caso o usuário digite um caracter não permitido, o caracter simplesmente não irá aparacer no JTextField e o usuário consegue saber no momento que está digitando que o caracter digitado não é permitido no campo que ele está preenchendo.

Classe Java com as funções:

import java.awt.event.KeyEvent;
import java.text.Normalizer;

public class StringFunctions {

	public static void onlyText(KeyEvent onlyText) {
		if (!"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ áíúéóâêôãõàüçÁÍÚÉÓÂÊÔÃÕÀÜÇ"
				.contains(onlyText.getKeyChar() + ""))
			onlyText.consume();
	}

	public static void onlyTextAndNumber(KeyEvent onlyTextAndNumber) {
		if (!"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ áíúéóâêôãõàüçÁÍÚÉÓÂÊÔÃÕÀÜÇ0987654321"
				.contains(onlyTextAndNumber.getKeyChar() + ""))
			onlyTextAndNumber.consume();
	}

	public static void onlySimpleText(KeyEvent onlySimpleText) {
		if (!"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ".contains(onlySimpleText.getKeyChar() + ""))
			onlySimpleText.consume();
	}

	public static void onlyLoginText(KeyEvent onlyLoginText) {
		if (!"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".contains(onlyLoginText.getKeyChar() + ""))
			onlyLoginText.consume();
	}

	public static void onlyPasswordText(KeyEvent onlyPasswordText) {
		if (!"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0987654321!@#$%&"
				.contains(onlyPasswordText.getKeyChar() + ""))
			onlyPasswordText.consume();
	}

	public static void onlySimpleTextAndNumber(KeyEvent onlySimpleTextAndNumber) {
		if (!"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0987654321"
				.contains(onlySimpleTextAndNumber.getKeyChar() + ""))
			onlySimpleTextAndNumber.consume();
	}

	public static void onlyNumber(KeyEvent onlyNumber) {
		if (!"0987654321".contains(onlyNumber.getKeyChar() + ""))
			onlyNumber.consume();
	}

	public static void onlyTextAndNumberAndSpecial(KeyEvent onlyTextAndNumberAndSpecial) {
		if (!"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZáíúéóâêôãõàüçÁÍÚÉÓÂÊÔÃÕÀÜÇ 0987654321_/$%,.|:@()-ºª"
				.contains(onlyTextAndNumberAndSpecial.getKeyChar() + ""))
			onlyTextAndNumberAndSpecial.consume();
	}

	public static void onlyAddressText(KeyEvent onlyAddressText) {
		if (!"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZáíúéóâêôãõàüçÁÍÚÉÓÂÊÔÃÕÀÜÇ 0987654321-,.()"
				.contains(onlyAddressText.getKeyChar() + ""))
			onlyAddressText.consume();
	}

	public static void onlyEmailText(KeyEvent onlyEmailText) {
		if (!"abcdefghijklmnopqrstuvwxyz0987654321_@-.".contains(onlyEmailText.getKeyChar() + ""))
			onlyEmailText.consume();
	}

	public static void onlyDateTimeText(KeyEvent onlyDateTimeText) {
		if (!"0987654321-:/ ".contains(onlyDateTimeText.getKeyChar() + ""))
			onlyDateTimeText.consume();
	}

	public static void onlyWebsiteText(KeyEvent onlyWebsiteText) {
		if (!"abcdefghijklmnopqrstuvwxyz0987654321:/-.".contains(onlyWebsiteText.getKeyChar() + ""))
			onlyWebsiteText.consume();
	}

	public static void onlyUpperText(KeyEvent onlyUpperText) {
		if (!"ABCDEFGHIJKLMNOPQRSTUVWXYZÁÍÚÉÂÊÔÃÕÀÜÇ ".contains(onlyUpperText.getKeyChar() + ""))
			onlyUpperText.consume();
	}

	public static void onlyLowerText(KeyEvent onlyLowerText) {
		if (!"abcdefghijklmnopqrstuvwxyzáíúéâêôãõàüç ".contains(onlyLowerText.getKeyChar() + ""))
			onlyLowerText.consume();
	}

	public static void onlyLinkText(KeyEvent onlyLinkText) {
		if (!"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZáíúéóâêôãõàüçÁÍÚÉÓÂÊÔÃÕÀÜÇ0987654321-.:/?@%$&*()+={}[]<>|"
				.contains(onlyLinkText.getKeyChar() + ""))
			onlyLinkText.consume();
	}

	public static void onlyFileNameText(KeyEvent onlyFileNameText) {
		if (!"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0987654321"
				.contains(onlyFileNameText.getKeyChar() + ""))
			onlyFileNameText.consume();
	}

	public static void onlyAllText(KeyEvent onlyAllText) {
		if (!"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZáíúéóâêôãõàüçÁÍÚÉÓÂÊÔÃÕÀÜÇ 0987654321-.:/?@%$&*()+={}[]<>|'"
				.contains(onlyAllText.getKeyChar() + ""))
			onlyAllText.consume();
	}
	
	public static String removeAccents(String str) {
	    return Normalizer.normalize(str, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "");
	}
}

Exemplo de uso:

JTextField tfEmail = new JTextField();
		tfEmail.addKeyListener(new KeyAdapter() {
			public void keyTyped(KeyEvent ke) {
				StringFunctions.onlyEmailText(ke);
			}
		});