在 JTextArea 中剪切和粘贴
我正在开发一个应用程序,它要求 JTextArea 中只有 165 个字符。 我已经强加了这个条件。我使用静态计数器来计算在文本区域中输入的字符数,并进行编码以处理用户从文本中删除任何字符串时的情况,计数器必须通过考虑所选字符串的长度来增加。
但是现在我想处理用户通过按“Ctrl+X”和“Ctrl+V”执行“剪切”或“粘贴”选项时的情况。我知道 JTextComponent 的默认方法是在 JTextArea 中继承的,但我想获取剪切文本并知道剪切文本的长度,以便减少为字符维护的计数器并在粘贴适当数量时增加它。
I'm developing an application which requires that only 165 characters to be in the JTextArea.
I've imposed that condition. I've used a static counter for counting number of characters entered in the textarea and also coded to handle the condition when user deletes any string from the text the counter must be incremented by considering length of the string selected.
However now I want to handle the condition when user performs 'cut' or 'paste' option by pressing 'Ctrl+X' and 'Ctrl+V'. I know that default methods from JTextComponent are inherited in JTextArea but I want to get the cut text and know the length of the cut text so as to decrement the counter maintained for characters and increment it while pasting by appropriate amount.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
创建一个
DocumentFilter
并将其设置在新的PlainDocument
上。使用此文档创建JTextArea
。 (或者在转换为 AbstractDocument 后使用 JTextArea 的默认文档)。请参阅我的答案此处获取示例。
Create a
DocumentFilter
and set it on a newPlainDocument
. Use this document to create theJTextArea
. (Or use the default document of the JTextArea, after casting to AbstractDocument).See my answer here for a sample.
听起来您需要使用
DocumentListener
来跟踪更改。文档侦听器中的事件将告诉您在任何给定更改中添加/删除了多少个字符,并且还为您提供了对支持文本区域的Document
的引用。以下是名为
textArea
的JTextArea
的示例文档侦听器实现:此侦听器将检测剪切和粘贴以及按键操作。
It sounds like you need to use
DocumentListener
to track the changes. The events in the document listener will tell you how many characters are added/removed in any given change, and also gives you a reference to theDocument
that is backing the text area.The following is an example document listener implementation for a
JTextArea
calledtextArea
:This listener will detect cut and pastes as well as key presses.
阅读 Swing 教程中有关实现文档过滤器的部分 用于限制文本组件中字符数的工作代码。
过滤器比侦听器更可取,因为它可以防止文档被更新。如果您使用侦听器,则当文本超出限制时,您将需要撤消更改。
Read the section from the Swing tutorial on Implementing a Document Filter for working code that limits the number of characters in a text component.
A filter is preferable to a listener because it prevents the Document from being updated. If you use a listener you will need to undo changes when the text exceeds your limit.