Javafx Tableview setting values to Tablecolumn

Asked

Viewed 594 times

2

I ended up finding a problem that I believe is trivial but I don’t know how to solve. I have a class Seller who has an association with another class: Department. And I need a Tableview that populates two columns with database data, the first being @FXML private TableColumn<Seller, String> sellerName and the second @FXML private TableColumn<Seller, String> departmentName and the Table view: @FXML private TableView<Seller> tableViewSeller.

The first column should be responsible for listing the names of all sellers (Seller) and the second column of their respective departments (Department), in an associated form. The problem is time to pass what he should put in the column of the department name, and in the class Sellerit has an association with Department and its builder receives a new Department("Exemplo");to instantiate a Seller. To access for example, the name of the department should be done Seller seller = new Seller(); seller.getDepartment().getName;. How do I get the second column popular with the respective department of a seller and there is nothing that can happen here departmentName.setCellValueFactory(new PropertyValueFactory<>("*****")); referencing an attribute of an association ?

1 answer

0

I suppose the structure of your Seller class is as follows:

public class Seller {

    private String sellerName;
    private Departamento department;

    public Seller(...) {
        department = new Department("Exemplo");
    }
}

You have the following options:

1: Build a toString method in the Department class using only the department name.

@Override
public String toString() {
    return nome;
}

@FXML private TableColumn<Seller, Department> department;
department.setCellValueFactory(new PropertyValueFactory<>("department"));

2: Use Cell Factory (Usually used when we want to format table cells, using dates for example)

@FXML private TableColumn<Seller, Department> department;
department.setCellValueFactory(new PropertyValueFactory<>("department"));
department.setCellFactory(coluna -> {
    return new TableCell<Seller, Department>(){
        @Override
        protected void updateItem(Department item, boolean empty) {
            super.updateItem(item, empty);
            if(item != null && !empty) {
                setText(item.getName());
            } else {
                setText("");
            }
        }
    };
 });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.