How to populate a TableView that is defined in an fxml file that is designed in JavaFx Scene Builder

て烟熏妆下的殇ゞ 提交于 2019-11-27 20:07:51

To access to tableview you need to define a controller of your FXML page. Add

fx:controller="path.to.MyController"

attribute to the AnchorPane in FXML file. Then create the controller and link TableView, TableColumns from FXML file by putting @FXML annotation in front of these variables:

package path.to;

public class MyController implements Initializable {

    @FXML private TableView<User> tableView;
    @FXML private TableColumn<User, String> UserId;
    @FXML private TableColumn<User, String> UserName;
    @FXML private TableColumn<User, String> Active;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        UserId.setCellValueFactory(new PropertyValueFactory<User, String>("id"));
        UserName.setCellValueFactory(new PropertyValueFactory<User, String>("name"));
        Active.setCellValueFactory(new PropertyValueFactory<User, String>("active"));

        tableView.getItems().setAll(parseUserList());
    }
    private List<User> parseUserList(){
        // parse and construct User datamodel list by looping your ResultSet rs
        // and return the list   
    }
}

The tableview is populated in the initialize method. Note that in controller we are not creating new tableview or tablecolumns, since they are already created whlle the FXML file is being loaded. Also note that the TableView and Tablecolumn variable names must be the same with fx:id values in the corresponding FXML file. So while UserId, UserName and Active names are not convenient namings, change them both in FXML file and in Controller to names like userIdCol, userNameCol and userActiveCol respectively.

Yo can do this in your controller:

 @FXML
private TableView<User> table;
private List<User> users;

@Override
public void initialize(URL url, ResourceBundle rb) {
    // Set the columns width auto size
    table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    table.getColumns().get(0).prefWidthProperty().bind(table.widthProperty().multiply(0.33));    // 33% for id column size
    table.getColumns().get(1).prefWidthProperty().bind(table.widthProperty().multiply(0.33));   // 33% for dt column size
    table.getColumns().get(2).prefWidthProperty().bind(table.widthProperty().multiply(0.33));    // 33% for cv column size
    table.getItems().setAll(this.users);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!