取一个TXT文件,然后插入到TableView(Javafx)



我尝试从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);

请帮助我有关此主题..

您可以尝试使用split()方法从文件中分解数据:

拆分(字符串正则)

将此字符串围绕给定的正则表达式的匹配。

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);

最新更新