action event for JTextPane contents

2019-08-02 04:06发布

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.

3条回答
倾城 Initia
2楼-- · 2019-08-02 04:36

You might look into Charles Bell's HTMLDocumentEditor.

查看更多
不美不萌又怎样
3楼-- · 2019-08-02 04:43

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

查看更多
Summer. ? 凉城
4楼-- · 2019-08-02 04:46

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.

查看更多
登录 后发表回答