2012-03-04 66 views
0

我正在爲我的計算機科學課進行這個年級保留課程,而我還沒有開始工作的一件事就是保存/加載課程。正如我現在設置它,它會自動保存,當你退出時加載,當你啓動時加載,如果有文件加載。但是,我覺得我正在加載或保存不正確;有一個主要的JFrame包含所有的數據,並且這是保存的一個對象。當它被加載時,它會更容易向你展示。如何從文件正確加載JFrame?

If it looks like this when I close it:

pre-save snapshot

然後it'll look like this when I start it up again:

post-load snapshot

此外, 「輸入學生」 按鈕,以及用於輸入對JTextFieldActionListener,停止工作當程序加載JFrame時。該計劃被分爲3類文件:

成績冊:

import javax.swing.*; 
import java.awt.event.*; 
import java.io.*; 

public class GradeBook implements java.io.Serializable { 
    private static JFrame frame; 
    public static void main(String[] args) throws Exception{ 
     try{ 
      FileInputStream fis = new FileInputStream("t.tmp"); 
      ObjectInputStream ois = new ObjectInputStream(fis); 

      frame = (JFrame) ois.readObject(); 

      ois.close(); 
     } catch(Throwable t) { 
      frame = new JFrame("Course Grades"); 
     } 

     frame.addWindowListener(new closing()); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(new CourseGrade()); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

收盤:

private static class closing extends WindowAdapter { 
     public void windowClosing(WindowEvent e) { 
      try { 
       FileOutputStream fos = new FileOutputStream("t.tmp"); 
       ObjectOutputStream oos = new ObjectOutputStream(fos); 

       oos.writeObject(frame); 

       oos.close(); 
      } catch(Throwable t){System.out.println(t.getMessage());} 
     } 
    } 
} 

CourseGrade:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
import java.awt.FlowLayout; 
import java.util.Random; 
import javax.swing.table.*; 
import java.io.*; 
public class CourseGrade extends JPanel implements java.io.Serializable { 
    private JLabel entername; 
    private JTextField in; 
    private JTextArea list; 
    private JScrollPane scroll; 
    private String[] students = new String[1000]; 
    private JButton enter; 
    private JButton[] studentbuttons = new JButton[1000]; 
    private JButton[] delete=new JButton[1000]; 
    private int numstudents; 
    private JFrame[] studentframes=new JFrame[1000]; 
    private static JTable[] tables=new JTable[1000]; 
    private static DefaultTableModel[] model=new DefaultTableModel[1000]; 
    private static int[] numass=new int[1000]; 
    public CourseGrade() { 
     String[][] data = {{"", "", "", ""}}; 
     String[] headers = {"Assignment", "Date Assigned", "Score", "Percentage"}; 
     for(int i=0; i<tables.length; i++){ 
      model[i] = new DefaultTableModel(data, headers); 
      tables[i] = new JTable(model[i]){ 
       public boolean isCellEditable(int rowIndex, int colIndex) { 
        return false; 
       } 
      }; 
     } 
     numstudents=0; 
     in=new JTextField(13); 
     in.addActionListener(new enterListener()); 
     list=new JTextArea(); 
     scroll=new JScrollPane(list); 
     list.setEditable(false); 
     entername=new JLabel("Enter a student's name"); 
     enter=new JButton("Enter Student"); 
     enter.addActionListener(new enterListener()); 
     setPreferredSize(new Dimension(260, 300)); 
     setBackground(Color.green); 

     add(entername); 
     add(in); 
     add(enter); 
     add(scroll); 

     scroll.setPreferredSize(new Dimension(240, 200)); 
    } 

    private class enterListener implements ActionListener { 
     public void actionPerformed(ActionEvent event) { 
      String x=in.getText(); 
      String y=""; 
      String z=""; 
      in.setText(""); 
      int a=numstudents+1; 
      if(x.length()>0) x=a+". " + x + "\n"; 
      students[numstudents] = x; 
      if(x.length()>0)numstudents++; 
      for(int i=0; i<numstudents; i++){ 
       x=students[i]; 
       if(x.length()>13)x=x.substring(0,11)+"...\n"; 
       y+=x; 
      } 
      studentbuttons[numstudents]=new JButton("Edit"); 
      studentbuttons[numstudents].addActionListener(new grades()); 
      delete[numstudents]=new JButton("Delete"); 
      delete[numstudents].addActionListener(new del()); 
      list.setText(y); 
      list.add(studentbuttons[numstudents]); 
      studentbuttons[numstudents].setBounds(100,(numstudents-1)*16,55,15); 
      list.add(delete[numstudents]); 
      delete[numstudents].setBounds(160,(numstudents-1)*16,70,15); 
     } 
    } 

