Salvataggio JTable() [RISOLTO]

di il
7 risposte

Salvataggio JTable() [RISOLTO]

Salve ragazzi e ben ritrovati

Come da titolo ho un problema con un salvataggio di una JTable.

Praticamente inserisco una nuova riga e funziona tutto...però quando voglio salvarla non succede nulla.

Ecco il codice :
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.MaskFormatter;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Daniele
 */
public class SalvaT extends JFrame implements ActionListener {
    
    private JTable table;
    private JTextField NomeRicetta;
    private JTextField tempi;
    private JTextField calorie;
    private JTextField ingredienti;
    
    public FileInputStream fis;
    public ObjectInputStream in;
    public FileOutputStream fos;
    public ObjectOutputStream out;
    public JMenuItem savecontact;
    public String filename;
    public DefaultTableModel model;
    public JMenuItem loadcontact;
    public JMenuItem close;
    
    
    public SalvaT() {
        
        fis = null;
        in = null;
        fos = null;
        out = null;
        filename = "test.ref";
        initGui();
        
    }
    
    public void initGui(){
        
        getContentPane().setLayout(null);
        JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        tabbedPane.setBackground(new Color(189, 183, 107));
        tabbedPane.setBounds(0, 32, 650, 365);
        getContentPane().add(tabbedPane);
        try {
            MaskFormatter mf2 = new MaskFormatter("(###) ###-####");
        } catch (ParseException ex) {
            Logger.getLogger(SalvaT.class.getName()).log(Level.SEVERE, null, ex);
        }

        // the main panel that hold the search bar and table
        JPanel MainPanel = new JPanel(); 
        MainPanel.setBackground(Color.LIGHT_GRAY);
        tabbedPane.addTab("Main", null, MainPanel, null);
        MainPanel.setLayout(null);        

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(10, 42, 604, 195);
        MainPanel.add(scrollPane);

        table = new JTable();
        table.setBorder(UIManager.getBorder("DesktopIcon.border"));
        scrollPane.setViewportView(table);

        // the column in the table
        table.setModel(new DefaultTableModel(

                new Object[][] {
            },
            new String[] {
                "Nome Ricetta", "Tempi (min)", "Calorie a persona", "Ingredienti", "Descrizione"
            }
        ));


        // a panel that hold the first name, last name, phone number and email text field for entering 
        // information into the table on the main panel 
        JPanel AddentryPanel = new JPanel();
        AddentryPanel.setBackground(Color.LIGHT_GRAY);

        // add the entry tab for inputting information
        tabbedPane.addTab("Aggiungi Ricetta ", null, AddentryPanel, null); 
        // set absolute layout
        AddentryPanel.setLayout(null);

        // a text field for entering you first name
        NomeRicetta = new JTextField();

        NomeRicetta.setBounds(175, 49, 308, 34);

        // add the first name text field to the add entry panel
        AddentryPanel.add(NomeRicetta);
        NomeRicetta.setColumns(10);

        JLabel lblNewLabel = new JLabel("Nome Ricetta:");
        lblNewLabel.setForeground(Color.BLUE);
        lblNewLabel.setBounds(98, 59, 99, 14);
        AddentryPanel.add(lblNewLabel);

        JLabel Lastnamelabel = new JLabel("Tempi (min):");
        Lastnamelabel.setForeground(Color.BLUE);
        Lastnamelabel.setBounds(98, 104, 110, 14);
        AddentryPanel.add(Lastnamelabel);

        // a text field for entering you last name
        tempi = new JTextField();
        tempi.setColumns(10);
        tempi.setBounds(175, 94, 308, 34);

        // add the last name to the entry panel
        AddentryPanel.add(tempi);

        // add a formatted text field for you phone number. This field only allow number.
        calorie = new JTextField();
        calorie.setColumns(10);
        calorie.setBounds(175, 145, 308, 34);

        // add the formatted text field  to entry panel
        AddentryPanel.add(calorie);

        // a text field for entering you email 
        ingredienti = new JTextField();
        ingredienti.setColumns(10);
        ingredienti.setBounds(175, 190, 308, 34);

        // add the email text field to the add entry panel
        AddentryPanel.add(ingredienti);

        JLabel Phonenumberlabel = new JLabel("Calorie");
        Phonenumberlabel.setForeground(Color.BLUE);
        Phonenumberlabel.setBounds(125, 155, 93, 14);
        AddentryPanel.add(Phonenumberlabel);

        JLabel Email = new JLabel("Ingredienti");
        Email.setForeground(Color.BLUE);
        Email.setBounds(110, 200, 80, 14);
        AddentryPanel.add(Email);

        // a button that add information into the table from the first name, last name, email
        // and you phone number field.
        JButton AddEntrybutton = new JButton("Aggiungi");

        AddEntrybutton.setForeground(Color.GREEN);
        
        AddEntrybutton.addActionListener(new ActionListener() {
            /*
             * This action listener for entry button will prompt
             * you, if you want to add information into the table.
             * It also check if all the mandatory field have been filled correctly
             * so that it can proceed with the adding. If field has a error it will 
             * display a error.
             */

            public void actionPerformed(ActionEvent e) {

            // check if the option field are filled and correct before adding.
                if(NomeRicetta.getText().equalsIgnoreCase("")|| calorie.getText().equalsIgnoreCase("") || tempi.getText().equalsIgnoreCase("") || ingredienti.getText().equalsIgnoreCase("")){
                    JOptionPane.showMessageDialog (null, "Assicurati che i campi obbligatori siano riempiti"); 
                }

                // prompt if you are sure you want to add these information into the table
                else if (JOptionPane.showConfirmDialog(null, "Vuoi aggiungere la ricetta?", "Request", 
                        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
                        == JOptionPane.YES_OPTION)
                    {

                    DefaultTableModel dtm = (DefaultTableModel)table.getModel();

                    dtm.addRow(new Object[] { NomeRicetta.getText(), tempi.getText(), calorie.getText(), ingredienti.getText()});
                    }


            }
        });
        AddEntrybutton.setBounds(175, 253, 89, 23);

        // add the add button to the entry panel 
        AddentryPanel.add(AddEntrybutton);


        // a button the is use for clearing the field in the add entry panel
        JButton ClearButton = new JButton("Resetta");
        ClearButton.setForeground(Color.RED);
        ClearButton.addActionListener(new ActionListener() {
            /*
             *  prompt you if you want to clear the first name,
             *  last name, phone number and email text field.
             *  if you select yes the field will be clear.
             *  if you select no the field will not be clear.
             */

            public void actionPerformed(ActionEvent e) {
                if (JOptionPane.showConfirmDialog(null, "Sei sicuro di voler resettare i campi?", "Request", 
                        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
                        == JOptionPane.YES_OPTION)
                    {
                     NomeRicetta.setText("");
                     tempi.setText("");
                     calorie.setText("");
                     ingredienti.setText("");


                    }
                    else
                    {
                     //Go back to normal
                    }

            }
        });
        ClearButton.setBounds(394, 253, 89, 23);

        // add the clear button the entry panel
        AddentryPanel.add(ClearButton);

        // label tell that field is optional and doesn't need to be filled
        JLabel Optionallabel1 = new JLabel("Obbligatorio");
        
        Optionallabel1.setForeground(Color.RED);
        Optionallabel1.setBounds(493, 200, 90, 14);
        AddentryPanel.add(Optionallabel1);

        // label tell that field is optional and doesn't need to be filled
        JLabel Optionallabel2 = new JLabel("Obbligatorio");
        
        Optionallabel2.setForeground(Color.RED);
        Optionallabel2.setBounds(493, 104, 90, 14);
        AddentryPanel.add(Optionallabel2);

        // label that tell you that this field has to be filled
        JLabel Mandatorylabel1 = new JLabel("Opzionale");

        Mandatorylabel1.setBounds(493, 155, 90, 14);
        AddentryPanel.add(Mandatorylabel1);

        // label that tell you that this field has to be filled
        JLabel Manatorylabel2 = new JLabel("Obbligatorio");

        Manatorylabel2.setForeground(Color.RED);
        Manatorylabel2.setBounds(493, 59, 90, 14);
        AddentryPanel.add(Manatorylabel2);

        // a menu bar for displaying the option to load contact, save contact, 
        // export contact as excel file and be able to close option
        JMenuBar menuBar = new JMenuBar();
        menuBar.setBounds(0, 0, 650, 21);
        getContentPane().add(menuBar);


        JMenu fileoption = new JMenu("File");

        menuBar.add(fileoption);


        JMenuItem loadcontact = new JMenuItem("Carica");

        // add load contact file to menu
        fileoption.add(loadcontact);

        JMenuItem savecontact = new JMenuItem("Salva");
        
        
        

        // add a save contact file to menu
        fileoption.add(savecontact);

        JMenuItem close = new JMenuItem("Chiudi");
        close.addActionListener(new ActionListener() {

            /*
             * When selected the program will close.
             * 
             */
            public void actionPerformed(ActionEvent arg0) {
                System.exit(0);
            }
        });
        fileoption.add(close);
        table.getColumnModel().getColumn(2).setPreferredWidth(124);       
    }
    
    public void setModel(DefaultTableModel writeModel) {
        table.setModel(writeModel);
    }
    
    
    public void actionPerformed(ActionEvent e) {
        System.out.println("Clicked item!");
        if (e.getSource() == savecontact) {
            System.out.println("Save!");
            try {
                fos = new FileOutputStream(filename);
                out = new ObjectOutputStream(fos);
                table.clearSelection();
                table.setModel(new DefaultTableModel());
                out.writeObject(model);
                table.setModel(model);
            } catch (IOException e3) {
                e3.printStackTrace();
            } finally {
                try {
                    out.close();
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        } else if (e.getSource() == loadcontact) {
            System.out.println("Open!");
            try {
                fis = new FileInputStream(filename);
                in = new ObjectInputStream(fis);
                DefaultTableModel modelRead = (DefaultTableModel) in.readObject();
                setModel(modelRead);
                System.out.println("data loaded");
                in.close();
                fis.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            } catch (ClassNotFoundException e2) {
                e2.printStackTrace();
            }
        } else if (e.getSource() == close) {
            System.out.println("Exit!");
        }
    }
    
    

    
    public static void main(String[] args) {
        
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                SalvaT ex = new SalvaT();
                ex.setVisible(true);
            }
        });
    }
        
        
    }

Come sempre grazie wuajù




EDIT :

Ecco di seguito la soluzione del problema
P.S. ringrazio ttrash per la dritta
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.MaskFormatter;


public class SalvaT extends JFrame implements ActionListener {
    
