我的 Java 应用程序有点问题。我有2个框架,主机叫MasterFrame。MasterFrame 包含一个 JList + 3 个按钮。
按钮 1 可以将块形状添加到 JList,这将调用称为 BlockFrame 的第二帧。块形状是存储在 ArrayList shapecollection 中的对象。
MasterFrame 还包含一个保存按钮,它将对象存储在一个名为“test.txt”的 .txt 文件中。
MasterFrame 还包含一个加载按钮,它将打开 .txt 文件“test.txt”,读取文件中的对象并将对象设置回 JList。这就是真正的问题所在。保存功能有效,我不太确定加载方法。似乎它实际上是在读取我的 .txt 文件中的对象,但它不会把它放回我的 Jlist 中。
加载方法可能很好,但读取对象并将它们设置回 JList 可能会出现问题。如果你们之外的任何人可以帮我一把,我很高兴:)
import java.io.*;
// My File IO Class
public class ShapeIOController {
private String filename;
public ShapeIOController(){
filename= "C:\\Users\\Lars\\Desktop\\test.txt";
}
// The Save method which will save all my created blocks in "test.txt" file
public void save(ShapeCollection shapecollection){
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
out.writeObject(shapecollection);
out.close();
}
catch( IOException e){
System.out.println("Error occured when trying to open file" + filename);
e.printStackTrace();
}
}
// The open file method which will open "test.txt" file,
// read it's objects and return a ArrayList of shapes "shapecollection"
public ShapeCollection open(ShapeCollection shapecollection){
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
shapecollection= (ShapeCollection) in.readObject();
in.close();
}
catch (ClassNotFoundException e ) {
System.out.println("Unknown class by reading file" + filename);
}
catch ( IOException e ) {
System.out.println("Error occured when trying to open file " + filename);
e.printStackTrace();
}
shapecollection.giveCollection();
return shapecollection;
}
}
// The code for the save button which works
private void SaveShapeButtonActionPerformed(java.awt.event.ActionEvent evt) {
shapeiocontroller.save(shapecontroller.getShapeCollection());
}
// The code where it probably is going wrong
private void LoadShapeButtonActionPerformed(java.awt.event.ActionEvent evt) {
for(int i = 0; i < shapecontroller.getShapeCollection().giveCollection().size(); i++){
listModel.addElement(shapecontroller.getShapeCollection().giveShape(i).toString());
InfoShapeJList.setModel(listModel);
shapeiocontroller.open(shapecontroller.getShapeCollection());
}
}
// List of methods LoadShapeButtonActionPerformed is using:
// getShapeCollection()
public ShapeCollection getShapeCollection() {
return shapecollection;
}
// giveCollection()
public ArrayList<Shape> giveCollection(){
return shapecollection;
}
// giveShape()
public Shape giveShape(int index){
return shapecollection.get(index);
}
// toString()
public String toString(){
return "Block: " + length + " " + width + " " + height;
}