harishtps
harishtps

Reputation: 1439

Control space,numbers,special charaters,String in JTextfield in Java Swing

I have two textfield in my swing component. In one text field i need to have only numbers (no string,empty spaces,special charaters allowed) and in another textfield i need to have only string(no numbers,empty spaces,special charaters allowed). How can i implement that..???

Upvotes: 2

Views: 2940

Answers (3)

Gursel Koca
Gursel Koca

Reputation: 21300

You can extend javax.swing.text.PlainDocument class, and call setDocument method textfield. Here is one of the example ;

package textfield;
import java.awt.Toolkit;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;


public class LimitedValuePositiveIntegerDocument extends PlainDocument {

    int maxValue;
    int maxLength;
    Toolkit toolkit;

    /**
     * Constructor for the class.
     * @param max maximum value of the number
     */
    public LimitedValuePositiveIntegerDocument(int max){
        maxValue = max;
        maxLength = (""+max).length();
        toolkit = Toolkit.getDefaultToolkit();
    }

    /**
     * Inserts the input string to the current string after validation.
     * @param offs offset of the place where the input string is supposed to be inserted.
     * @param str input string to be inserted
     * @param a attribute set
     */
    @Override
    public void insertString(int offs, String str, AttributeSet a)
            throws BadLocationException {

        if(str == null)return;
        String currentText = getText(0,getLength());
        String resultText = new String();
        int i;
        boolean errorFound = false;
        boolean deleteFirstZero = false;
        int accepted=0;

        for (i = 0; (i<str.length())&&(!errorFound); i++) {
            if (Character.isDigit(str.charAt(i))) { /* if it is digit */
                if (offs==currentText.length()) {   /* calculates the resultant string*/
                    resultText = currentText+str.substring(0,i+1);
                } else if (offs==0) {
                    resultText = str.substring(0,i+1)+currentText;
                } else {
                    resultText = currentText.substring(0, offs)+str.substring(0,i+1)+currentText.substring(offs,currentText.length());
                }
                if (Integer.parseInt(resultText) > maxValue) {
                    errorFound = true;
                    toolkit.beep();
                } else {
                    if ( resultText.length() == maxLength+1) {
                        deleteFirstZero = true;
                    }
                    accepted++;
                }
            } else {
                errorFound = true;
                toolkit.beep();
            }
        }

        if ( accepted>0 ) { /* insert string */
            super.insertString(offs, str.substring(0,accepted), a);
            if (deleteFirstZero) {
                super.remove(0,1);
            }
        }
    }

    /**
     * Removes a part of the current string.
     * @param offs offset of the place to be removed.
     * @param len length to be removed
     */
    @Override
    public void remove(int offs, int len) throws BadLocationException{
        super.remove(offs, len);
    }

    /**
     * Returns max value of the number.
     * @return max value
     */
    public int getMaxValue() {
        return maxValue;
    }

    /**
     * Sets max value of the number.
     * @param max maximum value of the number
     */
    public void setMaxValue(int max) {
        this.maxValue = max;
    }
} // end of class

EDIT : and its usage;

LimitedValuePositiveIntegerDocument doc = new LimitedValuePositiveIntegerDocument(999);
JTextField numberField = new JtextField();
numberField.setDocument(doc);

You can only enter positive numbers less than 1000, and it check while you are pressing the key..

Upvotes: 0

Qwerky
Qwerky

Reputation: 18455

You have two choices, you can validate the text in the fields either 1) on entry or 2) when the user performs an action such as clicks a confirmation button.

For 2) npinti's answer should steer you in the right direction, just get the value of the field and validate it with a regular expression.

For 1) you might want to write a KeyListener that intercepts key presses and only allows the correct type of character for the field.

Upvotes: 1

npinti
npinti

Reputation: 52185

You can use the Pattern Class (Regular Expressions) to validate the input. A short tutorial is available here.

I am pretty sure that the basic tutorial covers all this...

"^//d+$" //The text must have at least one digit, no other characters are allowed
"^[a-zA-Z]+$" //The text must have at least one letter, no other characters are allowed

Upvotes: 1

Related Questions