java swing form_java – 如何记住Swing GUI表单中的最后一个值?
发布日期:2021-06-24 15:11:10 浏览次数:2 分类:技术文章

本文共 1667 字,大约阅读时间需要 5 分钟。

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

}

}

}

转载地址:https://blog.csdn.net/weixin_33572836/article/details/114559911 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:java中jdbc文件配置_jdbc.properties文件中的配置需要加上" jdbc."的前缀
下一篇:java speex转码_JAVA版-微信语音.speex转.wav

发表评论

最新留言

不错!
[***.144.177.141]2024年04月15日 09时59分03秒