Java Swing GUI

How to Make JTextField Accept Only Alphabet

In this tutorial, we are going to see how to make JTextField accept only alphabet. JTextField is a Swing component, so there must be a listener object for it to be useful. You can add KeyListener to prevent the user from entering special characters, spaces, numbers, etc. in a JTextField.


 

Example:
JTextField textField = new JTextField(15);
   
textField.addKeyListener(new KeyAdapter() {
	public void keyTyped(KeyEvent e) {
		char c = e.getKeyChar();
		   if(!(Character.isAlphabetic(c) || (c==KeyEvent.VK_BACK_SPACE) || c==KeyEvent.VK_DELETE )) {
			  e.consume();  // ignore the event if it's not an alphabet
		}
	 }
});

Here we ignore the captured event if it is a special character, space, or number.
 

 

Complete Example : How to Make JTextField Accept Only Alphabet
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class OnlyAlphabet extends JFrame 
{  
   public static void main(String[]args){
      new OnlyAlphabet().initComponent();
   }
   public void initComponent() {
      setLayout(new FlowLayout());
      JLabel lbl = new JLabel("Enter text: ");
      JTextField textField = new JTextField(15);
      add(lbl);
      add(textField);
   
      textField.addKeyListener(new KeyAdapter() {
         public void keyTyped(KeyEvent e) {
             char c = e.getKeyChar();
             if(!(Character.isAlphabetic(c) || (c==KeyEvent.VK_BACK_SPACE) || c==KeyEvent.VK_DELETE )) {
                 e.consume();  // ignore the event if it's not an alphabet
             }
         }
      });
   
      setSize(300,70);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }
}

Output:


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

One thought on “How to Make JTextField Accept Only Alphabet

Leave a Reply

Your email address will not be published. Required fields are marked *