    private JTable table;
    private JTextField NomeRicetta;
    private JTextField tempi;
    private JTextField calorie;
    private JTextField ingredienti;
    private JTextField descrizione;
    
    public FileInputStream fis;
    public ObjectInputStream in;
    public FileOutputStream fos;
    public ObjectOutputStream out;
    public JMenuItem savecontact;
    public String filename;
    public DefaultTableModel model;
    public JMenuItem loadcontact;
    public JMenuItem close;
    
    
    public SalvaT() {
        
        fis = null;
        in = null;
        fos = null;
        out = null;
        filename = "test.ref";
        setLocationRelativeTo(null);
        initGui();
        
    }
    
    public void initGui(){
        
        setSize(650,365);
        getContentPane().setLayout(null);
        JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        tabbedPane.setBackground(new Color(189, 183, 107));
        tabbedPane.setBounds(0, 32, 650, 365);
        getContentPane().add(tabbedPane);
        try {
            MaskFormatter mf2 = new MaskFormatter("(###) ###-####");
        } catch (ParseException ex) {
            Logger.getLogger(SalvaT.class.getName()).log(Level.SEVERE, null, ex);
        }

        // the main panel that hold the search bar and table
        JPanel MainPanel = new JPanel(); 
        MainPanel.setBackground(Color.LIGHT_GRAY);
        tabbedPane.addTab("Main", null, MainPanel, null);
        MainPanel.setLayout(null);        

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(10, 42, 604, 195);
        MainPanel.add(scrollPane);

        table = new JTable();
        table.setBorder(UIManager.getBorder("DesktopIcon.border"));
        scrollPane.setViewportView(table);

        // the column in the table
        table.setModel(new DefaultTableModel(

                new Object[][] {
            },
            new String[] {
                "Nome Ricetta", "Tempi (min)", "Calorie a persona", "Ingredienti", "Descrizione"
            }
        ));


        // a panel that hold the first name, last name, phone number and email text field for entering 
        // information into the table on the main panel 
        JPanel AddentryPanel = new JPanel();
        AddentryPanel.setBackground(Color.LIGHT_GRAY);

        // add the entry tab for inputting information
        tabbedPane.addTab("Aggiungi Ricetta ", null, AddentryPanel, null); 
        // set absolute layout
        AddentryPanel.setLayout(null);

        // a text field for entering you first name
        NomeRicetta = new JTextField();

        NomeRicetta.setBounds(175, 49, 308, 34);

        // add the first name text field to the add entry panel
        AddentryPanel.add(NomeRicetta);
        NomeRicetta.setColumns(10);

        JLabel lblNewLabel = new JLabel("Nome Ricetta:");
        lblNewLabel.setForeground(Color.BLUE);
        lblNewLabel.setBounds(98, 59, 99, 14);
        AddentryPanel.add(lblNewLabel);

        JLabel Tempi = new JLabel("Tempi (min):");
        Tempi.setForeground(Color.BLUE);
        Tempi.setBounds(98, 104, 110, 14);
        AddentryPanel.add(Tempi);

        // a text field for entering you last name
        tempi = new JTextField();
        tempi.setColumns(10);
        tempi.setBounds(175, 94, 308, 34);

        // add the last name to the entry panel
        AddentryPanel.add(tempi);

        // add a formatted text field for you phone number. This field only allow number.
        calorie = new JTextField();
        calorie.setColumns(10);
        calorie.setBounds(175, 145, 308, 34);

        // add the formatted text field  to entry panel
        AddentryPanel.add(calorie);

        // a text field for entering you email 
        ingredienti = new JTextField();
        ingredienti.setColumns(10);
        ingredienti.setBounds(175, 190, 308, 34);

        // add the email text field to the add entry panel
        AddentryPanel.add(ingredienti);

        JLabel Calorie = new JLabel("Calorie");
        Calorie.setForeground(Color.BLUE);
        Calorie.setBounds(125, 155, 93, 14);
        AddentryPanel.add(Calorie);

        JLabel Ingredienti = new JLabel("Ingredienti");
        Ingredienti.setForeground(Color.BLUE);
        Ingredienti.setBounds(110, 200, 80, 14);
        AddentryPanel.add(Ingredienti);
        
        descrizione = new JTextField();
        descrizione.setColumns(10);
        descrizione.setBounds(175, 230, 308, 34);
        
        AddentryPanel.add(descrizione);
        
        JLabel Descrizione = new JLabel("Descrizione");
        Descrizione.setForeground(Color.BLUE);
        Descrizione.setBounds(105, 240, 90, 14);
        AddentryPanel.add(Descrizione);
        

        // a button that add information into the table from the first name, last name, email
        // and you phone number field.
        JButton AddEntrybutton = new JButton("Aggiungi");

        AddEntrybutton.setForeground(Color.GREEN);
        
        AddEntrybutton.addActionListener(new ActionListener() {
            /*
             * This action listener for entry button will prompt
             * you, if you want to add information into the table.
             * It also check if all the mandatory field have been filled correctly
             * so that it can proceed with the adding. If field has a error it will 
             * display a error.
             */

            public void actionPerformed(ActionEvent e) {

            // check if the option field are filled and correct before adding.
                if(NomeRicetta.getText().equalsIgnoreCase("")|| calorie.getText().equalsIgnoreCase("") || tempi.getText().equalsIgnoreCase("") || ingredienti.getText().equalsIgnoreCase("") || descrizione.getText().equalsIgnoreCase("")){
                    JOptionPane.showMessageDialog (null, "Assicurati che i campi obbligatori siano riempiti"); 
                }

                // prompt if you are sure you want to add these information into the table
                else if (JOptionPane.showConfirmDialog(null, "Vuoi aggiungere la ricetta?", "Request", 
                        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
                        == JOptionPane.YES_OPTION)
                    {

                    DefaultTableModel dtm = (DefaultTableModel)table.getModel();

                    dtm.addRow(new Object[] { NomeRicetta.getText(), tempi.getText(), calorie.getText(), ingredienti.getText(), descrizione.getText()});
                    }


            }
        });
        AddEntrybutton.setBounds(175, 300, 89, 23);

        // add the add button to the entry panel 
        AddentryPanel.add(AddEntrybutton);


        // a button the is use for clearing the field in the add entry panel
        JButton ClearButton = new JButton("Resetta");
        ClearButton.setForeground(Color.RED);
        ClearButton.addActionListener(new ActionListener() {
            /*
             *  prompt you if you want to clear the first name,
             *  last name, phone number and email text field.
             *  if you select yes the field will be clear.
             *  if you select no the field will not be clear.
             */

            public void actionPerformed(ActionEvent e) {
                if (JOptionPane.showConfirmDialog(null, "Sei sicuro di voler resettare i campi?", "Request", 
                        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
                        == JOptionPane.YES_OPTION)
                    {
                     NomeRicetta.setText("");
                     tempi.setText("");
                     calorie.setText("");
                     ingredienti.setText("");
                     descrizione.setText("");

                    }
                    else
                    {
                     //Go back to normal
                    }

            }
        });
        ClearButton.setBounds(394, 300, 89, 23);

        // add the clear button the entry panel
        AddentryPanel.add(ClearButton);

        // label tell that field is optional and doesn't need to be filled
        JLabel Mandatorylabel1 = new JLabel("Obbligatorio");
        
        Mandatorylabel1.setForeground(Color.RED);
        Mandatorylabel1.setBounds(493, 200, 90, 14);
        AddentryPanel.add(Mandatorylabel1);

        // label tell that field is optional and doesn't need to be filled
        JLabel Mandatorylabe2 = new JLabel("Obbligatorio");
        
        Mandatorylabe2.setForeground(Color.RED);
        Mandatorylabe2.setBounds(493, 104, 90, 14);
        AddentryPanel.add(Mandatorylabe2);

        // label that tell you that this field has to be filled
        JLabel OptionLabel = new JLabel("Opzionale");

        OptionLabel.setBounds(493, 155, 90, 14);
        AddentryPanel.add(OptionLabel);

        // label that tell you that this field has to be filled
        JLabel Mandatorylabe3 = new JLabel("Obbligatorio");

        Mandatorylabe3.setForeground(Color.RED);
        Mandatorylabe3.setBounds(493, 59, 90, 14);
        AddentryPanel.add(Mandatorylabe3);
        
        JLabel Mandatorylabe4 = new JLabel("Obbligatorio");

        Mandatorylabe4.setForeground(Color.RED);
        Mandatorylabe4.setBounds(493, 245, 90, 14);
        AddentryPanel.add(Mandatorylabe4);
        
        
        
        

        // a menu bar for displaying the option to load contact, save contact, 
        // export contact as excel file and be able to close option
        JMenuBar menuBar = new JMenuBar();
        menuBar.setBounds(0, 0, 650, 21);
        getContentPane().add(menuBar);


        JMenu fileoption = new JMenu("File");

        menuBar.add(fileoption);
        
        JMenuItem savecontact = new JMenuItem("Salva");
        savecontact.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
        System.out.println("Clicked item!");
        if (e.getSource() == savecontact) {
            System.out.println("Save!");
            try {
                fos = new FileOutputStream(filename);
                out = new ObjectOutputStream(fos);
                table.clearSelection();
                model = (DefaultTableModel)table.getModel();
                out.writeObject(model);
                
            } catch (IOException e3) {
                e3.printStackTrace();
            } finally {
                try {
                    out.close();
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        } 
    }
            
        });
        
        
        

        // add a save contact file to menu
        fileoption.add(savecontact);
        


        JMenuItem loadcontact = new JMenuItem("Carica");
        loadcontact.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                
                if (e.getSource() == loadcontact) {
            System.out.println("Open!");
            try {
                fis = new FileInputStream(filename);
                in = new ObjectInputStream(fis);
                DefaultTableModel modelRead = (DefaultTableModel) in.readObject();
                setModel(modelRead);
                System.out.println("data loaded");
                in.close();
                fis.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            } catch (ClassNotFoundException e2) {
                e2.printStackTrace();
            }
        } else if (e.getSource() == close) {
            System.out.println("Exit!");
        }
                
            }
            
        });

