如何记住Swing GUI窗体中的最后一个值?
我有一个用Swing制作的简单的Java GUI窗体。它有一些文本输入和复选框,我希望它记住输入到这些的最后一个值。当然,可以手动将它们保存到某个文件中,然后读取文件并填充输入,但是我不知道是否有办法自动执行此操作。由于如何记住Swing GUI窗体中的最后一个值?
根据应用程序的大小和数据量,序列化整个UI可能是一种选择。
这可能是一个坏主意,但是,当信息基本上被检索并存储在数据库中了。在这种情况下,应该使用值对象和绑定,但对于UI与另一种持久化方式无关的一些简单应用程序,您可以使用它。
当然,你不能修改序列化值,直接这样,就认为这是一个额外的选项:
alt text 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);
}
}
这里的读/写为素描,有很多这里有待改进的余地。
/**
* 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){}
}
}
}
不是真的。您必须注意将值保存到文件或数据库中。
优选使用Preferences API。
它存储在系统中的喜好,但这个细节被隐藏你 - 你专注于你的喜好的结构和值,而不是实现细节(这是特定于平台)。
此API还允许在同一台机器上的不同用户的不同设置。
要试一试 – Fluffy 2010-01-11 16:43:54
只是不使用Java序列化! – 2010-01-11 16:34:06
@Tom:为什么不准确? – OscarRyz 2010-01-11 16:48:59