根据应用程序的大小和数据量,可以选择序列化整个UI.
但是,当信息基本上被检索并存储在数据库中时,这可能是一个坏主意.在这种情况下,应该使用值对象和绑定,但对于一些简单的应用程序,其中UI独立于另一种持久化方式,您可以使用它.
当然,您无法直接修改序列化值,只需将其视为额外选项:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class SwingTest {
public static void main( String [] args ) {
final JFrame frame = getFrame();
frame.pack();
frame.setVisible( true );
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
writeToFile( frame,"swingtest.ser");
}
});
}
/**
* Reads it serialized or create a new one if it doens't exists
*/
private static JFrame getFrame(){
File file = new File("swingtest.ser");
if( !file.exists() ) {
System.out.println("creating a new one");
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add( new JLabel("Some test here:"));
panel.add( new JTextField(10));
frame.add( panel );
return frame;
} else {
return ( JFrame ) readObjectFrom( file );
}
}
这里是读/写草图,这里有很大的改进空间.
/**
* write the object to a file
*/
private static void writeToFile( Serializable s,String fileName ) {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream( new FileOutputStream( new File( fileName )));
oos.writeObject( s );
} catch( IOException ioe ){
} finally {
if( oos != null ) try {
oos.close();
} catch( IOException ioe ){}
}
}
/**
* Read an object from the file
*/
private static Object readObjectFrom( File f ) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream( new FileInputStream( f )) ;
return ois.readObject();
} catch( ClassNotFoundException cnfe ){
return null;
} catch( IOException ioe ) {
return null;
} finally {
if( ois != null ) try {
ois.close();
} catch( IOException ioe ){}
}
}
}