我的问题如下:
我有一个:
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属性。当该值为true时 - 我希望允许用户在字段中输入大小写混合字符,但只允许该字段输入。
关于我如何做到这一点的任何提示/建议?
答案 0 :(得分: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);