java swing form_java – 如何记住Swing GUI表单中的最后一个值?

根据应用程序的大小和数据量,可以选择序列化整个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 ){}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值