gpt4 book ai didi

java - 从文件读取并在 GUI java 中显示

转载 作者:行者123 更新时间:2023-11-30 04:06:00 25 4
gpt4 key购买 nike

我需要读取主文件中的文件,而不是将红线(从文件中)添加到存储数组对象并在 GUI 类中显示的类中的数组中。我的问题是 GUI 没有任何内容。来自 TeamgetTeamName 返回 null

我读了文件

                fr = new FileReader("TeamsIn.txt"); 
Scanner in = new Scanner(fr);
while (in.hasNextLine()){
String line = in.nextLine();

team = new Team(line);
team = teamIn.addTeam(team);

然后我将行添加到 MatchManager 中的 Team [] 数组

    public  Team addTeam( Team teamName)
{
for(int i = 0; i < MAX_TEAMS; i++)

teams[i] = teamName;

return teamName;


}

我想在 GUI 中显示

         Team t = new Team(teamName);


display = new JTextArea(ROWS, COLUMNS);
display.setEditable(false);
display.setText(t.getTeamName());
JScrollPane scrollPane = new JScrollPane(display);
return scrollPane;




public class Team {


public Team(String teamName){
this.teamName = teamName;
//System.err.println(teamName);
}




public String getTeamName(){
return teamName;
}
public String setTeamName(String tName){
return teamName;
}

但是 display.setText(t.getTeamName()); 不会返回任何内容。

最佳答案

这里有一些建议。您可能想要重组整个程序。我知道这可能看起来像“你是真的吗?”,但我是认真的。我知道你可能已经花了很多时间在上面,你最不想做的就是重新开始,但事实是,你的设计似乎非常糟糕。这里有一些指针。

  • 将数据和 View 分开。并且对你的数据有一定的结构。我的意思是将所有数据和数据操作方法保留在一个类中。

这是一个使用您的程序中的想法的示例

public class MatchManager {          // This class holds all the teams

private List<Team> teams = new ArrayList<Team>();
private int countTeam;
private static int MAX_TEAMS=8;

public MatchManager(){
try {
FileReader fr = new FileReader("TeamsIn.txt");
Scanner in = new Scanner(fr);

while (in.hasNextLine()){
String line = in.nextLine();

Team team = new Team(line);
teams.add(team);
}
} catch ( ... ) {}
}

public List<Team> getTeams(){
return teams;
}
}

上面代码的作用是,一旦实例化 MatchManager,所有球队都会被填充。

<小时/>
  • JavaBallTournamentGUI 类是应该启动程序的类。请记住我如何谈论将数据和 View 分开。如果你想一想,数据应该运行吗?不,数据不是程序。 GUI虽然是一个程序。因此,运行 GUI 程序从您的 Model 类(MatchManager)获取数据。

类似这样的事情。

public class JavaBallTournamentGUI extends JFrame {
MatchManager manager = new MatchManager();
List<Team> teams;

public JavaBallTournamentGUI(){
teams = manager.getTeams();
}
}

现在您可以在 GUI 类中使用 MatchManager 中的所有数据。

<小时/>
  • 我注意到您在几个不同的地方实例化了 Team 类。这确实没有必要。每当你想获取某个团队的数据时,你可以从团队列表中调用它,

像这样

String oneTeam = teams.get(2).getTeamName();
textField.setText(oneTeam);

你是否注意到这样一切都变得更加顺利?如果你不这样做,抱歉,我已尽力解释。但我希望你能明白其中的要点。这种类型的设计更加简洁。

编辑:打印全部

如果它是 JTextArea

for (Team team : teams){
textArea.append(team.getTeamName() + "\n");
}

关于java - 从文件读取并在 GUI java 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20699688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com