【发布时间】:2014-08-19 14:24:21
【问题描述】:
我有一个电话簿应用程序,它将数据从 JTable 存储到数组列表中。 在 GUI 中,我有保存和打开按钮,它们假设将数据作为文件对象保存和打开。 我设法创建了一个文件,其中包含来自 arraylist 的信息。
更新:如何不能让它将信息加载回 JTable?
我是 Java 新手,感谢您的耐心和帮助。期待感谢!
代码如下:
在 model 类中(扩展 AbstractTableModel)
public void saveContact() throws FileNotFoundException, IOException {
f.createNewFile();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(listaContacte); // listaContacte is the arraylist
System.out.println("S-a salvat");
}
public void loadContact() throws IOException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
try {
ois.readObject();
} catch (ClassNotFoundException ex) {
Logger.getLogger(CarteDeTelefon.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("s-a incarcat ");
}
}
在GUI
中 private void saveActionPerformed(java.awt.event.ActionEvent evt) {
try {
model.saveContact();
} 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 {
model.loadContact();
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);}
}
}
}
更新:
public void loadContact() throws IOException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
try {
List<Abonat> obiect = (List<Abonat>) ois.readObject(); // "variable `obiect` is not used"
} catch (ClassNotFoundException ex) {
Logger.getLogger(CarteDeTelefon.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("s-a incarcat ");
}
【问题讨论】:
-
与往常一样,将任何大问题分解为更小的子问题,然后尝试孤立地解决每个问题。事实上,我担心您的问题过于宽泛,实际上应该是几个单独的问题(但不是一次全部问)。
-
另外,您需要接受 Camickr 对您的 question from yesterday 的回答。
-
使用
SwingWorker处理具有不确定延迟的周期性任务。 -
@Hovercraft Full Of Eels 感谢您的建议,我已经更新了我的问题
标签: java swing jtable objectinputstream objectoutputstream