Pre-Populate TableView Data Into an FXML Window

34 Views Asked by At

The basis of this is: I'm trying to get all of the components in the modify appointments.fxml file to pre-populate the contents of the 'customerTable' tableview into their respective components.

The main window controller is 'appointmentsandcustomerscontroller':

appointmentsandcustomerscontroller:

package com.company.controllers;

// ... IMPORT STATEMENTS ...
import com.company.models.Appointment;
import com.company.models.Contact;
import com.company.models.Customer;
import com.company.controllers.createcustomercontroller;
import com.mysql.cj.conf.StringProperty;


import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Modality;
import javafx.stage.Stage;
import helper.JDBC;
import com.company.models.Customer;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import com.company.controllers.createappointmentcontroller;
import javafx.scene.control.cell.PropertyValueFactory;


import javax.imageio.IIOParam;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;

public class appointmentsandcustomerscontroller {

    // ... APPOINTMENTS FXML TAGS ...

    @FXML
    private TableView<Appointment> appointmentsTable;

    @FXML
    private TableColumn<Appointment, Integer> appointmentID;

    @FXML
    private TableColumn<Appointment, String> appointmentTitle;

    @FXML
    private TableColumn<Appointment, String> appointmentType;

    @FXML
    private TableColumn<Appointment, String> appointmentDescription;

    @FXML
    private TableColumn<Appointment, LocalDateTime> appointmentStartDateTime;

    @FXML
    private TableColumn<Appointment, LocalDateTime> appointmentEndDateTime;

    @FXML
    private TableColumn<Appointment, Contact> appointmentContact;

    @FXML
    private TableColumn<Appointment, Integer> appointmentCustomerID;

    @FXML
    private TableColumn<Appointment, Integer> appointmentUserID;

    @FXML
    private TableColumn<Customer, String> customerCountryColumn;

    @FXML
    private TableColumn<Customer, String> createDate;

    @FXML
    private TableColumn<Customer, String> createdBy;

    @FXML
    private TableColumn<Customer, String> lastUpdate;

    @FXML
    private TableColumn<Customer, String> lastUpdatedBy;

    @FXML
    private TableColumn<Customer, String> divisionID;

    @FXML
    private Button appointmentAddButton;

    @FXML
    private Button appointmentModify;

   /* @FXML
    private Button appointmentDeleteButton;*/


    // ... CUSTOMER FXML TAGS

    @FXML
    private TableColumn<Customer, String> customerPostalCode;

    @FXML
    private TableView<Customer> customersTable;

    @FXML
    private TableColumn<Customer, Integer> customerID;

    @FXML
    private TableColumn<Customer, String> customerName;

    @FXML
    private TableColumn<Customer, String> customerAddress;

    @FXML
    private TableColumn<Customer, String> customerPhoneNumber;

    @FXML
    private Button customerAdd;

    @FXML
    private Button customerModify;




    // ... REPORTS AND LOGOUT ...
    @FXML
    private Button generateReport;

    @FXML
    private Button homeLogout;


    /*public int getSelectedAppointmentID() {

        int selectedAppointmentID = 0;
        return selectedAppointmentID;
    }*/


    public ObservableList<Customer> customerList;
    public ObservableList<Appointment> appointmentList = FXCollections.observableArrayList();
    private appointmentsandcustomerscontroller controllerReference;

    // private ObservableList<Contact> contacts;

