由于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) {// WriteJButton 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();}// Readtry { 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();}}}
import javax.swing.JButton;import javax.swing.JTree;
public class Save {
public static void main(String[] args) {
// WriteJButton 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();}
}
【编辑推荐】
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
现在虽然是移动互联网时代,但企业网站依然重要,包含PC站点,移动站。可以说企业网站关系企业的未来发展和前途,尤其对中小企业更是如此,一些中小企业老板,对自己的名片很在乎,因为这是个门面。...
用我们的专业和诚信赢得您的信赖,从PC到移动互联网均有您想要的服务!
如遇占线或暂未接听请拨:136xxx98888