Java File Reading Problem
I am trying to read my highscore.txt file so that I can show it on my game's highscores menu. The content of my highscore.txt is SCORE and NAME. Example:
150 John
100 Charice
10 May
So I write the following code to read the file in a text area but the file cannot be read. My code is as follows:
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); //the开发者_如何学运维re's a problem here. I don't know why
jTextArea1.add(jlScores, BorderLayout.CENTER);
}
}
What am i doing wrong??? How can I make this work>. You're help would be highly appreciated. Thank you in advance.
You are reading the contents of the file into an ArrayList v
which you are then doing nothing with after populating it.
Your code to display the scores is adding an empty JList
to your jTextArea1
. You likely want to fill the JList
with the contents of ArrayList v
.
You are trying to initialize JList with ArrayList object.
JList jlScores = new JList(v);
I think that could be the problem because there is no JList constructor with ArrayList, there is one with Vector.
JList jlScores = new JList(v); //there's a problem here. I don't know why
There isn't a constructor that takes an arraylist, have a look at the constructors in the javadoc. Instead, convert the arraylist to an array and then use that in the constructor.
As to how to convert the arraylist to an array, I'll leave that as an exercise since this is homework, a bit of Googling should do the job no problem!
As described in the JList Tutorial, I'd recommend using a ListModel to populate the JList, as follows:
//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);
精彩评论