![](/img/trans.png)
[英]What event listener should I use for on-screen keyboard if not keyEvents?
[英]What JEditorPane event should I create a listener for?
假設我在JPanel中有一個JEditorPane。 我希望每次用戶在JEditorPane組件中輸入/粘貼文本時都能執行回調。 我應該創建什么類型的聽眾?
您可以使用DocumentListener通知Document的任何更改。
由於我還不能留下評論,我只想說盡可能使用監聽器比覆蓋一個類更好,就像上面給出的覆蓋PlainDocument的例子一樣。
偵聽器方法將適用於JTextField,JTextArea,JEditorPane或JTextPane。 默認情況下,編輯器窗格使用HTMLDocument,而JTextPane使用StyledDocument。 因此,您通過強制組件使用PlainDocument來丟失功能。
如果您關注的是在將文本添加到Document之前編輯文本,那么您應該使用DocumentFilter
一種方法是創建自定義Document並覆蓋insertString方法。 例如:
class CustomDocument extends PlainDocument {
@Override
public void insertString(int offset, String string, AttributeSet attributeSet)
throws BadLocationException {
// Do something here
super.insertString(offset, string, attributeSet);
}
}
這允許您找出插入的內容並根據需要否決它(通過不調用super.insertString)。 您可以使用以下方法應用此文檔:
editorPane.setDocument(new CustomDocument());
在DocumentEvent接口中,您可以使用getOffset()和getLength()等方法來檢索實際更改。
希望這對你有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.