NonNumericDocument.java Source code

Java tutorial

Introduction

Here is the source code for NonNumericDocument.java

Source

import java.awt.BorderLayout;

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

class NonNumericDocument extends PlainDocument {
    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        if (str == null) {
            return;
        }
        char[] arr = str.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            if (Character.isDigit(arr[i]) || !Character.isLetter(arr[i])) {
                return;
            }
        }
        super.insertString(offs, new String(str), a);
    }
}

public class Main extends JFrame {
    JTextField tf;

    public void prepareAndShowGUI() {
        tf = new JTextField(30);
        tf.setDocument(new NonNumericDocument());
        getContentPane().add(tf, BorderLayout.NORTH);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        Main tFrame = new Main();
        tFrame.prepareAndShowGUI();
    }
}