我尝试从txt文件插入tableview,但我无法做到。
这是我的txt文件。
aa.txt(它包含int A,int B,int F)
0 0 0
1 0 1
0 1 0
1 0 0
这是产品类(信息部分)
public class Product {
private int A;
private int B;
private int F;
public Product(){
this.A = 0;
this.B = 0;
this.F = 0;
}
public Product(int A, int B, int F){
this.A = A;
this.B = B;
this.F = F;
}
public int getA() {
return A;
}
public void setA(int a) {
this.A = a;
}
public int getB() {
return B;
}
public void setB(int b) {
this.B = b;
}
public int getF() {
return F;
}
public void setF(int f) {
this.F = f;
} }
这是代码中的表格视图部分,但我无法进行此部分
TableColumn<Product, Integer> aColumn = new TableColumn<>("A");
aColumn.setMinWidth(100);
aColumn.setCellValueFactory(new PropertyValueFactory<>("A"));
TableColumn<Product, Integer> bColumn = new TableColumn<>("B");
bColumn.setMinWidth(100);
bColumn.setCellValueFactory(new PropertyValueFactory<>("B"));
TableColumn<Product, Integer> fColumn = new TableColumn<>("F");
fColumn.setMinWidth(100);
fColumn.setCellValueFactory(new PropertyValueFactory<>("F"));
table = new TableView<>();
table.setItems(getProduct());
table.getColumns().addAll(aColumn, bColumn, fColumn);
请帮我解决这个话题..
答案 0 :(得分:1)
您可以尝试使用split()
方法分割从文件中获取的数据:
split(String regex)
将此字符串拆分为给定正则表达式的匹配项。
private void getProductsFromFile() {
try {
BufferedReader br = new BufferedReader(new FileReader(new File("path/to/file.txt"));
String line;
String[] array;
while ((line = br.readLine()) != null){
array = line.split(" ");
table.getItems().add(new Product(Integer.parseInt(array[0]), Integer.parseInt(array[1]), Integer.parseInt(array[2])));
}
br.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
然后删除table.setItems(getProduct());
并调用您刚刚创建的此方法getProductsFromFile()
,因此您的代码应如下所示:
TableColumn<Product, Integer> aColumn = new TableColumn<>("A");
aColumn.setMinWidth(100);
aColumn.setCellValueFactory(new PropertyValueFactory<>("A"));
TableColumn<Product, Integer> bColumn = new TableColumn<>("B");
bColumn.setMinWidth(100);
bColumn.setCellValueFactory(new PropertyValueFactory<>("B"));
TableColumn<Product, Integer> fColumn = new TableColumn<>("F");
fColumn.setMinWidth(100);
fColumn.setCellValueFactory(new PropertyValueFactory<>("F"));
table = new TableView<>();
getProductsFromFile();
table.getColumns().addAll(aColumn, bColumn, fColumn);