对 Swing 的撤消管理器隐藏某些操作 [英] Hide certain actions from Swing's undo manager

查看:22
本文介绍了对 Swing 的撤消管理器隐藏某些操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个支持某种着色的 JTextPane:当用户输入文本时,我正在运行一些代码,根据特定算法为文本着色.这很好用.

I am trying to write a JTextPane which supports some sort of coloring: as the user is typing the text, I am running some code that colors the text according to a certain algorithm. This works well.

问题是着色操作是在撤销管理器中注册的(一个带有 EventType.CHANGE 的 DefaultDocumentEvent).因此,当用户单击撤消时,着色消失.只有在第二次撤消请求时,文本本身才会回滚.

The problem is that the coloring operations is registered with the undo manager (a DefaultDocumentEvent with EventType.CHANGE). So when the user clicks undo the coloring disappears. Only at the second undo request the text itself is rolled back.

(请注意,着色算法有点慢,因此我无法在插入文本时为文本着色).

(Note that the coloring algorithm is somewhat slow so I cannot color the text as it is being inserted).

如果我试图阻止 CHANGE 事件到达撤消管理器,我会在多次撤消请求后得到一个异常:这是因为文档内容不符合可撤消编辑对象的预期.

If I try to prevent the CHANGE events from reaching the undo manager I get an exception after several undo requests: this is because the document contents are not conforming to what the undoable-edit object expects.

有什么想法吗?

推荐答案

您可以拦截 CHANGE 编辑并将每个编辑都包装在另一个 UndoableEdit 中,其 isSignificant() 方法返回 false,在将其添加到 UndoManager 之前.然后每个撤消命令将撤消最近的 INSERT 或 REMOVE 编辑,以及此后发生的每个 CHANGE 编辑.

You could intercept the CHANGE edits and wrap each one in another UndoableEdit whose isSignificant() method returns false, before adding it to the UndoManager. Then each Undo command will undo the most recent INSERT or REMOVE edit, plus every CHANGE edit that occurred since then.

最终,我想您会发现 JTextPane/StyledDocument/等提供的样式机制.对于这种事情来说太有限了.它很慢,它使用太多内存,并且它基于用于跟踪文档词法结构的相同元素树.对于样式由用户应用的应用程序(如文字处理器)来说,这没问题(我猜),但对于必须在用户键入时不断更新样式的语法高亮器就不行了.

Ultimately, I think you'll find that the styling mechanism provided by JTextPane/StyledDocument/etc. is too limited for this kind of thing. It's slow, it uses too much memory, and it's based on the same Element tree that's used to keep track of the lexical structure of the document. It's okay (I guess) for applications in which the styles are applied by the user, like word processors, but not for a syntax highlighter that has to update the styles constantly as the user types.

有几个基于 Swing JTextComponentViewDocument 类的自定义实现的语法高亮编辑器示例.有些,比如 JEdit,实际上重新实现了整个 javax.swing.text 包,但我认为你不需要走那么远.

There are several examples out there of syntax-highlighting editors based on custom implementations of the Swing JTextComponent, View and Document classes. Some, like JEdit, re-implement practically the whole javax.swing.text package, but I don't think you need to go that far.

这篇关于对 Swing 的撤消管理器隐藏某些操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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