Help on writing your own javax.swing.text.Document

寵の児 提交于 2019-12-06 08:24:08

问题


I'm writing a Java TextComponent where the underlying document has some structure. It is very short, basically one line. I need to be able to override the response to inserting or deleting characters in some parts of the document.

My initial approach was to implement javax.swing.text.Document, but this seems to involve developing many associated classes (Element, EditorKit, View) and there don't seem to be many examples or tutorials on how to do this. There are plenty on using the pre-defined implementations.

Can anyone point me at tutorials or other aids for simple implementations of Document and what other classes I need to create to make this work.


回答1:


If you just want to react to character insertion/deletion then maybe a DocumentFilter is the better approach. This will allow you to prevent the insertion of characters to the Document is you so desire. Read the JTextField API and follow the link to the Swing tutorial on "Text Component Features" for more information.




回答2:


There is a Java Swing tutorial on using text components.

Basically speaking you can add your DocumentListener to the document and react to changes or write your own implementation of document. Using AbstractDocument that should be easy, because it has only a couple of abstract methods you need to implement. Alternatively you may alos subclass PlainDocument and only override a certaing set of methods of interest to you.

Given your constraints, that you only need to react somehow on insertion/deletion of characters adding a listener on the document should work best.

Let me know if you need more details.




回答3:


There is EditorKit – Document – Views relations tutorial, which gives some insight into implementation of custom javax.swing.text.Document.



来源:https://stackoverflow.com/questions/2516638/help-on-writing-your-own-javax-swing-text-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!