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) {}
}