Search code examples
javajavafxtableview

Take a txt file and Insert to tableview (JavaFX)


I try to insert to tableview from txt file, but I couldn't do it.

This is my txt file.

aa.txt (It contains int A, int B, int F)

0 0 0
1 0 1
0 1 0
1 0 0

This is Product class (information part)

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

This is table view part in the code but I can't carry on this part

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

Please help me about this topic..


Solution

  • You can try splitting the data you get from the file using the split() method:

    split(String regex)

    Splits this string around matches of the given regular expression.

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

    Then remove table.setItems(getProduct());

    and call this method getProductsFromFile() that you just created, so your code should look like this:

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