2014-02-12 42 views
0

我正在製作一個程序,它將JButton數組保存到文件.btn。這裏是正在保存代碼:無法加載保存的JButton

package avtech.software.compunav; 

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.ObjectOutputStream; 
import java.io.Serializable; 

import javax.swing.JButton; 

public class Buttons implements Serializable { 
public static Button[] buttons = new Button[15]; 

public Buttons() { 
    for (int i = 0; i < buttons.length; i++) { 
     buttons[i] = new Button(); 
     buttons[i].setText("Unassigned"); 
    } 
} 

public JButton[] getButtons() { 
    return buttons; 
} 

public JButton getButton(int index) { 
    return buttons[index]; 
} 

public void setButtonText(String txt, int index) { 
    buttons[index].setText(txt); 
} 

public void setButtonAction(String action, int index) { 

} 

public void save() { 
    try { 
     File dir = new File(Core.baseDir + "/bin/buttons.btn"); 

     FileOutputStream fos = new FileOutputStream(dir); 
     ObjectOutputStream oos = new ObjectOutputStream(fos); 

     if (dir.exists()) 
      dir.delete(); 

     oos.writeObject(this); 

     oos.flush(); 
     oos.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
} 

Button是擴展的JButton類,這裏是代碼:

package avtech.software.compunav; 

import java.awt.Desktop; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.File; 
import java.io.IOException; 

import javax.swing.JButton; 

import CompuNav.main.Dialogs; 

public class Button extends JButton implements ActionListener { 

private String action = ""; 

public Button() { 
    addActionListener(this); 
} 

public void setAction(String s) { 
    action = s; 
} 

@Override 
public void actionPerformed(ActionEvent arg0) { 
    if (action.equals("")) 
     return; 

    File file = new File(action); 
    Desktop dt = Desktop.getDesktop(); 

    try { 
     dt.open(file); 
    } catch (IOException e1) { 
     Dialogs.msg("Could not open " + action); 
    } 
} 

} 

基本上,代碼保存。在正確的目錄中有一個名爲buttons.btn的文件。問題是,當我在這裏使用的加載方法:

try { 
     FileInputStream fis = new FileInputStream(baseDir 
       + "/bin/buttons.btn"); 
     ObjectInputStream ois = new ObjectInputStream(fis); 

     buttonsClass = (Buttons) ois.readObject(); 

     ois.close(); 
    } catch (Exception e) {} 

使得按鍵的新對象並保存後,我得到試圖調用buttonsClass.getButton(0);當一個NullPointerException異常,這意味着這些Jbutton不保存,當我保存班級。

任何理由爲什麼,以及任何想法如何解決這個問題?

回答

1
public static Button[] buttons = new Button[15]; 

如果你希望它被序列化,這個變量不應該是靜態的。