Unable to serialize a root node of a JTree (groovy/java)
I am working on a swing application which primarily includes a JTree and some other components in it. The complete logic behind the UI display is based upon the root node of JTree. It is a nested node with individual custom UserObjects set to each of the child nodes.
I need to preserve the state of my application for which the single nested root node of开发者_如何学JAVA the JTree should be preserved. I am unable to do so.
class SerializeImpl implements Serializable{
def doSerialize() throws Exception{
def root = FeedTree.getInstance().getModel().getRoot()
def object = new SerializableNode(top:root)
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("new.txt"))
out.writeObject(object)
}
def doDeSerialize(){
def file = new File('new.txt')
def serNodeObj
try{
file.withObjectInputStream(getClass().classLoader){ ois ->
ois.eachObject{ serNodeObj = it }
}
return serNodeObj.getValue()
}
catch(FileNotFoundException ex){
return null
}
}
}
class SerializableNode implements Serializable{
def top
def getValue(){
return top
}
}
class FeedTree extends JTree{
...............
a singleton instance
...............
}
The doSerialize()
method is executed first followed by a System.exit(1)
and followed by a fresh display of UI which does doDeSerialize()
.. The doSerialize()
method does write something onto the news.txt
file but I am not sure if it is serializing the object corrrectly. Moreover the System.exit(1)
after serializing doesn't work.
After a forced Exit (from eclipse console close) the first execution of doDeSerialize()
throws the following exception.
Caught: java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: groovy.util.slurpersupport.NodeChildren
at functionalities.SerializeImpl$_doDeSerialize_closure1.doCall(SerializeImpl.groovy:23)
at functionalities.SerializeImpl.doDeSerialize(SerializeImpl.groovy:22)
I am unable to understand why the serialize is (probably) failing and why the System.exit(1)
is not functioning correctly after the serialize. Please help.
In order for SerializableNode
to actually be serializable, its whole object graph must be serializable. What type of value is top
? If that is not serializable, the node will thrown a NotSerializableException
when writing.
If top
cannot be made Serializable, then you should declare it as transient
and implement writeResolve
and readResolve
to properly write/read the non serializable value.
look at method invokeLater or better for Serializable for invokeAndWait(), because Swing code must be done on Event Dispatch Thread,
correct way, create JTree with DefaultTreeModel separatelly, and from your Serializable
methods just to add TreeNodes
wrapped into invokeLater
精彩评论