    @FXML
    public void initialize() {

        // ... Initialize Customers Table ...
        customerID.setCellValueFactory(new PropertyValueFactory<>("customerID"));
        customerName.setCellValueFactory(new PropertyValueFactory<>("customerName"));
        customerAddress.setCellValueFactory(new PropertyValueFactory<>("address"));
        customerPhoneNumber.setCellValueFactory(new PropertyValueFactory<>("phoneNumber"));
        customerPostalCode.setCellValueFactory(new PropertyValueFactory<>("postalCode"));


        // ... NOT NEEDED FOR CUSTOMERS TABLE?...
        /*createDate.setCellValueFactory(new PropertyValueFactory<>("createDate"));
        createdBy.setCellValueFactory(new PropertyValueFactory<>("createdBy"));
        lastUpdate.setCellValueFactory(new PropertyValueFactory<>("lastUpdate"));
        lastUpdatedBy.setCellValueFactory(new PropertyValueFactory<>("lastUpdatedBy"));
        divisionID.setCellValueFactory(new PropertyValueFactory<>("divisionID"));*/


        // ... Initialize Appointments Table ...

        appointmentID.setCellValueFactory(new PropertyValueFactory<>("appointmentId"));
        appointmentTitle.setCellValueFactory(new PropertyValueFactory<>("title"));
        appointmentType.setCellValueFactory(new PropertyValueFactory<>("type"));
        appointmentDescription.setCellValueFactory(new PropertyValueFactory<>("description"));
        appointmentStartDateTime.setCellValueFactory(new PropertyValueFactory<>("startDateTime"));
        appointmentEndDateTime.setCellValueFactory(new PropertyValueFactory<>("endDateTime"));
        appointmentContact.setCellValueFactory(new PropertyValueFactory<>("contact"));
        appointmentCustomerID.setCellValueFactory(new PropertyValueFactory<>("customerId"));
        appointmentUserID.setCellValueFactory(new PropertyValueFactory<>("userId"));

        populateAppointments();
        populateCustomers();
        customersTable.setItems(customerList);
        appointmentsTable.setItems(appointmentList);
        setControllerReference(this);
    }




