Java中怎样实现Swing组件的串行化和读取

原创|其它|编辑:郝浩|2009-07-03 11:13:29.000|阅读 600 次

概述:由于JButton和JTree都已经实现了Serializable接口,因此Java Swing组件的串行化和读取是可以做到的。

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

  由于JButton和JTree都已经实现了Serializable接口,因此Java Swing组件的串行化和读取是可以做到的。

  方法就是使用ObjectInputStream读取文件中的对象,使用ObjectOutputStream把对象写入文件。

  如:

  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.ObjectInputStream;
  import java.io.ObjectOutputStream;
  import javax.swing.JButton;
  import javax.swing.JTree;
  public class Save {
  public static void main(String[] args) {
  // Write
  JButton button = new JButton("TEST Button");
  JTree tree = new JTree();
  try {
  ObjectOutputStream outForButton = new ObjectOutputStream(
  new FileOutputStream("button"));
  outForButton.writeObject(button);
  outForButton.close();
  ObjectOutputStream outForTree = new ObjectOutputStream(
  new FileOutputStream("tree"));
  outForTree.writeObject(tree);
  outForTree.close();
  } catch (FileNotFoundException e) {
  e.printStackTrace();
  } catch (IOException e) {
  e.printStackTrace();
  }
  // Read
  try {
  ObjectInputStream inForButton = new ObjectInputStream(
  new FileInputStream("button"));
  JButton buttonReaded = (JButton) inForButton.readObject();
  ObjectInputStream inForTree = new ObjectInputStream(
  new FileInputStream("tree"));
  JTree treeReaded = (JTree) inForTree.readObject();
  } catch (FileNotFoundException e) {
  e.printStackTrace();
  } catch (IOException e) {
  e.printStackTrace();
  } catch (ClassNotFoundException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
  }
  }


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@evget.com

文章转载自:IT专家网论坛

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP