如何根据用户类型来限制JTextPane中的字符数(Java) [英] How do I limit the amount of characters in JTextPane as the user types (Java)

查看:118
本文介绍了如何根据用户类型来限制JTextPane中的字符数(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不需要在输入X后输入任何字符.键入X个字符后,我需要发出哔声.我知道在用户按下Enter键后如何执行此操作,但是我需要在用户按下Enter键之前执行此操作.我从Oracle网站发现的方法是将DocumentSizeFilter添加到JTextPane.我无法在用户走过去时通知它(直到他们按Enter才起作用).这是我所拥有的一个样本.

I need to not allow any characters to be entered after X have been typed. I need to send a beep after X characters have been typed. I know how to do this after the user presses enter, but I need to do it before the user presses enter. The approach I found from Oracle's site is to add a DocumentSizeFilter to the JTextPane. I can't get this to notify the user when they have gone over (it doesn't work until they press enter). This is a sample of what I have.

public class EndCycleTextAreaRenderer extends JTextPane
implements TableCellRenderer {

private final int maxNumberOfCharacters = 200;

public EndCycleTextAreaRenderer() {
    StyledDocument styledDoc = this.getStyledDocument();
    AbstractDocument doc;
    doc = (AbstractDocument)styledDoc;
    doc.setDocumentFilter(new DocumentSizeFilter(maxNumberOfCharacters ));

}

推荐答案

覆盖

Override the insertString method of the document in the JTextPane so that it doesn't insert any more characters once the maximum has been reached.

例如:

JTextPane textPane = new JTextPane(new DefaultStyledDocument() {
    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        if ((getLength() + str.length()) <= maxNumberOfCharacters) {
            super.insertString(offs, str, a);
        }
        else {
            Toolkit.getDefaultToolkit().beep();
        }
    }
});

更新:

您可以按以下步骤更改班级:

You can change your class as follows:

public class EndCycleTextAreaRenderer extends JTextPane implements TableCellRenderer {

    private final int maxNumberOfCharacters = 200;

    public EndCycleTextAreaRenderer() {
        setStyledDocument(new DefaultStyledDocument() {
            @Override
            public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
                if ((getLength() + str.length()) <= maxNumberOfCharacters) {
                    super.insertString(offs, str, a);
                } else {
                    Toolkit.getDefaultToolkit().beep();
                }
            }
        });
    }
}

这篇关于如何根据用户类型来限制JTextPane中的字符数(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