我正在使用 DefaultTableModel 来显示一个简单的用户统计信息页面。我已成功将数据保存到文件中,但无法将其读回(参见loadData()
底部的方法)。所以,我需要它做的是,当我启动我的程序时,它会读取文件,将值设置为模型并在表中显示现有数据(在 JPanel 中)。这是我的代码,它只是看起来“错误”,但我不确定在哪里。谁能给我一个提示?谢谢 IA
public class Statistics extends JPanel {
public Object[][] data;
public DefaultTableModel model;
public PrintWriter saveStats;
public Statistics() {
super(new GridLayout(1,0));
String[] columnNames = {"Name", "Games Played", "Games Won"};
Object[][] data = {};
model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model);
table.setFillsViewportHeight(true);
table.setVisible(true);
table.setEnabled(false);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
public void addRow(Object[] objects) {
model.addRow(objects);
}
public void updateGamesPlayed(String userFolderName, int gamesPlayed) {
int rowCount = model.getRowCount();
int columnCount = model.getColumnCount();
for (int i = 0; i < rowCount; i++){
for(int j = 0; j < columnCount; j++){
if (model.getValueAt(i,j) == userFolderName){
int count = (Integer) model.getValueAt(i, j+1);
count += gamesPlayed;
model.setValueAt(gamesPlayed, i, j+1);
}
}
}
saveGameStats(model);
}
public void saveGameStats(DefaultTableModel model){
this.model = model;
File gameStats;
try {
gameStats = new File("GameStats.txt");
System.out.print(gameStats);
saveStats = new PrintWriter(gameStats);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < model.getRowCount(); i++){
for (int j = 0; j < model.getColumnCount(); j++){
saveStats.print(model.getValueAt(i,j)+ " ");
}
}
saveStats.close();
}
public void loadData() {
String name = "";
int games = 0;
int won = 0;
Scanner loadData = new Scanner("GameStats.txt");
while(loadData.hasNextLine()){
if (loadData.hasNext()){
name = loadData.next();}
else if (loadData.hasNextInt()){
games = loadData.nextInt();}
else if (loadData.hasNextInt()){
won = loadData.nextInt();}
for (int i = 0; i < model.getRowCount(); i++){
for (int j = 0; j < model.getColumnCount(); j++){
model.setValueAt(name,i,j);
model.setValueAt(games, i, j+1);
model.setValueAt(won, i, j+2);
}
}
}
}
}