本文介绍了从jtextfield删除最后一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让JTextField具有最大字符数,我一直在尝试这段代码,我想做的是,如果用户输入的字符数超过13个,则应该删除最后输入的字符,我也尝试了Unicode字符(将\ b替换为\ u0008),但结果相同,这是我的代码:

I want to a JTextField to have maximum characters, Ive been trying out this code, what im trying to do is, if a user enters more then 13 characters it should erase the last character entered, I also tried with the Unicode Character (by replacing the \b to \u0008) but it gives the same result, this is my code:

if(EditTxtFName.getText().length() > 10)
{
    EditTxtFName.setBackground(Color.red);
    EditTxtFName.setText(EditTxtFName.getText() + "\b");
}
else
{
    EditTxtFName.setBackground(Color.white);
}

发生的事情是输出,而不是删除最后一个字符,而是增加了空间并继续.预先感谢..

The output of what happens is, instead of deleting the last character is adds space and continues..Thanks in advance..

推荐答案

使用DocumentFilter,它旨在允许您在将内容添加到文本组件的基础Document之前对其进行过滤...

Use a DocumentFilter, it is designed to allow you to filter the content before it is added to the underlying Document of the text component...

有关更多详细信息,请参见实施文档过滤器

See Implementing a Document Filter for more details

例如...

import java.awt.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class SizeFilter extends DocumentFilter {

    private int maxCharacters;

    public SizeFilter(int maxChars) {
        maxCharacters = maxChars;
    }

    public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
            throws BadLocationException {

        if ((fb.getDocument().getLength() + str.length()) <= maxCharacters)
            super.insertString(fb, offs, str, a);
        else
            Toolkit.getDefaultToolkit().beep();
    }

    public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a)
            throws BadLocationException {

        if ((fb.getDocument().getLength() + str.length()
                - length) <= maxCharacters)
            super.replace(fb, offs, length, str, a);
        else
            Toolkit.getDefaultToolkit().beep();
    }
}

可以使用类似...的方法

Which could be applied using something like...

((AbstractDocument) EditTxtFName.getDocument()).setDocumentFilter(new SizeFilter(13));

DocumentFilter示例中的示例

这篇关于从jtextfield删除最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:47