我想在JTextField中过滤用户的键盘输入以查找非法/禁止的文件名字符。我已经在JTextField中设置了大写过滤器。
DocumentFilter dfilter = new UpcaseFilter();
JTextField codeTF = new JTextField();
((AbstractDocument) codeTF.getDocument()).setDocumentFilter(dfilter);
这是我用来在JTextfield中将小写改为大写的过滤器。
class UpcaseFilter extends DocumentFilter
{
public void insertString (DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException
{
fb.insertString (offset, text.toUpperCase(), attr);
}
public void replace (DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr) throws BadLocationException
{
fb.replace(offset, length, text.toUpperCase(), attr);
}
}
如何解决这个问题?
答案 0 :(得分:4)
这些方面的东西:
class FileNameFilter extends DocumentFilter {
public void insertString (DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
fb.insertString (offset, fixText(text), attr);
}
public void replace (DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr) throws BadLocationException {
fb.replace(offset, length, fixText(text), attr);
}
private String fixText(String s) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.lenght(); ++i) {
if(isLegalFileNameChar(s.charAt(i))
sb.append(s.charAt(i));
}
return sb.toString();
}
private boolean isLegalFileNameChar(char c) {
// Your logic goes here ...
}
}
答案 1 :(得分:3)
答案 2 :(得分:2)
非常感谢您的回答。我决定使用Itay的答案来解决问题。这是我的解决方案。
DocumentFilter dfilter = new FileNameFilter();
JTextField codeTF = new JTextField();
((AbstractDocument) codeTF.getDocument()).setDocumentFilter(dfilter);
这是FileNameFilter,它阻止插入非法字符。这应该适用于Unix,Windows和Mac OS。
class FileNameFilter extends DocumentFilter
{
private static final char[] ILLEGAL_CHARACTERS = {'/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':', '.'};
public void insertString (DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException
{
fb.insertString (offset, fixText(text).toUpperCase(), attr);
}
public void replace (DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr) throws BadLocationException
{
fb.replace(offset, length, fixText(text).toUpperCase(), attr);
}
private String fixText (String s)
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); ++i)
{
if (!isIllegalFileNameChar (s.charAt (i)))
sb.append (s.charAt (i));
}
return sb.toString();
}
private boolean isIllegalFileNameChar (char c)
{
boolean isIllegal = false;
for (int i = 0; i < ILLEGAL_CHARACTERS.length; i++)
{
if (c == ILLEGAL_CHARACTERS[i])
isIllegal = true;
}
return isIllegal;
}
}
JFormattedTextField似乎也是一个很好的解决方案,但Itay的答案对我来说更简单。非常感谢你!
答案 3 :(得分:0)
InputVerifier
很好地补充了JFormattedTextField
,如here所示。