【问题标题】:Data not loading back to Jtable (using Serializable objects)数据未加载回 Jtable(使用 Serializable 对象)
【发布时间】:2014-07-03 19:37:50
【问题描述】:

我有一个 Jtable 上显示的对象数组列表。对于 Jtable,我实现了一个扩展 AbstractTableModel 的模型。我希望用户能够从 .txt 文件中保存和加载。现在,我可以创建和保存文件,但是当我尝试将数据加载回 jTable 时,什么也没有发生。
请看我的代码。任何建议表示赞赏!
谢谢!

模型

package cartedetelefon;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.AbstractTableModel;

public class CarteDeTelefon extends AbstractTableModel implements Serializable {

    private static List<Abonat> listaContacte = new ArrayList<Abonat>();
    public static File f;
    private static final long serialVersionUID = 1L;
    private static final Logger fLogger = Logger.getLogger(CarteDeTelefon.class.getPackage().getName());

    /**
     * @return the listaContacte
     */
    public static List<Abonat> getListaContacte() {
        return listaContacte;
    }

    /**
     * @param aListaContacte the listaContacte to set
     */
    public static void setListaContacte(List<Abonat> aListaContacte) {
        listaContacte = aListaContacte;
    }

    private final String[] numeColoane = {
        "Nume",
        "Prenume",
        "CNP",
        "Numar telefon"
    };

    // add contact to list
    public void adaugareContact(String nume, String prenume, String cnp, String tel) {

        try {
            Long s = Long.valueOf(tel);
            getListaContacte().add(new Abonat(nume, prenume, cnp, new NrTel(s)));

            fireTableDataChanged();
        } catch (NumberFormatException numberFormatException) {
        }

    }

    @Override
    public int getRowCount() {
        if (getListaContacte().size() <= 0) {
            return 0;
        } else {
            return getListaContacte().size();
        }

    }

    @Override
    public int getColumnCount() {
        return numeColoane.length;
    }

    @Override
    public String getColumnName(int col) {
        return numeColoane[col];
    }

    @Override
    public Object getValueAt(int row, int col) {
        if (col == 0) {
            return getListaContacte().get(row).getNume();
        } else if (col == 1) {
            return getListaContacte().get(row).getPrenume();
        } else if (col == 2) {
            return getListaContacte().get(row).getCNP();
        } else if (col == 3) {
            return getListaContacte().get(row).getNrTel();
        }

        return "Eroare";
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int colIndex) {

        Abonat abonat = getListaContacte().get(rowIndex);
        switch (colIndex) {
            case 2:
                abonat.setCNP((String) aValue);
                break;
            case 3:
                abonat.setNrTel((NrTel) aValue);
                break;
        }
        fireTableRowsUpdated(rowIndex, rowIndex);

    }

    @Override
    public boolean isCellEditable(int row, int colNum) {
        switch (colNum) {
            case 2:
                return false;
            default:
                return true;
        }
    }

    //save contacts
    public void salvareContacte() throws FileNotFoundException, IOException {

        try (
                OutputStream file = new FileOutputStream("contacts.txt");
                OutputStream buffer = new BufferedOutputStream(file);
                ObjectOutput output = new ObjectOutputStream(buffer);) {
            output.writeObject(listaContacte);
        } catch (IOException ex) {
            fLogger.log(Level.SEVERE, "Cannot perform output.", ex);
        }

    }

    //load contacts
    public void incarcareContacte() throws IOException, ClassNotFoundException {

        try (
                InputStream file = new FileInputStream("contacts.txt");
                InputStream buffer = new BufferedInputStream(file);
                ObjectInput input = new ObjectInputStream(buffer);) {
            //deserialize the List
            List<Abonat> recoveredContacts = (ArrayList<Abonat>) input.readObject();
            //display its data
            for (Abonat contacts : recoveredContacts) {
                System.out.println("Recovered contacts: " + contacts);
            }
        } catch (ClassNotFoundException ex) {
            fLogger.log(Level.SEVERE, "Cannot perform input. Class not found.", ex);
        } catch (IOException ex) {
            fLogger.log(Level.SEVERE, "Cannot perform input.", ex);
        }
    }

}

保存按钮

private void saveActionPerformed(java.awt.event.ActionEvent evt) { 



try {
    model.salvareContacte();
} catch (IOException ex) {
    Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}

}

打开按钮

private void openActionPerformed(java.awt.event.ActionEvent evt) {   



final JFileChooser fc = new JFileChooser();

if (evt.getSource() == open) {
    int returnVal = fc.showOpenDialog(GUI.this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        try {
            try {
                model.incarcareContacte();
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (IOException ex) {
            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

}

编辑:

加载文件后,incarcareContacte 方法会在控制台上为每个条目显示一行“Recovered contacts: cartedetelefon.Abonat@17207144”

【问题讨论】:

  • 什么都没有发生是什么意思?您的加载方法(incarcareContacte)是否执行?它会抛出异常吗?它会反序列化一个空列表吗?
  • @Mark W 请查看编辑
  • 这种形式的问题很难得到正确回答,问题可能在模型通知器中或不可能......,fireTableDataChanged() 可以重新加载任何内容,但可以是您代码的炸弹同样的方式

标签: java swing serialization arraylist jtable


【解决方案1】:

您永远不会将条目重新添加到模型中,请尝试以下代码。您可能还需要重新验证 JTable 以使其呈现新行。可能是对 jtable.fireTableDataChanged() 或类似的调用。

//load contacts
public void incarcareContacte() throws IOException, ClassNotFoundException {

    try (
            InputStream file = new FileInputStream("contacts.txt");
            InputStream buffer = new BufferedInputStream(file);
            ObjectInput input = new ObjectInputStream(buffer);) {
        //deserialize the List
        List<Abonat> recoveredContacts = (ArrayList<Abonat>) input.readObject();
        //display its data
        for (Abonat contacts : recoveredContacts) {
            System.out.println("Recovered contacts: " + contacts);
        }
        listaContacte = recoveredContacts;

    } catch (ClassNotFoundException ex) {
        fLogger.log(Level.SEVERE, "Cannot perform input. Class not found.", ex);
    } catch (IOException ex) {
        fLogger.log(Level.SEVERE, "Cannot perform input.", ex);
    }
}

【讨论】:

  • 非常感谢。我错过了!也错过了 fireTableDataChanged();
猜你喜欢
  • 2014-06-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2012-05-21
  • 1970-01-01
  • 2017-11-20
  • 2013-05-08
  • 2011-03-27
相关资源
最近更新 更多