Пространство управления, числа, специальные символы, строка в JTextfield в Java Swing - PullRequest
2 голосов
/ 10 января 2011

У меня есть два текстовых поля в моем компоненте свинга.В одном текстовом поле мне нужно иметь только цифры (без строки, пустые пробелы, разрешенные специальные символы), а в другом текстовом поле мне нужно иметь только строку (без цифр, пустых мест, разрешенные специальные символы).Как я могу реализовать это .. ???

Ответы [ 3 ]

1 голос
/ 10 января 2011

У вас есть два варианта, вы можете проверить текст в полях: 1) на входе или 2), когда пользователь выполняет действие, такое как нажатие кнопки подтверждения.

Для 2) ответ npinti должен направить вас в правильном направлении, просто получите значение поля и подтвердите его с помощью регулярного выражения.

Для 1) вы можете написать KeyListener, который перехватывает нажатия клавиш и допускает только правильный тип символа для поля.

1 голос
/ 10 января 2011

Вы можете использовать класс Pattern (регулярные выражения) для проверки ввода.Краткое руководство доступно здесь .

Я почти уверен, что базовый урок охватывает все это ...

"^//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
0 голосов
/ 10 января 2011

Вы можете расширить класс javax.swing.text.PlainDocument и вызвать текстовое поле метода setDocument.Вот один из примеров:

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

РЕДАКТИРОВАТЬ: и его использование;

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

Вы можете вводить только положительные числа меньше 1000, и он проверяется, пока вы нажимаете..

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...