导入的数据仅显示在 JTable (Java) 的第一列中



我试图制作一个简单的GUI,我可以在其中添加一个人的名字/姓氏和他们的出生日期。将数据添加到 JTable 后,我可以将其保存在 TxT 文件中,然后再次将其加载回 JTable 中。

保存数据的部分:

private void saveListener(){
jb1.addActionListener(e -> {
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showSaveDialog(PeopleGUI.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {     // Datei Explorer
try {
File file = fileChooser.getSelectedFile();
PrintWriter o = new PrintWriter(file); // o steht für Output
for (int col = 0; col < peopleModel.getColumnCount(); col++) {
o.print(peopleModel.getColumnName(col) + ";");
}
o.println("");
for (int row = 0; row < peopleModel.getRowCount(); row++) {
for (int col = 0; col < peopleModel.getColumnCount(); col++) {
o.println(peopleModel.getValueAt(row, col));
}
}
o.close();
// Output in der Konsole
System.out.println("Success!");
} catch (IOException c) {
c.printStackTrace();
}
}
});
}

加载数据的部分:

public void loadListener() {
jb2.addActionListener(e -> {
final JFileChooser fileChooser = new JFileChooser();
int response = fileChooser.showOpenDialog(PeopleGUI.this);
if (response == JFileChooser.APPROVE_OPTION) {
try {
BufferedReader br = new BufferedReader(new FileReader("jlist.txt"));
// Erste Linie sind Kolonnen Beschriftungen
String firstLine = br.readLine().trim();
String[] columnsName = firstLine.split(";");
DefaultTableModel model = (DefaultTableModel) peopleList.getModel();
model.setColumnIdentifiers(columnsName);
// Daten vom TxT holen
Object[] tableLines = br.lines().toArray();
// Reihen mit Daten
for (int i = 0; i < tableLines.length; i++) {
String line = tableLines[i].toString().trim();
String[] dataRow = line.split("/");
model.addRow(dataRow);
}
}
catch (IOException b) {
b.printStackTrace();
}
}
});
}

问题是,导入的数据仅显示在第一行中:

这就是它现在的样子

现在有人如何解决这个问题吗?

提前感谢!

问题是如何将数据保存到文件中

for (int row = 0; row < peopleModel.getRowCount(); row++) {
for (int col = 0; col < peopleModel.getColumnCount(); col++) {
o.println(peopleModel.getValueAt(row, col));
}
}

在这里,您将JTable的每个单元格保存在新行中。您希望将每一行保存在新行中,值由/分隔

for (int row = 0; row < peopleModel.getRowCount(); row++) {
String r = "";
for (int col = 0; col < peopleModel.getColumnCount(); col++) {
r += peopleModel.getValueAt(row, col);
if (col < peopleModel.getColumnCount() - 1) {
r += "/";
}
}
o.println(r);
}

编辑:如@camickr所述,使用StringJoiner更好

for (int row = 0; row < peopleModel.getRowCount(); row++) {
StringJoiner stringJoiner = new StringJoiner("/");
for (int col = 0; col < peopleModel.getColumnCount(); col++) {
stringJoiner.add(peopleModel.getValueAt(row, col).toString());
}
o.println(stringJoiner.toString());
}

最新更新