2011-01-31 121 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);