如何使用JFormattedTextField只允许使用字母?

时间:2015-04-01 15:51:55

标签: java jtextfield jformattedtextfield

我到处搜索解决方案,但我发现解决方案只允许使用数字,字母数字(使用DocumentFilter)。

但是,我只需要允许使用字母,并且由于某些优点,我打算使用JFormattedTextField

那么,如何使用JFormattedTextField只允许使用字母(a-zA-Z)(没有空格,标点符号,字母)!

2 个答案:

答案 0 :(得分:0)

由于数字是可变的,并且如果我没有错误,JFormattedTextField使用固定长度的数字掩码,将更容易使用litener更改文本事件并验证元素中的文本删除不允许的字符

类似的东西:

JTextField f = null;

f.getDocument().addDocumentListener(new DocumentListener()
{
  @Override
  public void insertUpdate(DocumentEvent e)
  {
    validateInputText();
  }

  @Override
  public void removeUpdate(DocumentEvent e)
  {
    validateInputText();
  }

  @Override
  public void changedUpdate(DocumentEvent e)
  {
    validateInputText();
  }
});

答案 1 :(得分:0)

在尝试了很多解决方案之后,我认为最好的解决方案是扩展DocumentFilter类。

以下是代码:

class AlphabetFilter extends DocumentFilter {

    @Override
    public void insertString(FilterBypass fb, int offset, String string,
            AttributeSet attr) throws BadLocationException {
        super.insertString(fb, offset, string.replaceAll("[^A-Za-z]+", ""), attr);
    }

    @Override
    public void replace(FilterBypass fb, int offset, int length,
            String string, AttributeSet attr) throws BadLocationException {
        super.replace(fb, offset, length, string.replaceAll("[^A-Za-z]+", ""), attr);
    }

}
相关问题