java - 在 n 个字符后阻止文本写入

标签 java swing keylistener jtextcomponent documentfilter

我有这段代码,在插入 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

最佳答案

您可以使用DocumentSizeFilter

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

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

引自那里:

To limit the characters allowed in the document, DocumentSizeFilter overrides the DocumentFilter class's insertString method, which is called each time that text is inserted into the document. It also overrides the replace method, which is most likely to be called when the user pastes in new text. In general, text insertion can result when the user types or pastes in new text, or when the setText method is called. Here is the DocumentSizeFilter class's implementation of the insertString method:

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

关于java - 在 n 个字符后阻止文本写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16671674/

相关文章:

java - java中如何从子类对象中调用重写的方法

java - 在 JFrame 中创建一个键事件

android - 键盘弹出后后退按钮代码未触发

Java KeyListener 停止工作

Java JUnit4 : Make simple assertEquals Test pass

java - 当jibx绑定(bind)中字段为空时如何设置默认值?

java - 使用 JPA native 查询和 MemSql 选择 json 列

java - 向 JList 添加滚动条(包括 DefaultListModel 对象)

java - 如何在 JPanel 上移动形状?

java - 如何在Java中将文本字段放置在框架的特定位置并使其具有特定的大小?