我有一个用Swing制作的简单Java GUI表单.它有一些文本输入和复选框,我希望它记住输入到这些输入的最后一个值.当然可以手动将它们保存到某个文件然后读取文件并填充输入,但我想知道是否有办法自动或多或少地执行此操作.谢谢
最好使用Preferences API.
它将首选项存储在系统中,但这些详细信息对您隐藏 - 您关注的是首选项的结构和值,而不是实现细节(特定于平台).
此API还允许同一台计算机上的不同用户进行不同的设置.
根据应用程序的大小和数据量,序列化整个 UI 可能是一种选择。
不过,当信息基本上已经被检索并存储在数据库中时,这可能是一个坏主意。在这种情况下,应该使用值对象和绑定,但对于一些 UI 独立于另一种持久方式的简单应用程序,您可以使用它。
当然,您不能直接修改序列化值,因此,只需将其视为额外选项:
替代文本http://img684.imageshack.us/img684/4581/capturadepantalla201001p.png
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 );
}
}
Run Code Online (Sandbox Code Playgroud)
这是读/写草图,这里还有很大的改进空间。
/**
* 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 ){}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1347 次 |
| 最近记录: |