        // add load contact file to menu
        fileoption.add(loadcontact);
        

        

        JMenuItem close = new JMenuItem("Chiudi");
        close.addActionListener(new ActionListener() {

         
            public void actionPerformed(ActionEvent arg0) {
                System.exit(0);
            }
        });
        fileoption.add(close);
        table.getColumnModel().getColumn(2).setPreferredWidth(124);       
    }
    
    public void setModel(DefaultTableModel writeModel) {
        table.setModel(writeModel);
    }
    
    
    
    
    

    
    public static void main(String[] args) {
        
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                SalvaT ex = new SalvaT();
                ex.setVisible(true);
            }
        });
    }

    @Override
    public void actionPerformed(ActionEvent ae) {}
        
        
    }

7 Risposte

  • Re: Salvataggio JTable() [RISOLTO]

    Javier ha scritto:


    Salve ragazzi e ben ritrovati

    Come da titolo ho un problema con un salvataggio di una JTable.

    Praticamente inserisco una nuova riga e funziona tutto...però quando voglio salvarla non succede nulla.

    Ecco il codice :
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.text.ParseException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.text.MaskFormatter;
    
    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    
    /**
     *
     * @author Daniele
     */
    public class SalvaT extends JFrame implements ActionListener {
        
        private JTable table;
        private JTextField NomeRicetta;
        private JTextField tempi;
        private JTextField calorie;
        private JTextField ingredienti;
        
        public FileInputStream fis;
        public ObjectInputStream in;
        public FileOutputStream fos;
        public ObjectOutputStream out;
        public JMenuItem savecontact;
        public String filename;
        public DefaultTableModel model;
        public JMenuItem loadcontact;
        public JMenuItem close;
        
        
        public SalvaT() {
            
            fis = null;
            in = null;
            fos = null;
            out = null;
            filename = "test.ref";
            initGui();
            
        }
        
        public void initGui(){
            
            getContentPane().setLayout(null);
            JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
            tabbedPane.setBackground(new Color(189, 183, 107));
            tabbedPane.setBounds(0, 32, 650, 365);
            getContentPane().add(tabbedPane);
            try {
                MaskFormatter mf2 = new MaskFormatter("(###) ###-####");
            } catch (ParseException ex) {
                Logger.getLogger(SalvaT.class.getName()).log(Level.SEVERE, null, ex);
            }
    
            // the main panel that hold the search bar and table
            JPanel MainPanel = new JPanel(); 
            MainPanel.setBackground(Color.LIGHT_GRAY);
            tabbedPane.addTab("Main", null, MainPanel, null);
            MainPanel.setLayout(null);        
    
            JScrollPane scrollPane = new JScrollPane();
            scrollPane.setBounds(10, 42, 604, 195);
            MainPanel.add(scrollPane);
    
            table = new JTable();
            table.setBorder(UIManager.getBorder("DesktopIcon.border"));
            scrollPane.setViewportView(table);
    
            // the column in the table
            table.setModel(new DefaultTableModel(
    
                    new Object[][] {
                },
                new String[] {
                    "Nome Ricetta", "Tempi (min)", "Calorie a persona", "Ingredienti", "Descrizione"
                }
            ));
    
    
            // a panel that hold the first name, last name, phone number and email text field for entering 
            // information into the table on the main panel 
            JPanel AddentryPanel = new JPanel();
            AddentryPanel.setBackground(Color.LIGHT_GRAY);
    
            // add the entry tab for inputting information
            tabbedPane.addTab("Aggiungi Ricetta ", null, AddentryPanel, null); 
            // set absolute layout
            AddentryPanel.setLayout(null);
    
            // a text field for entering you first name
            NomeRicetta = new JTextField();
    
            NomeRicetta.setBounds(175, 49, 308, 34);
    
            // add the first name text field to the add entry panel
            AddentryPanel.add(NomeRicetta);
            NomeRicetta.setColumns(10);
    
            JLabel lblNewLabel = new JLabel("Nome Ricetta:");
            lblNewLabel.setForeground(Color.BLUE);
            lblNewLabel.setBounds(98, 59, 99, 14);
            AddentryPanel.add(lblNewLabel);
    
            JLabel Lastnamelabel = new JLabel("Tempi (min):");
            Lastnamelabel.setForeground(Color.BLUE);
            Lastnamelabel.setBounds(98, 104, 110, 14);
            AddentryPanel.add(Lastnamelabel);
    
            // a text field for entering you last name
            tempi = new JTextField();
            tempi.setColumns(10);
            tempi.setBounds(175, 94, 308, 34);
    
            // add the last name to the entry panel
            AddentryPanel.add(tempi);
    
            // add a formatted text field for you phone number. This field only allow number.
            calorie = new JTextField();
            calorie.setColumns(10);
            calorie.setBounds(175, 145, 308, 34);
    
            // add the formatted text field  to entry panel
            AddentryPanel.add(calorie);
    
            // a text field for entering you email 
            ingredienti = new JTextField();
            ingredienti.setColumns(10);
            ingredienti.setBounds(175, 190, 308, 34);
    
            // add the email text field to the add entry panel
            AddentryPanel.add(ingredienti);
    
            JLabel Phonenumberlabel = new JLabel("Calorie");
            Phonenumberlabel.setForeground(Color.BLUE);
            Phonenumberlabel.setBounds(125, 155, 93, 14);
            AddentryPanel.add(Phonenumberlabel);
    
            JLabel Email = new JLabel("Ingredienti");
            Email.setForeground(Color.BLUE);
            Email.setBounds(110, 200, 80, 14);
            AddentryPanel.add(Email);
    
            // a button that add information into the table from the first name, last name, email
            // and you phone number field.
            JButton AddEntrybutton = new JButton("Aggiungi");
    
            AddEntrybutton.setForeground(Color.GREEN);
            
            AddEntrybutton.addActionListener(new ActionListener() {
                /*
                 * This action listener for entry button will prompt
                 * you, if you want to add information into the table.
                 * It also check if all the mandatory field have been filled correctly
                 * so that it can proceed with the adding. If field has a error it will 
                 * display a error.
                 */
    
                public void actionPerformed(ActionEvent e) {
    
                // check if the option field are filled and correct before adding.
                    if(NomeRicetta.getText().equalsIgnoreCase("")|| calorie.getText().equalsIgnoreCase("") || tempi.getText().equalsIgnoreCase("") || ingredienti.getText().equalsIgnoreCase("")){
                        JOptionPane.showMessageDialog (null, "Assicurati che i campi obbligatori siano riempiti"); 
                    }
    
                    // prompt if you are sure you want to add these information into the table
                    else if (JOptionPane.showConfirmDialog(null, "Vuoi aggiungere la ricetta?", "Request", 
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
                            == JOptionPane.YES_OPTION)
                        {
    
                        DefaultTableModel dtm = (DefaultTableModel)table.getModel();
    
                        dtm.addRow(new Object[] { NomeRicetta.getText(), tempi.getText(), calorie.getText(), ingredienti.getText()});
                        }
    
    
                }
            });
            AddEntrybutton.setBounds(175, 253, 89, 23);
    
            // add the add button to the entry panel 
            AddentryPanel.add(AddEntrybutton);
    
    
            // a button the is use for clearing the field in the add entry panel
            JButton ClearButton = new JButton("Resetta");
            ClearButton.setForeground(Color.RED);
            ClearButton.addActionListener(new ActionListener() {
                /*
                 *  prompt you if you want to clear the first name,
                 *  last name, phone number and email text field.
                 *  if you select yes the field will be clear.
                 *  if you select no the field will not be clear.
                 */
    
                public void actionPerformed(ActionEvent e) {
                    if (JOptionPane.showConfirmDialog(null, "Sei sicuro di voler resettare i campi?", "Request", 
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
                            == JOptionPane.YES_OPTION)
                        {
                         NomeRicetta.setText("");
                         tempi.setText("");
                         calorie.setText("");
                         ingredienti.setText("");
    
    
                        }
                        else
                        {
                         //Go back to normal
                        }
    
                }
            });
            ClearButton.setBounds(394, 253, 89, 23);
    
            // add the clear button the entry panel
            AddentryPanel.add(ClearButton);
    
            // label tell that field is optional and doesn't need to be filled
            JLabel Optionallabel1 = new JLabel("Obbligatorio");
            
            Optionallabel1.setForeground(Color.RED);
            Optionallabel1.setBounds(493, 200, 90, 14);
            AddentryPanel.add(Optionallabel1);
    
            // label tell that field is optional and doesn't need to be filled
            JLabel Optionallabel2 = new JLabel("Obbligatorio");
            
            Optionallabel2.setForeground(Color.RED);
            Optionallabel2.setBounds(493, 104, 90, 14);
            AddentryPanel.add(Optionallabel2);
    
            // label that tell you that this field has to be filled
            JLabel Mandatorylabel1 = new JLabel("Opzionale");
    
            Mandatorylabel1.setBounds(493, 155, 90, 14);
            AddentryPanel.add(Mandatorylabel1);
    
            // label that tell you that this field has to be filled
            JLabel Manatorylabel2 = new JLabel("Obbligatorio");
    
            Manatorylabel2.setForeground(Color.RED);
            Manatorylabel2.setBounds(493, 59, 90, 14);
            AddentryPanel.add(Manatorylabel2);
    
            // a menu bar for displaying the option to load contact, save contact, 
            // export contact as excel file and be able to close option
            JMenuBar menuBar = new JMenuBar();
            menuBar.setBounds(0, 0, 650, 21);
            getContentPane().add(menuBar);
    
    
            JMenu fileoption = new JMenu("File");
    
            menuBar.add(fileoption);
    
    
            JMenuItem loadcontact = new JMenuItem("Carica");
    
            // add load contact file to menu
            fileoption.add(loadcontact);
    
            JMenuItem savecontact = new JMenuItem("Salva");
            
            
            
    
            // add a save contact file to menu
            fileoption.add(savecontact);
    
            JMenuItem close = new JMenuItem("Chiudi");
            close.addActionListener(new ActionListener() {
    
                /*
                 * When selected the program will close.
                 * 
                 */
                public void actionPerformed(ActionEvent arg0) {
                    System.exit(0);
                }
            });
            fileoption.add(close);
            table.getColumnModel().getColumn(2).setPreferredWidth(124);       
        }
        
        public void setModel(DefaultTableModel writeModel) {
            table.setModel(writeModel);
        }
        
        
        public void actionPerformed(ActionEvent e) {
            System.out.println("Clicked item!");
            if (e.getSource() == savecontact) {
                System.out.println("Save!");
                try {
                    fos = new FileOutputStream(filename);
                    out = new ObjectOutputStream(fos);
                    table.clearSelection();
                    table.setModel(new DefaultTableModel());
                    out.writeObject(model);
                    table.setModel(model);
                } catch (IOException e3) {
                    e3.printStackTrace();
                } finally {
                    try {
                        out.close();
                        fos.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            } else if (e.getSource() == loadcontact) {
                System.out.println("Open!");
                try {
                    fis = new FileInputStream(filename);
                    in = new ObjectInputStream(fis);
                    DefaultTableModel modelRead = (DefaultTableModel) in.readObject();
                    setModel(modelRead);
                    System.out.println("data loaded");
                    in.close();
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                } catch (ClassNotFoundException e2) {
                    e2.printStackTrace();
                }
            } else if (e.getSource() == close) {
                System.out.println("Exit!");
            }
        }
        
        
    
        
        public static void main(String[] args) {
            
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    SalvaT ex = new SalvaT();
                    ex.setVisible(true);
                }
            });
        }
            
            
        }

    Come sempre grazie wuajù
    Applica il listener direttamente all' oggetto savecontact, dopodichè esegui il programma e vedrai quali sono gli errori.
    Innanzitutto assegni alla tabella una nuova istanza di un DefaultTableModel che non implementi (ma non ti serve perchè devi salvare la tabella già compilata, se non fosse null sovrascriveresti quello esistente). Quindi questa parte di codice è superflua.
    Dopodichè assegni al metodo writeObject di ObjectOutputStream il parametro model che punta a null perchè non gli hai mai assegnato alcun valore. Infine setti lo stesso model (null per lo stesso motivo di cui sopra) nella tabella (ma il tuo fine è salvare la tabella quindi anche questa parte di codice secondo me è superflua).
    Una soluzione potrebbe essere effettuare un ciclo nella tabella e salvare in un file di testo ciascuna cella (table.getValueAt(i,j)) attraverso un oggetto BufferedWriter.
  • Re: Salvataggio JTable() [RISOLTO]

    Grazie assai ttrash per la risposta.

    Grazie al tuo consiglio non ho più problemi inerenti al salvataggio della tabella...

    Ora ho problemi per il 'caricamento'

    ti ripropongo il codice
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.text.ParseException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.text.MaskFormatter;
    
    
    public class SalvaT extends JFrame implements ActionListener {
        
        private JTable table;
        private JTextField NomeRicetta;
        private JTextField tempi;
        private JTextField calorie;
        private JTextField ingredienti;
        
        public FileInputStream fis;
        public ObjectInputStream in;
        public FileOutputStream fos;
        public ObjectOutputStream out;
        public JMenuItem savecontact;
        public String filename;
        public DefaultTableModel model;
        public JMenuItem loadcontact;
        public JMenuItem close;
        
        
        public SalvaT() {
            
            fis = null;
            in = null;
            fos = null;
            out = null;
            filename = "test.ref";
            initGui();
            
        }
        
        public void initGui(){
            
            getContentPane().setLayout(null);
            JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
            tabbedPane.setBackground(new Color(189, 183, 107));
            tabbedPane.setBounds(0, 32, 650, 365);
            getContentPane().add(tabbedPane);
            try {
                MaskFormatter mf2 = new MaskFormatter("(###) ###-####");
            } catch (ParseException ex) {
                Logger.getLogger(SalvaT.class.getName()).log(Level.SEVERE, null, ex);
            }
    
            // the main panel that hold the search bar and table
            JPanel MainPanel = new JPanel(); 
            MainPanel.setBackground(Color.LIGHT_GRAY);
            tabbedPane.addTab("Main", null, MainPanel, null);
            MainPanel.setLayout(null);        
    
            JScrollPane scrollPane = new JScrollPane();
            scrollPane.setBounds(10, 42, 604, 195);
            MainPanel.add(scrollPane);
    
            table = new JTable();
            table.setBorder(UIManager.getBorder("DesktopIcon.border"));
            scrollPane.setViewportView(table);
    
            // the column in the table
            table.setModel(new DefaultTableModel(
    
                    new Object[][] {
                },
                new String[] {
                    "Nome Ricetta", "Tempi (min)", "Calorie a persona", "Ingredienti", "Descrizione"
                }
            ));
    
    
            // a panel that hold the first name, last name, phone number and email text field for entering 
            // information into the table on the main panel 
            JPanel AddentryPanel = new JPanel();
            AddentryPanel.setBackground(Color.LIGHT_GRAY);
    
            // add the entry tab for inputting information
            tabbedPane.addTab("Aggiungi Ricetta ", null, AddentryPanel, null); 
            // set absolute layout
            AddentryPanel.setLayout(null);
    
            // a text field for entering you first name
            NomeRicetta = new JTextField();
    
            NomeRicetta.setBounds(175, 49, 308, 34);
    
            // add the first name text field to the add entry panel
            AddentryPanel.add(NomeRicetta);
            NomeRicetta.setColumns(10);
    
            JLabel lblNewLabel = new JLabel("Nome Ricetta:");
            lblNewLabel.setForeground(Color.BLUE);
            lblNewLabel.setBounds(98, 59, 99, 14);
            AddentryPanel.add(lblNewLabel);
    
            JLabel Lastnamelabel = new JLabel("Tempi (min):");
            Lastnamelabel.setForeground(Color.BLUE);
            Lastnamelabel.setBounds(98, 104, 110, 14);
            AddentryPanel.add(Lastnamelabel);
    
            // a text field for entering you last name
            tempi = new JTextField();
            tempi.setColumns(10);
            tempi.setBounds(175, 94, 308, 34);
    
            // add the last name to the entry panel
            AddentryPanel.add(tempi);
    
            // add a formatted text field for you phone number. This field only allow number.
            calorie = new JTextField();
            calorie.setColumns(10);
            calorie.setBounds(175, 145, 308, 34);
    
            // add the formatted text field  to entry panel
            AddentryPanel.add(calorie);
    
            // a text field for entering you email 
            ingredienti = new JTextField();
            ingredienti.setColumns(10);
            ingredienti.setBounds(175, 190, 308, 34);
    
            // add the email text field to the add entry panel
            AddentryPanel.add(ingredienti);
    
            JLabel Phonenumberlabel = new JLabel("Calorie");
            Phonenumberlabel.setForeground(Color.BLUE);
            Phonenumberlabel.setBounds(125, 155, 93, 14);
            AddentryPanel.add(Phonenumberlabel);
    
            JLabel Email = new JLabel("Ingredienti");
            Email.setForeground(Color.BLUE);
            Email.setBounds(110, 200, 80, 14);
            AddentryPanel.add(Email);
    
            // a button that add information into the table from the first name, last name, email
            // and you phone number field.
            JButton AddEntrybutton = new JButton("Aggiungi");
    
            AddEntrybutton.setForeground(Color.GREEN);
            
            AddEntrybutton.addActionListener(new ActionListener() {
                /*
                 * This action listener for entry button will prompt
                 * you, if you want to add information into the table.
                 * It also check if all the mandatory field have been filled correctly
                 * so that it can proceed with the adding. If field has a error it will 
                 * display a error.
                 */
    
                public void actionPerformed(ActionEvent e) {
    
                // check if the option field are filled and correct before adding.
                    if(NomeRicetta.getText().equalsIgnoreCase("")|| calorie.getText().equalsIgnoreCase("") || tempi.getText().equalsIgnoreCase("") || ingredienti.getText().equalsIgnoreCase("")){
                        JOptionPane.showMessageDialog (null, "Assicurati che i campi obbligatori siano riempiti"); 
                    }
    
                    // prompt if you are sure you want to add these information into the table
                    else if (JOptionPane.showConfirmDialog(null, "Vuoi aggiungere la ricetta?", "Request", 
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
                            == JOptionPane.YES_OPTION)
                        {
    
                        DefaultTableModel dtm = (DefaultTableModel)table.getModel();
    
                        dtm.addRow(new Object[] { NomeRicetta.getText(), tempi.getText(), calorie.getText(), ingredienti.getText()});
                        }
    
    
                }
            });
            AddEntrybutton.setBounds(175, 253, 89, 23);
    
            // add the add button to the entry panel 
            AddentryPanel.add(AddEntrybutton);
    
    
            // a button the is use for clearing the field in the add entry panel
            JButton ClearButton = new JButton("Resetta");
            ClearButton.setForeground(Color.RED);
            ClearButton.addActionListener(new ActionListener() {
                /*
                 *  prompt you if you want to clear the first name,
                 *  last name, phone number and email text field.
                 *  if you select yes the field will be clear.
                 *  if you select no the field will not be clear.
                 */
    
                public void actionPerformed(ActionEvent e) {
                    if (JOptionPane.showConfirmDialog(null, "Sei sicuro di voler resettare i campi?", "Request", 
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
                            == JOptionPane.YES_OPTION)
                        {
                         NomeRicetta.setText("");
                         tempi.setText("");
                         calorie.setText("");
                         ingredienti.setText("");
    
    
                        }
                        else
                        {
                         //Go back to normal
                        }
    
                }
            });
            ClearButton.setBounds(394, 253, 89, 23);
    
            // add the clear button the entry panel
            AddentryPanel.add(ClearButton);
    
            // label tell that field is optional and doesn't need to be filled
            JLabel Optionallabel1 = new JLabel("Obbligatorio");
            
            Optionallabel1.setForeground(Color.RED);
            Optionallabel1.setBounds(493, 200, 90, 14);
            AddentryPanel.add(Optionallabel1);
    
            // label tell that field is optional and doesn't need to be filled
            JLabel Optionallabel2 = new JLabel("Obbligatorio");
            
            Optionallabel2.setForeground(Color.RED);
            Optionallabel2.setBounds(493, 104, 90, 14);
            AddentryPanel.add(Optionallabel2);
    
            // label that tell you that this field has to be filled
            JLabel Mandatorylabel1 = new JLabel("Opzionale");
    
            Mandatorylabel1.setBounds(493, 155, 90, 14);
            AddentryPanel.add(Mandatorylabel1);
    
            // label that tell you that this field has to be filled
            JLabel Manatorylabel2 = new JLabel("Obbligatorio");
    
            Manatorylabel2.setForeground(Color.RED);
            Manatorylabel2.setBounds(493, 59, 90, 14);
            AddentryPanel.add(Manatorylabel2);
    
            // a menu bar for displaying the option to load contact, save contact, 
            // export contact as excel file and be able to close option
            JMenuBar menuBar = new JMenuBar();
            menuBar.setBounds(0, 0, 650, 21);
            getContentPane().add(menuBar);
    
    
            JMenu fileoption = new JMenu("File");
    
            menuBar.add(fileoption);
    
    
            JMenuItem loadcontact = new JMenuItem("Carica");
            loadcontact.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    
                    if (e.getSource() == loadcontact) {
                System.out.println("Open!");
                try {
                    fis = new FileInputStream(filename);
                    in = new ObjectInputStream(fis);
                    DefaultTableModel modelRead = (DefaultTableModel) in.readObject();
                    setModel(modelRead);
                    System.out.println("data loaded");
                    in.close();
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                } catch (ClassNotFoundException e2) {
                    e2.printStackTrace();
                }
            } else if (e.getSource() == close) {
                System.out.println("Exit!");
            }
                    
                }
                
            });
    
            // add load contact file to menu
            fileoption.add(loadcontact);
    
            JMenuItem savecontact = new JMenuItem("Salva");
            savecontact.addActionListener(new ActionListener() {
                
                public void actionPerformed(ActionEvent e) {
            System.out.println("Clicked item!");
            if (e.getSource() == savecontact) {
                System.out.println("Save!");
                try {
                    fos = new FileOutputStream(filename);
                    out = new ObjectOutputStream(fos);
                    table.clearSelection();
                    out.writeObject(model);
                    
                } catch (IOException e3) {
                    e3.printStackTrace();
                } finally {
                    try {
                        out.close();
                        fos.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            } 
        }
                
            });
            
            
            
    
            // add a save contact file to menu
            fileoption.add(savecontact);
    
            JMenuItem close = new JMenuItem("Chiudi");
            close.addActionListener(new ActionListener() {
    
             
                public void actionPerformed(ActionEvent arg0) {
                    System.exit(0);
                }
            });
            fileoption.add(close);
            table.getColumnModel().getColumn(2).setPreferredWidth(124);       
        }
        
        public void setModel(DefaultTableModel writeModel) {
            table.setModel(writeModel);
        }
        
        
        
        
        
    
        
        public static void main(String[] args) {
            
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    SalvaT ex = new SalvaT();
                    ex.setVisible(true);
                }
            });
        }
    
        @Override
        public void actionPerformed(ActionEvent ae) {}
            
            
        }
    l'errore è questo :
    Open!
    Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Cannot set a null TableModel
    	at javax.swing.JTable.setModel(JTable.java:3678)
    	at SalvaT.setModel(SalvaT.java:355)
    	at SalvaT$3.actionPerformed(SalvaT.java:288)
    	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
    	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    	at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
    	at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
    	at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)
    	at java.awt.Component.processMouseEvent(Component.java:6525)
    	at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    	at java.awt.Component.processEvent(Component.java:6290)
    	at java.awt.Container.processEvent(Container.java:2234)
    	at java.awt.Component.dispatchEventImpl(Component.java:4881)
    	at java.awt.Container.dispatchEventImpl(Container.java:2292)
    	at java.awt.Component.dispatchEvent(Component.java:4703)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
    	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    	at java.awt.Container.dispatchEventImpl(Container.java:2278)
    	at java.awt.Window.dispatchEventImpl(Window.java:2739)
    	at java.awt.Component.dispatchEvent(Component.java:4703)
    	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
    	at java.awt.EventQueue.access$400(EventQueue.java:97)
    	at java.awt.EventQueue$3.run(EventQueue.java:697)
    	at java.awt.EventQueue$3.run(EventQueue.java:691)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    	at java.awt.EventQueue$4.run(EventQueue.java:719)
    	at java.awt.EventQueue$4.run(EventQueue.java:717)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    	at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    	at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

    grazie ancora
  • Re: Salvataggio JTable() [RISOLTO]

    Javier ha scritto:


    Grazie assai ttrash per la risposta.

    Grazie al tuo consiglio non ho più problemi inerenti al salvataggio della tabella...

    Ora ho problemi per il 'caricamento'

    ti ripropongo il codice
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.text.ParseException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.text.MaskFormatter;
    
    
    public class SalvaT extends JFrame implements ActionListener {
        
        private JTable table;
        private JTextField NomeRicetta;
        private JTextField tempi;
        private JTextField calorie;
        private JTextField ingredienti;
        
        public FileInputStream fis;
        public ObjectInputStream in;
        public FileOutputStream fos;
        public ObjectOutputStream out;
        public JMenuItem savecontact;
        public String filename;
        public DefaultTableModel model;
        public JMenuItem loadcontact;
        public JMenuItem close;
        
        
        public SalvaT() {
            
            fis = null;
            in = null;
            fos = null;
            out = null;
            filename = "test.ref";
            initGui();
            
        }
        
        public void initGui(){
            
            getContentPane().setLayout(null);
            JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
            tabbedPane.setBackground(new Color(189, 183, 107));
            tabbedPane.setBounds(0, 32, 650, 365);
            getContentPane().add(tabbedPane);
            try {
                MaskFormatter mf2 = new MaskFormatter("(###) ###-####");
            } catch (ParseException ex) {
                Logger.getLogger(SalvaT.class.getName()).log(Level.SEVERE, null, ex);
            }
    
            // the main panel that hold the search bar and table
            JPanel MainPanel = new JPanel(); 
            MainPanel.setBackground(Color.LIGHT_GRAY);
            tabbedPane.addTab("Main", null, MainPanel, null);
            MainPanel.setLayout(null);        
    
            JScrollPane scrollPane = new JScrollPane();
            scrollPane.setBounds(10, 42, 604, 195);
            MainPanel.add(scrollPane);
    
            table = new JTable();
            table.setBorder(UIManager.getBorder("DesktopIcon.border"));
            scrollPane.setViewportView(table);
    
            // the column in the table
            table.setModel(new DefaultTableModel(
    
                    new Object[][] {
                },
                new String[] {
                    "Nome Ricetta", "Tempi (min)", "Calorie a persona", "Ingredienti", "Descrizione"
                }
            ));
    
    
            // a panel that hold the first name, last name, phone number and email text field for entering 
            // information into the table on the main panel 
            JPanel AddentryPanel = new JPanel();
            AddentryPanel.setBackground(Color.LIGHT_GRAY);
    
            // add the entry tab for inputting information
            tabbedPane.addTab("Aggiungi Ricetta ", null, AddentryPanel, null); 
            // set absolute layout
            AddentryPanel.setLayout(null);
    
            // a text field for entering you first name
            NomeRicetta = new JTextField();
    
            NomeRicetta.setBounds(175, 49, 308, 34);
    
            // add the first name text field to the add entry panel
            AddentryPanel.add(NomeRicetta);
            NomeRicetta.setColumns(10);
    
            JLabel lblNewLabel = new JLabel("Nome Ricetta:");
            lblNewLabel.setForeground(Color.BLUE);
            lblNewLabel.setBounds(98, 59, 99, 14);
            AddentryPanel.add(lblNewLabel);
    
            JLabel Lastnamelabel = new JLabel("Tempi (min):");
            Lastnamelabel.setForeground(Color.BLUE);
            Lastnamelabel.setBounds(98, 104, 110, 14);
            AddentryPanel.add(Lastnamelabel);
    
            // a text field for entering you last name
            tempi = new JTextField();
            tempi.setColumns(10);
            tempi.setBounds(175, 94, 308, 34);
    
            // add the last name to the entry panel
            AddentryPanel.add(tempi);
    
            // add a formatted text field for you phone number. This field only allow number.
            calorie = new JTextField();
            calorie.setColumns(10);
            calorie.setBounds(175, 145, 308, 34);
    
            // add the formatted text field  to entry panel
            AddentryPanel.add(calorie);
    
            // a text field for entering you email 
            ingredienti = new JTextField();
            ingredienti.setColumns(10);
            ingredienti.setBounds(175, 190, 308, 34);
    
            // add the email text field to the add entry panel
            AddentryPanel.add(ingredienti);
    
            JLabel Phonenumberlabel = new JLabel("Calorie");
            Phonenumberlabel.setForeground(Color.BLUE);
            Phonenumberlabel.setBounds(125, 155, 93, 14);
            AddentryPanel.add(Phonenumberlabel);
    
            JLabel Email = new JLabel("Ingredienti");
            Email.setForeground(Color.BLUE);
            Email.setBounds(110, 200, 80, 14);
            AddentryPanel.add(Email);
    
            // a button that add information into the table from the first name, last name, email
            // and you phone number field.
            JButton AddEntrybutton = new JButton("Aggiungi");
    
            AddEntrybutton.setForeground(Color.GREEN);
            
            AddEntrybutton.addActionListener(new ActionListener() {
                /*
                 * This action listener for entry button will prompt
                 * you, if you want to add information into the table.
                 * It also check if all the mandatory field have been filled correctly
                 * so that it can proceed with the adding. If field has a error it will 
                 * display a error.
                 */
    
                public void actionPerformed(ActionEvent e) {
    
                // check if the option field are filled and correct before adding.
                    if(NomeRicetta.getText().equalsIgnoreCase("")|| calorie.getText().equalsIgnoreCase("") || tempi.getText().equalsIgnoreCase("") || ingredienti.getText().equalsIgnoreCase("")){
                        JOptionPane.showMessageDialog (null, "Assicurati che i campi obbligatori siano riempiti"); 
                    }
    
                    // prompt if you are sure you want to add these information into the table
                    else if (JOptionPane.showConfirmDialog(null, "Vuoi aggiungere la ricetta?", "Request", 
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
                            == JOptionPane.YES_OPTION)
                        {
    
                        DefaultTableModel dtm = (DefaultTableModel)table.getModel();
    
                        dtm.addRow(new Object[] { NomeRicetta.getText(), tempi.getText(), calorie.getText(), ingredienti.getText()});
                        }
    
    
                }
            });
            AddEntrybutton.setBounds(175, 253, 89, 23);
    
            // add the add button to the entry panel 
            AddentryPanel.add(AddEntrybutton);
    
    
            // a button the is use for clearing the field in the add entry panel
            JButton ClearButton = new JButton("Resetta");
            ClearButton.setForeground(Color.RED);
            ClearButton.addActionListener(new ActionListener() {
                /*
                 *  prompt you if you want to clear the first name,
                 *  last name, phone number and email text field.
                 *  if you select yes the field will be clear.
                 *  if you select no the field will not be clear.
                 */
    
                public void actionPerformed(ActionEvent e) {
                    if (JOptionPane.showConfirmDialog(null, "Sei sicuro di voler resettare i campi?", "Request", 
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
                            == JOptionPane.YES_OPTION)
                        {
                         NomeRicetta.setText("");
                         tempi.setText("");
                         calorie.setText("");
                         ingredienti.setText("");
    
    
                        }
                        else
                        {
                         //Go back to normal
                        }
    
                }
            });
            ClearButton.setBounds(394, 253, 89, 23);
    
            // add the clear button the entry panel
            AddentryPanel.add(ClearButton);
    
            // label tell that field is optional and doesn't need to be filled
            JLabel Optionallabel1 = new JLabel("Obbligatorio");
            
            Optionallabel1.setForeground(Color.RED);
            Optionallabel1.setBounds(493, 200, 90, 14);
            AddentryPanel.add(Optionallabel1);
    
            // label tell that field is optional and doesn't need to be filled
            JLabel Optionallabel2 = new JLabel("Obbligatorio");
            
            Optionallabel2.setForeground(Color.RED);
            Optionallabel2.setBounds(493, 104, 90, 14);
            AddentryPanel.add(Optionallabel2);
    
            // label that tell you that this field has to be filled
            JLabel Mandatorylabel1 = new JLabel("Opzionale");
    
            Mandatorylabel1.setBounds(493, 155, 90, 14);
            AddentryPanel.add(Mandatorylabel1);
    
            // label that tell you that this field has to be filled
            JLabel Manatorylabel2 = new JLabel("Obbligatorio");
    
            Manatorylabel2.setForeground(Color.RED);
            Manatorylabel2.setBounds(493, 59, 90, 14);
            AddentryPanel.add(Manatorylabel2);
    
            // a menu bar for displaying the option to load contact, save contact, 
            // export contact as excel file and be able to close option
            JMenuBar menuBar = new JMenuBar();
            menuBar.setBounds(0, 0, 650, 21);
            getContentPane().add(menuBar);
    
    
            JMenu fileoption = new JMenu("File");
    
            menuBar.add(fileoption);
    
    
            JMenuItem loadcontact = new JMenuItem("Carica");
            loadcontact.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    
                    if (e.getSource() == loadcontact) {
                System.out.println("Open!");
                try {
                    fis = new FileInputStream(filename);
                    in = new ObjectInputStream(fis);
                    DefaultTableModel modelRead = (DefaultTableModel) in.readObject();
                    setModel(modelRead);
                    System.out.println("data loaded");
                    in.close();
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                } catch (ClassNotFoundException e2) {
                    e2.printStackTrace();
                }
            } else if (e.getSource() == close) {
                System.out.println("Exit!");
            }
                    
                }
                
            });
    
            // add load contact file to menu
            fileoption.add(loadcontact);
    
            JMenuItem savecontact = new JMenuItem("Salva");
            savecontact.addActionListener(new ActionListener() {
                
                public void actionPerformed(ActionEvent e) {
            System.out.println("Clicked item!");
            if (e.getSource() == savecontact) {
                System.out.println("Save!");
                try {
                    fos = new FileOutputStream(filename);
                    out = new ObjectOutputStream(fos);
                    table.clearSelection();
                    out.writeObject(model);
                    
                } catch (IOException e3) {
                    e3.printStackTrace();
                } finally {
                    try {
                        out.close();
                        fos.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            } 
        }
                
            });
            
            
            
    
            // add a save contact file to menu
            fileoption.add(savecontact);
    
            JMenuItem close = new JMenuItem("Chiudi");
            close.addActionListener(new ActionListener() {
    
             
                public void actionPerformed(ActionEvent arg0) {
                    System.exit(0);
                }
            });
            fileoption.add(close);
            table.getColumnModel().getColumn(2).setPreferredWidth(124);       
        }
        
        public void setModel(DefaultTableModel writeModel) {
            table.setModel(writeModel);
        }
        
        
        
        
        
    
        
        public static void main(String[] args) {
            
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    SalvaT ex = new SalvaT();
                    ex.setVisible(true);
                }
            });
        }
    
        @Override
        public void actionPerformed(ActionEvent ae) {}
            
            
        }
    l'errore è questo :
    Open!
    Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Cannot set a null TableModel
    	at javax.swing.JTable.setModel(JTable.java:3678)
    	at SalvaT.setModel(SalvaT.java:355)
    	at SalvaT$3.actionPerformed(SalvaT.java:288)
    	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
    	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    	at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
    	at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
    	at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)
    	at java.awt.Component.processMouseEvent(Component.java:6525)
    	at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    	at java.awt.Component.processEvent(Component.java:6290)
    	at java.awt.Container.processEvent(Container.java:2234)
    	at java.awt.Component.dispatchEventImpl(Component.java:4881)
    	at java.awt.Container.dispatchEventImpl(Container.java:2292)
    	at java.awt.Component.dispatchEvent(Component.java:4703)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
    	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    	at java.awt.Container.dispatchEventImpl(Container.java:2278)
    	at java.awt.Window.dispatchEventImpl(Window.java:2739)
    	at java.awt.Component.dispatchEvent(Component.java:4703)
    	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
    	at java.awt.EventQueue.access$400(EventQueue.java:97)
    	at java.awt.EventQueue$3.run(EventQueue.java:697)
    	at java.awt.EventQueue$3.run(EventQueue.java:691)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    	at java.awt.EventQueue$4.run(EventQueue.java:719)
    	at java.awt.EventQueue$4.run(EventQueue.java:717)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    	at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    	at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

    grazie ancora
    Il motivo è sempre lo stesso. Crei un riferimento a DefaultTableModel (lo chiami model) e senza inizializzarlo lo assegni come modello alla tabella. Il riferimento è ovviamente null.
    Prima della riga: out.writeObject(model);
    prova ad assegnare a model il valore (DefaultTableModel)table.getModel(); e vedrai che non avrai più quell' errore
  • Re: Salvataggio JTable() [RISOLTO]

    Ttrash mi riporta sempre un errore alla riga :
    public void setModel(DefaultTableModel writeModel) {
            table.setModel(writeModel);
        }

    anche se faccio come tu mi hai suggerito, l'esito non cambia
  • Re: Salvataggio JTable() [RISOLTO]

    Javier ha scritto:


    ttrash mi riporta sempre un errore alla riga :
    public void setModel(DefaultTableModel writeModel) {
            table.setModel(writeModel);
        }

    anche se faccio come tu mi hai suggerito, l'esito non cambia
    Hai salvato prima la tabella?? Se prima non la salvi con la modalità corretta quel model è sempre null
  • Re: Salvataggio JTable() [RISOLTO]

    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.text.ParseException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.text.MaskFormatter;
    
    
    public class SalvaT extends JFrame implements ActionListener {
        
        private JTable table;
        private JTextField NomeRicetta;
        private JTextField tempi;
        private JTextField calorie;
        private JTextField ingredienti;
        
        public FileInputStream fis;
        public ObjectInputStream in;
        public FileOutputStream fos;
        public ObjectOutputStream out;
        public JMenuItem savecontact;
        public String filename;
        public DefaultTableModel model;
        public JMenuItem loadcontact;
        public JMenuItem close;
        
        
        public SalvaT() {
            
            fis = null;
            in = null;
            fos = null;
            out = null;
            filename = "test.ref";
            initGui();
            
        }
        
        public void initGui(){
            
            getContentPane().setLayout(null);
            JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
            tabbedPane.setBackground(new Color(189, 183, 107));
            tabbedPane.setBounds(0, 32, 650, 365);
            getContentPane().add(tabbedPane);
            try {
                MaskFormatter mf2 = new MaskFormatter("(###) ###-####");
            } catch (ParseException ex) {
                Logger.getLogger(SalvaT.class.getName()).log(Level.SEVERE, null, ex);
            }
    
            // the main panel that hold the search bar and table
            JPanel MainPanel = new JPanel(); 
            MainPanel.setBackground(Color.LIGHT_GRAY);
            tabbedPane.addTab("Main", null, MainPanel, null);
            MainPanel.setLayout(null);        
    
            JScrollPane scrollPane = new JScrollPane();
            scrollPane.setBounds(10, 42, 604, 195);
            MainPanel.add(scrollPane);
    
            table = new JTable();
            table.setBorder(UIManager.getBorder("DesktopIcon.border"));
            scrollPane.setViewportView(table);
    
            // the column in the table
            table.setModel(new DefaultTableModel(
    
                    new Object[][] {
                },
                new String[] {
                    "Nome Ricetta", "Tempi (min)", "Calorie a persona", "Ingredienti", "Descrizione"
                }
            ));
    
    
            // a panel that hold the first name, last name, phone number and email text field for entering 
            // information into the table on the main panel 
            JPanel AddentryPanel = new JPanel();
            AddentryPanel.setBackground(Color.LIGHT_GRAY);
    
            // add the entry tab for inputting information
            tabbedPane.addTab("Aggiungi Ricetta ", null, AddentryPanel, null); 
            // set absolute layout
            AddentryPanel.setLayout(null);
    
            // a text field for entering you first name
            NomeRicetta = new JTextField();
    
            NomeRicetta.setBounds(175, 49, 308, 34);
    
            // add the first name text field to the add entry panel
            AddentryPanel.add(NomeRicetta);
            NomeRicetta.setColumns(10);
    
            JLabel lblNewLabel = new JLabel("Nome Ricetta:");
            lblNewLabel.setForeground(Color.BLUE);
            lblNewLabel.setBounds(98, 59, 99, 14);
            AddentryPanel.add(lblNewLabel);
    
            JLabel Lastnamelabel = new JLabel("Tempi (min):");
            Lastnamelabel.setForeground(Color.BLUE);
            Lastnamelabel.setBounds(98, 104, 110, 14);
            AddentryPanel.add(Lastnamelabel);
    
            // a text field for entering you last name
            tempi = new JTextField();
            tempi.setColumns(10);
            tempi.setBounds(175, 94, 308, 34);
    
            // add the last name to the entry panel
            AddentryPanel.add(tempi);
    
            // add a formatted text field for you phone number. This field only allow number.
            calorie = new JTextField();
            calorie.setColumns(10);
            calorie.setBounds(175, 145, 308, 34);
    
            // add the formatted text field  to entry panel
            AddentryPanel.add(calorie);
    
            // a text field for entering you email 
            ingredienti = new JTextField();
            ingredienti.setColumns(10);
            ingredienti.setBounds(175, 190, 308, 34);
    
            // add the email text field to the add entry panel
            AddentryPanel.add(ingredienti);
    
            JLabel Phonenumberlabel = new JLabel("Calorie");
            Phonenumberlabel.setForeground(Color.BLUE);
            Phonenumberlabel.setBounds(125, 155, 93, 14);
            AddentryPanel.add(Phonenumberlabel);
    
            JLabel Email = new JLabel("Ingredienti");
            Email.setForeground(Color.BLUE);
            Email.setBounds(110, 200, 80, 14);
            AddentryPanel.add(Email);
    
            // a button that add information into the table from the first name, last name, email
            // and you phone number field.
            JButton AddEntrybutton = new JButton("Aggiungi");
    
            AddEntrybutton.setForeground(Color.GREEN);
            
            AddEntrybutton.addActionListener(new ActionListener() {
                /*
                 * This action listener for entry button will prompt
                 * you, if you want to add information into the table.
                 * It also check if all the mandatory field have been filled correctly
                 * so that it can proceed with the adding. If field has a error it will 
                 * display a error.
                 */
    
                public void actionPerformed(ActionEvent e) {
    
                // check if the option field are filled and correct before adding.
                    if(NomeRicetta.getText().equalsIgnoreCase("")|| calorie.getText().equalsIgnoreCase("") || tempi.getText().equalsIgnoreCase("") || ingredienti.getText().equalsIgnoreCase("")){
                        JOptionPane.showMessageDialog (null, "Assicurati che i campi obbligatori siano riempiti"); 
                    }
    
                    // prompt if you are sure you want to add these information into the table
                    else if (JOptionPane.showConfirmDialog(null, "Vuoi aggiungere la ricetta?", "Request", 
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
                            == JOptionPane.YES_OPTION)
                        {
    
                        DefaultTableModel dtm = (DefaultTableModel)table.getModel();
    
                        dtm.addRow(new Object[] { NomeRicetta.getText(), tempi.getText(), calorie.getText(), ingredienti.getText()});
                        }
    
    
                }
            });
            AddEntrybutton.setBounds(175, 253, 89, 23);
    
            // add the add button to the entry panel 
            AddentryPanel.add(AddEntrybutton);
    
    
            // a button the is use for clearing the field in the add entry panel
            JButton ClearButton = new JButton("Resetta");
            ClearButton.setForeground(Color.RED);
            ClearButton.addActionListener(new ActionListener() {
                /*
                 *  prompt you if you want to clear the first name,
                 *  last name, phone number and email text field.
                 *  if you select yes the field will be clear.
                 *  if you select no the field will not be clear.
                 */
    
                public void actionPerformed(ActionEvent e) {
                    if (JOptionPane.showConfirmDialog(null, "Sei sicuro di voler resettare i campi?", "Request", 
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
                            == JOptionPane.YES_OPTION)
                        {
                         NomeRicetta.setText("");
                         tempi.setText("");
                         calorie.setText("");
                         ingredienti.setText("");
    
    
                        }
                        else
                        {
                         //Go back to normal
                        }
    
                }
            });
            ClearButton.setBounds(394, 253, 89, 23);
    
            // add the clear button the entry panel
            AddentryPanel.add(ClearButton);
    
            // label tell that field is optional and doesn't need to be filled
            JLabel Optionallabel1 = new JLabel("Obbligatorio");
            
            Optionallabel1.setForeground(Color.RED);
            Optionallabel1.setBounds(493, 200, 90, 14);
            AddentryPanel.add(Optionallabel1);
    
            // label tell that field is optional and doesn't need to be filled
            JLabel Optionallabel2 = new JLabel("Obbligatorio");
            
            Optionallabel2.setForeground(Color.RED);
            Optionallabel2.setBounds(493, 104, 90, 14);
            AddentryPanel.add(Optionallabel2);
    
            // label that tell you that this field has to be filled
            JLabel Mandatorylabel1 = new JLabel("Opzionale");
    
            Mandatorylabel1.setBounds(493, 155, 90, 14);
            AddentryPanel.add(Mandatorylabel1);
    
            // label that tell you that this field has to be filled
            JLabel Manatorylabel2 = new JLabel("Obbligatorio");
    
            Manatorylabel2.setForeground(Color.RED);
            Manatorylabel2.setBounds(493, 59, 90, 14);
            AddentryPanel.add(Manatorylabel2);
    
            // a menu bar for displaying the option to load contact, save contact, 
            // export contact as excel file and be able to close option
            JMenuBar menuBar = new JMenuBar();
            menuBar.setBounds(0, 0, 650, 21);
            getContentPane().add(menuBar);
    
    
            JMenu fileoption = new JMenu("File");
    
            menuBar.add(fileoption);
            
            JMenuItem savecontact = new JMenuItem("Salva");
            savecontact.addActionListener(new ActionListener() {
                
                public void actionPerformed(ActionEvent e) {
            System.out.println("Clicked item!");
            if (e.getSource() == savecontact) {
                System.out.println("Save!");
                try {
                    fos = new FileOutputStream(filename);
                    out = new ObjectOutputStream(fos);
                    table.clearSelection();
                    out.writeObject(model);
                    
                } catch (IOException e3) {
                    e3.printStackTrace();
                } finally {
                    try {
                        out.close();
                        fos.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            } 
        }
                
            });
            
            
            
    
            // add a save contact file to menu
            fileoption.add(savecontact);
            
    
    
            JMenuItem loadcontact = new JMenuItem("Carica");
            loadcontact.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    
                    if (e.getSource() == loadcontact) {
                System.out.println("Open!");
                try {
                    table.getModel();
                    fis = new FileInputStream(filename);
                    in = new ObjectInputStream(fis);
                    DefaultTableModel modelRead = (DefaultTableModel) in.readObject();
                    setModel(modelRead);
                    System.out.println("data loaded");
                    in.close();
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                } catch (ClassNotFoundException e2) {
                    e2.printStackTrace();
                }
            } else if (e.getSource() == close) {
                System.out.println("Exit!");
            }
                    
                }
                
            });
    
            // add load contact file to menu
            fileoption.add(loadcontact);
            
    
            
    
            JMenuItem close = new JMenuItem("Chiudi");
            close.addActionListener(new ActionListener() {
    
             
                public void actionPerformed(ActionEvent arg0) {
                    System.exit(0);
                }
            });
            fileoption.add(close);
            table.getColumnModel().getColumn(2).setPreferredWidth(124);       
        }
        
        public void setModel(DefaultTableModel writeModel) {
            table.setModel(writeModel);
        }
        
        
        
        
        
    
        
        public static void main(String[] args) {
            
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    SalvaT ex = new SalvaT();
                    ex.setVisible(true);
                }
            });
        }
    
        @Override
        public void actionPerformed(ActionEvent ae) {}
            
            
        }

    questo è file modificato...ho salvato la tabella...chiudo il programma...lo riavvio e quando clicco su carica i da sempre quell'errore...
  • Re: Salvataggio JTable() [RISOLTO]

    Javier ha scritto:


    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.text.ParseException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.text.MaskFormatter;
    
    
    public class SalvaT extends JFrame implements ActionListener {
        
        private JTable table;
        private JTextField NomeRicetta;
        private JTextField tempi;
        private JTextField calorie;
        private JTextField ingredienti;
        
        public FileInputStream fis;
        public ObjectInputStream in;
        public FileOutputStream fos;
        public ObjectOutputStream out;
        public JMenuItem savecontact;
        public String filename;
        public DefaultTableModel model;
        public JMenuItem loadcontact;
        public JMenuItem close;
        
        
        public SalvaT() {
            
            fis = null;
            in = null;
            fos = null;
            out = null;
            filename = "test.ref";
            initGui();
            
        }
        
        public void initGui(){
            
            getContentPane().setLayout(null);
            JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
            tabbedPane.setBackground(new Color(189, 183, 107));
            tabbedPane.setBounds(0, 32, 650, 365);
            getContentPane().add(tabbedPane);
            try {
                MaskFormatter mf2 = new MaskFormatter("(###) ###-####");
            } catch (ParseException ex) {
                Logger.getLogger(SalvaT.class.getName()).log(Level.SEVERE, null, ex);
            }
    
            // the main panel that hold the search bar and table
            JPanel MainPanel = new JPanel(); 
            MainPanel.setBackground(Color.LIGHT_GRAY);
            tabbedPane.addTab("Main", null, MainPanel, null);
            MainPanel.setLayout(null);        
    
            JScrollPane scrollPane = new JScrollPane();
            scrollPane.setBounds(10, 42, 604, 195);
            MainPanel.add(scrollPane);
    
            table = new JTable();
            table.setBorder(UIManager.getBorder("DesktopIcon.border"));
            scrollPane.setViewportView(table);
    
            // the column in the table
            table.setModel(new DefaultTableModel(
    
                    new Object[][] {
                },
                new String[] {
                    "Nome Ricetta", "Tempi (min)", "Calorie a persona", "Ingredienti", "Descrizione"
                }
            ));
    
    
            // a panel that hold the first name, last name, phone number and email text field for entering 
            // information into the table on the main panel 
            JPanel AddentryPanel = new JPanel();
            AddentryPanel.setBackground(Color.LIGHT_GRAY);
    
            // add the entry tab for inputting information
            tabbedPane.addTab("Aggiungi Ricetta ", null, AddentryPanel, null); 
            // set absolute layout
            AddentryPanel.setLayout(null);
    
            // a text field for entering you first name
            NomeRicetta = new JTextField();
    
            NomeRicetta.setBounds(175, 49, 308, 34);
    
            // add the first name text field to the add entry panel
            AddentryPanel.add(NomeRicetta);
            NomeRicetta.setColumns(10);
    
            JLabel lblNewLabel = new JLabel("Nome Ricetta:");
            lblNewLabel.setForeground(Color.BLUE);
            lblNewLabel.setBounds(98, 59, 99, 14);
            AddentryPanel.add(lblNewLabel);
    
            JLabel Lastnamelabel = new JLabel("Tempi (min):");
            Lastnamelabel.setForeground(Color.BLUE);
            Lastnamelabel.setBounds(98, 104, 110, 14);
            AddentryPanel.add(Lastnamelabel);
    
            // a text field for entering you last name
            tempi = new JTextField();
            tempi.setColumns(10);
            tempi.setBounds(175, 94, 308, 34);
    
            // add the last name to the entry panel
            AddentryPanel.add(tempi);
    
            // add a formatted text field for you phone number. This field only allow number.
            calorie = new JTextField();
            calorie.setColumns(10);
            calorie.setBounds(175, 145, 308, 34);
    
            // add the formatted text field  to entry panel
            AddentryPanel.add(calorie);
    
            // a text field for entering you email 
            ingredienti = new JTextField();
            ingredienti.setColumns(10);
            ingredienti.setBounds(175, 190, 308, 34);
    
            // add the email text field to the add entry panel
            AddentryPanel.add(ingredienti);
    
            JLabel Phonenumberlabel = new JLabel("Calorie");
            Phonenumberlabel.setForeground(Color.BLUE);
            Phonenumberlabel.setBounds(125, 155, 93, 14);
            AddentryPanel.add(Phonenumberlabel);
    
            JLabel Email = new JLabel("Ingredienti");
            Email.setForeground(Color.BLUE);
            Email.setBounds(110, 200, 80, 14);
            AddentryPanel.add(Email);
    
            // a button that add information into the table from the first name, last name, email
            // and you phone number field.
            JButton AddEntrybutton = new JButton("Aggiungi");
    
            AddEntrybutton.setForeground(Color.GREEN);
            
            AddEntrybutton.addActionListener(new ActionListener() {
                /*
                 * This action listener for entry button will prompt
                 * you, if you want to add information into the table.
                 * It also check if all the mandatory field have been filled correctly
                 * so that it can proceed with the adding. If field has a error it will 
                 * display a error.
                 */
    
                public void actionPerformed(ActionEvent e) {
    
                // check if the option field are filled and correct before adding.
                    if(NomeRicetta.getText().equalsIgnoreCase("")|| calorie.getText().equalsIgnoreCase("") || tempi.getText().equalsIgnoreCase("") || ingredienti.getText().equalsIgnoreCase("")){
                        JOptionPane.showMessageDialog (null, "Assicurati che i campi obbligatori siano riempiti"); 
                    }
    
                    // prompt if you are sure you want to add these information into the table
                    else if (JOptionPane.showConfirmDialog(null, "Vuoi aggiungere la ricetta?", "Request", 
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
                            == JOptionPane.YES_OPTION)
                        {
    
                        DefaultTableModel dtm = (DefaultTableModel)table.getModel();
    
                        dtm.addRow(new Object[] { NomeRicetta.getText(), tempi.getText(), calorie.getText(), ingredienti.getText()});
                        }
    
    
                }
            });
            AddEntrybutton.setBounds(175, 253, 89, 23);
    
            // add the add button to the entry panel 
            AddentryPanel.add(AddEntrybutton);
    
    
            // a button the is use for clearing the field in the add entry panel
            JButton ClearButton = new JButton("Resetta");
            ClearButton.setForeground(Color.RED);
            ClearButton.addActionListener(new ActionListener() {
                /*
                 *  prompt you if you want to clear the first name,
                 *  last name, phone number and email text field.
                 *  if you select yes the field will be clear.
                 *  if you select no the field will not be clear.
                 */
    
                public void actionPerformed(ActionEvent e) {
                    if (JOptionPane.showConfirmDialog(null, "Sei sicuro di voler resettare i campi?", "Request", 
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
                            == JOptionPane.YES_OPTION)
                        {
                         NomeRicetta.setText("");
                         tempi.setText("");
                         calorie.setText("");
                         ingredienti.setText("");
    
    
                        }
                        else
                        {
                         //Go back to normal
                        }
    
                }
            });
            ClearButton.setBounds(394, 253, 89, 23);
    
            // add the clear button the entry panel
            AddentryPanel.add(ClearButton);
    
            // label tell that field is optional and doesn't need to be filled
            JLabel Optionallabel1 = new JLabel("Obbligatorio");
            
            Optionallabel1.setForeground(Color.RED);
            Optionallabel1.setBounds(493, 200, 90, 14);
            AddentryPanel.add(Optionallabel1);
    
            // label tell that field is optional and doesn't need to be filled
            JLabel Optionallabel2 = new JLabel("Obbligatorio");
            
            Optionallabel2.setForeground(Color.RED);
            Optionallabel2.setBounds(493, 104, 90, 14);
            AddentryPanel.add(Optionallabel2);
    
            // label that tell you that this field has to be filled
            JLabel Mandatorylabel1 = new JLabel("Opzionale");
    
            Mandatorylabel1.setBounds(493, 155, 90, 14);
            AddentryPanel.add(Mandatorylabel1);
    
            // label that tell you that this field has to be filled
            JLabel Manatorylabel2 = new JLabel("Obbligatorio");
    
            Manatorylabel2.setForeground(Color.RED);
            Manatorylabel2.setBounds(493, 59, 90, 14);
            AddentryPanel.add(Manatorylabel2);
    
            // a menu bar for displaying the option to load contact, save contact, 
            // export contact as excel file and be able to close option
            JMenuBar menuBar = new JMenuBar();
            menuBar.setBounds(0, 0, 650, 21);
            getContentPane().add(menuBar);
    
    
            JMenu fileoption = new JMenu("File");
    
            menuBar.add(fileoption);
            
            JMenuItem savecontact = new JMenuItem("Salva");
            savecontact.addActionListener(new ActionListener() {
                
                public void actionPerformed(ActionEvent e) {
            System.out.println("Clicked item!");
            if (e.getSource() == savecontact) {
                System.out.println("Save!");
                try {
                    fos = new FileOutputStream(filename);
                    out = new ObjectOutputStream(fos);
                    table.clearSelection();
                    out.writeObject(model);
                    
                } catch (IOException e3) {
                    e3.printStackTrace();
                } finally {
                    try {
                        out.close();
                        fos.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            } 
        }
                
            });
            
            
            
    
            // add a save contact file to menu
            fileoption.add(savecontact);
            
    
    
            JMenuItem loadcontact = new JMenuItem("Carica");
            loadcontact.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    
                    if (e.getSource() == loadcontact) {
                System.out.println("Open!");
                try {
                    table.getModel();
                    fis = new FileInputStream(filename);
                    in = new ObjectInputStream(fis);
                    DefaultTableModel modelRead = (DefaultTableModel) in.readObject();
                    setModel(modelRead);
                    System.out.println("data loaded");
                    in.close();
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                } catch (ClassNotFoundException e2) {
                    e2.printStackTrace();
                }
            } else if (e.getSource() == close) {
                System.out.println("Exit!");
            }
                    
                }
                
            });
    
            // add load contact file to menu
            fileoption.add(loadcontact);
            
    
            
    
            JMenuItem close = new JMenuItem("Chiudi");
            close.addActionListener(new ActionListener() {
    
             
                public void actionPerformed(ActionEvent arg0) {
                    System.exit(0);
                }
            });
            fileoption.add(close);
            table.getColumnModel().getColumn(2).setPreferredWidth(124);       
        }
        
        public void setModel(DefaultTableModel writeModel) {
            table.setModel(writeModel);
        }
        
        
        
        
        
    
        
        public static void main(String[] args) {
            
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    SalvaT ex = new SalvaT();
                    ex.setVisible(true);
                }
            });
        }
    
        @Override
        public void actionPerformed(ActionEvent ae) {}
            
            
        }

    questo è file modificato...ho salvato la tabella...chiudo il programma...lo riavvio e quando clicco su carica i da sempre quell'errore...
    Leggi bene quello che ti ho scritto e non mettere a caso table.getModel().... Non ti ho detto di metterlo dove lo hai scritto tu.
    Il tuo problema non è nel leggere la tabella ma nel salvarla
    Voglio farti capire quello che succede (sono un autodidatta pure io per cui posso usare in maniera impropria alcuni termini o concetti):
    salvi un oggetto che vale null in un file (perchè non hai mai inizializzato il riferimento model). Quando lo vai a leggere il tuo programma esegue senza segnalare errori l' istruzione (legge il file). Fino a qui nessuna eccezione viene lanciata, giustamente (altrimenti avrebbe lanciato una IOException): il file esiste, lo apre e lo legge.
    Ci legge qualcosa dentro? Certo: un riferimento ad un oggetto DefaultTableModel, che tu hai salvato in precedenza (out.writeObject(model)) ma che è null. Poi vuoi riempire una tabella con lo stesso oggetto contenuto nel file, che è, appunto, null. A quel punto il runtime ti dice: "mi stai dicendo di voler riempire una tabella ma non mi hai dato niente con cui riempirla" e quindi lancia quella eccezione ("Cannot set a null TableModel").
Devi accedere o registrarti per scrivere nel forum
7 risposte