How to populate TableView dynamically with FXML and JavaFX

后端 未结 1 1108
时光说笑
时光说笑 2021-01-01 08:19

How do I define my table in FXML and then use my JavaFX code to populate it dynamically at runtime?

1条回答
  •  借酒劲吻你
    2021-01-01 08:34

    1. Define the TableView in the fxml file. Few things to note:
      • the root should have a controller class associated with it.
      • the TableView and TableColumn should have fx:id attributes specified.

    1. Define the controller class. Few things to note:

      • the variables should be linked with the @FXML tag and a new object of TableView/TableColumn should not be created.
      • the variables should be named the same as the corresponding attribute value of fx:id as mentioned in the fxml.
      • the controller class should implement javafx.fxml.Initializable and hence should define the method public void initialize(URL location, ResourceBundle resources)
      • a class Data Model class MyDataModel is used to populate the data.

        public class MyController implements Initializable {

        @FXML
        private TableView myTableView;
        
        @FXML
        private TableColumn idColumn;
        
        @Override
        public void initialize(URL location, ResourceBundle resources) {
        idColumn.setCellValueFactory(new PropertyValueFactory"idColumn"));
        
        myTableView.getItems().setAll(getItemsToAdd());
        }
        
        private List getItemsToAdd(){
        // this method would fetch the necessary items from database.
        }
        

        }

    2. Define the Data Model class. Few things to note:

      • the variable should be named as idColumnProperty as the string passed for PropertyValueFactory is "idColumn".
      • the variable must be private final SimpleStringProperty as the type mentioned in controller class is String for the column.
      • the model class must have the methods getIdColumn() and setIdColumn(String id)

        public class MyDataModel {

        private final SimpleStringProperty idColumnProperty = new SimpleStringProperty("");
        
        public MyDataModel(){
        this("");
        }
        
        public MyDataModel(String id){
        setIdColumn(id);    
        }
        
        public String getIdColumn(){
        idColumnProperty.get();
        }
        
        public void setIdColumn(String id){
        idColumnProperty.set(id);
        }
        

        }

    0 讨论(0)
提交回复
热议问题