问题
Suppose I have a JTextPane with HTMLEditorKit. I'm displaying a paragraph of text and want to capture events when user clicks on individual word or presses a certain hotkey while a word is highlighted. For example, when a word is highlighted and user presses D, the word is removed from the text. Also, how to implemented custom cursor navigation - that is, move cursor on word boundaries only?
What would be the simplest way to implement these features? I realise this is a lot of code, so just stating useful class listener names, relevant methods, etc would be sufficient to get me going :) Thanks.
回答1:
For example, when a word is highlighted and user presses D, the word is removed from the text
This is already supported by the default EditorKit. See Key Bindings for the supported bindings. The link also shows you how to share the existing Actions with different KeyStrokes if you wish.
If you need to implement other Actions then you would start by extending TextAction to add your custom functionality. Then you bind your action to a key stroke.
回答2:
You might look into Charles Bell's HTMLDocumentEditor.
回答3:
You may want to take a look at DocumentListener
if you want to detect when the user has changed the underlying document or CaretListener
for changes to the caret (which is, I think, what you are looking for).
See http://download.oracle.com/javase/6/docs/api/javax/swing/event/DocumentListener.html and http://download.oracle.com/javase/6/docs/api/javax/swing/event/CaretListener.html
来源:https://stackoverflow.com/questions/5898912/action-event-for-jtextpane-contents