我试图制作一个简单的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();
}
}
});
}
问题是,导入的数据仅显示在第一行:
This is how it looks right now
现在有人可以解决此问题吗?
提前感谢!
问题是如何将数据保存到文件中
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());
}
.txt
文件的内容看起来如何,可以提供屏幕截图吗?您正在“分割”第一行,请尝试以下操作:
try {
BufferedReader br = new BufferedReader(new FileReader("jlist.txt"));
DefaultTableModel model = (DefaultTableModel) peopleList.getModel();
Object[] tableLines = br.lines().toArray();
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();
}
}