2013-12-07 12 views
2

我目前正在用Java編寫我的學校項目,在這個項目中你必須管理一個小村莊的經濟。 所以遊戲看起來像這樣:有一個框架,其中有49個SpecButtons(稍後解釋)代表村莊的瓷磚。點擊一個打開一個生成菜單,您可以從中選擇要在那裏建造什麼類型的建築物等。我該如何序列化JButton []

我創建了一個新類,它擴展了JButton類和Implements Serializable,名爲SpacButtons。爲了這個類,我添加了兩個整數,以及一個Buildings類類型構建變量(也是我創建的類)和一些方法。

SpecButtons buttons=new SpecButtons[49]; 

所以我要保存遊戲,使用序列,這是我怎麼想這樣做:

 private class SaveButtonActionListener implements ActionListener{ 
    public void actionPerformed(ActionEvent button) { 
     try{ 
      FileOutputStream fos = new FileOutputStream("saves.ser"); 
      ObjectOutputStream oos = new ObjectOutputStream(fos); 

      for(int x = 0;x<49;x++){ 
       oos.writeObject(buttons[x]); 
      } 
      oos.close(); 
      fos.close(); 
      }catch(IOException e){System.out.println("File Writing Error!");} 

    } 
} 

private class LoadButtonActionListener implements ActionListener{ 
    public void actionPerformed(ActionEvent button) { 

     try{ 
      FileInputStream fip = new FileInputStream("saves.ser"); 
      ObjectInputStream oip = new ObjectInputStream(fip); 
      for(int x=0;x<49;x++){ 
       buttons[x] = (SpecButtons) oip.readObject(); 
      } 
      oip.close(); 
      fip.close(); 
     }catch(IOException e){System.out.println("File Reading Error!");} 
     catch(ClassNotFoundException ce){System.out.println("Class Not Found!");} 
} 
} 

所以,它會創建.ser文件,但是當我嘗試加載它沒有任何反應。 如果你們有任何想法如何使它工作,我會非常感激。

+0

您的文件是否被創建?當你從文件中加載按鈕時,是否包含正確的數據(使用調試器來查看它們是否被正確地反序列化) – GETah

回答

1

因此,它創建.ser文件,但是當我嘗試加載它時,沒有任何反應。

假設您的按鈕被正確地反序列化,您應該將它們添加到您的主框架一旦從.ser文件加載。

for(int x=0;x<49;x++){ 
    buttons[x] = (SpecButtons) oip.readObject(); 
} 
// Add the buttons to the main frame where you would like them to appear... 
+0

謝謝,它工作正常! – Lexandro

相關問題