【问题标题】:How to remove DocumentFilter text from JTextField on button click如何在单击按钮时从 JTextField 中删除 DocumentFilter 文本
【发布时间】:2018-04-09 18:42:36
【问题描述】:
class MyDocumentFilter extends DocumentFilter {

@Override
public void replace(FilterBypass fb, int i, int i1, String string, AttributeSet as) throws BadLocationException {

    for (int n = string.length(); n > 0; n--) {//an inserted string may be more than a single character i.e a copy and paste of 'aaa123d', also we iterate from the back as super.XX implementation will put last insterted string first and so on thus 'aa123d' would be 'daa', but because we iterate from the back its 'aad' like we want
        char c = string.charAt(n - 1);//get a single character of the string

        if (Character.isAlphabetic(c) || c == ' ') {//if its an alphabetic character or white space
            super.replace(fb, i, i1, String.valueOf(c), as);//allow update to take place for the given character
        } else {//it was not an alphabetic character or white space

        }

    }

}

@Override
public void remove(FilterBypass fb, int i, int i1) throws BadLocationException {
    super.remove(fb, i, i1);

}

@Override
public void insertString(FilterBypass fb, int i, String string, AttributeSet as) throws BadLocationException {
    super.insertString(fb, i, string, as);

}

}

我在 JTextField 中添加了这个。现在我想在按钮单击时清除 JTextField 文本。 这就是我填写表格的方式

提前致谢**

【问题讨论】:

  • 为什么不能在按钮的 ActionListener 中使用textField.setText("")?如果您需要更多帮助(以及将来发布问题时),请发布正确的minimal reproducible example 来证明问题。在这种情况下,您只需要一个带有文本字段和按钮以及 DocumentFilter 和 ActionListener 的框架。我们应该可以编译代码看到问题。
  • 否,如果文本框充满字母,则不会使用 txtField.setText("");
  • 请阅读整个评论。你在哪里 minimal reproducible example 演示问题?

标签: java swing jtextfield documentfilter


【解决方案1】:

是因为我在 JTextField 上使用了 DocumentFilter,它没有从 JtextField 中删除文本。文本将使用 DocumentFilter remove() 方法删除

    try {
        txtFirstName.getDocument().remove(0, txtFirstName.getText().length());
    } catch (BadLocationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

【讨论】:

    【解决方案2】:

    我同意@camickr - 任何文本字段在执行 .setText("") 时都会清除。一个 ActionListener 就足够了。

    clearFieldsButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae){
            txtField.setText("");
            ...
        }
    });
    

    我能想到的原因只有一个,正如您在对 camickr 的回复中提到的那样,TextField 没有被 .setText("") 清除。 您可能必须使用以下方法刷新您的 JPanel:

    panel1.revalidate();
    panel1.repaint();
    

    【讨论】:

      猜你喜欢
      • 2013-04-12
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多