[英]How Read from Text File to JLabel or JTextArea?
我正在尝试创建一个弹出窗口,如下所示:
玩过的游戏次数: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条代码都试图从同一数据池中读取,因此games
结束后, 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
数组
不要那样做
不要将“持久性”(信息保存在文件中)与“演示文稿”混合使用。
代替; 阅读有关Swing文档模型的信息; 或使用“模型视图控制器”方法。
但是,从您编写的代码来看,似乎您仍在使用Swing UI的非常基本的元素时遇到问题。 关键是:有javadoc; 以及来自Oracle的优秀教程。 不要期望其他人向您解释如何详细使用它们。 我的意思是:首先学习如何使用各种UI元素; 逐一; 了解如何将数据放入其中; 以及这些信息的外观。
然后,当您了解UI元素时; 考虑一种合理的方式来持久化您的数据; 并将其放入您的UI元素中(如上所述:在同一段代码中完成所有这些都是不好的设计;应避免这样做)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.