    public List<Appointment> fetchDataFromDatabase() {
        // Create a list to store the fetched appointments
        List<Appointment> appointments = new ArrayList<>();

        // Automatically close the connection
        try (Connection connection = JDBC.openConnection()) {
            // Create and execute a SQL query to fetch the necessary data
            String query = "SELECT * FROM Appointments"; // Adjust the query as needed
            ResultSet resultSet = connection.createStatement().executeQuery(query);

            // Iterate through the result set and create Appointment objects
            while (resultSet.next()) {
                // Retrieve data from the result set
                int appointmentId = resultSet.getInt("Appointment_ID");
                String title = resultSet.getString("Title");
                String description = resultSet.getString("Description");
                String location = resultSet.getString("Location");
                String type = resultSet.getString("Type");
                LocalDateTime startDateTime = resultSet.getTimestamp("Start_DateTime").toLocalDateTime();
                LocalDateTime endDateTime = resultSet.getTimestamp("End_DateTime").toLocalDateTime();
                int customerId = resultSet.getInt("Customer_ID");
                int userId = resultSet.getInt("User_ID");
                int contactId = resultSet.getInt("Contact_ID");

                // Create a Contact object (you may fetch contact details from another table)
                Contact contact = new Contact("ContactName"); // Replace with actual contact details

                // Create an Appointment object and add it to the list
                Appointment appointment = new Appointment(
                        appointmentId,
                        title,
                        description,
                        location,
                        contact,
                        type,
                        startDateTime,
                        endDateTime,
                        customerId,
                        userId,
                        contactId
                );

                appointments.add(appointment); // Add the appointment to the list
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return appointments;
    }




    private void populateCustomers() {
        try {
            // Open the database connection
            JDBC.openConnection();


            // SQL query to retrieve data from the 'customers' table
            String query = "SELECT * FROM customers";


            // Execute the query and retrieve the result set
            ResultSet resultSet = JDBC.connection.createStatement().executeQuery(query);

            // Populate the customerList with retrieved data
            customerList = FXCollections.observableArrayList();


            while (resultSet.next()) {
                int customerID = resultSet.getInt("Customer_ID");
                String customerName = resultSet.getString("Customer_Name");
                String address = resultSet.getString("Address");
                String postalCode = resultSet.getString("Postal_Code");
                String phoneNumber = resultSet.getString("Phone");


                // Create a Customer object without the extra parameters
                Customer customer = new Customer(customerID, customerName, address, postalCode, phoneNumber);
                customerList.add(customer);
            }



            // Set the populated customerList to the customersTable
            /*customersTable.setItems(customerList);
            customersTable.refresh();*/

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // Close the database connection
            JDBC.closeConnection();
        }
    }

    public void populateAppointments() {
        try {
            // Open the database connection
            JDBC.openConnection();

            // SQL query to retrieve all columns from the 'appointments' table
            String query = "SELECT * FROM appointments";

            // Execute the query and retrieve the result set
            ResultSet resultSet = JDBC.connection.createStatement().executeQuery(query);

            // Populate the appointmentList with retrieved data
            appointmentList = FXCollections.observableArrayList();

            while (resultSet.next()) {
                int appointmentId = resultSet.getInt("Appointment_ID");
                String title = resultSet.getString("Title");
                String type = resultSet.getString("Type");
                String description = resultSet.getString("Description");
                String location = resultSet.getString("Location"); // Retrieve the "location" column
                LocalDateTime startDateTime = resultSet.getTimestamp("Start").toLocalDateTime();
                LocalDateTime endDateTime = resultSet.getTimestamp("End").toLocalDateTime();
                int contactId = resultSet.getInt("Contact_ID");
                int customerId = resultSet.getInt("Customer_ID");
                int userId = resultSet.getInt("User_ID");


                Contact contact = getContactFromResultSet(contactId);

                // Create an Appointment object and add it to the list
                Appointment appointment = new Appointment(appointmentId, title, description, location, contact, type, startDateTime, endDateTime, customerId, userId, contactId);

                appointmentList.add(appointment);
            }

            // Set the populated appointmentList to the appointmentsTable
            /*appointmentsTable.setItems(appointmentList);
            appointmentsTable.refresh();*/

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // Close the database connection
            JDBC.closeConnection();
        }
    }

    private Contact getContactFromResultSet(int contactId) {
        try {
            // SQL query to retrieve the contact information by ID
            String query = "SELECT * FROM contacts WHERE Contact_ID = " + contactId;

            // Execute the query and retrieve the result set
            ResultSet resultSet = JDBC.connection.createStatement().executeQuery(query);

            // Check if there is a result
            if (resultSet.next()) {
                String contactName = resultSet.getString("Contact_Name");

                // Create and return a Contact object
                return new Contact(contactId, contactName);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // Return null if no contact is found
        return null;
    }

    @FXML
    public void showInformationDialog(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    @FXML
    public void showErrorDialog(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }


    // ... Delete Appointments ...
    @FXML
    public void appointmentDeleteButton() {
        // Get the selected items from the appointmentsTable
        ObservableList<Appointment> selectedAppointments = appointmentsTable.getSelectionModel().getSelectedItems();

        if (selectedAppointments.isEmpty()) {
            // No appointments are selected, display a message or handle it as needed
            // You can show an alert or a message to inform the user.

        } else {
            // Confirm the deletion with the user (you can use JavaFX dialogs for this)
            boolean confirmed = showConfirmationDialog("Confirm Deletion", "Are you sure you want to delete selected appointments?");

            if (confirmed) {
                try {
                    // Open the database connection
                    JDBC.openConnection();

                    // Define the SQL query to delete appointments by their IDs
                    String deleteQuery = "DELETE FROM appointments WHERE Appointment_ID = ?";


                    // Use a PreparedStatement to execute the query
                    PreparedStatement preparedStatement = JDBC.connection.prepareStatement(deleteQuery);

                    // Delete each selected appointment
                    for (Appointment appointment : selectedAppointments) {
                        int appointmentId = appointment.getAppointmentId(); // Use getAppointmentId
                        preparedStatement.setInt(1, appointmentId);
                        preparedStatement.executeUpdate();
                    }


                    // Close the PreparedStatement
                    preparedStatement.close();

                    // Remove the deleted appointments from the appointmentsTable
                    appointmentsTable.getItems().removeAll(selectedAppointments);
                    System.out.println("Appointments removed from the list.");

                    // Inform the user about the successful deletion (you can use JavaFX alerts)
                    showInformationDialog("Deletion Successful", "Selected appointments have been deleted.");

                } catch (SQLException e) {
                    e.printStackTrace();
                    // Handle database errors or show an error message
                    showErrorDialog("Error", "An error occurred while deleting appointments.");
                } finally {
                    // Close the database connection
                    JDBC.closeConnection();
                }
            }
        }
    }

    public boolean showConfirmationDialog(String title, String message) {
        Alert confirmationDialog = new Alert(Alert.AlertType.CONFIRMATION);
        confirmationDialog.setTitle(title);
        confirmationDialog.setHeaderText(null);
        confirmationDialog.setContentText(message);

        // Add OK and Cancel buttons to the dialog
        ButtonType okButton = new ButtonType("OK", ButtonBar.ButtonData.OK_DONE);
        ButtonType cancelButton = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
        confirmationDialog.getButtonTypes().setAll(okButton, cancelButton);

        // Show the dialog and wait for a button press
        Optional<ButtonType> result = confirmationDialog.showAndWait();

        // Check if the OK button was pressed
        return result.isPresent() && result.get() == okButton;
    }



    // CODE FOR THE BUTTONS THAT OPEN THE WINDOWS
    @FXML
    private void appointmentAddButton() {
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/com/company/views/appointments/createappointment.fxml"));
            // fxmlLoader.setController(this);
            Parent root = fxmlLoader.load();

            // ... If I remove this, the appointment saves, but it doesn't refresh the database
            createappointmentcontroller controller = fxmlLoader.getController();
            controller.setAppointmentsController(this);

            Stage stage = new Stage();
            stage.initModality(Modality.APPLICATION_MODAL);
            stage.setTitle("Create Appointment");
            stage.setScene(new Scene(root));
            stage.showAndWait();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // ... Launches modifyappointment.fxml -- commented out for testing
   /* @FXML
    private void appointmentModifyButton() {
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/com/company/views/appointments/modifyappointment.fxml"));
            Parent root = fxmlLoader.load();

            Stage stage = new Stage();
            stage.initModality(Modality.APPLICATION_MODAL);
            stage.setTitle("Modify Appointment");
            stage.setScene(new Scene(root));
            stage.showAndWait();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/





    // ... Appointment Modify Test ...

    public void appointmentModifyButton(ActionEvent event) throws IOException {
        // Assuming you have a class for your Appointment and a TableView named 'customersTable'
        Appointment selectedAppointment = appointmentsTable.getSelectionModel().getSelectedItem();
        if (selectedAppointment == null) {
            return;
        }

        Stage stage = (Stage) ((Button) event.getSource()).getScene().getWindow();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/company/views/appointments/modifyappointment.fxml"));
        Parent scene = loader.load();
        modifyappointmentcontroller controller = loader.getController();

        // Pass the selectedAppointment to the controller
        controller.setModifyAppointmentID(selectedAppointment);

        stage.setTitle("Modify Appointment");
        stage.setScene(new Scene(scene));
        stage.show();
    }







    @FXML
    private void customerAddButton() {
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/com/company/views/customers/createcustomer.fxml"));
            Parent root = fxmlLoader.load();

            Stage stage = new Stage();
            stage.initModality(Modality.APPLICATION_MODAL);
            stage.setTitle("Add Customer");
            stage.setScene(new Scene(root));
            stage.showAndWait();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void customerModifyButton() {
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/com/company/views/customers/modifycustomer.fxml"));
            Parent root = fxmlLoader.load();

            // ... START TEST ...

            /*modifyappointmentcontroller controller = loader.getController();
            controller.initialize(selectedAppointment);*/
            // ... END TEST ...

            Stage stage = new Stage();
            stage.initModality(Modality.APPLICATION_MODAL);
            stage.setTitle("Modify Customer");
            stage.setScene(new Scene(root));
            stage.showAndWait();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void setControllerReference(appointmentsandcustomerscontroller controller) {
        this.controllerReference = controller;
    }

    // Refresh Appointments Table
    public void refreshCustomerTable(ActionEvent actionEvent) {
        populateAppointments();
        appointmentsTable.setItems(appointmentList);
    }
}

Appointment Class:

package com.company.models;
import com.company.controllers.modifyappointmentcontroller;
import java.time.LocalDateTime;

public class Appointment {

    // if these fail, they were set to private - contactId is always private
    private int appointmentId = 1;
    private String title;
    private String description;
    private String location;
    private Contact contact;
    private String type;
    private LocalDateTime startDateTime;
    private LocalDateTime endDateTime;
    private int customerId;
    private int userId;
    private int contactId;

    public Appointment(int appointmentId, String title, String description, String location,
                       Contact contact, String type, LocalDateTime startDateTime,
                       LocalDateTime endDateTime, int customerId, int userId, int contactId) {
        this.appointmentId = appointmentId;
        this.title = title;
        this.description = description;
        this.location = location;
        this.contact = contact;
        this.type = type;
        this.startDateTime = startDateTime;
        this.endDateTime = endDateTime;
        this.customerId = customerId;
        this.userId = userId;
        this.contactId = contactId;
    }




    public Appointment(int appointmentId) {
        this.appointmentId = appointmentId;
    }

    public int getAppointmentId() {
        return appointmentId;
    }

    public String getTitle() {
        return title;
    }

    public String getDescription() {
        return description;
    }

    public String getLocation() {
        return location;
    }

    public Contact getContact() {
        return contact;
    }

    public String getType() {
        return type;
    }

    public LocalDateTime getStartDateTime() {
        return startDateTime;
    }

    public LocalDateTime getEndDateTime() {
        return endDateTime;
    }

    public int getCustomerId() {
        return customerId;
    }

    public int getUserId() {
        return userId;
    }

    public int getContactId() {
        return contactId;
    }

    public void setContactId(int contactId) {
        this.contactId = contactId;
    }
}


modifyappointmentcontroller:

package com.company.controllers;

import javafx.fxml.FXML;
import javafx.scene.control.*;
import com.company.models.Appointment;
import javafx.scene.control.TextField;
import javafx.scene.control.TableColumn;


public class modifyappointmentcontroller {

    private TableColumn<TextField, Integer> appointmentIDColumn;

    private int appointmentID;

    @FXML private TextField modifyAppointmentID; // Keep this as it is with the same fx:id
    @FXML private TextField modifyAppointmentTitle;
    @FXML private TextField modifyAppointmentDescribe;
    @FXML private TextField modifyAppointmentLocation;
    @FXML private ComboBox modifyAppointmentContact;
    @FXML private ComboBox modifyAppointmentType;
    @FXML private DatePicker modifyAppointmentStartDate;
    @FXML private DatePicker modifyAppointmentEndDate;
    @FXML private ComboBox  modifyAppointmentStartTime;
    @FXML private ComboBox  modifyAppointmentEndTime;
    @FXML private ComboBox  modifyAppointmentCustomer;
    @FXML private ComboBox  modifyAppointmentUser;

    public modifyappointmentcontroller(TextField modifyAppointmentID, TableColumn<TextField, Integer> appointmentIDColumn, TextField modifyAppointmentTitle, TextField modifyAppointmentDescribe, TextField modifyAppointmentLocation, ComboBox modifyAppointmentContact, ComboBox modifyAppointmentType, DatePicker modifyAppointmentStartDate, DatePicker modifyAppointmentEndDate, ComboBox modifyAppointmentStartTime, ComboBox modifyAppointmentEndTime, ComboBox modifyAppointmentCustomer, ComboBox modifyAppointmentUser) {
        this.modifyAppointmentID = modifyAppointmentID;
        this.appointmentIDColumn = appointmentIDColumn;
        this.modifyAppointmentTitle = modifyAppointmentTitle;
        this.modifyAppointmentDescribe = modifyAppointmentDescribe;
        this.modifyAppointmentLocation = modifyAppointmentLocation;
        this.modifyAppointmentContact = modifyAppointmentContact;
        this.modifyAppointmentType = modifyAppointmentType;
        this.modifyAppointmentStartDate = modifyAppointmentStartDate;
        this.modifyAppointmentEndDate = modifyAppointmentEndDate;
        this.modifyAppointmentStartTime = modifyAppointmentStartTime;
        this.modifyAppointmentEndTime = modifyAppointmentEndTime;
        this.modifyAppointmentCustomer = modifyAppointmentCustomer;
        this.modifyAppointmentUser = modifyAppointmentUser;
    }

    // refer to software 1 - you have to have a new method that will accept the selected card on main controller, that data will be passed to this method
    // this data has to be passed on to the text field... modifyAppointmentID.setText(selectedRecord.appointmentID) 'selectedRecord' is just a varible name that can be whatever you want.

    @FXML
    private void initialize() {
        modifyAppointmentID.setText(String.valueOf(getSelectedAppointmentID())); // Assuming appointmentID has a getAppointmentID() method
       // modifyAppointmentID.setText("");
    }


    private int getSelectedAppointmentID() {

        return appointmentID;

    }


    

    public void setModifyAppointmentID(Appointment appointment) {
        this.appointmentID = appointment.getAppointmentId(); // Assuming getAppointmentId() returns an int
        /*modifyAppointmentID.setText(String.valueOf(this.appointmentID));
        modifyAppointmentID.setText(String.valueOf(appointment.getAppointmentId()));*/
        modifyAppointmentID.setText(Integer.toString(getSelectedAppointmentID()));
    }
}

I'm not sure if I have my variables messed up, but I've got everything initialized (that I can think of). I've got the constructors properly coded.

Reality is, I'm a complete beginner (so take it easy on me lol) and have it to the point where I can add what I need to the tables, I just can't get the data to pre-populate.

0

There are 0 best solutions below