FormattedTextField с символами смешанного регистра с DocumentFilter установленным в верхний регистр

Моя проблема заключается в следующем:

У меня есть:

public class WWFormattedTextField extends JFormattedTextField implements FocusListener {

Все отформатированные текстовые поля на всех экранах всегда будут в верхнем регистре. Мы хотим, чтобы они отображались в верхнем регистре при наборе текста и т. д. Итак, вот что мы для этого сделали:

public class WWFormattedTextField extends JFormattedTextField implements FocusListener {

private DocumentFilter filter = new UppercaseDocumentFilter();
private boolean isEmail = false;

public WWFormattedTextField() {
    super();
    init();
}

private void init() {
    addFocusListener(this);
    ((AbstractDocument) this.getDocument()).setDocumentFilter(filter);
}
public void setIsEmail(boolean email) {
    //Normally this is where I would put something like
    //if email is true - allow mixed case characters
    this.isEmail = email;
}

public boolean getIsEmail() {
    return isEmail;
}

Теперь все поля WWFormattedTextField на всех экранах печатаются в верхнем регистре. Вот упомянутый выше UppercaseDocumentFilter():

public class UppercaseDocumentFilter extends DocumentFilter{
    @Override
    public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
        fb.insertString(offset, text.toUpperCase(), attr);
    }

    @Override
    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
        fb.replace(offset, length, text.toUpperCase(), attrs);
    }
}

Как видите, это FormattedTextField также имеет свойство isEmail. Когда это значение истинно, я хочу разрешить пользователю вводить в поле символы смешанного регистра, но только этот конкретный.

Любые подсказки/предложения о том, как я могу это сделать?


person Metal Wing    schedule 26.09.2013    source источник


Ответы (1)


Добавьте свойство isEmail к UppercaseDocumentFilter, чтобы определенные фильтры могли создавать текст в верхнем регистре.

public class UppercaseDocumentFilter extends DocumentFilter {

    private boolean isEmail;

    public UppercaseDocumentFilter(boolean isEmail) {
        this.isEmail = isEmail; 
    }

    @Override
    public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
        fb.insertString(offset, isEmail? text: text.toUpperCase(), attr);
    }

    @Override
    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
        fb.replace(offset, length, isEmail? text: text.toUpperCase(), attrs);
    }
}

затем установите фильтр следующим образом

DocumentFilter filter = new UppercaseDocumentFilter(isEmail);
((AbstractDocument) this.getDocument()).setDocumentFilter(filter);
person Reimeus    schedule 26.09.2013
comment
Спасибо за ответ, @Reimeus! Возможно, я неправильно понимаю использование кода, но теперь все мои текстовые поля имеют смешанный регистр, независимо от истинности или ложности для isEmail. Не могли бы вы дать небольшое уточнение? Я вижу логику для UppercaseDocumentFilter, но не уверен, какие изменения должны произойти в классе TextField. - person Metal Wing; 26.09.2013
comment
Я подозреваю, что вы устанавливаете флаг isEmail после создания текстового поля. Это не сработает, поскольку вы просто устанавливаете флаг isEmail. Вам нужно вызвать setDocument если это так - person Reimeus; 26.09.2013