    private class grades implements ActionListener { 
     public void actionPerformed(ActionEvent event) { 
      Object obj = event.getSource(); 
      if(obj instanceof JButton){ 
       JButton clicked = (JButton)obj; 
       int x=clicked.getY()/16; 
       String y=students[x]; 
       for(int i=0; i<y.length(); i++){ 
        String q=y.substring(i,i+1); 
        if(q.equals(" ")) { 
         y=y.substring(i+1); 
         i=y.length()+1; 
        } 
       } 
       studentframes[x]=new JFrame(y+"'s Grades"); 
       studentframes[x].setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
       try{studentframes[x].getContentPane().add(new GradePage(x, tables[x], numass[x]));} 
       catch(Exception e){} 
       studentframes[x].pack(); 
       studentframes[x].setVisible(true); 
      } 
     } 
    } 

    private class del implements ActionListener { 
     public void actionPerformed(ActionEvent event) { 
      Object obj = event.getSource(); 
      if(obj instanceof JButton){ 
       JButton clicked = (JButton)obj; 
       int x=clicked.getY()/16; 
       String y="", z=""; 
       studentbuttons[numstudents].setVisible(false); 
       delete[numstudents].setVisible(false); 
       numstudents--; 
       int q=3; 
       int w=0; 
       for(int i=x; i<=numstudents; i++){ 
        if(i<10)q=1; 
        else if(i<100) q=2; 
        tables[i]=tables[i+1]; 
        numass[i]=numass[i+1]; 
        model[i]=model[i+1]; 
        w=i+1; 
        try{if(!students[i+1].equals(null)){students[i]=w+students[i+1].substring(q);} else{students[i]=null;}}catch(Throwable t){} 
       } 
       for(int i=0; i<numstudents; i++){ 
        y=students[i]; 
        if(y.length()>13)y=y.substring(0,11)+"...\n"; 
        z+=y; 
       } 
       list.setText(z); 
      } 
     } 
    } 
    public static void setTable(int numtable, JTable table){ 
     tables[numtable]=table; 
    } 
    public static void newRow(int numtable){ 
     model[numtable].addRow(new Object[]{"", "", "", ""}); 
    } 
    public static void setNumEntries(int numtable, int num){ 
     numass[numtable]=num; 
    } 
} 

第三類不應該有什麼關係有了這個,所以我現在不會發布它。

我意識到代碼可能寫得不好,但我只是在高中計算機科學的第二年,我們並沒有真正涉及到這一點。這個程序甚至不應該是一個圖形用戶界面,這是我第一次聽說過輸入或輸出流,所以我真的不知道它們。我現在意識到讓這些類實現java.io.Serializable可能是不必要的,但是當我試圖研究這個時,我遇到了一些人在考慮如何保存某些對象,因爲它們不會自然地實現它。非常抱歉,如果這是一個愚蠢的錯誤,並感謝您的時間。

+4

我不會被執行'Serializable'用於閱讀這種類型的功能。相反,請看一系列其他不太脆弱的持久設置和屬性的方法。例如。在[這個答案](http://stackoverflow.com/a/7778332/418556)(它使用'屬性')。 Java提供了一種「麪包師」來堅持信息。 – 2012-03-04 20:21:15

+1

如果用戶在序列化和反序列化之間更新他的Java,那麼很可能你的方法會失敗。 – 2012-03-04 20:32:00

回答

0

我不建議你保存JFrame對象。這裏有一個更好的解決方案,你可以保存學生的姓名和成績在文本文件上,每次你的程序加載時都會從文本文件中加載信息。

提示:您可以使用輸入&輸出流消法,但它也許有點sonfusing所以,去了解這兩個類:

  1. 掃描儀(以及如何使用它從文件中讀取)
  2. PrintWriter的(以及如何使用它來寫入文件)

PS:我could'v給你的代碼,但它是更好的學習體驗挨一點點地查找信息,因爲當你試圖弄清楚你會學會還有很多其他的事情。

+0

有更好的方法序列化對象 – mbatchkarov 2012-03-04 22:43:02

0

框架不是應用程序狀態的組成部分,它只是顯示重要信息(名稱,等級等)的一種方式。如果要保存會話,請保存當前屏幕上的信息,然後使用反序列化的信息重新創建JFrame。一個ObjectOutputStream是寫東西到磁盤的一種合理的方式,並且ObjectInputStream適合於讀取返回的數據。該文檔包含很好的示例。此外,您的課程需要實施Serializable

+0

如何讀取同一對象的多個實例?我有多個JButton數組,我需要保存/加載,但是如果使用readObject,我不知道如何指定要加載的兩個保存數組中的哪一個。 – Tim 2012-03-05 02:47:04

1

您可以在一個記事本文件中存儲數據這樣

  try 
      { 
       FileWriter file = new FileWriter("insert file name here"); 
       BufferedWriter buffer = new BufferedWriter(file) ; 
       buffer.write("insert file content here") ; 
       buffer.newLine(); 
       buffer.close(); 
      } 
      catch (IOException e) 
      { 
       //Insert error message here 
      } 

再這樣

try 
    { 
     FileReader file = new FileReader("insert file name here") ; 

     BufferedReader buffer = new BufferedReader(file); 

     String line = "" ; 

     while((line = buffer.readLine()) != null) 
     { 
      System.out.println(line) ; 
     } 

     buffer.close() ; 
    } 
    catch(IOException e) 
    { 
     //Insert error message here 
    } 

希望幫助