2011-01-31 118 views
0

我想讀取我的highscore.txt文件,以便我可以在我的遊戲的高分菜單上顯示它。 我的highscore.txt的內容是SCORE和NAME。例如:Java文件讀取問題

150 John 
    100 Charice 
    10 May 

所以我寫了下面的代碼讀取文本區域中的文件,但該文件無法讀取。我的代碼如下:

public HighScores(JFrame owner) { 
     super(owner, true); 
     initComponents(); 
     setSize(500, 500); 
     setLocation(300, 120); 
     getContentPane().setBackground(Color.getHSBColor(204, 204, 255)); 

     File fIn = new File("highscores.txt"); 
     if (!fIn.exists()) { 
      jTextArea1.setText("No high scores recorded!"); 
     } else { 
      ArrayList v = new ArrayList(); 
      try { 
       BufferedReader br = new BufferedReader(new FileReader(fIn)); 
       String s = br.readLine(); 
       while (s != null) { 
        s = s.substring(2); 
        v.add(s); 
        s = br.readLine(); 
       } 

       br.close(); 
      } catch (IOException ioe) { 
       JOptionPane.showMessageDialog(null, "Couldn't read high scores file"); 
      } 

      // list to display high scores 
      JList jlScores = new JList(v); //there's a problem here. I don't know why 
      jTextArea1.add(jlScores, BorderLayout.CENTER); 

     } 
    } 

我在做什麼錯???我怎樣才能做這件事>。你的幫助將不勝感激。先謝謝你。

+0

你可能想看看你是如何從你的文件解析文本行。 `s = s.substring(2);`只是從字符串中刪除前兩個字符。你可能會想要在空間字符串上拆分字符串以獲得一個令牌數組;在這種情況下,[0]將是得分,[1]將是名稱。 – Qwerky 2011-01-31 16:46:20

+0

@Qwerky我怎麼做分裂?謝謝 – newbie 2011-01-31 16:47:36

回答

3

您正在將文件的內容讀取到ArrayList v中,然後在填充文件之後您無需執行任何操作。

您顯示分數的代碼是向您的jTextArea1添加一個空的JList。您可能需要填寫內容爲ArrayList vJList

1

您試圖用ArrayList對象初始化JList。

JList jlScores = new JList(v); 

我認爲這可能是問題,因爲沒有JList的構造與ArrayList中,有one with Vector

1
JList jlScores = new JList(v); //there's a problem here. I don't know why 

沒有接受一個ArrayList的構造,看看在javadoc建設者。相反,將數組列表轉換爲數組,然後在構造函數中使用它。

至於如何將數組列表轉換爲數組,因爲這是作業,所以我會將其作爲一個練習,因爲這是作業,有點谷歌應該做的工作沒有問題!

1

正如JList Tutorial描述,我建議使用ListModel的填充JList中,如下所示:

//create a model 
DefaultListModel listModel = new DefaultListModel(); 

//now read your file and add each score to the model like this: 
listModel.addElement(score); 

//after you have read your file, set the model into the JList 
JList list = new JList(listModel);