我的Java App遇到了一些问题。我有2帧,大型机称为MasterFrame。 MasterFrame包含一个JList + 3按钮。
按钮1可以将块形状添加到JList,这将调用名为BlockFrame的第2帧。块形状是存储在ArrayList shapecollection中的对象。
MasterFrame还包含一个Save按钮,用于将对象存储在名为“test.txt”的.txt文件中。
MasterFrame还包含一个Load按钮,它将打开.txt文件“test.txt”,读取文件中的对象并将对象设置回JList。这就是实际出错的地方。保存功能有效,我不太确定加载方法。它似乎实际上正在读取我的.txt文件中的对象,但它不会把它放回我的Jlist中。
load方法可能不错,但是读取对象并将它们设置回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;
}