2012-11-29 23 views
2

我正在序列化一個JTextPaneDocument以便將它的樣式文本保存到數據庫。我有一個caretListener連接到JTextPane,我想知道是否序列化這Document序列化caretListener以及。爲什麼我需要知道的原因是因爲自定義caretListener類containes JComboBox和我出現以下情況例外,當我試圖序列化:序列化JTextPane的Document,序列化JTextPane的偵聽器嗎?

java.io.NotSerializableException: com.apple.laf.AquaComboBoxUI 

我懷疑,如果文檔包含caretListener,這就是原因例外。

下面是其序列代碼:

DefaultStyledDocument doc = (DefaultStyledDocument) getCellEditor().getCellEditorValue(); 
doc.setDocumentFilter(null); 
ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
ObjectOutputStream oos = new ObjectOutputStream(bos); 
oos.writeObject((DefaultStyledDocument) doc); 
oos.flush(); 

byte[] data = bos.toByteArray(); 

oos.close(); 
bos.close(); 

然後,我只是保存在數據庫中data

附錄

這裏的自定義插入符偵聽:

MyTextPane textpane = new MyTextPane(); 
textpane.addCaretListener(new caretListener()); 
public class caretListener implements CaretListener { 

    MyTextpane textArea; 
    JToggleButton boldbutton; 
    JToggleButton italicbutton; 
    JToggleButton underlinebutton; 
    JComboBox fontscomboBox; 
    JComboBox fontSizecombobox; 
    // Methods 
    ... 
} 
+0

爲什麼要序列化文檔而不只是編寫自己的機制。請參閱每個搖擺課程結束時的警告:*此課程的序列化對象將與未來的Swing版本不兼容* – Robin

+0

@Robin看起來像更容易做的事情。如果這是問題的原因,我會寫我自己的機制,標籤也許。 – Igor

回答

2

Document通過Writer序列,並通過Reader反序列化。使用JTextPanegetEditorKit()和套件的寫/讀方法。

+0

感謝您的答案,但它並沒有真正回答標題中的主要問題。如果你可以補充一點,那將是非常棒的。 – Igor

+0

這個問題出現了[here](http://stackoverflow.com/q/13540613/230513),但我不知道'ComboBoxUI'如何被拖入。'EditorKit'的+1。 – trashgod

+0

@trashgod難道是因爲插入符偵聽器有'JComboBox'字段。請參閱問題中的**附錄**。 – Igor

相關問題