2014-02-12 2 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) {} 

을, 나는 JButton의가 저장되지 않습니다 암시, buttonsClass.getButton(0);를 호출하는 시도는 NullPointerException을받을 때 수업을 저장하십시오.

왜 그런지, 그리고 어떤 문제 해결 방법이 있습니까?

답변

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

이 변수는 직렬화하려는 경우 정적이어서는 안됩니다.

관련 문제