[英]how to import a txt file into a JTable and make the first column auto increment according to the number of lines of the file
我正在做一些 java 編碼,我必須將一個文件導入到一個有 4 列的 Jtable 中,而我的文件有 3 列(由空格分隔,我需要每行的第一列自動遞增,這是我的代碼:
try {
FileReader files = new FileReader(file);
BufferedReader buf = new BufferedReader(files);
String line = null;
String tokens[] = null;
while ((line = buf.readLine()) != null) {
tokens = line.split("\\p{javaWhitespace}+");
//System.out.println( Arrays.toString( tokens ));
model.addRow(tokens);
}
}
只需在數據前面添加一個額外的令牌。 這是使用向量而不是數組最簡單的方法。 向量中的第一項是您的行索引,下一項是從您的標記數組中填充的。 例如:
try {
FileReader files = new FileReader(file);
BufferedReader buf = new BufferedReader(files);
String line = null;
String tokens[] = null;
int count = 0;
while ((line = buf.readLine()) != null) {
tokens = line.split("\\p{javaWhitespace}+");
Vector<Object> row = new Vector<>();
row.add(count);
count++;
for (String text: tokens) {
row.add(text);
}
model.addRow(row); // add the Vector, not the tokens array
}
}
還有其他方法,包括擴展表 model 以便它自動執行此操作,這些可能需要根據您的需要完成 - 例如,如果在運行期間刪除或添加一行,則重新編號的行該程序? 如果是這樣,邏輯需要在表 model 內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.