[英]Java File Reading Problem
我正在嘗試讀取highscore.txt文件,以便可以在游戲的highscores菜單上顯示該文件。 我的highscore.txt的內容是SCORE和NAME。 例:
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);
}
}
我究竟做錯了什么??? 我怎樣才能使這項工作>。 您的幫助將不勝感激。 先感謝您。
您正在將文件的內容讀取到ArrayList v
,然后在填充文件之后不執行任何操作。
您顯示分數的代碼是向jTextArea1
添加一個空的JList
。 您可能想用ArrayList v
的內容填充JList
。
JList jlScores = new JList(v); //there's a problem here. I don't know why
沒有采用arraylist的構造函數,請查看javadoc中的構造函數。 而是將arraylist轉換為數組,然后在構造函數中使用它。
至於如何將arraylist轉換為數組,由於這是家庭作業,因此我將其留為練習,一點點Google搜索就可以了!
如JList教程中所述,我建議使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.