java - 如何序列化JPanel?

标签 java swing serialization nullpointerexception

所以我有这段代码。我正在尝试在 JMenuBar 上实现点击保存并点击加载。我在序列化 JPanel 时遇到问题。

如何保存当前的绘图 View ?布局设置为 AbsoluteLayout 因此 GroupLayout 问题不是问题。我已通读 Google 搜索,我知道不推荐这样做,但我还能如何保存和加载它?

package tester;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import javax.swing.*;
import static tester.Plot.XMAX;
import static tester.Plot.XMIN;
import static tester.Plot.YMAX;
import static tester.Plot.YMIN;
import java.io.*;

/**
 *
 * @author Sana
 */
public class NewJFrame2 extends javax.swing.JFrame{

    public class Plot extends JPanel implements java.io.Serializable {

    public double xmin=0;
    public double xmax=0;
    public double ymin=0;
    public double ymax=0;
    public static final int XMIN = 45;
    public static final int XMAX = 420;
    public static final int YMIN = 300;
    public static final int YMAX = 25;
    Plottable2D plotFunction;
    Shape myShape;
    double[]xS;
    double[]yS;
    Graphics2D g2d;


    public void setAxis(double[] a){
       xmin=a[0];
       xmax=a[1];
       ymin=a[2];
       ymax=a[3];
    }

    public void setFunction(Plottable2D plotFunction){
        this.plotFunction = plotFunction; 
        xS = new double[100];
        for (int i=0;i<99;i++)
            xS=HW6ArrayMath.linspace(xmin, xmax, 99);
        yS = plotFunction.evaluate(xS);

        //repaint();

    }


    @Override
    public void paintComponent(Graphics g){
        Plot myPlot = (Plot) jPanel1;

        g.setColor(Color.white);
        g.fillRect(0, 0, getWidth(), getHeight());

        myPlot.setAxis(new double[] {0,1,0,1});
        myPlot.setFunction(new MyFunction());
        Graphics2D g2d = (Graphics2D) g;

        String xminString = "" + xmin;
        String xmaxString = "" + xmax;
        String yminString = "" + ymin;
        String ymaxString = "" + ymax;

        g2d.setColor(Color.BLUE);
        g2d.drawLine(XMIN,YMIN,XMAX,YMIN);
        g2d.drawString(xminString,XMIN, YMIN+10);
        g2d.drawString(xmaxString,XMAX, YMIN+10);
        g2d.drawLine(XMIN,YMIN, XMIN, YMAX);
        g2d.drawString(yminString,XMIN-15,YMIN);
        g2d.drawString(ymaxString,XMIN-15,YMAX); 


        for (int i=0;i<99-1;i++){
            double a = (xS[i]*(XMAX-XMIN))+XMIN;
            double b = (YMIN-(yS[i]*(YMIN-YMAX)));
            double c = (xS[i+1]*(XMAX-XMIN))+XMIN;
            double d = (YMIN-((yS[i+1]*(YMIN-YMAX))));
            g2d.draw(new Line2D.Double(a, b, c,d));
        }
    }

}


    /**
     * Creates new form NewJFrame2
     */
    public NewJFrame2() {
        initComponents();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new Plot();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jMenuBar2 = new javax.swing.JMenuBar();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel1.setBackground(new java.awt.Color(255, 240, 240));
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel2.setText("X Axis");
        jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 330, -1, -1));

        jLabel3.setText("Y Axis");
        jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 151, -1, -1));

        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(57, 46, 520, 360));

        jLabel1.setText("My Plot");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 30, 40, -1));

        jMenu3.setText("File");

        jMenuItem2.setLabel("Save");
        jMenuItem2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenuItem2MouseClicked(evt);
            }
        });
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem2);

        jMenuItem3.setLabel("Load");
        jMenuItem3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenuItem3MouseClicked(evt);
            }
        });
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem3);

        jMenuBar2.add(jMenu3);

        setJMenuBar(jMenuBar2);

        pack();
    }// </editor-fold>                        

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        try {  
       ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("C:\\Users\\Sana\\Documents\\NetBeansProjects\\MyPlot.ser"));

       out.writeObject(jLabel1);
       out.writeObject(jLabel2);
       out.writeObject(jLabel3);
       out.close();

        }
        catch(Exception e) {
            e.printStackTrace();
    }        
    }                                          

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                          

    private void jMenuItem2MouseClicked(java.awt.event.MouseEvent evt) {                                        

    }                                       


    private void jMenuItem3MouseClicked(java.awt.event.MouseEvent evt) {                                        
       try { 
           FileInputStream saveFile = new FileInputStream("MyPlot.ser");
           ObjectInputStream restore = new ObjectInputStream(saveFile);
           jPanel1 = (Plot) restore.readObject();
           restore.close();
       }catch (Exception exc){
       exc.printStackTrace();
       }

       repaint();
    }                                       


    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame2().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}

现在它给出了这个错误:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.plaf.synth.SynthLookAndFeel.paintRegion(SynthLookAndFeel.java:371)
    at javax.swing.plaf.synth.SynthLookAndFeel.update(SynthLookAndFeel.java:335)
    at javax.swing.plaf.synth.SynthRootPaneUI.update(SynthRootPaneUI.java:119)
    at javax.swing.JComponent.paintComponent(JComponent.java:780)
    at javax.swing.JComponent.paint(JComponent.java:1056) etc.

最佳答案

你的做法是错误的。您应该序列化 plotview 从中读取的数据,而不是 plotview 本身。

创建一个对象来包含你的数据:

public class PlotViewData implements Serializable {
    public double xmin=0; //Should be private
    public double xmax=0;
    public double ymin=0;
    public double ymax=0;
    public static final int XMIN = 45;
    public static final int XMAX = 420;
    public static final int YMIN = 300;
    public static final int YMAX = 25;
    //Extra data with getters and setters goes here.
}

然后序列化并从该对象中读取,组件应该由您的应用程序重新创建。

关于java - 如何序列化JPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30262387/

相关文章:

c# - protobuf-net 使用 DynamicType 序列化 System.Object 抛出异常

java - 以不同方式从另一个对象创建一个对象的设计模式

java - 附加到 StringBuffer (Java Servlet) 未作为 Servlet 中的属性获取

java - 设置大小在java中不起作用

java - 我想把这个白色的小东西藏在 JTable 上

c++ - 位域的二进制 "bulk"序列化

javascript - 字符串化时间戳对象

java - MSSQL 数据库锁阻止我的应用程序?

java - 使用基类对象调用派生类方法

Java Applet 包装器规模输出