怎么把在Panel上画的图片,比如:一个圆或矩形,用IO流保存为文件

解决方案 »

  1.   

    要保存就要保存这个对象,不如你如果实在JFrame上画的图,那你就应该把这个JFrame保存下来,在AWT和SWING中的可视组建,他们都是实现了Serializable接口的,该接口允许将一个对象以及这个对象所引用的其他对象数据流化,并允许ObjectOutputStream操作它(你想把它保存为什么就可以是什么,当然也包括文件形式)
      

  2.   

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;public class Test11 {
    private File myFile = new File("c:\\mytestFile.txt");
    private ObjectOutputStream myObjectOutputStream;
    /**
     * 只是将要被写入文件的对象
     * */
    private MyClass1 myClass = new MyClass1();
    /**
     * 该方法负责将对象存储于文件中
     * */
    public void doWrite(){
    this.myClass.setString("343432434");
    try{
    //这段代码不用解释了吧
    this.myFile.createNewFile();
    this.myObjectOutputStream =  new ObjectOutputStream(
    new FileOutputStream(myFile));

    this.myObjectOutputStream.writeObject(this.myClass);
    this.myObjectOutputStream.flush();
    }catch(Exception e){

    }
    }

    /**
     * 该方法负责从文件读取MyClass对象,并观察这个对象的状态
     * */
    public void doRead(){
    ObjectInputStream myObjectInputStream;
    try{
    myObjectInputStream = new ObjectInputStream(
    new FileInputStream(this.myFile));
    MyClass1 test = (MyClass1)myObjectInputStream.readObject();
    System.out.println(test.getString());
    }catch(Exception e){

    }
    }

    public static void main(String[] src){
    Test11 temp = new Test11();
    temp.doWrite();
    temp.doRead();
    }
    }
    /**
     * 下是需要序列化的类
     * */
    class MyClass1 implements Serializable{
    private String string = "哈哈哈哈!"; /**
     * @return 返回 string。
     */
    public String getString() {
    return string;
    } /**
     * @param string 要设置的 string。
     */
    public void setString(String string) {
    this.string = string;
    }
    }