stringjavafxtableviewobservablelist

JavaFX adding ObservableList<String> to single column TableView


I want to add the data from ObservableList batchNumber to a tableview which only contains one column yet im stucked because all the tutorials i found is about adding object type, not string type.

This is a function i used to generate a random batch number of format AAA0000

public String generateBatch(){
    Random rand = new Random();
    String[] alphabet = "Q W E R T Y U I O P A S D F G H J K L Z X C V B N M".split(" ");
    String batch = new String();
    batch = alphabet[rand.nextInt(0, 26)] + alphabet[rand.nextInt(0, 26)] + alphabet[rand.nextInt(0, 26)] + rand.nextInt(1000, 9999);
    return batch;
}

and then i add bunch of batch number into a ObservableList

    ObservableList<String> batchNumber = FXCollections.observableArrayList();
    for(int i = 0; i < 10; i++){
        batchNumber.add(generateBatch());
    }

so now batchNumber is loaded with bunch of Strings and then i tried to assign them to a tableView

TableView<String> batchNumberTableView = new TableView<>();
TableColumn<String, ?> batchColumn = new TableColumn<>("Vaccine Batch Number");
batchNumberTableView.getColumns().add(batchColumn);

and here is where im stucked, i've had successfully added a column into the tableview but i have no idea how to assign the datas from batchNumber into the tableview.


Solution

  • You need

    TableColumn<String, String> batchColumn = new TableColumn<>("Vaccine Batch Number");
    batchColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue()));