我正在序列化一個JTextPane
的Document
以便將它的樣式文本保存到數據庫。我有一個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
...
}
爲什麼要序列化文檔而不只是編寫自己的機制。請參閱每個搖擺課程結束時的警告:*此課程的序列化對象將與未來的Swing版本不兼容* – Robin
@Robin看起來像更容易做的事情。如果這是問題的原因,我會寫我自己的機制,標籤也許。 – Igor