【问题标题】:Block text-writing after n characters在 n 个字符后阻止文本写入
【发布时间】:2013-05-21 13:47:10
【问题描述】:

我有这段代码,在插入 n 个字符后“禁用”JTextField 上的用户输入:

JTextField tf = new JTextField();
tf.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) {
        if (((JTextField) e.getSource()).getText().length() > n) {
            e.consume();
        }
    }
});

它有效,但我想知道是否有替代方法,因为我在一台旧的慢速计算机上尝试过,当我在文本字段中输入内容时,字母被添加,然后它消失了......我想避免使用e.consume() 在用户输入后直接阻止插入。

有可能吗?

编辑

我忘了提到我仅在此示例中使用了JTextField,但我希望此代码可以与JTextPaneJTextArea 等通用文本输入组件一起使用

【问题讨论】:

标签: java swing keylistener jtextcomponent documentfilter


【解决方案1】:

你可以使用DocumentSizeFilter

这是为特定用途而制作的: http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TextComponentDemoProject/src/components/DocumentSizeFilter.java

关于如何在实现文档过滤器部分中执行此操作的教程:

从那里引用:

为了限制文档中允许的字符,DocumentSizeFilter 覆盖 DocumentFilter 类的 insertString 方法,即 每次将该文本插入文档时调用。它也是 覆盖 replace 方法,该方法最有可能在何时调用 用户粘贴新文本。通常,文本插入可能会导致 当用户键入或粘贴新文本时,或 setText 方法时 叫做。这是 DocumentSizeFilter 类的实现 insertString 方法:

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(); }

【讨论】:

    猜你喜欢
    • 2014-09-14
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多