mardi 8 mai 2018

How to create an Observable List connected to MySQL?

I want to create an Observable List in order to set my items on the Table View. I want to remain my items there even if I close the windows. I created the Table View with reflection. My Java program is connected to the MySQL Workbench.

Here is the Diagram from MySQL if necessary.

The class which generates my Table View is this one:

 public class TableGenerator<T>{
   public TableView<T> generateTable(Object o){
       TableView<T> table = new TableView<>();
       Class oClass = o.getClass();
       for (Field f: oClass.getDeclaredFields()){
           TableColumn<T, ?> column = new TableColumn<>(f.getName());
           column.setCellValueFactory(new PropertyValueFactory<>(f.getName()));
           table.getColumns().add(column);
       }
       return table;
   }
}

In the UI Class I have this part of code regarding the Table View:

    TableView<Customer> tableViewC = new TableView<>();
    Customer customer = new Customer(-1, "", "", "", "");
    TableGenerator<Customer> t = new TableGenerator<Customer>();
    tableViewC = t.generateTable(customer);
    tableViewC.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

Also, when I want to add an item, I have this part of code:

addCustomerButton.setOnAction(e -> {
        CustomerBLL customerBLL = new CustomerBLL();
        Customer c = new Customer(nameCInput.getText(), phoneInput.getText(), emailInput.getText(),
                addressInput.getText());
        customerBLL.insertCustomer(c);
        tableViewC.getItems().add(c);
        tableViewC.refresh();
        clearAll();
    });

But the code above, where I only add an item adds it in the database, but it remains on the table only as long as my window is opened. And I want to remain it like forever...

From my searching I have found out that I need an Observable List, but I do not really know how to create it. What I did is:

 public ObservableList<Customer> getCustomers() {
    ObservableList<Customer> customers = FXCollections.observableArrayList();
    Customer c;
    c = CustomerDAO.findCustomerById(Integer.parseInt(idCInput.getText()));
    customers.add(c);
    return customers;

}

I will put the class CustomerDAO and CustomerBLL only if necessary, because they work both fine (including their functions, I have verified). I only want to set the Table View...

Any help will be of use. Massive thanks in advanced!





Aucun commentaire:

Enregistrer un commentaire