我正在尝试创建一个如下所示的弹出窗口:
玩过的游戏数量:2
总分:10
平均分:5
我将数字 2、10 和 5 存储在文本文件中。我只是希望能够将文本文件中的数字读取到 JLabel 或 JTextArea(这就是我感到困惑的地方)?我还希望能够清除分数并将其全部重置为 0。我认为这应该不会太难,但我可能是错的。当我读入数字时,我应该将它们存储到 ArrayList 中吗?
这是我到目前为止的代码:
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Scanner;
public class HistoryPopUp {
JFrame history;
JPanel panel;
JLabel numGames, totalScore, avgScore;
JTextArea games,score,aScore;
JButton clearHistory;
HistoryPopUp(){
history = new JFrame();
panel = new JPanel(new GridLayout(3, 1));
numGames = new JLabel("Number of Games Played: ");
totalScore = new JLabel("Total Score: ");
avgScore = new JLabel("Average Score: ");
games = new JTextArea();
score = new JTextArea();
aScore = new JTextArea();
clearHistory = new JButton();
try {
String textLine;
FileReader fr = new FileReader("history.txt");
BufferedReader reader = new BufferedReader(fr);
while((textLine=reader.readLine()) != null){
textLine = reader.readLine();
games.read(reader,"Something");
score.read(reader, "seomthing");
aScore.read(reader,"balh");
}
reader.close();
}catch(IOException ex){
System.out.println("ABORT! YOU KILLED IT!!");
}
history.pack();
history.setVisible(true);
panel.add(games);
panel.add(score);
panel.add(aScore);
JOptionPane.showMessageDialog(null, panel, "History of Games Played", JOptionPane.PLAIN_MESSAGE);
}
}
编辑:格式
最佳答案
您遇到的问题是您有 4 段代码都试图从同一个数据池中读取数据,score
或 aScore
不太可能有任何数据游戏
结束后读取器中的数据
如果您只想使用JLabel
,您可以这样做......
String[] headers = {"Number of Games Played:", "Total Score:", "Average Score:"};
JLabel[] labels = new JLabel[3];
for (int index = 0; index < labels.length; index++) {
labels[index] = new JLabel();
// Add label to screen
}
try (BufferedReader br = new BufferedReader(new FileReader(new File("history.txt")))) {
String text = null;
int lineCount = 0;
while ((text = br.readLine()) != null && lineCount < 3) {
System.out.println(text);
labels[lineCount].setText(headers[lineCount] + " " + text);
lineCount++;
}
} catch (IOException ex) {
ex.printStackTrace();
}
如果你想使用JTextArea
,你可以这样做......
String[] headers = {"Number of Games Played:", "Total Score:", "Average Score:"};
JTextArea textArea = new JTextArea(3, 20);
// Add text area to container
try (BufferedReader br = new BufferedReader(new FileReader(new File("history.txt")))) {
String text = null;
int lineCount = 0;
while ((text = br.readLine()) != null && lineCount < 3) {
System.out.println(text);
textArea.append(headers[lineCount] + " " + text + "\n");
lineCount++;
}
} catch (IOException ex) {
ex.printStackTrace();
}
您还可以以类似的方式使用 JTextField
数组
关于java - 如何从文本文件读取到JLabel或JTextArea?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36442152/